method2testcases
stringlengths 118
3.08k
|
---|
### Question:
MappingContentBuilder { XContentBuilder createMapping(Mapping mapping) { try (XContentBuilder contentBuilder = XContentFactory.contentBuilder(xContentType)) { createMapping(mapping, contentBuilder); return contentBuilder; } catch (IOException e) { throw new UncheckedIOException(e); } } MappingContentBuilder(); MappingContentBuilder(XContentType xContentType); static final String KEYWORD_TYPE; static final String FIELDS; static final String TYPE; static final String INDEX; }### Answer:
@Test void testCreateMappingKeywordCaseSensitive() throws IOException { Mapping mapping = createMapping( FieldMapping.builder() .setName("field") .setType(MappingType.KEYWORD) .setCaseSensitive(true) .build()); XContentBuilder xContentBuilder = mappingContentBuilder.createMapping(mapping); assertEquals(JSON_KEYWORD_CASE_SENSITIVE, xContentBuilder.string()); }
@Test void testCreateMappingNested() throws IOException { FieldMapping nestedFieldMapping = FieldMapping.builder().setName("nestedField").setType(MappingType.BOOLEAN).build(); Mapping mapping = createMapping( FieldMapping.builder() .setName("field") .setType(MappingType.NESTED) .setNestedFieldMappings(singletonList(nestedFieldMapping)) .build()); XContentBuilder xContentBuilder = mappingContentBuilder.createMapping(mapping); assertEquals(JSON_NESTED, xContentBuilder.string()); }
|
### Question:
ClientFactory { Client createClient() throws InterruptedException { Client client = retryTemplate.execute(this::tryCreateClient); LOG.info("Connected to Elasticsearch cluster '{}'.", clusterName); return client; } ClientFactory(
RetryTemplate retryTemplate,
String clusterName,
List<InetSocketAddress> inetAddresses,
PreBuiltTransportClientFactory preBuiltTransportClientFactory); }### Answer:
@Test void testCreateClient() throws Exception { initMockClient(); int port = 8032; String clusterName = "testCluster"; when(preBuildClientFactory.build(clusterName, null)) .thenReturn(unConnectedClient, unConnectedClient, connectedClient); ClientFactory clientFactory = new ClientFactory( retryTemplate, clusterName, singletonList(new InetSocketAddress(port)), preBuildClientFactory); Client client = clientFactory.createClient(); assertEquals(connectedClient, client); verify(preBuildClientFactory, times(3)).build(clusterName, null); verify(unConnectedClient, times(2)).close(); }
|
### Question:
ClientFacade implements Closeable { public boolean indexesExist(Index index) { return indexesExist(singletonList(index)); } ClientFacade(Client client); void createIndex(Index index, IndexSettings indexSettings, Stream<Mapping> mappingStream); boolean indexesExist(Index index); void deleteIndex(Index index); void refreshIndexes(); long getCount(Index index); long getCount(QueryBuilder query, Index index); SearchHits search(QueryBuilder query, int from, int size, List<Index> indexes); SearchHits search(QueryBuilder query, int from, int size, Sort sort, Index index); Aggregations aggregate(
List<AggregationBuilder> aggregations, QueryBuilder query, Index index); Explanation explain(SearchHit searchHit, QueryBuilder query); void index(Index index, Document document); void deleteById(Index index, Document document); void processDocumentActions(Stream<DocumentAction> documentActions); @Override void close(); }### Answer:
@Test void testIndexesExistThrowsException() { Index index = Index.create("index"); when(indicesAdminClient.prepareExists("index")).thenReturn(indicesExistsRequestBuilder); when(indicesExistsRequestBuilder.get()).thenThrow(new ElasticsearchException("exception")); Exception exception = assertThrows(IndexException.class, () -> clientFacade.indexesExist(index)); assertThat(exception.getMessage()) .containsPattern("Error determining index\\(es\\) 'index' existence\\."); }
|
### Question:
ClientFacade implements Closeable { public void deleteIndex(Index index) { deleteIndexes(singletonList(index)); } ClientFacade(Client client); void createIndex(Index index, IndexSettings indexSettings, Stream<Mapping> mappingStream); boolean indexesExist(Index index); void deleteIndex(Index index); void refreshIndexes(); long getCount(Index index); long getCount(QueryBuilder query, Index index); SearchHits search(QueryBuilder query, int from, int size, List<Index> indexes); SearchHits search(QueryBuilder query, int from, int size, Sort sort, Index index); Aggregations aggregate(
List<AggregationBuilder> aggregations, QueryBuilder query, Index index); Explanation explain(SearchHit searchHit, QueryBuilder query); void index(Index index, Document document); void deleteById(Index index, Document document); void processDocumentActions(Stream<DocumentAction> documentActions); @Override void close(); }### Answer:
@Test void testDeleteIndexThrowsException() { Index index = Index.create("index"); when(indicesAdminClient.prepareDelete("index")).thenReturn(deleteIndexRequestBuilder); when(deleteIndexRequestBuilder.get()).thenThrow(new ElasticsearchException("exception")); Exception exception = assertThrows(IndexException.class, () -> clientFacade.deleteIndex(index)); assertThat(exception.getMessage()).containsPattern("Error deleting index\\(es\\) 'index'\\."); }
@Test void testDeleteIndexNotAcknowledged() { Index index = Index.create("index"); when(indicesAdminClient.prepareDelete("index")).thenReturn(deleteIndexRequestBuilder); when(deleteIndexRequestBuilder.get()).thenReturn(deleteIndexResponse); when(deleteIndexResponse.isAcknowledged()).thenReturn(false); Exception exception = assertThrows(IndexException.class, () -> clientFacade.deleteIndex(index)); assertThat(exception.getMessage()).containsPattern("Error deleting index\\(es\\) 'index'\\."); }
|
### Question:
ClientFacade implements Closeable { @Override public void close() { try { client.close(); } catch (ElasticsearchException e) { LOG.error("Error closing Elasticsearch client", e); } } ClientFacade(Client client); void createIndex(Index index, IndexSettings indexSettings, Stream<Mapping> mappingStream); boolean indexesExist(Index index); void deleteIndex(Index index); void refreshIndexes(); long getCount(Index index); long getCount(QueryBuilder query, Index index); SearchHits search(QueryBuilder query, int from, int size, List<Index> indexes); SearchHits search(QueryBuilder query, int from, int size, Sort sort, Index index); Aggregations aggregate(
List<AggregationBuilder> aggregations, QueryBuilder query, Index index); Explanation explain(SearchHit searchHit, QueryBuilder query); void index(Index index, Document document); void deleteById(Index index, Document document); void processDocumentActions(Stream<DocumentAction> documentActions); @Override void close(); }### Answer:
@Test void testCloseThrowsException() throws Exception { doThrow(new ElasticsearchException("exception")).when(client).close(); clientFacade.close(); verify(mockAppender).doAppend(matcher(ERROR, "Error closing Elasticsearch client")); }
|
### Question:
SortContentBuilder { List<SortBuilder> createSorts(Sort sort) { return sort.getOrders().stream().map(this::createSort).collect(toList()); } }### Answer:
@Test void createSortsAsc() { List<SortBuilder> sorts = sortContentBuilder.createSorts(Sort.create(singletonList(SortOrder.create("field", ASC)))); assertSortsEqual(sorts, singletonList(JSON_SORT_ASC)); }
@Test void createSortsDesc() { List<SortBuilder> sorts = sortContentBuilder.createSorts(Sort.create(singletonList(SortOrder.create("field", DESC)))); assertSortsEqual(sorts, singletonList(JSON_SORT_DESC)); }
|
### Question:
CouldNotUploadAppException extends CodedRuntimeException { @Override public String getMessage() { return fileName; } CouldNotUploadAppException(String fileName); @Override String getMessage(); }### Answer:
@Test void testGetMessage() { CodedRuntimeException ex = new CouldNotUploadAppException("app.zip"); assertEquals("app.zip", ex.getMessage()); }
|
### Question:
CouldNotDeleteAppException extends CodedRuntimeException { @Override public String getMessage() { return id; } CouldNotDeleteAppException(String id); @Override String getMessage(); }### Answer:
@Test void testGetMessage() { CodedRuntimeException ex = new CouldNotDeleteAppException("app"); assertEquals("app", ex.getMessage()); }
|
### Question:
App extends StaticEntity { public String getId() { return getString(ID); } App(Entity entity); App(EntityType entityType); App(String label, EntityType entityType); String getId(); void setId(String id); String getName(); void setName(String name); String getLabel(); void setLabel(String label); @Nullable @CheckForNull String getDescription(); void setDescription(String description); boolean isActive(); void setActive(boolean isActive); boolean includeMenuAndFooter(); void setIncludeMenuAndFooter(boolean includeMenuAndFooter); String getTemplateContent(); void setTemplateContent(String templateContent); String getAppVersion(); void setAppVersion(String appVersion); String getApiDependency(); void setApiDependency(String apiDependency); String getAppConfig(); void setAppConfig(String appConfig); String getResourceFolder(); void setResourceFolder(String resourceFolder); }### Answer:
@Test void testConstructorParams() { app = appFactory.create(); assertNotNull(app.getId()); }
|
### Question:
AppManagerServiceImpl implements AppManagerService { @Override public List<AppResponse> getApps() { return dataService .findAll(AppMetadata.APP, App.class) .map(AppResponse::create) .collect(toList()); } AppManagerServiceImpl(
AppFactory appFactory,
DataService dataService,
FileStore fileStore,
Gson gson,
PluginFactory pluginFactory); @Override List<AppResponse> getApps(); @Override AppResponse getAppByName(String appName); @Override @Transactional void activateApp(App app); @Override @Transactional void deactivateApp(App app); @Override @Transactional void deleteApp(String id); @Override String uploadApp(InputStream zipData, String zipFileName, String formFieldName); @Override AppConfig checkAndObtainConfig(String tempDir, String configContent); @Override @Transactional void configureApp(AppConfig appConfig, String htmlTemplate); @Override String extractFileContent(String appDir, String fileName); static final String APPS_DIR; static final String ZIP_INDEX_FILE; static final String ZIP_CONFIG_FILE; static final String APP_PLUGIN_ROOT; }### Answer:
@Test void testGetApps() { AppResponse appResponse = AppResponse.create(app); when(dataService.findAll(AppMetadata.APP, App.class)).thenReturn(newArrayList(app).stream()); List<AppResponse> actual = appManagerServiceImpl.getApps(); List<AppResponse> expected = newArrayList(appResponse); assertEquals(expected, actual); }
|
### Question:
AppManagerServiceImpl implements AppManagerService { @Override @Transactional public void activateApp(App app) { String pluginId = generatePluginId(app); Plugin plugin = pluginFactory.create(pluginId); plugin.setLabel(app.getLabel()); plugin.setPath(APP_PLUGIN_ROOT + app.getName()); plugin.setDescription(app.getDescription()); dataService.add(PluginMetadata.PLUGIN, plugin); } AppManagerServiceImpl(
AppFactory appFactory,
DataService dataService,
FileStore fileStore,
Gson gson,
PluginFactory pluginFactory); @Override List<AppResponse> getApps(); @Override AppResponse getAppByName(String appName); @Override @Transactional void activateApp(App app); @Override @Transactional void deactivateApp(App app); @Override @Transactional void deleteApp(String id); @Override String uploadApp(InputStream zipData, String zipFileName, String formFieldName); @Override AppConfig checkAndObtainConfig(String tempDir, String configContent); @Override @Transactional void configureApp(AppConfig appConfig, String htmlTemplate); @Override String extractFileContent(String appDir, String fileName); static final String APPS_DIR; static final String ZIP_INDEX_FILE; static final String ZIP_CONFIG_FILE; static final String APP_PLUGIN_ROOT; }### Answer:
@Test void testActivateApp() { when(dataService.findOneById(AppMetadata.APP, "test", App.class)).thenReturn(app); app.setActive(true); Plugin plugin = mock(Plugin.class); when(pluginFactory.create(APP_PREFIX + "app1")).thenReturn(plugin); plugin.setLabel("label"); plugin.setDescription("description"); appManagerServiceImpl.activateApp(app); verify(dataService).add("sys_Plugin", plugin); }
|
### Question:
AppManagerServiceImpl implements AppManagerService { @Override @Transactional public void deactivateApp(App app) { String pluginId = generatePluginId(app); dataService.deleteById(PluginMetadata.PLUGIN, pluginId); } AppManagerServiceImpl(
AppFactory appFactory,
DataService dataService,
FileStore fileStore,
Gson gson,
PluginFactory pluginFactory); @Override List<AppResponse> getApps(); @Override AppResponse getAppByName(String appName); @Override @Transactional void activateApp(App app); @Override @Transactional void deactivateApp(App app); @Override @Transactional void deleteApp(String id); @Override String uploadApp(InputStream zipData, String zipFileName, String formFieldName); @Override AppConfig checkAndObtainConfig(String tempDir, String configContent); @Override @Transactional void configureApp(AppConfig appConfig, String htmlTemplate); @Override String extractFileContent(String appDir, String fileName); static final String APPS_DIR; static final String ZIP_INDEX_FILE; static final String ZIP_CONFIG_FILE; static final String APP_PLUGIN_ROOT; }### Answer:
@Test void testDeactivateApp() { when(dataService.findOneById(AppMetadata.APP, "test", App.class)).thenReturn(app); app.setActive(false); appManagerServiceImpl.deactivateApp(app); verify(dataService).deleteById(PluginMetadata.PLUGIN, APP_PREFIX + "app1"); }
|
### Question:
AppManagerServiceImpl implements AppManagerService { @Override @Transactional public void deleteApp(String id) { App app = getAppById(id); if (app.isActive()) { deactivateApp(app); } try { deleteDirectory(fileStore.getFileUnchecked(app.getResourceFolder())); } catch (IOException err) { throw new CouldNotDeleteAppException(id); } } AppManagerServiceImpl(
AppFactory appFactory,
DataService dataService,
FileStore fileStore,
Gson gson,
PluginFactory pluginFactory); @Override List<AppResponse> getApps(); @Override AppResponse getAppByName(String appName); @Override @Transactional void activateApp(App app); @Override @Transactional void deactivateApp(App app); @Override @Transactional void deleteApp(String id); @Override String uploadApp(InputStream zipData, String zipFileName, String formFieldName); @Override AppConfig checkAndObtainConfig(String tempDir, String configContent); @Override @Transactional void configureApp(AppConfig appConfig, String htmlTemplate); @Override String extractFileContent(String appDir, String fileName); static final String APPS_DIR; static final String ZIP_INDEX_FILE; static final String ZIP_CONFIG_FILE; static final String APP_PLUGIN_ROOT; }### Answer:
@Test void testDeleteApp() { when(dataService.findOneById(AppMetadata.APP, "test", App.class)).thenReturn(app); appManagerServiceImpl.deleteApp("test"); verify(dataService).deleteById(PluginMetadata.PLUGIN, APP_PREFIX + "app1"); }
@Test void testAppIdDoesNotExist() { when(dataService.findOneById(AppMetadata.APP, "test", App.class)).thenReturn(null); try { appManagerServiceImpl.deleteApp("test"); fail(); } catch (AppForIDDoesNotExistException actual) { assertEquals("test", actual.getId()); } }
|
### Question:
AppManagerServiceImpl implements AppManagerService { @Override public String extractFileContent(String appDir, String fileName) { File indexFile = fileStore.getFileUnchecked(appDir + separator + fileName); return utf8Encodedfiletostring(indexFile); } AppManagerServiceImpl(
AppFactory appFactory,
DataService dataService,
FileStore fileStore,
Gson gson,
PluginFactory pluginFactory); @Override List<AppResponse> getApps(); @Override AppResponse getAppByName(String appName); @Override @Transactional void activateApp(App app); @Override @Transactional void deactivateApp(App app); @Override @Transactional void deleteApp(String id); @Override String uploadApp(InputStream zipData, String zipFileName, String formFieldName); @Override AppConfig checkAndObtainConfig(String tempDir, String configContent); @Override @Transactional void configureApp(AppConfig appConfig, String htmlTemplate); @Override String extractFileContent(String appDir, String fileName); static final String APPS_DIR; static final String ZIP_INDEX_FILE; static final String ZIP_CONFIG_FILE; static final String APP_PLUGIN_ROOT; }### Answer:
@Test void testExtractFileContent() throws URISyntaxException { URL resourceUrl = Resources.getResource(AppControllerTest.class, "/index.html"); File testIndexHtml = new File(new URI(resourceUrl.toString()).getPath()); when(fileStore.getFileUnchecked("testDir" + separator + "test")).thenReturn(testIndexHtml); appManagerServiceImpl.extractFileContent("testDir", "test"); }
|
### Question:
AppManagerController extends PluginController { @GetMapping public String init() { return "view-app-manager"; } AppManagerController(AppManagerService appManagerService, DataService dataService); @GetMapping String init(); @ResponseBody @GetMapping("/apps") List<AppResponse> getApps(); @ResponseStatus(HttpStatus.OK) @PostMapping("/activate/{id}") void activateApp(@PathVariable(value = "id") String id); @ResponseStatus(HttpStatus.OK) @PostMapping("/deactivate/{id}") void deactivateApp(@PathVariable(value = "id") String id); @ResponseStatus(HttpStatus.OK) @DeleteMapping("/delete/{id}") void deleteApp(@PathVariable("id") String id); @ResponseStatus(HttpStatus.OK) @PostMapping("/upload") void uploadApp(@RequestParam("file") MultipartFile multipartFile); static final String ID; static final String URI; }### Answer:
@Test void testInit() throws Exception { mockMvc .perform(get(AppManagerController.URI)) .andExpect(status().is(200)) .andExpect(view().name("view-app-manager")); }
|
### Question:
AppManagerController extends PluginController { @ResponseBody @GetMapping("/apps") public List<AppResponse> getApps() { return appManagerService.getApps(); } AppManagerController(AppManagerService appManagerService, DataService dataService); @GetMapping String init(); @ResponseBody @GetMapping("/apps") List<AppResponse> getApps(); @ResponseStatus(HttpStatus.OK) @PostMapping("/activate/{id}") void activateApp(@PathVariable(value = "id") String id); @ResponseStatus(HttpStatus.OK) @PostMapping("/deactivate/{id}") void deactivateApp(@PathVariable(value = "id") String id); @ResponseStatus(HttpStatus.OK) @DeleteMapping("/delete/{id}") void deleteApp(@PathVariable("id") String id); @ResponseStatus(HttpStatus.OK) @PostMapping("/upload") void uploadApp(@RequestParam("file") MultipartFile multipartFile); static final String ID; static final String URI; }### Answer:
@Test void testGetApps() throws Exception { when(appManagerService.getApps()).thenReturn(newArrayList(appResponse)); mockMvc .perform(get(AppManagerController.URI + "/apps")) .andExpect(status().is(200)) .andExpect( content() .string( "[{\"id\":\"id\",\"name\":\"app1\",\"label\":\"label\",\"description\":\"description\",\"isActive\":true,\"includeMenuAndFooter\":true,\"templateContent\":\"\\u003ch1\\u003eTest\\u003c/h1\\u003e\",\"version\":\"v1.0.0\",\"resourceFolder\":\"resource-folder\",\"appConfig\":\"{\\u0027config\\u0027: \\u0027test\\u0027}\"}]")); }
|
### Question:
AppManagerController extends PluginController { @ResponseStatus(HttpStatus.OK) @PostMapping("/activate/{id}") public void activateApp(@PathVariable(value = "id") String id) { App app = getApp(id); app.setActive(true); dataService.update(AppMetadata.APP, app); } AppManagerController(AppManagerService appManagerService, DataService dataService); @GetMapping String init(); @ResponseBody @GetMapping("/apps") List<AppResponse> getApps(); @ResponseStatus(HttpStatus.OK) @PostMapping("/activate/{id}") void activateApp(@PathVariable(value = "id") String id); @ResponseStatus(HttpStatus.OK) @PostMapping("/deactivate/{id}") void deactivateApp(@PathVariable(value = "id") String id); @ResponseStatus(HttpStatus.OK) @DeleteMapping("/delete/{id}") void deleteApp(@PathVariable("id") String id); @ResponseStatus(HttpStatus.OK) @PostMapping("/upload") void uploadApp(@RequestParam("file") MultipartFile multipartFile); static final String ID; static final String URI; }### Answer:
@Test void testActivateApp() throws Exception { App app = mock(App.class); when(dataService.findOneById(AppMetadata.APP, "id", App.class)).thenReturn(app); mockMvc.perform(post(AppManagerController.URI + "/activate/id")).andExpect(status().is(200)); verify(app).setActive(true); verify(dataService).update(AppMetadata.APP, app); }
|
### Question:
AppManagerController extends PluginController { @ResponseStatus(HttpStatus.OK) @PostMapping("/deactivate/{id}") public void deactivateApp(@PathVariable(value = "id") String id) { App app = getApp(id); app.setActive(false); dataService.update(AppMetadata.APP, app); } AppManagerController(AppManagerService appManagerService, DataService dataService); @GetMapping String init(); @ResponseBody @GetMapping("/apps") List<AppResponse> getApps(); @ResponseStatus(HttpStatus.OK) @PostMapping("/activate/{id}") void activateApp(@PathVariable(value = "id") String id); @ResponseStatus(HttpStatus.OK) @PostMapping("/deactivate/{id}") void deactivateApp(@PathVariable(value = "id") String id); @ResponseStatus(HttpStatus.OK) @DeleteMapping("/delete/{id}") void deleteApp(@PathVariable("id") String id); @ResponseStatus(HttpStatus.OK) @PostMapping("/upload") void uploadApp(@RequestParam("file") MultipartFile multipartFile); static final String ID; static final String URI; }### Answer:
@Test void testDeactivateApp() throws Exception { App app = mock(App.class); when(dataService.findOneById(AppMetadata.APP, "id", App.class)).thenReturn(app); mockMvc.perform(post(AppManagerController.URI + "/deactivate/id")).andExpect(status().is(200)); verify(app).setActive(false); verify(dataService).update(AppMetadata.APP, app); }
|
### Question:
AppManagerController extends PluginController { @ResponseStatus(HttpStatus.OK) @DeleteMapping("/delete/{id}") public void deleteApp(@PathVariable("id") String id) { dataService.deleteById(AppMetadata.APP, id); } AppManagerController(AppManagerService appManagerService, DataService dataService); @GetMapping String init(); @ResponseBody @GetMapping("/apps") List<AppResponse> getApps(); @ResponseStatus(HttpStatus.OK) @PostMapping("/activate/{id}") void activateApp(@PathVariable(value = "id") String id); @ResponseStatus(HttpStatus.OK) @PostMapping("/deactivate/{id}") void deactivateApp(@PathVariable(value = "id") String id); @ResponseStatus(HttpStatus.OK) @DeleteMapping("/delete/{id}") void deleteApp(@PathVariable("id") String id); @ResponseStatus(HttpStatus.OK) @PostMapping("/upload") void uploadApp(@RequestParam("file") MultipartFile multipartFile); static final String ID; static final String URI; }### Answer:
@Test void testDeleteApp() throws Exception { mockMvc.perform(delete(AppManagerController.URI + "/delete/id")).andExpect(status().is(200)); verify(dataService).deleteById(AppMetadata.APP, "id"); }
|
### Question:
AppManagerController extends PluginController { @ResponseStatus(HttpStatus.OK) @PostMapping("/upload") public void uploadApp(@RequestParam("file") MultipartFile multipartFile) { String filename = multipartFile.getOriginalFilename(); String formFieldName = multipartFile.getName(); try (InputStream fileInputStream = multipartFile.getInputStream()) { String tempDir = appManagerService.uploadApp(fileInputStream, filename, formFieldName); String configFile = appManagerService.extractFileContent(tempDir, ZIP_CONFIG_FILE); AppConfig appConfig = appManagerService.checkAndObtainConfig(tempDir, configFile); String htmlTemplate = appManagerService.extractFileContent( APPS_DIR + separator + appConfig.getName(), ZIP_INDEX_FILE); appManagerService.configureApp(appConfig, htmlTemplate); } catch (IOException err) { throw new CouldNotUploadAppException(filename); } } AppManagerController(AppManagerService appManagerService, DataService dataService); @GetMapping String init(); @ResponseBody @GetMapping("/apps") List<AppResponse> getApps(); @ResponseStatus(HttpStatus.OK) @PostMapping("/activate/{id}") void activateApp(@PathVariable(value = "id") String id); @ResponseStatus(HttpStatus.OK) @PostMapping("/deactivate/{id}") void deactivateApp(@PathVariable(value = "id") String id); @ResponseStatus(HttpStatus.OK) @DeleteMapping("/delete/{id}") void deleteApp(@PathVariable("id") String id); @ResponseStatus(HttpStatus.OK) @PostMapping("/upload") void uploadApp(@RequestParam("file") MultipartFile multipartFile); static final String ID; static final String URI; }### Answer:
@Test void testUploadApp() throws Exception { AppConfig appConfig = mock(AppConfig.class); when(appConfig.getName()).thenReturn(""); when(appManagerService.checkAndObtainConfig(null, null)).thenReturn(appConfig); String testFile = AppManagerControllerTest.class.getResource("/test-app.zip").getFile(); mockMvc .perform(multipart(AppManagerController.URI + "/upload").file("file", testFile.getBytes())) .andExpect(status().is(200)); }
|
### Question:
AppController extends PluginController { @GetMapping("/{appName}/**") @Nullable @CheckForNull public ModelAndView serveApp( @PathVariable String appName, Model model, HttpServletRequest request, HttpServletResponse response) throws IOException { PluginIdentity pluginIdentity = new PluginIdentity(APP_PREFIX + appName); if (!userPermissionEvaluator.hasPermission(pluginIdentity, VIEW_PLUGIN)) { throw new PluginPermissionDeniedException(appName, VIEW_PLUGIN); } String wildCardPath = extractWildcardPath(request, appName); if (wildCardPath.isEmpty()) { RedirectView redirectView = new RedirectView(findAppMenuURL(appName)); redirectView.setExposePathVariables(false); return new ModelAndView(redirectView); } AppResponse appResponse = appManagerService.getAppByName(appName); if (!appResponse.getIsActive()) { throw new AppIsInactiveException(appName); } else if (isResourceRequest(wildCardPath)) { serveAppResource(response, wildCardPath, appResponse); return null; } else { return serveAppTemplate(appName, model, appResponse); } } AppController(
AppManagerService appManagerService,
UserPermissionEvaluator userPermissionEvaluator,
AppSettings appSettings,
MenuReaderService menuReaderService,
FileStore fileStore); @GetMapping("/{appName}/**") @Nullable @CheckForNull ModelAndView serveApp(
@PathVariable String appName,
Model model,
HttpServletRequest request,
HttpServletResponse response); static final String ID; static final String URI; }### Answer:
@Test void testServeApp() throws Exception { PluginIdentity pluginIdentity = new PluginIdentity(APP_PREFIX + "app1"); when(userPermissionEvaluator.hasPermission(pluginIdentity, VIEW_PLUGIN)).thenReturn(true); mockMvc .perform(get(AppController.URI + "/app1/")) .andExpect(status().isOk()) .andExpect(model().attribute("app", appResponse)) .andExpect(model().attribute("baseUrl", "/test/path")) .andExpect(view().name("view-app")); }
|
### Question:
AppRepositoryDecorator extends AbstractRepositoryDecorator<App> { @Override public void delete(App entity) { deleteById(entity.getId()); } AppRepositoryDecorator(
Repository<App> delegateRepository, AppManagerService appManagerService); @Override void delete(App entity); @Override void deleteById(Object id); @Override void deleteAll(); @Override void update(App app); @Override void update(Stream<App> apps); }### Answer:
@Test void testDelete() { String appId = "app"; App app = when(mock(App.class).getId()).thenReturn(appId).getMock(); appRepositoryDecorator.delete(app); verify(repository).deleteById(appId); }
|
### Question:
AppRepositoryDecorator extends AbstractRepositoryDecorator<App> { @Override public void deleteById(Object id) { appManagerService.deleteApp((String) id); delegate().deleteById(id); } AppRepositoryDecorator(
Repository<App> delegateRepository, AppManagerService appManagerService); @Override void delete(App entity); @Override void deleteById(Object id); @Override void deleteAll(); @Override void update(App app); @Override void update(Stream<App> apps); }### Answer:
@Test void testDeleteById() { appRepositoryDecorator.deleteById("app"); verify(appManagerService).deleteApp("app"); verify(repository).deleteById("app"); }
|
### Question:
AppRepositoryDecorator extends AbstractRepositoryDecorator<App> { @Override public void deleteAll() { findAll(new QueryImpl<>()).forEach(app -> deleteById(app.getId())); } AppRepositoryDecorator(
Repository<App> delegateRepository, AppManagerService appManagerService); @Override void delete(App entity); @Override void deleteById(Object id); @Override void deleteAll(); @Override void update(App app); @Override void update(Stream<App> apps); }### Answer:
@Test void testDeleteAll() { App app1 = mock(App.class); when(app1.getId()).thenReturn("app1"); App app2 = mock(App.class); when(app2.getId()).thenReturn("app2"); Stream<App> apps = Stream.of(app1, app2); when(repository.findAll(new QueryImpl<>())).thenReturn(apps); appRepositoryDecorator.deleteAll(); verify(appManagerService).deleteApp("app1"); verify(repository).deleteById("app1"); verify(appManagerService).deleteApp("app2"); verify(repository).deleteById("app2"); }
|
### Question:
AppRepositoryDecorator extends AbstractRepositoryDecorator<App> { @Override protected Repository<App> delegate() { return delegateRepository; } AppRepositoryDecorator(
Repository<App> delegateRepository, AppManagerService appManagerService); @Override void delete(App entity); @Override void deleteById(Object id); @Override void deleteAll(); @Override void update(App app); @Override void update(Stream<App> apps); }### Answer:
@Test void testDelegate() { assertEquals(repository, appRepositoryDecorator.delegate()); }
|
### Question:
DataExplorerServiceImpl implements DataExplorerService { DataExplorerServiceImpl( DataExplorerSettings dataExplorerSettings, UserPermissionEvaluator userPermissionEvaluator) { this.dataExplorerSettings = requireNonNull(dataExplorerSettings); this.userPermissionEvaluator = requireNonNull(userPermissionEvaluator); } DataExplorerServiceImpl(
DataExplorerSettings dataExplorerSettings, UserPermissionEvaluator userPermissionEvaluator); @Override List<Module> getModules(EntityType entityType); }### Answer:
@Test void testDataExplorerServiceImpl() { assertThrows(NullPointerException.class, () -> new DataExplorerServiceImpl(null, null)); }
|
### Question:
DataExplorerServiceImpl implements DataExplorerService { @Override public List<Module> getModules(EntityType entityType) { List<Module> modules = new ArrayList<>(); for (Module module : Module.values()) { boolean includeModule; switch (module) { case DATA: includeModule = includeDataModule(entityType); break; case AGGREGATION: includeModule = includeAggregationModule(entityType); break; case REPORT: includeModule = includeReportModule(entityType); break; default: throw new UnexpectedEnumException(module); } if (includeModule) { modules.add(module); } } return modules; } DataExplorerServiceImpl(
DataExplorerSettings dataExplorerSettings, UserPermissionEvaluator userPermissionEvaluator); @Override List<Module> getModules(EntityType entityType); }### Answer:
@Test void testGetModulesData() { EntityType entityType = getMockEntityType(); when(dataExplorerSettings.getModData()).thenReturn(true); when(userPermissionEvaluator.hasPermission( new EntityTypeIdentity(entityType), EntityTypePermission.READ_DATA)) .thenReturn(true); assertEquals(singletonList(DATA), dataExplorerServiceImpl.getModules(entityType)); }
@Test void testGetModulesAggregation() { EntityType entityType = getMockEntityType(); when(dataExplorerSettings.getModAggregates()).thenReturn(true); when(userPermissionEvaluator.hasPermission( new EntityTypeIdentity(entityType), EntityTypePermission.AGGREGATE_DATA)) .thenReturn(true); assertEquals(singletonList(AGGREGATION), dataExplorerServiceImpl.getModules(entityType)); }
@Test void testGetModulesReport() { EntityType entityType = getMockEntityType(); when(dataExplorerSettings.getModReports()).thenReturn(true); when(userPermissionEvaluator.hasPermission( new EntityTypeIdentity(entityType), EntityTypeReportPermission.VIEW_REPORT)) .thenReturn(true); when(dataExplorerSettings.getEntityReport("MyEntityType")).thenReturn("MyEntityReport"); assertEquals(singletonList(REPORT), dataExplorerServiceImpl.getModules(entityType)); }
|
### Question:
EntityReportPermissionChecker implements PermissionChecker<FreemarkerTemplate> { EntityReportPermissionChecker(UserPermissionEvaluator permissionEvaluator) { this.permissionEvaluator = requireNonNull(permissionEvaluator); } EntityReportPermissionChecker(UserPermissionEvaluator permissionEvaluator); @Override boolean isAddAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isCountAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isReadAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isUpdateAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isDeleteAllowed(FreemarkerTemplate freemarkerTemplate); }### Answer:
@Test void testEntityReportPermissionChecker() { assertThrows(NullPointerException.class, () -> new EntityReportPermissionChecker(null)); }
|
### Question:
EntityReportPermissionChecker implements PermissionChecker<FreemarkerTemplate> { @Override public boolean isAddAllowed(FreemarkerTemplate freemarkerTemplate) { return hasEntityTypeReportPermission(freemarkerTemplate, MANAGE_REPORT); } EntityReportPermissionChecker(UserPermissionEvaluator permissionEvaluator); @Override boolean isAddAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isCountAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isReadAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isUpdateAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isDeleteAllowed(FreemarkerTemplate freemarkerTemplate); }### Answer:
@Test void testIsAddAllowedTrue() { FreemarkerTemplate freemarkerTemplate = mock(FreemarkerTemplate.class); when(freemarkerTemplate.getName()).thenReturn("view-entityreport-specific-MyEntityType.ftl"); when(permissionEvaluator.hasPermission( new EntityTypeIdentity("MyEntityType"), EntityTypeReportPermission.MANAGE_REPORT)) .thenReturn(true); assertTrue(entityReportPermissionChecker.isAddAllowed(freemarkerTemplate)); }
@Test void testIsAddAllowedFalse() { FreemarkerTemplate freemarkerTemplate = mock(FreemarkerTemplate.class); when(freemarkerTemplate.getName()).thenReturn("view-entityreport-specific-MyEntityType.ftl"); assertFalse(entityReportPermissionChecker.isAddAllowed(freemarkerTemplate)); }
@Test void testIsAddNotAnEntityReport() { FreemarkerTemplate freemarkerTemplate = mock(FreemarkerTemplate.class); when(freemarkerTemplate.getName()).thenReturn("not-an-entity-report.ftl"); assertTrue(entityReportPermissionChecker.isAddAllowed(freemarkerTemplate)); }
|
### Question:
EntityReportPermissionChecker implements PermissionChecker<FreemarkerTemplate> { @Override public boolean isCountAllowed(FreemarkerTemplate freemarkerTemplate) { return isReadAllowed(freemarkerTemplate); } EntityReportPermissionChecker(UserPermissionEvaluator permissionEvaluator); @Override boolean isAddAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isCountAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isReadAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isUpdateAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isDeleteAllowed(FreemarkerTemplate freemarkerTemplate); }### Answer:
@Test void testIsCountAllowedTrue() { FreemarkerTemplate freemarkerTemplate = mock(FreemarkerTemplate.class); when(freemarkerTemplate.getName()).thenReturn("view-entityreport-specific-MyEntityType.ftl"); when(permissionEvaluator.hasPermission( new EntityTypeIdentity("MyEntityType"), EntityTypeReportPermission.VIEW_REPORT)) .thenReturn(true); assertTrue(entityReportPermissionChecker.isCountAllowed(freemarkerTemplate)); }
@Test void testIsCountAllowedFalse() { FreemarkerTemplate freemarkerTemplate = mock(FreemarkerTemplate.class); when(freemarkerTemplate.getName()).thenReturn("view-entityreport-specific-MyEntityType.ftl"); assertFalse(entityReportPermissionChecker.isCountAllowed(freemarkerTemplate)); }
@Test void testIsCountAllowedNotAnEntityReport() { FreemarkerTemplate freemarkerTemplate = mock(FreemarkerTemplate.class); when(freemarkerTemplate.getName()).thenReturn("not-an-entity-report.ftl"); assertTrue(entityReportPermissionChecker.isCountAllowed(freemarkerTemplate)); }
|
### Question:
EntityReportPermissionChecker implements PermissionChecker<FreemarkerTemplate> { @Override public boolean isReadAllowed(FreemarkerTemplate freemarkerTemplate) { return hasEntityTypeReportPermission(freemarkerTemplate, VIEW_REPORT); } EntityReportPermissionChecker(UserPermissionEvaluator permissionEvaluator); @Override boolean isAddAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isCountAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isReadAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isUpdateAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isDeleteAllowed(FreemarkerTemplate freemarkerTemplate); }### Answer:
@Test void testIsReadAllowedTrue() { FreemarkerTemplate freemarkerTemplate = mock(FreemarkerTemplate.class); when(freemarkerTemplate.getName()).thenReturn("view-entityreport-specific-MyEntityType.ftl"); when(permissionEvaluator.hasPermission( new EntityTypeIdentity("MyEntityType"), EntityTypeReportPermission.VIEW_REPORT)) .thenReturn(true); assertTrue(entityReportPermissionChecker.isReadAllowed(freemarkerTemplate)); }
@Test void testIsReadAllowedFalse() { FreemarkerTemplate freemarkerTemplate = mock(FreemarkerTemplate.class); when(freemarkerTemplate.getName()).thenReturn("view-entityreport-specific-MyEntityType.ftl"); assertFalse(entityReportPermissionChecker.isReadAllowed(freemarkerTemplate)); }
@Test void testIsReadAllowedotAnEntityReport() { FreemarkerTemplate freemarkerTemplate = mock(FreemarkerTemplate.class); when(freemarkerTemplate.getName()).thenReturn("not-an-entity-report.ftl"); assertTrue(entityReportPermissionChecker.isReadAllowed(freemarkerTemplate)); }
|
### Question:
EntityReportPermissionChecker implements PermissionChecker<FreemarkerTemplate> { @Override public boolean isUpdateAllowed(FreemarkerTemplate freemarkerTemplate) { return hasEntityTypeReportPermission(freemarkerTemplate, MANAGE_REPORT); } EntityReportPermissionChecker(UserPermissionEvaluator permissionEvaluator); @Override boolean isAddAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isCountAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isReadAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isUpdateAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isDeleteAllowed(FreemarkerTemplate freemarkerTemplate); }### Answer:
@Test void testIsUpdateAllowedTrue() { FreemarkerTemplate freemarkerTemplate = mock(FreemarkerTemplate.class); when(freemarkerTemplate.getName()).thenReturn("view-entityreport-specific-MyEntityType.ftl"); when(permissionEvaluator.hasPermission( new EntityTypeIdentity("MyEntityType"), EntityTypeReportPermission.MANAGE_REPORT)) .thenReturn(true); assertTrue(entityReportPermissionChecker.isUpdateAllowed(freemarkerTemplate)); }
@Test void testIsUpdateAllowedFalse() { FreemarkerTemplate freemarkerTemplate = mock(FreemarkerTemplate.class); when(freemarkerTemplate.getName()).thenReturn("view-entityreport-specific-MyEntityType.ftl"); assertFalse(entityReportPermissionChecker.isUpdateAllowed(freemarkerTemplate)); }
@Test void testIsUpdateAllowedotAnEntityReport() { FreemarkerTemplate freemarkerTemplate = mock(FreemarkerTemplate.class); when(freemarkerTemplate.getName()).thenReturn("not-an-entity-report.ftl"); assertTrue(entityReportPermissionChecker.isUpdateAllowed(freemarkerTemplate)); }
|
### Question:
EntityReportPermissionChecker implements PermissionChecker<FreemarkerTemplate> { @Override public boolean isDeleteAllowed(FreemarkerTemplate freemarkerTemplate) { return hasEntityTypeReportPermission(freemarkerTemplate, MANAGE_REPORT); } EntityReportPermissionChecker(UserPermissionEvaluator permissionEvaluator); @Override boolean isAddAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isCountAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isReadAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isUpdateAllowed(FreemarkerTemplate freemarkerTemplate); @Override boolean isDeleteAllowed(FreemarkerTemplate freemarkerTemplate); }### Answer:
@Test void testIsDeleteAllowedTrue() { FreemarkerTemplate freemarkerTemplate = mock(FreemarkerTemplate.class); when(freemarkerTemplate.getName()).thenReturn("view-entityreport-specific-MyEntityType.ftl"); when(permissionEvaluator.hasPermission( new EntityTypeIdentity("MyEntityType"), EntityTypeReportPermission.MANAGE_REPORT)) .thenReturn(true); assertTrue(entityReportPermissionChecker.isDeleteAllowed(freemarkerTemplate)); }
@Test void testIsDeleteAllowedFalse() { FreemarkerTemplate freemarkerTemplate = mock(FreemarkerTemplate.class); when(freemarkerTemplate.getName()).thenReturn("view-entityreport-specific-MyEntityType.ftl"); assertFalse(entityReportPermissionChecker.isDeleteAllowed(freemarkerTemplate)); }
@Test void testIsDeleteAllowedotAnEntityReport() { FreemarkerTemplate freemarkerTemplate = mock(FreemarkerTemplate.class); when(freemarkerTemplate.getName()).thenReturn("not-an-entity-report.ftl"); assertTrue(entityReportPermissionChecker.isDeleteAllowed(freemarkerTemplate)); }
|
### Question:
SpringExceptionHandler { @ExceptionHandler(HttpMediaTypeNotAcceptableException.class) public final Object handleSpringNotAcceptableException(Exception e, HandlerMethod handlerMethod) { return logAndHandleException(e, NOT_ACCEPTABLE, handlerMethod); } @ExceptionHandler(HttpRequestMethodNotSupportedException.class) final Object handleSpringMethodNotAllowedException(
Exception e, HttpServletRequest request); @ExceptionHandler(NoHandlerFoundException.class) final Object handleSpringNotFoundException(Exception e, HttpServletRequest request); @ExceptionHandler(MaxUploadSizeExceededException.class) final Object handleSpringPayloadTooLargeException(
Exception e, HttpServletRequest request); @ExceptionHandler(HttpMediaTypeNotSupportedException.class) final Object handleSpringUnsupportedMediaTypeException(
Exception e, HandlerMethod handlerMethod); @ExceptionHandler(HttpMediaTypeNotAcceptableException.class) final Object handleSpringNotAcceptableException(Exception e, HandlerMethod handlerMethod); @ExceptionHandler({ MissingServletRequestParameterException.class, ServletRequestBindingException.class, TypeMismatchException.class, HttpMessageNotReadableException.class, MethodArgumentNotValidException.class, MissingServletRequestPartException.class, BindException.class, ConstraintViolationException.class }) final Object handleSpringBadRequestException(Exception e, HandlerMethod handlerMethod); @ExceptionHandler(AsyncRequestTimeoutException.class) final Object handleSpringServiceUnavailableException(
Exception e, HandlerMethod handlerMethod); }### Answer:
@Test void testHandleSpringNotAcceptableException() { Exception e = mock(Exception.class); HandlerMethod method = mock(HandlerMethod.class); springExceptionHandler.handleSpringNotAcceptableException(e, method); verify(springExceptionHandler).logAndHandleException(e, NOT_ACCEPTABLE, method); }
|
### Question:
PluginController { public String getId() { return uri.substring(PLUGIN_URI_PREFIX.length()); } PluginController(String uri); String getUri(); String getId(); @SuppressWarnings("WeakerAccess") Entity getPluginSettings(); static final String PLUGIN_URI_PREFIX; }### Answer:
@Test void getId() { String uri = PluginController.PLUGIN_URI_PREFIX + "test"; PluginController molgenisPlugin = new PluginController(uri) {}; assertEquals("test", molgenisPlugin.getId()); }
|
### Question:
NegotiatorController extends PluginController { @RunAsSystem public boolean showDirectoryButton(String entityTypeId) { Optional<NegotiatorEntityConfig> settings = getNegotiatorEntityConfig(entityTypeId); return settings.isPresent() && permissions.hasPermission(new PluginIdentity(ID), PluginPermission.VIEW_PLUGIN); } NegotiatorController(
RestTemplate restTemplate,
UserPermissionEvaluator permissions,
DataService dataService,
QueryRsqlConverter rsqlQueryConverter,
JsMagmaScriptEvaluator jsMagmaScriptEvaluator,
MessageSource messageSource); @RunAsSystem boolean showDirectoryButton(String entityTypeId); @PostMapping("/validate") @ResponseBody ExportValidationResponse validateNegotiatorExport(@RequestBody NegotiatorRequest request); @PostMapping("/export") @ResponseBody String exportToNegotiator(@RequestBody NegotiatorRequest request); @ExceptionHandler(RuntimeException.class) @ResponseBody @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) ErrorMessageResponse handleRuntimeException(RuntimeException e); static final String ID; }### Answer:
@Test void testShowButtonNoPermissionsOnPlugin() { when(permissionService.hasPermission( new PluginIdentity("directory"), PluginPermission.VIEW_PLUGIN)) .thenReturn(false); assertFalse(negotiatorController.showDirectoryButton("molgenis_id_1")); }
@Test void testShowButton() { when(permissionService.hasPermission( new PluginIdentity("directory"), PluginPermission.VIEW_PLUGIN)) .thenReturn(true); assertTrue(negotiatorController.showDirectoryButton("molgenis_id_1")); }
@Test void testShowButtonPermissionsOnPluginNoConfig() { when(permissionService.hasPermission( new PluginIdentity("directory"), PluginPermission.VIEW_PLUGIN)) .thenReturn(false); assertFalse(negotiatorController.showDirectoryButton("blah2")); }
|
### Question:
VcfImporterService implements ImportService { @Override public boolean canImport(File file, RepositoryCollection source) { for (String extension : getSupportedFileExtensions()) { if (file.getName().toLowerCase().endsWith(extension)) { return true; } } return false; } VcfImporterService(
DataService dataService,
PermissionSystemService permissionSystemService,
MetaDataService metaDataService); @Transactional @Override EntityImportReport doImport(
RepositoryCollection source,
MetadataAction metadataAction,
DataAction dataAction,
@Nullable @CheckForNull String packageId); @Override EntitiesValidationReport validateImport(RepositoryCollection source); @Override boolean canImport(File file, RepositoryCollection source); @Override int getOrder(); @Override List<MetadataAction> getSupportedMetadataActions(); @Override List<DataAction> getSupportedDataActions(); @Override boolean getMustChangeEntityName(); @Override Set<String> getSupportedFileExtensions(); @Override Map<String, Boolean> determineImportableEntities(
MetaDataService metaDataService,
RepositoryCollection repositoryCollection,
String defaultPackage); @Override MetadataAction getMetadataAction(RepositoryCollection source); }### Answer:
@Test void canImportVcf() { RepositoryCollection source = mock(RepositoryCollection.class); assertTrue(vcfImporterService.canImport(new File("file.vcf"), source)); }
@Test void canImportVcfGz() { RepositoryCollection source = mock(RepositoryCollection.class); assertTrue(vcfImporterService.canImport(new File("file.vcf.gz"), source)); }
@Test void canImportXls() { RepositoryCollection source = mock(RepositoryCollection.class); assertFalse(vcfImporterService.canImport(new File("file.xls"), source)); }
|
### Question:
VcfImporterService implements ImportService { @Override public MetadataAction getMetadataAction(RepositoryCollection source) { return MetadataAction.ADD; } VcfImporterService(
DataService dataService,
PermissionSystemService permissionSystemService,
MetaDataService metaDataService); @Transactional @Override EntityImportReport doImport(
RepositoryCollection source,
MetadataAction metadataAction,
DataAction dataAction,
@Nullable @CheckForNull String packageId); @Override EntitiesValidationReport validateImport(RepositoryCollection source); @Override boolean canImport(File file, RepositoryCollection source); @Override int getOrder(); @Override List<MetadataAction> getSupportedMetadataActions(); @Override List<DataAction> getSupportedDataActions(); @Override boolean getMustChangeEntityName(); @Override Set<String> getSupportedFileExtensions(); @Override Map<String, Boolean> determineImportableEntities(
MetaDataService metaDataService,
RepositoryCollection repositoryCollection,
String defaultPackage); @Override MetadataAction getMetadataAction(RepositoryCollection source); }### Answer:
@Test void getMetadataAction() { RepositoryCollection source = mock(RepositoryCollection.class); assertEquals(ADD, vcfImporterService.getMetadataAction(source)); }
|
### Question:
AttributeRepositoryDecorator extends AbstractRepositoryDecorator<Attribute> { @Override public void update(Attribute attr) { updateBackend(attr); delegate().update(attr); } AttributeRepositoryDecorator(
Repository<Attribute> delegateRepository, DataService dataService); @Override void update(Attribute attr); @Override void update(Stream<Attribute> attrs); }### Answer:
@Test void updateNonSystemAbstractEntity() { when(dataService.getMeta()).thenReturn(metadataService); when(metadataService.getConcreteChildren(abstractEntityType)) .thenReturn(Stream.of(concreteEntityType1, concreteEntityType2)); doReturn(backend1).when(metadataService).getBackend(concreteEntityType1); doReturn(backend2).when(metadataService).getBackend(concreteEntityType2); String attributeId = "SDFSADFSDAF"; when(attribute.getIdentifier()).thenReturn(attributeId); Attribute currentAttribute = mock(Attribute.class); when(delegateRepository.findOneById(attributeId)).thenReturn(currentAttribute); when(currentAttribute.getEntity()).thenReturn(abstractEntityType); repo.update(attribute); verify(delegateRepository).update(attribute); verify(backend1).updateAttribute(concreteEntityType1, currentAttribute, attribute); verify(backend2).updateAttribute(concreteEntityType2, currentAttribute, attribute); }
|
### Question:
MetadataManagerController extends PluginController { @GetMapping("/**") public String init(Model model) { model.addAttribute(KEY_BASE_URL, menuReaderService.findMenuItemPath(METADATA_MANAGER)); return "view-metadata-manager"; } MetadataManagerController(
MenuReaderService menuReaderService, MetadataManagerService metadataManagerService); @GetMapping("/**") String init(Model model); @ResponseBody @GetMapping(value = "/editorPackages", produces = "application/json") List<EditorPackageIdentifier> getEditorPackages(); @ResponseBody @GetMapping(value = "/entityType/{id:.*}", produces = "application/json") EditorEntityTypeResponse getEditorEntityType(@PathVariable("id") String id); @ResponseBody @GetMapping(value = "/create/entityType", produces = "application/json") EditorEntityTypeResponse createEditorEntityType(); @ResponseStatus(OK) @PostMapping(value = "/entityType", consumes = "application/json") void upsertEntityType(@RequestBody EditorEntityType editorEntityType); @ResponseBody @GetMapping(value = "/create/attribute", produces = "application/json") EditorAttributeResponse createEditorAttribute(); static final String METADATA_MANAGER; static final String URI; }### Answer:
@Test void testInit() throws Exception { when(localeResolver.resolveLocale(any())).thenReturn(Locale.GERMAN); mockMvc .perform(get("/plugin/metadata-manager")) .andExpect(status().isOk()) .andExpect(view().name("view-metadata-manager")) .andExpect(model().attribute("baseUrl", "/test/path")); }
|
### Question:
MetadataManagerController extends PluginController { @ResponseBody @GetMapping(value = "/editorPackages", produces = "application/json") public List<EditorPackageIdentifier> getEditorPackages() { return metadataManagerService.getEditorPackages(); } MetadataManagerController(
MenuReaderService menuReaderService, MetadataManagerService metadataManagerService); @GetMapping("/**") String init(Model model); @ResponseBody @GetMapping(value = "/editorPackages", produces = "application/json") List<EditorPackageIdentifier> getEditorPackages(); @ResponseBody @GetMapping(value = "/entityType/{id:.*}", produces = "application/json") EditorEntityTypeResponse getEditorEntityType(@PathVariable("id") String id); @ResponseBody @GetMapping(value = "/create/entityType", produces = "application/json") EditorEntityTypeResponse createEditorEntityType(); @ResponseStatus(OK) @PostMapping(value = "/entityType", consumes = "application/json") void upsertEntityType(@RequestBody EditorEntityType editorEntityType); @ResponseBody @GetMapping(value = "/create/attribute", produces = "application/json") EditorAttributeResponse createEditorAttribute(); static final String METADATA_MANAGER; static final String URI; }### Answer:
@Test void testGetEditorPackages() throws Exception { when(metadataManagerService.getEditorPackages()).thenReturn(getEditorPackageResponse()); mockMvc .perform(get("/plugin/metadata-manager/editorPackages")) .andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON_UTF8)) .andExpect(content().string(getEditorPackageResponseJson())); }
|
### Question:
MetadataManagerController extends PluginController { @ResponseBody @GetMapping(value = "/entityType/{id:.*}", produces = "application/json") public EditorEntityTypeResponse getEditorEntityType(@PathVariable("id") String id) { return metadataManagerService.getEditorEntityType(id); } MetadataManagerController(
MenuReaderService menuReaderService, MetadataManagerService metadataManagerService); @GetMapping("/**") String init(Model model); @ResponseBody @GetMapping(value = "/editorPackages", produces = "application/json") List<EditorPackageIdentifier> getEditorPackages(); @ResponseBody @GetMapping(value = "/entityType/{id:.*}", produces = "application/json") EditorEntityTypeResponse getEditorEntityType(@PathVariable("id") String id); @ResponseBody @GetMapping(value = "/create/entityType", produces = "application/json") EditorEntityTypeResponse createEditorEntityType(); @ResponseStatus(OK) @PostMapping(value = "/entityType", consumes = "application/json") void upsertEntityType(@RequestBody EditorEntityType editorEntityType); @ResponseBody @GetMapping(value = "/create/attribute", produces = "application/json") EditorAttributeResponse createEditorAttribute(); static final String METADATA_MANAGER; static final String URI; }### Answer:
@Test void testGetEditorEntityType() throws Exception { when(metadataManagerService.getEditorEntityType("id_1")) .thenReturn(getEditorEntityTypeResponse()); mockMvc .perform(get("/plugin/metadata-manager/entityType/{id}", "id_1")) .andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON_UTF8)) .andExpect(content().string(getEditorEntityTypeResponseJson())); }
|
### Question:
MetadataManagerController extends PluginController { @ResponseBody @GetMapping(value = "/create/entityType", produces = "application/json") public EditorEntityTypeResponse createEditorEntityType() { return metadataManagerService.createEditorEntityType(); } MetadataManagerController(
MenuReaderService menuReaderService, MetadataManagerService metadataManagerService); @GetMapping("/**") String init(Model model); @ResponseBody @GetMapping(value = "/editorPackages", produces = "application/json") List<EditorPackageIdentifier> getEditorPackages(); @ResponseBody @GetMapping(value = "/entityType/{id:.*}", produces = "application/json") EditorEntityTypeResponse getEditorEntityType(@PathVariable("id") String id); @ResponseBody @GetMapping(value = "/create/entityType", produces = "application/json") EditorEntityTypeResponse createEditorEntityType(); @ResponseStatus(OK) @PostMapping(value = "/entityType", consumes = "application/json") void upsertEntityType(@RequestBody EditorEntityType editorEntityType); @ResponseBody @GetMapping(value = "/create/attribute", produces = "application/json") EditorAttributeResponse createEditorAttribute(); static final String METADATA_MANAGER; static final String URI; }### Answer:
@Test void testCreateEditorEntityType() throws Exception { EditorEntityTypeResponse editorEntityTypeResponse = getEditorEntityTypeResponse(); when(metadataManagerService.createEditorEntityType()).thenReturn(editorEntityTypeResponse); mockMvc .perform(get("/plugin/metadata-manager/create/entityType")) .andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON_UTF8)) .andExpect(content().string(getEditorEntityTypeResponseJson())); }
|
### Question:
MetadataManagerController extends PluginController { @ResponseStatus(OK) @PostMapping(value = "/entityType", consumes = "application/json") public void upsertEntityType(@RequestBody EditorEntityType editorEntityType) { metadataManagerService.upsertEntityType(editorEntityType); } MetadataManagerController(
MenuReaderService menuReaderService, MetadataManagerService metadataManagerService); @GetMapping("/**") String init(Model model); @ResponseBody @GetMapping(value = "/editorPackages", produces = "application/json") List<EditorPackageIdentifier> getEditorPackages(); @ResponseBody @GetMapping(value = "/entityType/{id:.*}", produces = "application/json") EditorEntityTypeResponse getEditorEntityType(@PathVariable("id") String id); @ResponseBody @GetMapping(value = "/create/entityType", produces = "application/json") EditorEntityTypeResponse createEditorEntityType(); @ResponseStatus(OK) @PostMapping(value = "/entityType", consumes = "application/json") void upsertEntityType(@RequestBody EditorEntityType editorEntityType); @ResponseBody @GetMapping(value = "/create/attribute", produces = "application/json") EditorAttributeResponse createEditorAttribute(); static final String METADATA_MANAGER; static final String URI; }### Answer:
@Test void testUpsertEntityType() throws Exception { mockMvc .perform( post("/plugin/metadata-manager/entityType") .contentType(APPLICATION_JSON_UTF8) .content(getEditorEntityTypeJson())) .andExpect(status().isOk()); verify(metadataManagerService, times(1)).upsertEntityType(getEditorEntityType()); }
|
### Question:
MetadataManagerController extends PluginController { @ResponseBody @GetMapping(value = "/create/attribute", produces = "application/json") public EditorAttributeResponse createEditorAttribute() { return metadataManagerService.createEditorAttribute(); } MetadataManagerController(
MenuReaderService menuReaderService, MetadataManagerService metadataManagerService); @GetMapping("/**") String init(Model model); @ResponseBody @GetMapping(value = "/editorPackages", produces = "application/json") List<EditorPackageIdentifier> getEditorPackages(); @ResponseBody @GetMapping(value = "/entityType/{id:.*}", produces = "application/json") EditorEntityTypeResponse getEditorEntityType(@PathVariable("id") String id); @ResponseBody @GetMapping(value = "/create/entityType", produces = "application/json") EditorEntityTypeResponse createEditorEntityType(); @ResponseStatus(OK) @PostMapping(value = "/entityType", consumes = "application/json") void upsertEntityType(@RequestBody EditorEntityType editorEntityType); @ResponseBody @GetMapping(value = "/create/attribute", produces = "application/json") EditorAttributeResponse createEditorAttribute(); static final String METADATA_MANAGER; static final String URI; }### Answer:
@Test void testCreateEditorAttribute() throws Exception { when(metadataManagerService.createEditorAttribute()).thenReturn(getEditorAttributeResponse()); mockMvc .perform(get("/plugin/metadata-manager/create/attribute")) .andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON_UTF8)) .andExpect(content().string(getEditorAttributeResponseJson())); }
|
### Question:
EntityTypeParentMapper { public EntityTypeParentMapper( AttributeReferenceMapper attributeReferenceMapper, EntityTypeMetadata entityTypeMetadata, DataService dataService) { this.attributeReferenceMapper = requireNonNull(attributeReferenceMapper); this.entityTypeMetadata = requireNonNull(entityTypeMetadata); this.dataService = requireNonNull(dataService); } EntityTypeParentMapper(
AttributeReferenceMapper attributeReferenceMapper,
EntityTypeMetadata entityTypeMetadata,
DataService dataService); }### Answer:
@Test void testEntityTypeParentMapper() { assertThrows(NullPointerException.class, () -> new EntityTypeParentMapper(null, null, null)); }
|
### Question:
EntityTypeParentMapper { EntityType toEntityTypeReference(EditorEntityTypeParent editorEntityTypeParent) { if (editorEntityTypeParent == null) { return null; } return new EntityType( new LazyEntity(entityTypeMetadata, dataService, editorEntityTypeParent.getId())); } EntityTypeParentMapper(
AttributeReferenceMapper attributeReferenceMapper,
EntityTypeMetadata entityTypeMetadata,
DataService dataService); }### Answer:
@Test void testToEntityTypeReference() { String id = "id"; String label = "label"; @SuppressWarnings("unchecked") List<EditorAttributeIdentifier> attributes = mock(List.class); EditorEntityTypeParent parent = mock(EditorEntityTypeParent.class); EditorEntityTypeParent editorEntityTypeParent = EditorEntityTypeParent.create(id, label, attributes, parent); EntityType entityType = entityTypeParentMapper.toEntityTypeReference(editorEntityTypeParent); assertEquals(id, entityType.getIdValue()); }
@Test void testToEntityTypeReferenceNull() { assertNull(entityTypeParentMapper.toEntityTypeReference(null)); }
|
### Question:
TagMapper { TagMapper(TagFactory tagFactory, DataService dataService) { this.tagFactory = requireNonNull(tagFactory); this.dataService = requireNonNull(dataService); } TagMapper(TagFactory tagFactory, DataService dataService); }### Answer:
@Test void testTagMapper() { assertThrows(NullPointerException.class, () -> new TagMapper(null, null)); }
|
### Question:
TagMapper { Iterable<Tag> toTagReferences(List<EditorTagIdentifier> tags) { return tags.stream().map(this::toTagReference).collect(toList()); } TagMapper(TagFactory tagFactory, DataService dataService); }### Answer:
@Test void testToTagReferences() { String id0 = "id0"; String id1 = "id1"; EditorTagIdentifier tagIdentifier0 = EditorTagIdentifier.create(id0, "label0"); EditorTagIdentifier tagIdentifier1 = EditorTagIdentifier.create(id1, "label1"); List<Tag> tags = copyOf(tagMapper.toTagReferences(of(tagIdentifier0, tagIdentifier1))); assertEquals(2, tags.size()); assertEquals(id0, tags.get(0).getIdValue()); assertEquals(id1, tags.get(1).getIdValue()); }
|
### Question:
TagMapper { ImmutableList<EditorTagIdentifier> toEditorTags(Iterable<Tag> tags) { return ImmutableList.copyOf(stream(tags).map(this::toEditorTag).iterator()); } TagMapper(TagFactory tagFactory, DataService dataService); }### Answer:
@Test void testToEditorTags() { String id0 = "id0"; String label0 = "label0"; String id1 = "id1"; String label1 = "label1"; Tag tag0 = mock(Tag.class); when(tag0.getId()).thenReturn(id0); when(tag0.getLabel()).thenReturn(label0); Tag tag1 = mock(Tag.class); when(tag1.getId()).thenReturn(id1); when(tag1.getLabel()).thenReturn(label1); List<EditorTagIdentifier> editorTags = tagMapper.toEditorTags(of(tag0, tag1)); assertEquals(of(create(id0, label0), create(id1, label1)), editorTags); }
|
### Question:
AttributeMapper { AttributeMapper( AttributeFactory attributeFactory, TagMapper tagMapper, EntityTypeReferenceMapper entityTypeReferenceMapper, AttributeReferenceMapper attributeReferenceMapper, SortMapper sortMapper) { this.attributeFactory = requireNonNull(attributeFactory); this.tagMapper = requireNonNull(tagMapper); this.entityTypeReferenceMapper = requireNonNull(entityTypeReferenceMapper); this.attributeReferenceMapper = requireNonNull(attributeReferenceMapper); this.sortMapper = requireNonNull(sortMapper); } AttributeMapper(
AttributeFactory attributeFactory,
TagMapper tagMapper,
EntityTypeReferenceMapper entityTypeReferenceMapper,
AttributeReferenceMapper attributeReferenceMapper,
SortMapper sortMapper); EditorAttribute createEditorAttribute(); }### Answer:
@Test void testAttributeMapper() { assertThrows( NullPointerException.class, () -> new AttributeMapper(null, null, null, null, null)); }
|
### Question:
AttributeMapper { public EditorAttribute createEditorAttribute() { Attribute attribute = attributeFactory.create(); return toEditorAttribute(attribute); } AttributeMapper(
AttributeFactory attributeFactory,
TagMapper tagMapper,
EntityTypeReferenceMapper entityTypeReferenceMapper,
AttributeReferenceMapper attributeReferenceMapper,
SortMapper sortMapper); EditorAttribute createEditorAttribute(); }### Answer:
@Test void testCreateEditorAttribute() { String id = "id"; Integer sequenceNumber = 0; Attribute attribute = mock(Attribute.class); when(attribute.getIdentifier()).thenReturn(id); when(attribute.getRangeMin()).thenReturn(null); when(attribute.getRangeMax()).thenReturn(null); when(attribute.getDataType()).thenReturn(AttributeType.STRING); @SuppressWarnings("unchecked") Iterable<Tag> tags = mock(Iterable.class); when(attribute.getTags()).thenReturn(tags); when(attributeFactory.create()).thenReturn(attribute); @SuppressWarnings("unchecked") ImmutableList<EditorTagIdentifier> editorTags = mock(ImmutableList.class); when(tagMapper.toEditorTags(tags)).thenReturn(editorTags); EditorAttribute editorAttribute = attributeMapper.createEditorAttribute(); assertEquals( create( id, null, "string", null, null, false, null, null, null, false, false, false, null, ImmutableMap.of(), null, ImmutableMap.of(), false, of(), null, null, false, false, editorTags, null, null, null, null, sequenceNumber), editorAttribute); }
|
### Question:
SortMapper { Sort toSort(EditorSort editorSort) { if (editorSort == null) { return null; } List<Sort.Order> orders = editorSort.getOrders().stream().map(this::toOrder).collect(toList()); return new Sort(orders); } }### Answer:
@Test void testToSort() { String attributeName = "attr"; String direction = Sort.Direction.DESC.name(); EditorSort editorSort = EditorSort.create(of(EditorOrder.create(attributeName, direction))); Sort sort = sortMapper.toSort(editorSort); Iterator<Sort.Order> iterator = sort.iterator(); assertTrue(iterator.hasNext()); Sort.Order order = iterator.next(); assertEquals(attributeName, order.getAttr()); assertEquals(DESC, order.getDirection()); assertFalse(iterator.hasNext()); }
@Test void testToSortNull() { assertNull(sortMapper.toSort(null)); }
|
### Question:
SortMapper { EditorSort toEditorSort(Sort sort) { if (sort == null) { return null; } return EditorSort.create(toEditorOrders(sort)); } }### Answer:
@Test void testToEditorSort() { String attr = "attr"; Sort sort = new Sort(of(new Sort.Order(attr, Sort.Direction.ASC))); EditorSort editorSort = sortMapper.toEditorSort(sort); assertEquals(create(of(EditorOrder.create(attr, "ASC"))), editorSort); }
@Test void testToEditorSortNull() { assertNull(sortMapper.toEditorSort(null)); }
|
### Question:
AttributeReferenceMapper { AttributeReferenceMapper(AttributeMetadata attributeMetadata, DataService dataService) { this.attributeMetadata = requireNonNull(attributeMetadata); this.dataService = requireNonNull(dataService); } AttributeReferenceMapper(AttributeMetadata attributeMetadata, DataService dataService); }### Answer:
@Test void testAttributeReferenceMapper() { assertThrows(NullPointerException.class, () -> new AttributeReferenceMapper(null, null)); }
|
### Question:
AttributeReferenceMapper { ImmutableList<EditorAttributeIdentifier> toEditorAttributeIdentifiers( Iterable<Attribute> attributes) { return ImmutableList.copyOf( stream(attributes).map(this::toEditorAttributeIdentifier).iterator()); } AttributeReferenceMapper(AttributeMetadata attributeMetadata, DataService dataService); }### Answer:
@Test void testToEditorAttributeIdentifiers() { String id = "id"; String label = "label"; String entityTypeId = "id"; String entityTypeLabel = "label"; Attribute attribute = mock(Attribute.class); EntityType entityType = mock(EntityType.class); when(attribute.getIdentifier()).thenReturn(id); when(attribute.getLabel()).thenReturn(label); when(attribute.getEntity()).thenReturn(entityType); when(entityType.getId()).thenReturn(entityTypeId); when(entityType.getLabel()).thenReturn(entityTypeLabel); ImmutableList<EditorAttributeIdentifier> editorAttributeIdentifier = attributeReferenceMapper.toEditorAttributeIdentifiers(of(attribute)); EditorEntityTypeIdentifier editorEntityTypeIdentifier = EditorEntityTypeIdentifier.create(entityTypeId, entityTypeLabel); assertEquals(of(create(id, label, editorEntityTypeIdentifier)), editorAttributeIdentifier); }
|
### Question:
AttributeReferenceMapper { EditorAttributeIdentifier toEditorAttributeIdentifier(Attribute attribute) { if (attribute == null) { return null; } return EditorAttributeIdentifier.create( attribute.getIdentifier(), attribute.getLabel(), EditorEntityTypeIdentifier.create( attribute.getEntity().getId(), attribute.getEntity().getLabel())); } AttributeReferenceMapper(AttributeMetadata attributeMetadata, DataService dataService); }### Answer:
@Test void testToEditorAttributeIdentifier() { String id = "id"; String label = "label"; String entityTypeId = "id"; String entityTypeLabel = "label"; Attribute attribute = mock(Attribute.class); EntityType entityType = mock(EntityType.class); when(attribute.getIdentifier()).thenReturn(id); when(attribute.getLabel()).thenReturn(label); when(attribute.getEntity()).thenReturn(entityType); when(entityType.getId()).thenReturn(entityTypeId); when(entityType.getLabel()).thenReturn(entityTypeLabel); EditorAttributeIdentifier editorAttributeIdentifier = attributeReferenceMapper.toEditorAttributeIdentifier(attribute); EditorEntityTypeIdentifier editorEntityTypeIdentifier = EditorEntityTypeIdentifier.create(entityTypeId, entityTypeLabel); assertEquals(create(id, label, editorEntityTypeIdentifier), editorAttributeIdentifier); }
@Test void testToEditorAttributeIdentifierNull() { assertNull(attributeReferenceMapper.toEditorAttributeIdentifier(null)); }
|
### Question:
AttributeReferenceMapper { Attribute toAttributeReference(EditorAttributeIdentifier editorAttributeIdentifier) { if (editorAttributeIdentifier == null) { return null; } return new Attribute( new LazyEntity(attributeMetadata, dataService, editorAttributeIdentifier.getId())); } AttributeReferenceMapper(AttributeMetadata attributeMetadata, DataService dataService); }### Answer:
@Test void testToAttributeReference() { String id = "id"; String label = "label"; EditorAttributeIdentifier editorAttributeIdentifier = EditorAttributeIdentifier.create(id, label); Attribute attribute = attributeReferenceMapper.toAttributeReference(editorAttributeIdentifier); assertEquals(id, attribute.getIdValue()); }
@Test void testToAttributeReferenceNull() { assertNull(attributeReferenceMapper.toAttributeReference(null)); }
|
### Question:
PackageMapper { PackageMapper(PackageFactory packageFactory, DataService dataService) { this.packageFactory = requireNonNull(packageFactory); this.dataService = requireNonNull(dataService); } PackageMapper(PackageFactory packageFactory, DataService dataService); EditorPackageIdentifier toEditorPackage(Package aPackage); }### Answer:
@Test void testPackageMapper() { assertThrows(NullPointerException.class, () -> new PackageMapper(null, null)); }
|
### Question:
PackageMapper { Package toPackageReference(EditorPackageIdentifier editorPackageIdentifier) { if (editorPackageIdentifier == null) { return null; } return new Package( new LazyEntity( packageFactory.getEntityType(), dataService, editorPackageIdentifier.getId())); } PackageMapper(PackageFactory packageFactory, DataService dataService); EditorPackageIdentifier toEditorPackage(Package aPackage); }### Answer:
@Test void testToPackageReference() { String id = "id0"; EditorPackageIdentifier packageIdentifier = EditorPackageIdentifier.create(id, "label"); Package package_ = packageMapper.toPackageReference(packageIdentifier); assertEquals(id, package_.getIdValue()); }
@Test void testToPackageReferenceNull() { assertNull(packageMapper.toPackageReference(null)); }
|
### Question:
PackageMapper { public EditorPackageIdentifier toEditorPackage(Package aPackage) { if (aPackage == null) { return null; } return EditorPackageIdentifier.create(aPackage.getId(), aPackage.getLabel()); } PackageMapper(PackageFactory packageFactory, DataService dataService); EditorPackageIdentifier toEditorPackage(Package aPackage); }### Answer:
@Test void testToEditorPackage() { String id = "id0"; String label = "label0"; Package package_ = mock(Package.class); when(package_.getId()).thenReturn(id); when(package_.getLabel()).thenReturn(label); EditorPackageIdentifier editorPackage = packageMapper.toEditorPackage(package_); assertEquals(create(id, label), editorPackage); }
@Test void testToEditorPackageNull() { assertNull(packageMapper.toEditorPackage(null)); }
|
### Question:
EntityTypeReferenceMapper { EntityType toEntityTypeReference(String entityTypeId) { if (entityTypeId == null) { return null; } return new EntityType(new LazyEntity(entityTypeMetadata, dataService, entityTypeId)); } EntityTypeReferenceMapper(EntityTypeMetadata entityTypeMetadata, DataService dataService); }### Answer:
@Test void testToEntityTypeReference() { String id = "id"; EntityType entityType = entityTypeReferenceMapper.toEntityTypeReference(id); assertEquals(id, entityType.getIdValue()); }
@Test void testToEntityTypeReferenceNull() { assertNull(entityTypeReferenceMapper.toEntityTypeReference(null)); }
|
### Question:
EntityTypeReferenceMapper { ImmutableList<EditorEntityTypeIdentifier> toEditorEntityTypeIdentifiers( Iterable<EntityType> extendedBy) { return ImmutableList.copyOf( stream(extendedBy).map(this::toEditorEntityTypeIdentifier).iterator()); } EntityTypeReferenceMapper(EntityTypeMetadata entityTypeMetadata, DataService dataService); }### Answer:
@Test void testToEditorEntityTypeIdentifiers() { String id = "id"; String label = "label"; EntityType entityType = mock(EntityType.class); when(entityType.getId()).thenReturn(id); when(entityType.getLabel()).thenReturn(label); List<EditorEntityTypeIdentifier> editorEntityTypeIdentifiers = entityTypeReferenceMapper.toEditorEntityTypeIdentifiers(of(entityType)); assertEquals(of(create(id, label)), editorEntityTypeIdentifiers); }
|
### Question:
EntityTypeReferenceMapper { EditorEntityTypeIdentifier toEditorEntityTypeIdentifier(EntityType entityType) { String id = entityType.getId(); String label = entityType.getLabel(); return EditorEntityTypeIdentifier.create(id, label); } EntityTypeReferenceMapper(EntityTypeMetadata entityTypeMetadata, DataService dataService); }### Answer:
@Test void testToEditorEntityTypeIdentifier() { String id = "id"; String label = "label"; EntityType entityType = mock(EntityType.class); when(entityType.getId()).thenReturn(id); when(entityType.getLabel()).thenReturn(label); EditorEntityTypeIdentifier editorEntityTypeIdentifier = entityTypeReferenceMapper.toEditorEntityTypeIdentifier(entityType); assertEquals(create(id, label), editorEntityTypeIdentifier); }
|
### Question:
EntityTypeMapper { EntityTypeMapper( EntityTypeFactory entityTypeFactory, AttributeMapper attributeMapper, AttributeReferenceMapper attributeReferenceMapper, PackageMapper packageMapper, TagMapper tagMapper, EntityTypeParentMapper entityTypeParentMapper) { this.entityTypeFactory = requireNonNull(entityTypeFactory); this.attributeMapper = requireNonNull(attributeMapper); this.attributeReferenceMapper = requireNonNull(attributeReferenceMapper); this.packageMapper = requireNonNull(packageMapper); this.tagMapper = requireNonNull(tagMapper); this.entityTypeParentMapper = requireNonNull(entityTypeParentMapper); } EntityTypeMapper(
EntityTypeFactory entityTypeFactory,
AttributeMapper attributeMapper,
AttributeReferenceMapper attributeReferenceMapper,
PackageMapper packageMapper,
TagMapper tagMapper,
EntityTypeParentMapper entityTypeParentMapper); EditorEntityType toEditorEntityType(
EntityType entityType, List<Attribute> referringAttributes); EditorEntityType createEditorEntityType(); EntityType toEntityType(EditorEntityType editorEntityType); }### Answer:
@Test void testEntityTypeMapper() { assertThrows( NullPointerException.class, () -> new EntityTypeMapper(null, null, null, null, null, null)); }
|
### Question:
RScriptRunner implements ScriptRunner { @Override public boolean hasFileOutput(Script script) { return ScriptUtils.hasScriptVariable(script, PARAM_OUTPUT_FILE); } RScriptRunner(RScriptExecutor rScriptExecutor); @Override String getName(); @Override boolean hasFileOutput(Script script); @Override String runScript(Script script, Map<String, Object> parameters); }### Answer:
@Test void testHasFileOutputTrue() { Script script = when(mock(Script.class).getContent()).thenReturn("lorum ${outputFile} ipsum").getMock(); assertTrue(rScriptRunner.hasFileOutput(script)); }
@Test void testHasFileOutputFalse() { Script script = when(mock(Script.class).getContent()).thenReturn("lorum ${x} ipsum").getMock(); assertFalse(rScriptRunner.hasFileOutput(script)); }
|
### Question:
PostgreSqlQueryUtils { static Stream<Attribute> getJunctionTableAttributes(EntityType entityType) { return getPersistedAttributes(entityType) .filter( attr -> isMultipleReferenceType(attr) && !(attr.getDataType() == ONE_TO_MANY && attr.isMappedBy())); } private PostgreSqlQueryUtils(); }### Answer:
@Test void getJunctionTableAttributes() throws Exception { EntityType entityType = when(mock(EntityType.class).getId()).thenReturn("entity").getMock(); Attribute stringAttr = mock(Attribute.class); when(stringAttr.getDataType()).thenReturn(STRING); Attribute mrefAttr = mock(Attribute.class); when(mrefAttr.getDataType()).thenReturn(MREF); Attribute mrefAttrWithExpression = mock(Attribute.class); when(mrefAttrWithExpression.getDataType()).thenReturn(MREF); when(mrefAttrWithExpression.getExpression()).thenReturn("expression"); Attribute xrefAttr = mock(Attribute.class); when(xrefAttr.getDataType()).thenReturn(XREF); Attribute xrefAttrInversedBy = mock(Attribute.class); when(xrefAttrInversedBy.getDataType()).thenReturn(XREF); when(xrefAttrInversedBy.isInversedBy()).thenReturn(true); Attribute refAttr = mock(Attribute.class); when(refAttr.getDataType()).thenReturn(ONE_TO_MANY); when(xrefAttrInversedBy.getInversedBy()).thenReturn(refAttr); when(entityType.getAtomicAttributes()) .thenReturn( newArrayList( stringAttr, mrefAttr, mrefAttrWithExpression, xrefAttr, xrefAttrInversedBy)); List<Attribute> junctionTableAttrs = newArrayList(mrefAttr); assertEquals( junctionTableAttrs, PostgreSqlQueryUtils.getJunctionTableAttributes(entityType).collect(toList())); }
|
### Question:
PostgreSqlQueryUtils { static Stream<Attribute> getTableAttributes(EntityType entityType) { return getPersistedAttributes(entityType).filter(PostgreSqlQueryUtils::isTableAttribute); } private PostgreSqlQueryUtils(); }### Answer:
@Test void getTableAttributes() throws Exception { EntityType entityType = when(mock(EntityType.class).getId()).thenReturn("entity").getMock(); Attribute stringAttr = mock(Attribute.class); when(stringAttr.getDataType()).thenReturn(STRING); Attribute mrefAttr = mock(Attribute.class); when(mrefAttr.getDataType()).thenReturn(MREF); Attribute mrefAttrWithExpression = mock(Attribute.class); when(mrefAttrWithExpression.getDataType()).thenReturn(MREF); when(mrefAttrWithExpression.getExpression()).thenReturn("expression"); Attribute xrefAttr = mock(Attribute.class); when(xrefAttr.getDataType()).thenReturn(XREF); Attribute xrefAttrInversedBy = mock(Attribute.class); when(xrefAttrInversedBy.getDataType()).thenReturn(XREF); when(xrefAttrInversedBy.isInversedBy()).thenReturn(true); Attribute refAttr = mock(Attribute.class); when(refAttr.getDataType()).thenReturn(ONE_TO_MANY); when(xrefAttrInversedBy.getInversedBy()).thenReturn(refAttr); when(entityType.getAtomicAttributes()) .thenReturn( newArrayList( stringAttr, mrefAttr, mrefAttrWithExpression, xrefAttr, xrefAttrInversedBy)); List<Attribute> junctionTableAttrs = newArrayList(stringAttr, xrefAttr, xrefAttrInversedBy); assertEquals( junctionTableAttrs, PostgreSqlQueryUtils.getTableAttributes(entityType).collect(toList())); }
|
### Question:
PostgreSqlQueryUtils { static boolean isTableAttribute(Attribute attr) { return !isMultipleReferenceType(attr) && !(attr.getDataType() == ONE_TO_MANY && attr.isMappedBy()); } private PostgreSqlQueryUtils(); }### Answer:
@Test void isTableAttributeStringAttr() throws Exception { Attribute attr = when(mock(Attribute.class).getDataType()).thenReturn(STRING).getMock(); assertTrue(PostgreSqlQueryUtils.isTableAttribute(attr)); }
@Test void isTableAttributeMrefAttr() throws Exception { Attribute attr = when(mock(Attribute.class).getDataType()).thenReturn(MREF).getMock(); assertFalse(PostgreSqlQueryUtils.isTableAttribute(attr)); }
|
### Question:
PostgreSqlRepository extends AbstractRepository { @Override public void add(Entity entity) { if (entity == null) { throw new NullPointerException("PostgreSqlRepository.add() failed: entity was null"); } add(Stream.of(entity)); } PostgreSqlRepository(
PostgreSqlEntityFactory postgreSqlEntityFactory,
JdbcTemplate jdbcTemplate,
DataSource dataSource,
EntityType entityType); @Override Iterator<Entity> iterator(); @Override Set<RepositoryCapability> getCapabilities(); @Override Set<Operator> getQueryOperators(); @Override EntityType getEntityType(); @Override long count(Query<Entity> q); @Override Stream<Entity> findAll(Query<Entity> q); @Override Entity findOne(Query<Entity> q); @Override Entity findOneById(Object id); @Override Entity findOneById(Object id, Fetch fetch); @Override void update(Entity entity); @Override void update(Stream<Entity> entities); @Override void delete(Entity entity); @Override void delete(Stream<Entity> entities); @Override void deleteById(Object id); @Override void deleteAll(Stream<Object> ids); @Override void deleteAll(); @Override void add(Entity entity); @Override Integer add(Stream<Entity> entities); @Override void forEachBatched(Fetch fetch, Consumer<List<Entity>> consumer, int batchSize); }### Answer:
@SuppressWarnings("ConstantConditions") @Test void testAddEntityNull() { Entity entity = null; Exception exception = assertThrows(NullPointerException.class, () -> postgreSqlRepo.add(entity)); assertThat(exception.getMessage()) .containsPattern("PostgreSqlRepository.add\\(\\) failed: entity was null"); }
|
### Question:
PostgreSqlEntityFactory { EntityMapper createRowMapper(EntityType entityType, Fetch fetch) { return new EntityMapper(entityManager, entityType, fetch); } PostgreSqlEntityFactory(EntityManager entityManager); }### Answer:
@Test void createRowMapperXref() throws Exception { Attribute refIdAttr = mock(Attribute.class); when(refIdAttr.getDataType()).thenReturn(STRING); EntityType refEntityType = mock(EntityType.class); when(refEntityType.getIdAttribute()).thenReturn(refIdAttr); String xrefAttr = "xrefAttr"; Attribute oneToManyAttr = mock(Attribute.class); when(oneToManyAttr.getName()).thenReturn(xrefAttr); when(oneToManyAttr.getDataType()).thenReturn(XREF); when(oneToManyAttr.getRefEntity()).thenReturn(refEntityType); EntityType entityType = mock(EntityType.class); when(entityType.getAtomicAttributes()).thenReturn(singleton(oneToManyAttr)); ResultSet rs = mock(ResultSet.class); when(rs.getString(xrefAttr)).thenReturn("id0"); int rowNum = 0; Entity entity = mock(Entity.class); when(entityManager.createFetch(entityType, null)).thenReturn(entity); Entity refEntity = mock(Entity.class); when(entityManager.getReference(refEntityType, "id0")).thenReturn(refEntity); assertEquals( entity, postgreSqlEntityFactory.createRowMapper(entityType, null).mapRow(rs, rowNum)); verify(entity).set(xrefAttr, refEntity); }
|
### Question:
PostgreSqlQueryGenerator { static String getSqlSetNotNull(EntityType entityType, Attribute attr) { return "ALTER TABLE " + getTableName(entityType) + " ALTER COLUMN " + getColumnName(attr) + " SET NOT NULL"; } private PostgreSqlQueryGenerator(); }### Answer:
@Test void getSqlSetNotNull() { EntityType entityType = when(mock(EntityType.class).getId()).thenReturn("entity").getMock(); when(entityType.getId()).thenReturn("entityTypeId"); Attribute attr = when(mock(Attribute.class).getName()).thenReturn("attr").getMock(); when(attr.getIdentifier()).thenReturn("attrId"); when(attr.isNillable()).thenReturn(true); assertEquals( "ALTER TABLE \"entityTypeId#c34894ba\" ALTER COLUMN \"attr\" SET NOT NULL", PostgreSqlQueryGenerator.getSqlSetNotNull(entityType, attr)); }
|
### Question:
PostgreSqlQueryGenerator { static String getSqlDropNotNull(EntityType entityType, Attribute attr) { return "ALTER TABLE " + getTableName(entityType) + " ALTER COLUMN " + getColumnName(attr) + " DROP NOT NULL"; } private PostgreSqlQueryGenerator(); }### Answer:
@Test void getSqlDropNotNull() { EntityType entityType = when(mock(EntityType.class).getId()).thenReturn("entity").getMock(); when(entityType.getId()).thenReturn("entityTypeId"); Attribute attr = when(mock(Attribute.class).getName()).thenReturn("attr").getMock(); when(attr.getIdentifier()).thenReturn("attrId"); when(attr.isNillable()).thenReturn(false); assertEquals( "ALTER TABLE \"entityTypeId#c34894ba\" ALTER COLUMN \"attr\" DROP NOT NULL", PostgreSqlQueryGenerator.getSqlDropNotNull(entityType, attr)); }
|
### Question:
PostgreSqlQueryGenerator { static String getSqlSetDataType(EntityType entityType, Attribute attr) { return "ALTER TABLE " + getTableName(entityType) + " ALTER COLUMN " + getColumnName(attr) + " SET DATA TYPE " + getPostgreSqlType(attr) + " USING " + getColumnName(attr) + "::" + getPostgreSqlType(attr); } private PostgreSqlQueryGenerator(); }### Answer:
@Test void getSqlSetDataType() { EntityType entityType = when(mock(EntityType.class).getId()).thenReturn("entity").getMock(); when(entityType.getId()).thenReturn("entityTypeId"); Attribute attr = when(mock(Attribute.class).getName()).thenReturn("attr").getMock(); when(attr.getIdentifier()).thenReturn("attrId"); when(attr.getDataType()).thenReturn(LONG); assertEquals( "ALTER TABLE \"entityTypeId#c34894ba\" ALTER COLUMN \"attr\" SET DATA TYPE bigint USING \"attr\"::bigint", PostgreSqlQueryGenerator.getSqlSetDataType(entityType, attr)); }
|
### Question:
PostgreSqlQueryGenerator { static String getSqlDropFunctionValidateUpdate(EntityType entityType) { return "DROP FUNCTION " + getFunctionValidateUpdateName(entityType) + "();"; } private PostgreSqlQueryGenerator(); }### Answer:
@Test void getSqlDropFunctionValidateUpdate() { EntityType entityType = when(mock(EntityType.class).getId()).thenReturn("entity").getMock(); when(entityType.getId()).thenReturn("entityTypeId"); String expectedSql = "DROP FUNCTION \"validate_update_entityTypeId#c34894ba\"();"; assertEquals( expectedSql, PostgreSqlQueryGenerator.getSqlDropFunctionValidateUpdate(entityType)); }
|
### Question:
PostgreSqlQueryGenerator { static String getSqlCreateUpdateTrigger( EntityType entityType, Collection<Attribute> readonlyTableAttrs) { StringBuilder strBuilder = new StringBuilder(512) .append("CREATE TRIGGER ") .append(getUpdateTriggerName(entityType)) .append(" AFTER UPDATE ON ") .append(getTableName(entityType)) .append(" FOR EACH ROW WHEN ("); strBuilder.append( readonlyTableAttrs.stream() .map( attr -> "OLD." + getColumnName(attr) + " IS DISTINCT FROM NEW." + getColumnName(attr)) .collect(joining(" OR "))); strBuilder .append(") EXECUTE PROCEDURE ") .append(getFunctionValidateUpdateName(entityType)) .append("();"); return strBuilder.toString(); } private PostgreSqlQueryGenerator(); }### Answer:
@Test void getSqlCreateUpdateTrigger() { EntityType entityType = when(mock(EntityType.class).getId()).thenReturn("entity").getMock(); when(entityType.getId()).thenReturn("entityTypeId"); Attribute attr0 = when(mock(Attribute.class).getName()).thenReturn("attr0").getMock(); when(attr0.getIdentifier()).thenReturn("attr0Id"); Attribute attr1 = when(mock(Attribute.class).getName()).thenReturn("attr1").getMock(); when(attr1.getIdentifier()).thenReturn("attr1Id"); String expectedSql = "CREATE TRIGGER \"update_trigger_entityTypeId#c34894ba\" AFTER UPDATE ON \"entityTypeId#c34894ba\" FOR EACH ROW WHEN (OLD.\"attr0\" IS DISTINCT FROM NEW.\"attr0\" OR OLD.\"attr1\" IS DISTINCT FROM NEW.\"attr1\") EXECUTE PROCEDURE \"validate_update_entityTypeId#c34894ba\"();"; assertEquals( expectedSql, PostgreSqlQueryGenerator.getSqlCreateUpdateTrigger(entityType, asList(attr0, attr1))); }
|
### Question:
PostgreSqlQueryGenerator { static String getSqlDropUpdateTrigger(EntityType entityType) { return "DROP TRIGGER " + getUpdateTriggerName(entityType) + " ON " + getTableName(entityType); } private PostgreSqlQueryGenerator(); }### Answer:
@Test void getSqlDropUpdateTrigger() { String expectedSql = "DROP TRIGGER \"update_trigger_entityTypeId#c34894ba\" ON \"entityTypeId#c34894ba\""; EntityType entityType = when(mock(EntityType.class).getId()).thenReturn("entity").getMock(); when(entityType.getId()).thenReturn("entityTypeId"); assertEquals(expectedSql, PostgreSqlQueryGenerator.getSqlDropUpdateTrigger(entityType)); }
|
### Question:
PostgreSqlQueryGenerator { static String getSqlDropForeignKey(EntityType entityType, Attribute attr) { return "ALTER TABLE " + getTableName(entityType) + " DROP CONSTRAINT " + getForeignKeyName(entityType, attr); } private PostgreSqlQueryGenerator(); }### Answer:
@Test void getSqlDropForeignKey() { Attribute refIdAttr = when(mock(Attribute.class).getName()).thenReturn("refIdAttr").getMock(); when(refIdAttr.getIdentifier()).thenReturn("refIdAttrId"); EntityType refEntityType = when(mock(EntityType.class).getId()).thenReturn("refEntity").getMock(); when(refEntityType.getId()).thenReturn("refEntityId"); when(refEntityType.getIdAttribute()).thenReturn(refIdAttr); EntityType entityType = when(mock(EntityType.class).getId()).thenReturn("entity").getMock(); when(entityType.getId()).thenReturn("entityTypeId"); Attribute refAttr = when(mock(Attribute.class).getName()).thenReturn("attr").getMock(); when(refAttr.getIdentifier()).thenReturn("refAttrId"); when(refAttr.getDataType()).thenReturn(XREF); when(refAttr.getRefEntity()).thenReturn(refEntityType); String expectedSql = "ALTER TABLE \"entityTypeId#c34894ba\" DROP CONSTRAINT \"entityTypeId#c34894ba_attr_fkey\""; assertEquals(expectedSql, PostgreSqlQueryGenerator.getSqlDropForeignKey(entityType, refAttr)); }
|
### Question:
PostgreSqlQueryGenerator { static String getSqlCreateUniqueKey(EntityType entityType, Attribute attr) { return "ALTER TABLE " + getTableName(entityType) + " ADD " + getSqlUniqueKey(entityType, attr); } private PostgreSqlQueryGenerator(); }### Answer:
@Test void getSqlCreateUniqueKey() { EntityType entityType = when(mock(EntityType.class).getId()).thenReturn("entity").getMock(); when(entityType.getId()).thenReturn("entityTypeId"); Attribute attr = when(mock(Attribute.class).getName()).thenReturn("attr").getMock(); when(attr.getIdentifier()).thenReturn("attrId"); when(attr.getDataType()).thenReturn(STRING); String expectedSql = "ALTER TABLE \"entityTypeId#c34894ba\" ADD CONSTRAINT \"entityTypeId#c34894ba_attr_key\" UNIQUE (\"attr\")"; assertEquals(expectedSql, PostgreSqlQueryGenerator.getSqlCreateUniqueKey(entityType, attr)); }
|
### Question:
SpringExceptionHandler { @ExceptionHandler({ MissingServletRequestParameterException.class, ServletRequestBindingException.class, TypeMismatchException.class, HttpMessageNotReadableException.class, MethodArgumentNotValidException.class, MissingServletRequestPartException.class, BindException.class, ConstraintViolationException.class }) public final Object handleSpringBadRequestException(Exception e, HandlerMethod handlerMethod) { return logAndHandleException(e, BAD_REQUEST, handlerMethod); } @ExceptionHandler(HttpRequestMethodNotSupportedException.class) final Object handleSpringMethodNotAllowedException(
Exception e, HttpServletRequest request); @ExceptionHandler(NoHandlerFoundException.class) final Object handleSpringNotFoundException(Exception e, HttpServletRequest request); @ExceptionHandler(MaxUploadSizeExceededException.class) final Object handleSpringPayloadTooLargeException(
Exception e, HttpServletRequest request); @ExceptionHandler(HttpMediaTypeNotSupportedException.class) final Object handleSpringUnsupportedMediaTypeException(
Exception e, HandlerMethod handlerMethod); @ExceptionHandler(HttpMediaTypeNotAcceptableException.class) final Object handleSpringNotAcceptableException(Exception e, HandlerMethod handlerMethod); @ExceptionHandler({ MissingServletRequestParameterException.class, ServletRequestBindingException.class, TypeMismatchException.class, HttpMessageNotReadableException.class, MethodArgumentNotValidException.class, MissingServletRequestPartException.class, BindException.class, ConstraintViolationException.class }) final Object handleSpringBadRequestException(Exception e, HandlerMethod handlerMethod); @ExceptionHandler(AsyncRequestTimeoutException.class) final Object handleSpringServiceUnavailableException(
Exception e, HandlerMethod handlerMethod); }### Answer:
@Test void testHandleSpringBadRequestException() { Exception e = mock(Exception.class); HandlerMethod method = mock(HandlerMethod.class); springExceptionHandler.handleSpringBadRequestException(e, method); verify(springExceptionHandler).logAndHandleException(e, BAD_REQUEST, method); }
|
### Question:
PostgreSqlQueryGenerator { static String getSqlDropUniqueKey(EntityType entityType, Attribute attr) { return "ALTER TABLE " + getTableName(entityType) + " DROP CONSTRAINT " + getUniqueKeyName(entityType, attr); } private PostgreSqlQueryGenerator(); }### Answer:
@Test void getSqlDropUniqueKey() { EntityType entityType = when(mock(EntityType.class).getId()).thenReturn("entity").getMock(); when(entityType.getId()).thenReturn("entityTypeId"); Attribute attr = when(mock(Attribute.class).getName()).thenReturn("attr").getMock(); when(attr.getIdentifier()).thenReturn("attrId"); when(attr.getDataType()).thenReturn(STRING); String expectedSql = "ALTER TABLE \"entityTypeId#c34894ba\" DROP CONSTRAINT \"entityTypeId#c34894ba_attr_key\""; assertEquals(expectedSql, PostgreSqlQueryGenerator.getSqlDropUniqueKey(entityType, attr)); }
|
### Question:
PostgreSqlQueryGenerator { static String getSqlCreateCheckConstraint(EntityType entityType, Attribute attr) { return "ALTER TABLE " + getTableName(entityType) + " ADD " + getSqlCheckConstraint(entityType, attr); } private PostgreSqlQueryGenerator(); }### Answer:
@Test void getSqlCreateCheckConstraint() { EntityType entityType = when(mock(EntityType.class).getId()).thenReturn("entity").getMock(); when(entityType.getId()).thenReturn("entityTypeId"); Attribute attr = when(mock(Attribute.class).getName()).thenReturn("attr").getMock(); when(attr.getIdentifier()).thenReturn("attrId"); when(attr.getDataType()).thenReturn(ENUM); when(attr.getEnumOptions()).thenReturn(newArrayList("enum0", "enum1", "enum2")); assertEquals( "ALTER TABLE \"entityTypeId#c34894ba\" ADD CONSTRAINT \"entityTypeId#c34894ba_attr_chk\" CHECK (\"attr\" IN ('enum0','enum1','enum2'))", PostgreSqlQueryGenerator.getSqlCreateCheckConstraint(entityType, attr)); }
@SuppressWarnings("deprecation") @Test void getSqlCreateCheckConstraintWrongDataType() { EntityType entityType = when(mock(EntityType.class).getId()).thenReturn("entity").getMock(); when(entityType.getId()).thenReturn("entityTypeId"); Attribute attr = when(mock(Attribute.class).getName()).thenReturn("attr").getMock(); when(attr.getIdentifier()).thenReturn("attrId"); when(attr.getDataType()).thenReturn(STRING); assertThrows( MolgenisDataException.class, () -> PostgreSqlQueryGenerator.getSqlCreateCheckConstraint(entityType, attr)); }
|
### Question:
PostgreSqlQueryGenerator { static String getSqlDropCheckConstraint(EntityType entityType, Attribute attr) { if (attr.getDataType() != ENUM) { throw new MolgenisDataException( format("Check constraint only allowed for attribute type [%s]", ENUM.toString())); } return "ALTER TABLE " + getTableName(entityType) + " DROP CONSTRAINT " + getCheckConstraintName(entityType, attr); } private PostgreSqlQueryGenerator(); }### Answer:
@Test void getSqlDropCheckConstraint() { EntityType entityType = when(mock(EntityType.class).getId()).thenReturn("entity").getMock(); when(entityType.getId()).thenReturn("entityTypeId"); Attribute attr = when(mock(Attribute.class).getName()).thenReturn("attr").getMock(); when(attr.getIdentifier()).thenReturn("attrId"); when(attr.getDataType()).thenReturn(ENUM); when(attr.getEnumOptions()).thenReturn(newArrayList("enum0", "enum1", "enum2")); assertEquals( "ALTER TABLE \"entityTypeId#c34894ba\" DROP CONSTRAINT \"entityTypeId#c34894ba_attr_chk\"", PostgreSqlQueryGenerator.getSqlDropCheckConstraint(entityType, attr)); }
@Test void getSqlDropCheckConstraintWrongDataType() { EntityType entityType = when(mock(EntityType.class).getId()).thenReturn("entity").getMock(); when(entityType.getId()).thenReturn("entityTypeId"); Attribute attr = when(mock(Attribute.class).getName()).thenReturn("attr").getMock(); when(attr.getIdentifier()).thenReturn("attrId"); when(attr.getDataType()).thenReturn(STRING); assertThrows( MolgenisDataException.class, () -> PostgreSqlQueryGenerator.getSqlDropCheckConstraint(entityType, attr)); }
|
### Question:
PostgreSqlQueryGenerator { static String getSqlJunctionTableSelect(EntityType entityType, Attribute attr, int numOfIds) { String idColName = getColumnName(entityType.getIdAttribute()); String refIdColName = getColumnName(attr); return "SELECT " + idColName + "," + getJunctionTableOrderColumnName() + "," + refIdColName + " FROM " + getJunctionTableName(entityType, attr) + " WHERE " + idColName + " in (" + range(0, numOfIds).mapToObj(x -> "?").collect(joining(", ")) + ") ORDER BY " + idColName + "," + getJunctionTableOrderColumnName(); } private PostgreSqlQueryGenerator(); }### Answer:
@Test void getJunctionTableSelect() { EntityType entityType = when(mock(EntityType.class).getId()).thenReturn("entity").getMock(); when(entityType.getId()).thenReturn("entityTypeId"); Attribute idAttr = when(mock(Attribute.class).getName()).thenReturn("idAttr").getMock(); when(idAttr.getIdentifier()).thenReturn("idAttrId"); Attribute attr = when(mock(Attribute.class).getName()).thenReturn("attr").getMock(); when(attr.getIdentifier()).thenReturn("attrId"); when(attr.getDataType()).thenReturn(MREF); when(entityType.getIdAttribute()).thenReturn(idAttr); assertEquals( "SELECT \"idAttr\",\"order\",\"attr\" FROM \"entityTypeId#c34894ba_attr\" WHERE \"idAttr\" in (?, ?, ?) ORDER BY \"idAttr\",\"order\"", getSqlJunctionTableSelect(entityType, attr, 3)); }
|
### Question:
PostgreSqlQueryGenerator { static String getSqlDropColumn(EntityType entityType, Attribute attr) { return "ALTER TABLE " + getTableName(entityType) + " DROP COLUMN " + getColumnName(attr); } private PostgreSqlQueryGenerator(); }### Answer:
@Test void getSqlDropColumn() { EntityType entityType = when(mock(EntityType.class).getId()).thenReturn("entity").getMock(); when(entityType.getId()).thenReturn("entityTypeId"); Attribute attr = when(mock(Attribute.class).getName()).thenReturn("attr").getMock(); when(attr.getIdentifier()).thenReturn("attrId"); assertEquals( "ALTER TABLE \"entityTypeId#c34894ba\" DROP COLUMN \"attr\"", PostgreSqlQueryGenerator.getSqlDropColumn(entityType, attr)); }
|
### Question:
PostgreSqlQueryGenerator { static String getSqlDropColumnDefault(EntityType entityType, Attribute attr) { return "ALTER TABLE " + getTableName(entityType) + " ALTER COLUMN " + getColumnName(attr) + " DROP DEFAULT"; } private PostgreSqlQueryGenerator(); }### Answer:
@Test void getSqlDropColumnDefault() { EntityType entityType = when(mock(EntityType.class).getId()).thenReturn("entity").getMock(); when(entityType.getId()).thenReturn("entityTypeId"); Attribute attr = when(mock(Attribute.class).getName()).thenReturn("attr").getMock(); when(attr.getIdentifier()).thenReturn("attrId"); assertEquals( "ALTER TABLE \"entityTypeId#c34894ba\" ALTER COLUMN \"attr\" DROP DEFAULT", PostgreSqlQueryGenerator.getSqlDropColumnDefault(entityType, attr)); }
|
### Question:
PostgreSqlQueryGenerator { static String getSqlCreateJunctionTableIndex(EntityType entityType, Attribute attr) { Attribute idAttr = entityType.getIdAttribute(); String junctionTableName = getJunctionTableName(entityType, attr); String junctionTableIndexName = getJunctionTableIndexName(entityType, attr, idAttr); String idxColumnName = getColumnName(idAttr); return "CREATE INDEX " + junctionTableIndexName + " ON " + junctionTableName + " (" + idxColumnName + ')'; } private PostgreSqlQueryGenerator(); }### Answer:
@Test void getSqlCreateJunctionTableIndex() { EntityType entityType = when(mock(EntityType.class).getId()).thenReturn("entity").getMock(); when(entityType.getId()).thenReturn("entityTypeId"); Attribute attr = when(mock(Attribute.class).getName()).thenReturn("attr").getMock(); when(attr.getIdentifier()).thenReturn("attrId"); Attribute idxAttr = when(mock(Attribute.class).getName()).thenReturn("idAttr").getMock(); when(idxAttr.getIdentifier()).thenReturn("idAttrId"); when(entityType.getIdAttribute()).thenReturn(idxAttr); assertEquals( "CREATE INDEX \"entityType#c34894ba_attr_idAttr_idx\" ON \"entityTypeId#c34894ba_attr\" (\"idAttr\")", PostgreSqlQueryGenerator.getSqlCreateJunctionTableIndex(entityType, attr)); }
|
### Question:
PostgreSqlQueryGenerator { static String getSqlUpdate(EntityType entityType) { return getSqlUpdate(entityType, null); } private PostgreSqlQueryGenerator(); }### Answer:
@Test void testGetSqlUpdate() { String idAttributeName = "MyIdAttribute"; Attribute idAttribute = when(mock(Attribute.class).getName()).thenReturn(idAttributeName).getMock(); when(idAttribute.getDataType()).thenReturn(STRING); String entityTypeId = "MyEntityTypeId"; EntityType entityType = when(mock(EntityType.class).getId()).thenReturn(entityTypeId).getMock(); when(entityType.getIdAttribute()).thenReturn(idAttribute); String labelAttributeName = "MyLabelAttribute"; Attribute labelAttribute = when(mock(Attribute.class).getName()).thenReturn(labelAttributeName).getMock(); when(labelAttribute.getDataType()).thenReturn(STRING); when(entityType.getAtomicAttributes()).thenReturn(asList(idAttribute, labelAttribute)); String sqlUpdate = PostgreSqlQueryGenerator.getSqlUpdate(entityType); String expectedSqlUpdate = "UPDATE \"MyEntityTypeId#55dde9c3\" SET \"MyIdAttribute\" = ?, \"MyLabelAttribute\" = ? WHERE \"MyIdAttribute\"= ?"; assertEquals(expectedSqlUpdate, sqlUpdate); }
@Test void testGetSqlUpdateAttribute() { String idAttributeName = "MyIdAttribute"; Attribute idAttribute = when(mock(Attribute.class).getName()).thenReturn(idAttributeName).getMock(); when(idAttribute.getDataType()).thenReturn(STRING); String entityTypeId = "MyEntityTypeId"; EntityType entityType = when(mock(EntityType.class).getId()).thenReturn(entityTypeId).getMock(); when(entityType.getIdAttribute()).thenReturn(idAttribute); String sqlUpdate = PostgreSqlQueryGenerator.getSqlUpdate(entityType, idAttribute); String expectedSqlUpdate = "UPDATE \"MyEntityTypeId#55dde9c3\" SET \"MyIdAttribute\" = ? WHERE \"MyIdAttribute\"= ?"; assertEquals(expectedSqlUpdate, sqlUpdate); }
|
### Question:
PostgreSqlUtils { static Object getPostgreSqlValue(Entity entity, Attribute attr) { String attrName = attr.getName(); AttributeType attrType = attr.getDataType(); switch (attrType) { case BOOL: return entity.getBoolean(attrName); case CATEGORICAL: case XREF: Entity xrefEntity = entity.getEntity(attrName); return xrefEntity != null ? getPostgreSqlValue(xrefEntity, xrefEntity.getEntityType().getIdAttribute()) : null; case CATEGORICAL_MREF: case MREF: case ONE_TO_MANY: Iterable<Entity> entities = entity.getEntities(attrName); return stream(entities) .map( mrefEntity -> getPostgreSqlValue(mrefEntity, mrefEntity.getEntityType().getIdAttribute())) .collect(toList()); case DATE: return entity.getLocalDate(attrName); case DATE_TIME: Instant instant = entity.getInstant(attrName); return instant != null ? instant.truncatedTo(ChronoUnit.SECONDS).atOffset(UTC) : null; case DECIMAL: return entity.getDouble(attrName); case EMAIL: case ENUM: case HTML: case HYPERLINK: case SCRIPT: case STRING: case TEXT: return entity.getString(attrName); case FILE: FileMeta fileEntity = entity.getEntity(attrName, FileMeta.class); return fileEntity != null ? getPostgreSqlValue(fileEntity, fileEntity.getEntityType().getIdAttribute()) : null; case INT: return entity.getInt(attrName); case LONG: return entity.getLong(attrName); case COMPOUND: throw new IllegalAttributeTypeException(attrType); default: throw new UnexpectedEnumException(attrType); } } private PostgreSqlUtils(); }### Answer:
@Test void getPostgreSqlValueCompound() { assertThrows( RuntimeException.class, () -> PostgreSqlUtils.getPostgreSqlValue( mock(Entity.class), createAttr("attrCompound", COMPOUND))); }
|
### Question:
PostgreSqlRepositoryCollectionDecorator extends AbstractRepositoryCollectionDecorator { @Override public Repository<Entity> createRepository(EntityType entityType) { Repository<Entity> repo = delegate().createRepository(entityType); entityTypeRegistry.registerEntityType(entityType); return repo; } PostgreSqlRepositoryCollectionDecorator(
RepositoryCollection delegateRepositoryCollection, EntityTypeRegistry entityTypeRegistry); @Override Repository<Entity> createRepository(EntityType entityType); @Override void deleteRepository(EntityType entityType); @Override void updateRepository(EntityType entityType, EntityType updatedEntityType); @Override void addAttribute(EntityType entityType, Attribute attribute); @Override void updateAttribute(EntityType entityType, Attribute attr, Attribute updatedAttr); @Override void deleteAttribute(EntityType entityType, Attribute attr); }### Answer:
@Test void testCreateRepository() { repoCollectionDecorator.createRepository(entityType); inOrder.verify(repoCollection).createRepository(entityType); inOrder.verify(entityTypeRegistry).registerEntityType(entityType); }
|
### Question:
PostgreSqlRepositoryCollectionDecorator extends AbstractRepositoryCollectionDecorator { @Override public void deleteRepository(EntityType entityType) { delegate().deleteRepository(entityType); entityTypeRegistry.unregisterEntityType(entityType); } PostgreSqlRepositoryCollectionDecorator(
RepositoryCollection delegateRepositoryCollection, EntityTypeRegistry entityTypeRegistry); @Override Repository<Entity> createRepository(EntityType entityType); @Override void deleteRepository(EntityType entityType); @Override void updateRepository(EntityType entityType, EntityType updatedEntityType); @Override void addAttribute(EntityType entityType, Attribute attribute); @Override void updateAttribute(EntityType entityType, Attribute attr, Attribute updatedAttr); @Override void deleteAttribute(EntityType entityType, Attribute attr); }### Answer:
@Test void testDeleteRepository() { repoCollectionDecorator.deleteRepository(entityType); inOrder.verify(repoCollection).deleteRepository(entityType); inOrder.verify(entityTypeRegistry).unregisterEntityType(entityType); }
|
### Question:
PostgreSqlRepositoryCollectionDecorator extends AbstractRepositoryCollectionDecorator { @Override public void addAttribute(EntityType entityType, Attribute attribute) { entityTypeRegistry.addAttribute(entityType, attribute); delegate().addAttribute(entityType, attribute); } PostgreSqlRepositoryCollectionDecorator(
RepositoryCollection delegateRepositoryCollection, EntityTypeRegistry entityTypeRegistry); @Override Repository<Entity> createRepository(EntityType entityType); @Override void deleteRepository(EntityType entityType); @Override void updateRepository(EntityType entityType, EntityType updatedEntityType); @Override void addAttribute(EntityType entityType, Attribute attribute); @Override void updateAttribute(EntityType entityType, Attribute attr, Attribute updatedAttr); @Override void deleteAttribute(EntityType entityType, Attribute attr); }### Answer:
@Test void testAddAttribute() { repoCollectionDecorator.addAttribute(entityType, attr); inOrder.verify(entityTypeRegistry).addAttribute(entityType, attr); inOrder.verify(repoCollection).addAttribute(entityType, attr); }
|
### Question:
PostgreSqlRepositoryCollectionDecorator extends AbstractRepositoryCollectionDecorator { @Override public void updateAttribute(EntityType entityType, Attribute attr, Attribute updatedAttr) { entityTypeRegistry.updateAttribute(entityType, attr, updatedAttr); delegate().updateAttribute(entityType, attr, updatedAttr); } PostgreSqlRepositoryCollectionDecorator(
RepositoryCollection delegateRepositoryCollection, EntityTypeRegistry entityTypeRegistry); @Override Repository<Entity> createRepository(EntityType entityType); @Override void deleteRepository(EntityType entityType); @Override void updateRepository(EntityType entityType, EntityType updatedEntityType); @Override void addAttribute(EntityType entityType, Attribute attribute); @Override void updateAttribute(EntityType entityType, Attribute attr, Attribute updatedAttr); @Override void deleteAttribute(EntityType entityType, Attribute attr); }### Answer:
@Test void testUpdateAttribute() { repoCollectionDecorator.updateAttribute(entityType, attr, updatedAttr); inOrder.verify(entityTypeRegistry).updateAttribute(entityType, attr, updatedAttr); inOrder.verify(repoCollection).updateAttribute(entityType, attr, updatedAttr); }
|
### Question:
PostgreSqlRepositoryCollectionDecorator extends AbstractRepositoryCollectionDecorator { @Override public void deleteAttribute(EntityType entityType, Attribute attr) { entityTypeRegistry.deleteAttribute(entityType, attr); delegate().deleteAttribute(entityType, attr); } PostgreSqlRepositoryCollectionDecorator(
RepositoryCollection delegateRepositoryCollection, EntityTypeRegistry entityTypeRegistry); @Override Repository<Entity> createRepository(EntityType entityType); @Override void deleteRepository(EntityType entityType); @Override void updateRepository(EntityType entityType, EntityType updatedEntityType); @Override void addAttribute(EntityType entityType, Attribute attribute); @Override void updateAttribute(EntityType entityType, Attribute attr, Attribute updatedAttr); @Override void deleteAttribute(EntityType entityType, Attribute attr); }### Answer:
@Test void testDeleteAttribute() { repoCollectionDecorator.deleteAttribute(entityType, attr); inOrder.verify(entityTypeRegistry).deleteAttribute(entityType, attr); inOrder.verify(repoCollection).deleteAttribute(entityType, attr); }
|
### Question:
PostgreSqlTransactionManager extends DataSourceTransactionManager implements TransactionManager { @Override protected Object doGetTransaction() { Object dataSourceTransactionManager = super.doGetTransaction(); String id; if (TransactionSynchronizationManager.hasResource( TransactionConstants.TRANSACTION_ID_RESOURCE_NAME)) { id = (String) TransactionSynchronizationManager.getResource( TransactionConstants.TRANSACTION_ID_RESOURCE_NAME); } else { id = idGenerator.generateId().toLowerCase(); } return new MolgenisTransaction(id, dataSourceTransactionManager); } PostgreSqlTransactionManager(
IdGenerator idGenerator,
DataSource dataSource,
TransactionExceptionTranslatorRegistry transactionExceptionTranslatorRegistry); @Override synchronized void addTransactionListener(TransactionListener transactionListener); }### Answer:
@Test void doGetTransaction() { String id = "unique_id"; when(idGenerator.generateId()).thenReturn(id); Object trans = molgenisTransactionManager.doGetTransaction(); assertNotNull(trans); assertTrue(trans instanceof MolgenisTransaction); MolgenisTransaction molgenisTransaction = (MolgenisTransaction) trans; assertEquals(id, molgenisTransaction.getId()); }
|
### Question:
EntityTypeRegistryImpl implements EntityTypeRegistry, TransactionListener { @Override public void unregisterEntityType(EntityType entityType) { Iterable<Attribute> attributes = entityType.getAtomicAttributes(); registerTableNames(getTableNames(entityType, stream(attributes)), null); } EntityTypeRegistryImpl(TransactionManager transactionManager); @Override void registerEntityType(EntityType entityType); @Override void unregisterEntityType(EntityType entityType); @Override void addAttribute(EntityType entityType, Attribute attribute); @Override void updateAttribute(EntityType entityType, Attribute attr, Attribute updatedAttr); @Override void deleteAttribute(EntityType entityType, Attribute attr); @Override EntityTypeDescription getEntityTypeDescription(String tableName); @Override void afterCommitTransaction(String transactionId); @Override void rollbackTransaction(String transactionId); }### Answer:
@Test public void testUnregisterEntityType() { entityTypeRegistryImpl.unregisterEntityType(entityType); assertNull( entityTypeRegistryImpl.getEntityTypeDescription( "org_molgenis_test_many_packages_deep#2409e1c6")); assertNull( entityTypeRegistryImpl.getEntityTypeDescription( "org_molgenis_test_many#2409e1c6_xref_attribute_with_a_long_name")); assertNull( entityTypeRegistryImpl.getEntityTypeDescription("org_molgenis_test_many#2409e1c6_mref")); }
|
### Question:
EntityTypeRegistryImpl implements EntityTypeRegistry, TransactionListener { @Override public void rollbackTransaction(String transactionId) { transactionsEntityTypeDescriptionMap.remove(transactionId); } EntityTypeRegistryImpl(TransactionManager transactionManager); @Override void registerEntityType(EntityType entityType); @Override void unregisterEntityType(EntityType entityType); @Override void addAttribute(EntityType entityType, Attribute attribute); @Override void updateAttribute(EntityType entityType, Attribute attr, Attribute updatedAttr); @Override void deleteAttribute(EntityType entityType, Attribute attr); @Override EntityTypeDescription getEntityTypeDescription(String tableName); @Override void afterCommitTransaction(String transactionId); @Override void rollbackTransaction(String transactionId); }### Answer:
@Test public void testRollbackTransaction() { bindResource(TRANSACTION_ID_RESOURCE_NAME, "1"); entityTypeRegistryImpl.unregisterEntityType(entityType); assertNull( entityTypeRegistryImpl.getEntityTypeDescription( "org_molgenis_test_many_packages_deep#2409e1c6")); assertNull( entityTypeRegistryImpl.getEntityTypeDescription("org_molgenis_test_many#2409e1c6_mref")); assertNull( entityTypeRegistryImpl.getEntityTypeDescription( "org_molgenis_test_many#2409e1c6_stringAttribute")); assertNull( entityTypeRegistryImpl.getEntityTypeDescription( "org_molgenis_test_many#2409e1c6_xref_attribute_with_a_long_name")); entityTypeRegistryImpl.rollbackTransaction("1"); testGetEntityTypeDescription(); }
|
### Question:
EntityTypeRegistryImpl implements EntityTypeRegistry, TransactionListener { @Override public void afterCommitTransaction(String transactionId) { Map<String, EntityTypeDescription> transactionEntityTypeDescriptionMap = transactionsEntityTypeDescriptionMap.remove(transactionId); if (transactionEntityTypeDescriptionMap != null) { transactionEntityTypeDescriptionMap.forEach( (tableName, entityTypeDescription) -> { if (entityTypeDescription != null) { entityTypeDescriptionMap.put(tableName, entityTypeDescription); } else { entityTypeDescriptionMap.remove(tableName); } }); } } EntityTypeRegistryImpl(TransactionManager transactionManager); @Override void registerEntityType(EntityType entityType); @Override void unregisterEntityType(EntityType entityType); @Override void addAttribute(EntityType entityType, Attribute attribute); @Override void updateAttribute(EntityType entityType, Attribute attr, Attribute updatedAttr); @Override void deleteAttribute(EntityType entityType, Attribute attr); @Override EntityTypeDescription getEntityTypeDescription(String tableName); @Override void afterCommitTransaction(String transactionId); @Override void rollbackTransaction(String transactionId); }### Answer:
@Test public void testAfterCommitTransaction() { entityTypeRegistryImpl.afterCommitTransaction("1"); entityTypeRegistryImpl.rollbackTransaction("1"); testGetEntityTypeDescription(); }
|
### Question:
PostgreSqlNameGenerator { static String getJunctionTableOrderColumnName() { return getQuotedIdentifier(JUNCTION_TABLE_ORDER_ATTR_NAME); } private PostgreSqlNameGenerator(); static String getTableName(EntityType entityType, boolean quotedIdentifier); static String getJunctionTableName(
EntityType entityType, Attribute attr, boolean quotedIdentifier); static String getColumnName(Attribute attr, boolean quotedIdentifier); }### Answer:
@Test void testGetJunctionTableOrderColumnName() { assertEquals('"' + JUNCTION_TABLE_ORDER_ATTR_NAME + '"', getJunctionTableOrderColumnName()); }
|
### Question:
PostgreSqlExceptionTranslator extends SQLErrorCodeSQLExceptionTranslator implements TransactionExceptionTranslator { PostgreSqlExceptionTranslator(DataSource dataSource, EntityTypeRegistry entityTypeRegistry) { super(requireNonNull(dataSource)); this.entityTypeRegistry = requireNonNull(entityTypeRegistry); } PostgreSqlExceptionTranslator(DataSource dataSource, EntityTypeRegistry entityTypeRegistry); @Override @Nullable @CheckForNull DataAccessException doTranslate(TransactionException transactionException); }### Answer:
@Test void PostgreSqlExceptionTranslator() { assertThrows(NullPointerException.class, () -> new PostgreSqlExceptionTranslator(null, null)); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.