method2testcases
stringlengths
118
3.08k
### Question: PostgreSqlExceptionTranslator extends SQLErrorCodeSQLExceptionTranslator implements TransactionExceptionTranslator { ValueLengthExceededException translateValueTooLongViolation(Throwable sourceThrowable) { return new ValueLengthExceededException(sourceThrowable); } PostgreSqlExceptionTranslator(DataSource dataSource, EntityTypeRegistry entityTypeRegistry); @Override @Nullable @CheckForNull DataAccessException doTranslate(TransactionException transactionException); }### Answer: @Test void translateValueTooLongViolation() { ServerErrorMessage serverErrorMessage = mock(ServerErrorMessage.class); when(serverErrorMessage.getMessage()) .thenReturn("ERROR: value too long for type character varying(255)"); ValueLengthExceededException e = postgreSqlExceptionTranslator.translateValueTooLongViolation(mock(Throwable.class)); assertNull(e.getMessage()); }
### Question: PostgreSqlExceptionTranslator extends SQLErrorCodeSQLExceptionTranslator implements TransactionExceptionTranslator { UnknownEnumValueException translateCheckConstraintViolation( Throwable sourceThrowable, PSQLException pSqlException) { ServerErrorMessage serverErrorMessage = pSqlException.getServerErrorMessage(); String tableName = serverErrorMessage.getTable(); String constraintName = serverErrorMessage.getConstraint(); String columnName = constraintName.substring(tableName.length() + 1, constraintName.length() - 4); String entityTypeId = tryGetEntityTypeName(tableName).orElse(null); String attributeName = tryGetAttributeName(tableName, columnName).orElse(null); return new UnknownEnumValueException(entityTypeId, attributeName, sourceThrowable); } PostgreSqlExceptionTranslator(DataSource dataSource, EntityTypeRegistry entityTypeRegistry); @Override @Nullable @CheckForNull DataAccessException doTranslate(TransactionException transactionException); }### Answer: @Test void translateCheckConstraintViolation() { ServerErrorMessage serverErrorMessage = mock(ServerErrorMessage.class); when(serverErrorMessage.getTable()).thenReturn("myTable"); when(serverErrorMessage.getConstraint()).thenReturn("myTable_myColumn_chk"); UnknownEnumValueException e = postgreSqlExceptionTranslator.translateCheckConstraintViolation( mock(Throwable.class), new PSQLException(serverErrorMessage)); assertEquals("entityTypeId:myEntity attributeName:myAttr", e.getMessage()); }
### Question: PostgreSqlExceptionTranslator extends SQLErrorCodeSQLExceptionTranslator implements TransactionExceptionTranslator { static MolgenisValidationException translateUndefinedColumnException( PSQLException pSqlException) { ServerErrorMessage serverErrorMessage = pSqlException.getServerErrorMessage(); String message = serverErrorMessage.getMessage(); ConstraintViolation constraintViolation = new ConstraintViolation(message); return new MolgenisValidationException(singleton(constraintViolation)); } PostgreSqlExceptionTranslator(DataSource dataSource, EntityTypeRegistry entityTypeRegistry); @Override @Nullable @CheckForNull DataAccessException doTranslate(TransactionException transactionException); }### Answer: @Test void translateUndefinedColumnException() { ServerErrorMessage serverErrorMessage = mock(ServerErrorMessage.class); when(serverErrorMessage.getSQLState()).thenReturn("42703"); when(serverErrorMessage.getMessage()) .thenReturn("Undefined column: 7 ERROR: column \"test\" does not exist"); Exception e = PostgreSqlExceptionTranslator.translateUndefinedColumnException( new PSQLException(serverErrorMessage)); assertEquals("Undefined column: 7 ERROR: column \"test\" does not exist", e.getMessage()); }
### Question: FilesServiceImpl implements FilesService { @Transactional(readOnly = true) @Override public FileMeta getFileMeta(String fileId) { FileMeta fileMeta = dataService.findOneById(FILE_META, fileId, FileMeta.class); if (fileMeta == null) { throw new UnknownEntityException(FILE_META, fileId); } return fileMeta; } FilesServiceImpl(DataService dataService, BlobStore blobStore, FileMetaFactory fileMetaFactory); @Transactional(readOnly = true) @Override FileMeta getFileMeta(String fileId); @Override void delete(String fileId); @Transactional @Override CompletableFuture<FileMeta> upload(HttpServletRequest httpServletRequest); @Transactional(readOnly = true) @Override ResponseEntity<StreamingResponseBody> download(String fileId); }### Answer: @Test void testGetFileMeta() { String fileId = "MyFileId"; FileMeta fileMeta = mock(FileMeta.class); when(dataService.findOneById("sys_FileMeta", fileId, FileMeta.class)).thenReturn(fileMeta); assertEquals(fileMeta, filesApiServiceImpl.getFileMeta(fileId)); } @Test void testGetFileMetaUnknown() { String fileId = "MyFileId"; assertThrows(UnknownEntityException.class, () -> filesApiServiceImpl.getFileMeta(fileId)); }
### Question: FilesServiceImpl implements FilesService { @Override public void delete(String fileId) { dataService.deleteById(FILE_META, fileId); } FilesServiceImpl(DataService dataService, BlobStore blobStore, FileMetaFactory fileMetaFactory); @Transactional(readOnly = true) @Override FileMeta getFileMeta(String fileId); @Override void delete(String fileId); @Transactional @Override CompletableFuture<FileMeta> upload(HttpServletRequest httpServletRequest); @Transactional(readOnly = true) @Override ResponseEntity<StreamingResponseBody> download(String fileId); }### Answer: @Test void testDeleteFile() { String fileId = "MyFileId"; filesApiServiceImpl.delete(fileId); verify(dataService).deleteById("sys_FileMeta", fileId); }
### Question: FilesServiceImpl implements FilesService { @Transactional @Override public CompletableFuture<FileMeta> upload(HttpServletRequest httpServletRequest) { BlobMetadata blobMetadata; try (ReadableByteChannel fromChannel = newChannel(httpServletRequest.getInputStream())) { blobMetadata = blobStore.store(fromChannel); } catch (IOException e) { throw new UncheckedIOException(e); } FileMeta fileMeta = createFileMeta(httpServletRequest, blobMetadata); dataService.add(FILE_META, fileMeta); return CompletableFuture.completedFuture(fileMeta); } FilesServiceImpl(DataService dataService, BlobStore blobStore, FileMetaFactory fileMetaFactory); @Transactional(readOnly = true) @Override FileMeta getFileMeta(String fileId); @Override void delete(String fileId); @Transactional @Override CompletableFuture<FileMeta> upload(HttpServletRequest httpServletRequest); @Transactional(readOnly = true) @Override ResponseEntity<StreamingResponseBody> download(String fileId); }### Answer: @Test void testUpload() throws ExecutionException, InterruptedException { String blobId = "MyBlobId"; BlobMetadata blobMetadata = when(mock(BlobMetadata.class).getId()).thenReturn(blobId).getMock(); when(blobMetadata.getSize()).thenReturn(1L); when(blobStore.store(any())).thenReturn(blobMetadata); FileMeta fileMeta = mock(FileMeta.class); when(fileMetaFactory.create(blobId)).thenReturn(fileMeta); MockHttpServletRequest httpServletRequest = new MockHttpServletRequest(); httpServletRequest.setContent(new byte[] {0x00}); String contentType = "application/octet-stream"; httpServletRequest.setContentType(contentType); String filename = "myfile.bin"; httpServletRequest.addHeader("x-molgenis-filename", filename); assertEquals(fileMeta, filesApiServiceImpl.upload(httpServletRequest).get()); verify(fileMeta).setContentType(contentType); verify(fileMeta).setSize(1L); verify(fileMeta).setFilename(filename); verify(fileMeta).setUrl("/MyBlobId?alt=media"); verifyNoMoreInteractions(fileMeta); }
### Question: FilesServiceImpl implements FilesService { @Transactional(readOnly = true) @Override public ResponseEntity<StreamingResponseBody> download(String fileId) { FileMeta fileMeta = getFileMeta(fileId); ResponseEntity.BodyBuilder builder = ResponseEntity.ok(); builder.header(CONTENT_TYPE, fileMeta.getContentType()); builder.header(CONTENT_DISPOSITION, "attachment; filename=\"" + fileMeta.getFilename() + "\""); Long contentLength = fileMeta.getSize(); if (contentLength != null) { builder.contentLength(contentLength); } return builder.body( outputStream -> { try (ReadableByteChannel fromChannel = blobStore.newChannel(fileId)) { ByteStreams.copy(fromChannel, Channels.newChannel(outputStream)); } }); } FilesServiceImpl(DataService dataService, BlobStore blobStore, FileMetaFactory fileMetaFactory); @Transactional(readOnly = true) @Override FileMeta getFileMeta(String fileId); @Override void delete(String fileId); @Transactional @Override CompletableFuture<FileMeta> upload(HttpServletRequest httpServletRequest); @Transactional(readOnly = true) @Override ResponseEntity<StreamingResponseBody> download(String fileId); }### Answer: @Test void testDownload() { String fileId = "MyFileId"; String contentType = "application/octet-stream"; String filename = "filename"; FileMeta fileMeta = mock(FileMeta.class); when(fileMeta.getContentType()).thenReturn(contentType); when(fileMeta.getFilename()).thenReturn(filename); when(dataService.findOneById("sys_FileMeta", fileId, FileMeta.class)).thenReturn(fileMeta); ResponseEntity<StreamingResponseBody> responseEntity = filesApiServiceImpl.download(fileId); assertEquals(OK, responseEntity.getStatusCode()); assertEquals(valueOf(contentType), responseEntity.getHeaders().getContentType()); assertEquals( parse("attachment; filename=\"filename\""), responseEntity.getHeaders().getContentDisposition()); }
### Question: FilesController extends ApiController { @PostMapping(consumes = {"application/x-www-form-urlencoded", "multipart/form-data"}) @ResponseStatus(BAD_REQUEST) public CompletableFuture<ResponseEntity<FileResponse>> createFileFromForm( HttpServletRequest httpServletRequest) { throw new UnsupportedOperationException( "Media type '" + httpServletRequest.getContentType() + "' not supported"); } FilesController(FilesService filesService, UserPermissionEvaluator userPermissionEvaluator); @ApiOperation("Upload file (see documentation)") @PostMapping @ResponseStatus(CREATED) CompletableFuture<ResponseEntity<FileResponse>> createFile( HttpServletRequest httpServletRequest); @PostMapping(consumes = {"application/x-www-form-urlencoded", "multipart/form-data"}) @ResponseStatus(BAD_REQUEST) CompletableFuture<ResponseEntity<FileResponse>> createFileFromForm( HttpServletRequest httpServletRequest); @ApiOperation("Retrieve file metadata (see documentation)") @GetMapping(value = "/{fileId}") FileResponse readFile(@PathVariable("fileId") String fileId); @ApiOperation("Download file (see documentation)") @GetMapping(value = "/{fileId}", params = "alt=media") ResponseEntity<StreamingResponseBody> downloadFile(@PathVariable("fileId") String fileId); @ApiOperation("Delete file (see documentation)") @DeleteMapping(value = "/{fileId}") @ResponseStatus(NO_CONTENT) void deleteFile(@PathVariable("fileId") String fileId); }### Answer: @Test void testCreateFileFromForm() { HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); when(httpServletRequest.getContentType()).thenReturn("multipart/form-data"); Exception exception = assertThrows( UnsupportedOperationException.class, () -> filesApiController.createFileFromForm(httpServletRequest)); assertThat(exception.getMessage()) .containsPattern("Media type 'multipart/form-data' not supported"); }
### Question: FilesController extends ApiController { @ApiOperation("Download file (see documentation)") @GetMapping(value = "/{fileId}", params = "alt=media") public ResponseEntity<StreamingResponseBody> downloadFile(@PathVariable("fileId") String fileId) { validateReadPermission(); return filesService.download(fileId); } FilesController(FilesService filesService, UserPermissionEvaluator userPermissionEvaluator); @ApiOperation("Upload file (see documentation)") @PostMapping @ResponseStatus(CREATED) CompletableFuture<ResponseEntity<FileResponse>> createFile( HttpServletRequest httpServletRequest); @PostMapping(consumes = {"application/x-www-form-urlencoded", "multipart/form-data"}) @ResponseStatus(BAD_REQUEST) CompletableFuture<ResponseEntity<FileResponse>> createFileFromForm( HttpServletRequest httpServletRequest); @ApiOperation("Retrieve file metadata (see documentation)") @GetMapping(value = "/{fileId}") FileResponse readFile(@PathVariable("fileId") String fileId); @ApiOperation("Download file (see documentation)") @GetMapping(value = "/{fileId}", params = "alt=media") ResponseEntity<StreamingResponseBody> downloadFile(@PathVariable("fileId") String fileId); @ApiOperation("Delete file (see documentation)") @DeleteMapping(value = "/{fileId}") @ResponseStatus(NO_CONTENT) void deleteFile(@PathVariable("fileId") String fileId); }### Answer: @Test void testDownloadFile() { when(userPermissionEvaluator.hasPermission(new EntityTypeIdentity(FILE_META), READ_DATA)) .thenReturn(true); String fileId = "MyId"; @SuppressWarnings("unchecked") ResponseEntity<StreamingResponseBody> responseEntity = mock(ResponseEntity.class); when(filesApiService.download(fileId)).thenReturn(responseEntity); assertEquals(responseEntity, filesApiController.downloadFile(fileId)); } @Test void testDownloadFileNotPermitted() { String fileId = "MyId"; assertThrows( EntityTypePermissionDeniedException.class, () -> filesApiController.downloadFile(fileId)); }
### Question: FilesController extends ApiController { @ApiOperation("Delete file (see documentation)") @DeleteMapping(value = "/{fileId}") @ResponseStatus(NO_CONTENT) public void deleteFile(@PathVariable("fileId") String fileId) { validateDeletePermission(); filesService.delete(fileId); } FilesController(FilesService filesService, UserPermissionEvaluator userPermissionEvaluator); @ApiOperation("Upload file (see documentation)") @PostMapping @ResponseStatus(CREATED) CompletableFuture<ResponseEntity<FileResponse>> createFile( HttpServletRequest httpServletRequest); @PostMapping(consumes = {"application/x-www-form-urlencoded", "multipart/form-data"}) @ResponseStatus(BAD_REQUEST) CompletableFuture<ResponseEntity<FileResponse>> createFileFromForm( HttpServletRequest httpServletRequest); @ApiOperation("Retrieve file metadata (see documentation)") @GetMapping(value = "/{fileId}") FileResponse readFile(@PathVariable("fileId") String fileId); @ApiOperation("Download file (see documentation)") @GetMapping(value = "/{fileId}", params = "alt=media") ResponseEntity<StreamingResponseBody> downloadFile(@PathVariable("fileId") String fileId); @ApiOperation("Delete file (see documentation)") @DeleteMapping(value = "/{fileId}") @ResponseStatus(NO_CONTENT) void deleteFile(@PathVariable("fileId") String fileId); }### Answer: @Test void testDeleteFile() { when(userPermissionEvaluator.hasPermission(new EntityTypeIdentity(FILE_META), DELETE_DATA)) .thenReturn(true); String fileId = "MyFileId"; filesApiController.deleteFile(fileId); verify(filesApiService).delete(fileId); } @Test void testDeleteFileNotPermitted() { String fileId = "MyId"; assertThrows( EntityTypePermissionDeniedException.class, () -> filesApiController.deleteFile(fileId)); }
### Question: Step42RemoveFormsUrlRow extends MolgenisUpgrade { @Override public void upgrade() { LOG.debug("Remove form_not_a_valid_url row"); removeFromsUrlMsg(); LOG.info("row (id = 'form_not_a_valid_url') has been removed from sys_L10nString"); } Step42RemoveFormsUrlRow(DataSource dataSource); Step42RemoveFormsUrlRow(JdbcTemplate jdbcTemplate); @Override void upgrade(); }### Answer: @Test void upgrade() { step42.upgrade(); verify(jdbcTemplate).execute(any(String.class)); } @Test void upgradeException() { DataAccessException dataAccessException = mock(DataAccessException.class); doThrow(dataAccessException).when(jdbcTemplate).execute(any(String.class)); assertThrows(DataAccessException.class, () -> step42.upgrade()); }
### Question: MolgenisUpgradeServiceImpl implements MolgenisUpgradeService { @Override public boolean upgrade() { int schemaVersion = versionService.getSchemaVersion(); if (schemaVersion < 31) { throw new UnsupportedOperationException( "Upgrading from schema version below 31 is not supported"); } if (schemaVersion < versionService.getAppVersion()) { LOG.info( "Metadata version:{}, current version:{} upgrade needed", schemaVersion, versionService.getAppVersion()); upgrades.stream() .filter(upgrade -> upgrade.getFromVersion() >= schemaVersion) .forEach(this::runUpgrade); versionService.setSchemaVersion(versionService.getAppVersion()); LOG.info("Metadata upgrade done."); return true; } else { LOG.debug( "Metadata version:{}, current version:{} upgrade not needed", schemaVersion, versionService.getAppVersion()); return false; } } MolgenisUpgradeServiceImpl(MolgenisVersionService versionService); void addUpgrade(MolgenisUpgrade upgrade); @Override boolean upgrade(); }### Answer: @Test void testUpgradeFromVersion30() { when(molgenisVersionService.getSchemaVersion()).thenReturn(30); assertThrows(UnsupportedOperationException.class, () -> molgenisUpgradeServiceImpl.upgrade()); } @Test void testUpgradeFromVersion31() { when(molgenisVersionService.getSchemaVersion()).thenReturn(31); assertFalse(molgenisUpgradeServiceImpl.upgrade()); }
### Question: Step40AddRoleSystem extends MolgenisUpgrade { @Override public void upgrade() { LOG.debug("Adding ROLE_SYSTEM to ROLE_SU..."); addRoleSystem(); LOG.info("Added ROLE_SYSTEM to ROLE_SU"); } Step40AddRoleSystem(DataSource dataSource); Step40AddRoleSystem(JdbcTemplate jdbcTemplate); @Override void upgrade(); }### Answer: @Test void upgrade() { step40AddRoleSystem.upgrade(); verify(jdbcTemplate).execute(any(String.class)); } @Test void upgradeException() { DataAccessException dataAccessException = mock(DataAccessException.class); doThrow(dataAccessException).when(jdbcTemplate).execute(any(String.class)); assertThrows(DataAccessException.class, () -> step40AddRoleSystem.upgrade()); }
### Question: Step41Reindex extends MolgenisUpgrade { @Override public void upgrade() { LOG.debug("Removing attribute index to trigger a full reindex..."); try { clientFacade.deleteIndex(Index.create("sysmdattribute_c8d9a252")); LOG.info("The standard tokenizer got changed, will do a full reindex."); } catch (UnknownIndexException ignore) { LOG.info("Index not found, full index will be done already."); } } Step41Reindex(ClientFacade clientFacade); @Override void upgrade(); }### Answer: @Test void testUpgrade() { step41Reindex.upgrade(); verify(clientFacade).deleteIndex(attributeIndex); } @Test void testUpgradeIndexNotFound() { doThrow(new UnknownIndexException("Not found")).when(clientFacade).deleteIndex(attributeIndex); step41Reindex.upgrade(); }
### Question: MolgenisVersionService { int getAppVersion() { return VERSION; } MolgenisVersionService(DataSource dataSource); @PostConstruct void init(); }### Answer: @Test void testGetAppVersion() { assertEquals(VERSION, molgenisVersionService.getAppVersion()); }
### Question: MolgenisVersionService { int getSchemaVersion() { int version; try (Connection connection = dataSource.getConnection()) { try (Statement statement = connection.createStatement()) { String selectVersionSql = "SELECT \"id\" FROM \"Version\""; try (ResultSet resultSet = statement.executeQuery(selectVersionSql)) { if (resultSet.next()) { version = resultSet.getInt("id"); } else { throw new SQLException("Expected non-empty result set"); } } } } catch (SQLException e) { throw new UncheckedSqlException(e); } return version; } MolgenisVersionService(DataSource dataSource); @PostConstruct void init(); }### Answer: @Test void testGetSchemaVersion() throws SQLException { Connection connection = mock(Connection.class); when(dataSource.getConnection()).thenReturn(connection); Statement statement = mock(Statement.class); when(connection.createStatement()).thenReturn(statement); ResultSet resultSet = mock(ResultSet.class); when(statement.executeQuery("SELECT \"id\" FROM \"Version\"")).thenReturn(resultSet); when(resultSet.next()).thenReturn(true); when(resultSet.getInt("id")).thenReturn(30); assertEquals(30, molgenisVersionService.getSchemaVersion()); }
### Question: MolgenisVersionService { void setSchemaVersion(int version) { try (Connection connection = dataSource.getConnection()) { try (PreparedStatement statement = connection.prepareStatement("UPDATE \"Version\" SET \"id\"=?")) { statement.setInt(1, version); statement.execute(); } } catch (SQLException e) { throw new UncheckedSqlException(e); } } MolgenisVersionService(DataSource dataSource); @PostConstruct void init(); }### Answer: @Test void testSetSchemaVersion() throws SQLException { Connection connection = mock(Connection.class); when(dataSource.getConnection()).thenReturn(connection); PreparedStatement preparedStatement = mock(PreparedStatement.class); when(connection.prepareStatement("UPDATE \"Version\" SET \"id\"=?")) .thenReturn(preparedStatement); molgenisVersionService.setSchemaVersion(30); verify(preparedStatement).setInt(1, 30); verify(preparedStatement).execute(); }
### Question: GlobalControllerExceptionHandler extends SpringExceptionHandler { @ExceptionHandler(UnknownDataException.class) public Object handleNotFoundException(Exception e, HandlerMethod handlerMethod) { return logAndHandleException(e, NOT_FOUND, handlerMethod); } GlobalControllerExceptionHandler(ExceptionHandlerFacade exceptionHandlerFacade); @ExceptionHandler(UnknownDataException.class) Object handleNotFoundException(Exception e, HandlerMethod handlerMethod); @ExceptionHandler(DataAlreadyExistsException.class) Object handleConflictException(Exception e, HandlerMethod handlerMethod); @ExceptionHandler({ BadRequestException.class, DataConstraintViolationException.class, RepositoryConstraintViolationException.class }) Object handleBadRequestException(Exception e, HandlerMethod handlerMethod); @ExceptionHandler(ForbiddenException.class) Object handleForbiddenException(Exception e, HandlerMethod handlerMethod); @ExceptionHandler(PermissionDeniedException.class) Object handleUnauthorizedException(Exception e, HandlerMethod handlerMethod); }### Answer: @Test void testHandleNotFoundException() { Exception e = mock(Exception.class); HandlerMethod method = mock(HandlerMethod.class); globalControllerExceptionHandler.handleNotFoundException(e, method); verify(exceptionHandlerFacade).logAndHandleException(e, NOT_FOUND, method); }
### Question: ImportRun extends StaticEntity { public boolean getNotify() { return getBoolean(NOTIFY) != null && getBoolean(NOTIFY); } ImportRun(Entity entity); ImportRun(EntityType entityType); ImportRun(String id, EntityType entityType); String getId(); void setId(String id); Instant getStartDate(); void setStartDate(Instant startDate); Optional<Instant> getEndDate(); void setEndDate(Instant endDate); String getUsername(); void setUsername(String username); String getStatus(); void setStatus(String status); @Nullable @CheckForNull String getMessage(); void setMessage(String message); int getProgress(); void setProgress(int progress); @Nullable @CheckForNull String getImportedEntities(); void setImportedEntities(String importedEntities); boolean getNotify(); void setNotify(boolean notify); List<ValueLabel> getStatusOptions(); List<ValueLabel> getNotifyOptions(); }### Answer: @Test void testGetNotifyDefaultFalse() throws Exception { assertFalse(importRun.getNotify()); }
### Question: ImportRun extends StaticEntity { public void setNotify(boolean notify) { set(NOTIFY, notify); } ImportRun(Entity entity); ImportRun(EntityType entityType); ImportRun(String id, EntityType entityType); String getId(); void setId(String id); Instant getStartDate(); void setStartDate(Instant startDate); Optional<Instant> getEndDate(); void setEndDate(Instant endDate); String getUsername(); void setUsername(String username); String getStatus(); void setStatus(String status); @Nullable @CheckForNull String getMessage(); void setMessage(String message); int getProgress(); void setProgress(int progress); @Nullable @CheckForNull String getImportedEntities(); void setImportedEntities(String importedEntities); boolean getNotify(); void setNotify(boolean notify); List<ValueLabel> getStatusOptions(); List<ValueLabel> getNotifyOptions(); }### Answer: @Test void testSetNotify() throws Exception { importRun.setNotify(true); assertTrue(importRun.getNotify()); }
### Question: ImportBootstrapper { public void bootstrap() { LOG.trace("Failing import runs that were left running..."); dataService .query(ImportRunMetadata.IMPORT_RUN, ImportRun.class) .eq(ImportRunMetadata.STATUS, ImportStatus.RUNNING.toString()) .findAll() .forEach(this::setFailed); LOG.debug("Failed import runs that were left running."); } ImportBootstrapper(DataService dataService); void bootstrap(); }### Answer: @Test void bootstrap() { ImportRun importRun = mock(ImportRun.class); @SuppressWarnings("unchecked") Query<ImportRun> query = mock(Query.class, RETURNS_DEEP_STUBS); when(query.eq("status", "RUNNING")).thenReturn(query); when(query.findAll()).thenReturn(Stream.of(importRun)); when(dataService.query("sys_ImportRun", ImportRun.class)).thenReturn(query); importBootstrapper.bootstrap(); verify(importRun).setStatus("FAILED"); verify(importRun).setMessage("Application terminated unexpectedly"); verify(dataService).update("sys_ImportRun", importRun); }
### Question: IntermediateParseResults { public EntityType addEntityType(String fullyQualifiedName) { String entityTypeLabel = fullyQualifiedName; Package pack = null; for (Package p : packages.values()) { String packageName = p.getId(); if (fullyQualifiedName.toLowerCase().startsWith(packageName.toLowerCase())) { entityTypeLabel = fullyQualifiedName.substring(packageName.length() + 1); pack = p; } } EntityType entityType = entityTypeFactory.create(fullyQualifiedName).setLabel(entityTypeLabel).setPackage(pack); entityTypes.put(fullyQualifiedName, entityType); return entityType; } IntermediateParseResults(EntityTypeFactory entityTypeFactory); void addTag(String identifier, Tag tag); boolean hasTag(String identifier); Tag getTag(String tagIdentifier); Package getPackage(String name); void addAttributes(String entityTypeId, List<EmxAttribute> emxAttrs); static void setDefaultLookupAttributes(EntityType entityType, int lookupAttributeIndex); EntityType addEntityType(String fullyQualifiedName); EntityType getEntityType(String name); void addLanguage(Language language); void addL10nString(L10nString l10nString); boolean hasEntityType(String name); boolean hasPackage(String name); void addPackage(String name, Package p); ImmutableMap<String, EntityType> getEntityMap(); ImmutableList<EntityType> getEntityTypes(); ImmutableMap<String, Package> getPackages(); ImmutableMap<String, Tag> getTags(); ImmutableMap<String, Language> getLanguages(); ImmutableMap<String, L10nString> getL10nStrings(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test void testAddEntityType() { EntityType entityType = mock(EntityType.class); when(entityType.setLabel(any())).thenReturn(entityType); when(entityType.setPackage(any())).thenReturn(entityType); when(entityTypeFactory.create("entityType")).thenReturn(entityType); assertEquals(entityType, intermediateParseResults.addEntityType("entityType")); verify(entityType).setLabel("entityType"); }
### Question: ImportWriter { ImportWriter( MetaDataService metaDataService, PermissionSystemService permissionSystemService, UserPermissionEvaluator permissionService, EntityManager entityManager, DataPersister dataPersister) { this.metaDataService = requireNonNull(metaDataService); this.permissionSystemService = requireNonNull(permissionSystemService); this.permissionService = requireNonNull(permissionService); this.entityManager = requireNonNull(entityManager); this.dataPersister = requireNonNull(dataPersister); } ImportWriter( MetaDataService metaDataService, PermissionSystemService permissionSystemService, UserPermissionEvaluator permissionService, EntityManager entityManager, DataPersister dataPersister); @Transactional EntityImportReport doImport(EmxImportJob job); }### Answer: @Test void testImportWriter() { assertThrows(NullPointerException.class, () -> new ImportWriter(null, null, null, null, null)); }
### Question: EmxDataProvider implements DataProvider { @Override public Stream<EntityType> getEntityTypes() { return job.getParsedMetaData().getEntities().stream(); } EmxDataProvider(EmxImportJob job, EntityManager entityManager); @Override Stream<EntityType> getEntityTypes(); @Override boolean hasEntities(EntityType entityType); @Override Stream<Entity> getEntities(EntityType entityType); }### Answer: @Test void testGetEntityTypes() { ImmutableCollection<EntityType> entityTypes = ImmutableList.of(); ParsedMetaData parsedMetaData = mock(ParsedMetaData.class); when(parsedMetaData.getEntities()).thenReturn(entityTypes).getMock(); when(emxImportJob.getParsedMetaData()).thenReturn(parsedMetaData); assertEquals(emptyList(), emxDataProvider.getEntityTypes().collect(toList())); }
### Question: ImportRunService { @SuppressWarnings("java:S3457") String createEnglishMailText(ImportRun importRun, ZoneId zone) { ZonedDateTime start = importRun.getStartDate().atZone(zone); ZonedDateTime end = importRun .getEndDate() .orElseThrow(() -> new IllegalStateException("ImportRun must have an end date")) .atZone(zone); String startDateTimeString = ofLocalizedDateTime(FULL).withLocale(ENGLISH).format(start); String endTimeString = ofLocalizedTime(MEDIUM).withLocale(ENGLISH).format(end); return String.format( "The import started by you on %1s finished on %2s with status: %3s\nMessage:\n%4s", startDateTimeString, endTimeString, importRun.getStatus(), importRun.getMessage()); } ImportRunService( DataService dataService, MailSender mailSender, UserService userService, ContextMessageSource contextMessageSource, ImportRunFactory importRunFactory); ImportRun addImportRun(String userName, boolean notify); }### Answer: @Test void testCreateEnglishMailText() { ImportRun importRun = mock(ImportRun.class); when(importRun.getMessage()).thenReturn("Entity already exists."); when(importRun.getStatus()).thenReturn(FAILED.toString()); Instant startDate = Instant.parse("2016-02-13T12:34:56.217Z"); when(importRun.getStartDate()).thenReturn(startDate); Instant endDate = Instant.parse("2016-02-13T12:35:12.231Z"); when(importRun.getEndDate()).thenReturn(Optional.of(endDate)); String mailText = importRunService.createEnglishMailText(importRun, ZoneId.of("Europe/Amsterdam")); assertEquals( "The import started by you on Saturday, February 13, 2016 at 1:34:56 PM Central European Standard Time finished on 1:35:12 PM with status: FAILED\n" + "Message:\n" + "Entity already exists.", mailText); }
### Question: ImportRunService { void finishImportRun(String importRunId, String message, String importedEntities) { ImportRun importRun = dataService.findOneById(IMPORT_RUN, importRunId, ImportRun.class); if (importRun == null) { throw new UnknownEntityException(IMPORT_RUN, importRunId); } try { importRun.setStatus(ImportStatus.FINISHED.toString()); importRun.setEndDate(now()); importRun.setMessage(message); importRun.setImportedEntities(importedEntities); dataService.update(IMPORT_RUN, importRun); } catch (Exception e) { LOG.error("Error updating run status", e); } if (importRun.getNotify()) createAndSendStatusMail(importRun); } ImportRunService( DataService dataService, MailSender mailSender, UserService userService, ContextMessageSource contextMessageSource, ImportRunFactory importRunFactory); ImportRun addImportRun(String userName, boolean notify); }### Answer: @Test void testFinishImportRun() { String importRunId = "MyImportRunId"; String message = "message"; String importedEntities = "importedEntities"; ImportRun importRun = mock(ImportRun.class); when(dataService.findOneById(IMPORT_RUN, importRunId, ImportRun.class)).thenReturn(importRun); importRunService.finishImportRun(importRunId, message, importedEntities); verify(importRun).setStatus(ImportStatus.FINISHED.toString()); verify(importRun).setEndDate(any()); verify(importRun).setMessage(message); verify(importRun).setImportedEntities(importedEntities); verify(dataService).update(IMPORT_RUN, importRun); } @Test void testFinishImportRunUnknown() { assertThrows( UnknownEntityException.class, () -> importRunService.finishImportRun("unknownImportRunId", "message", "importedEntities")); }
### Question: EmxExportServiceImpl implements EmxExportService { void writeEntityTypes(Collection<EntityType> entityTypes, XlsxWriter writer) { LinkedList<EntityType> sortedEntityTypes = sortEntityTypesAbstractFirst(entityTypes); if (!writer.hasSheet(EMX_ENTITIES)) { writer.createSheet(EMX_ENTITIES, newArrayList(ENTITIES_ATTRS.keySet())); } writer.writeRows(sortedEntityTypes.stream().map(EntityTypeMapper::map), EMX_ENTITIES); } EmxExportServiceImpl(DataService dataService, ContextMessageSource contextMessageSource); @Override @Transactional(readOnly = true, isolation = Isolation.SERIALIZABLE) void export( List<EntityType> entityTypes, List<Package> packages, Path downloadFilePath, Progress progress); }### Answer: @Test void writeEntityTypesTest() { EntityType entityType1 = mock(EntityType.class); EntityType entityType2 = mock(EntityType.class); EntityType entityType3 = mock(EntityType.class); EntityType entityType4 = mock(EntityType.class); when(entityType1.isAbstract()).thenReturn(false); when(entityType2.isAbstract()).thenReturn(false); when(entityType3.isAbstract()).thenReturn(true); when(entityType4.isAbstract()).thenReturn(false); when(entityType3.getId()).thenReturn("3"); LinkedList<EntityType> entityTypes = new LinkedList<>(); entityTypes.add(entityType1); entityTypes.add(entityType2); entityTypes.add(entityType3); entityTypes.add(entityType4); XlsxWriter xlsxWriter = mock(XlsxWriter.class); service.writeEntityTypes(entityTypes, xlsxWriter); ArgumentCaptor<Stream> argumentCaptor = ArgumentCaptor.forClass(Stream.class); verify(xlsxWriter).writeRows(argumentCaptor.capture(), eq(EMX_ENTITIES)); Stream<List> argument = argumentCaptor.getValue(); List<Object> actual = argument.collect(Collectors.toList()).get(0); assertEquals("3", actual.get(0)); }
### Question: LocalizationMessageSource extends AbstractMessageSource { @Override public String getDefaultMessage(String code) { return "#" + code + "#"; } LocalizationMessageSource( MessageFormatFactory messageFormatFactory, MessageResolution messageRepository, Supplier<Locale> fallbackLocaleSupplier); @Override String getDefaultMessage(String code); @Override MessageFormat resolveCode(String code, Locale locale); }### Answer: @Test void testGetDefaultMessage() { assertEquals("#CODE#", messageSource.getDefaultMessage("CODE")); }
### Question: GlobalControllerExceptionHandler extends SpringExceptionHandler { @ExceptionHandler(DataAlreadyExistsException.class) public Object handleConflictException(Exception e, HandlerMethod handlerMethod) { return logAndHandleException(e, CONFLICT, handlerMethod); } GlobalControllerExceptionHandler(ExceptionHandlerFacade exceptionHandlerFacade); @ExceptionHandler(UnknownDataException.class) Object handleNotFoundException(Exception e, HandlerMethod handlerMethod); @ExceptionHandler(DataAlreadyExistsException.class) Object handleConflictException(Exception e, HandlerMethod handlerMethod); @ExceptionHandler({ BadRequestException.class, DataConstraintViolationException.class, RepositoryConstraintViolationException.class }) Object handleBadRequestException(Exception e, HandlerMethod handlerMethod); @ExceptionHandler(ForbiddenException.class) Object handleForbiddenException(Exception e, HandlerMethod handlerMethod); @ExceptionHandler(PermissionDeniedException.class) Object handleUnauthorizedException(Exception e, HandlerMethod handlerMethod); }### Answer: @Test void testHandleConflictException() { Exception e = mock(Exception.class); HandlerMethod method = mock(HandlerMethod.class); globalControllerExceptionHandler.handleConflictException(e, method); verify(exceptionHandlerFacade).logAndHandleException(e, CONFLICT, method); }
### Question: LocalizationMessageSource extends AbstractMessageSource { @Override public MessageFormat resolveCode(String code, Locale locale) { String resolved = resolveCodeWithoutArguments(code, locale); if (resolved == null) { return null; } return createMessageFormat(resolved, locale); } LocalizationMessageSource( MessageFormatFactory messageFormatFactory, MessageResolution messageRepository, Supplier<Locale> fallbackLocaleSupplier); @Override String getDefaultMessage(String code); @Override MessageFormat resolveCode(String code, Locale locale); }### Answer: @Test void testResolveCode() { doReturn("The Label").when(labeled).getLabel("en"); when(messageRepository.resolveCodeWithoutArguments("TEST_MESSAGE_EN", ENGLISH)) .thenReturn("label: ''{0, label}''"); assertEquals( "label: 'The Label'", messageSource.resolveCode("TEST_MESSAGE_EN", ENGLISH).format(new Object[] {labeled})); }
### Question: ContextMessageSourceImpl implements ContextMessageSource { @Override public String getMessage(String code) { return getMessage(code, null); } @Override String getMessage(String code); @Override String getMessage(String code, @Nullable @CheckForNull Object[] args); }### Answer: @Test void testGetMessageCode() { String message = "MyMessage"; String code = "my_code"; Locale locale = Locale.GERMAN; when(messageSource.getMessage(code, null, locale)).thenReturn(message); LocaleContextHolder.setLocale(locale); MessageSourceHolder.setMessageSource(messageSource); assertEquals(message, userMessageSourceImpl.getMessage(code)); } @Test void testGetMessageCodeArgs() { String message = "MyMessage"; String code = "my_code"; Object[] args = {"arg0", "arg1"}; Locale locale = Locale.GERMAN; when(messageSource.getMessage(code, args, locale)).thenReturn(message); LocaleContextHolder.setLocale(locale); MessageSourceHolder.setMessageSource(messageSource); assertEquals(message, userMessageSourceImpl.getMessage(code, args)); }
### Question: SwaggerController extends PluginController { @GetMapping public String init(Model model) { final UriComponents uriComponents = ServletUriComponentsBuilder.fromCurrentContextPath().build(); model.addAttribute("molgenisUrl", uriComponents.toUriString() + URI + "/swagger.yml"); model.addAttribute("baseUrl", uriComponents.toUriString()); final String currentUsername = SecurityUtils.getCurrentUsername(); if (currentUsername != null) { model.addAttribute( "token", tokenService.generateAndStoreToken(currentUsername, "For Swagger UI")); } return "view-swagger-ui"; } SwaggerController(MetaDataService metaDataService, TokenService tokenService); @GetMapping String init(Model model); @GetMapping(value = "/swagger.yml", produces = "text/yaml") String swagger(Model model, HttpServletResponse response); static final String URI; }### Answer: @Test @WithMockUser void testInit() { MockHttpServletRequest request = new MockHttpServletRequest(); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); when(tokenService.generateAndStoreToken("user", "For Swagger UI")).thenReturn("ABCDEFG"); assertEquals("view-swagger-ui", swaggerController.init(model)); verify(model).addAttribute("molgenisUrl", "http: verify(model).addAttribute("baseUrl", "http: verify(model).addAttribute("token", "ABCDEFG"); verifyNoMoreInteractions(model); } @Test void testInitWithoutUser() { MockHttpServletRequest request = new MockHttpServletRequest(); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); assertEquals("view-swagger-ui", swaggerController.init(model)); verify(model).addAttribute("molgenisUrl", "http: verify(model).addAttribute("baseUrl", "http: verifyNoMoreInteractions(model); }
### Question: WebAppPermissionRegistry implements PermissionRegistry { @Override public Multimap<ObjectIdentity, Pair<PermissionSet, Sid>> getPermissions() { return builder.build(); } WebAppPermissionRegistry(); @Override Multimap<ObjectIdentity, Pair<PermissionSet, Sid>> getPermissions(); }### Answer: @Test public void testGetPermissions() { Multimap<ObjectIdentity, Pair<PermissionSet, Sid>> permissions = new WebAppPermissionRegistry().getPermissions(); assertFalse(permissions.isEmpty()); Collection<Pair<PermissionSet, Sid>> pairs = permissions.get(new PluginIdentity(HomeController.ID)); assertEquals( singleton(new Pair<>(READ, new GrantedAuthoritySid("ROLE_ANONYMOUS"))), copyOf(pairs)); }
### Question: IndexedRepositoryDecorator extends AbstractRepositoryDecorator<Entity> { IndexedRepositoryDecorator( Repository<Entity> delegateRepository, SearchService searchService, IndexJobScheduler indexJobScheduler) { super(delegateRepository); this.searchService = requireNonNull(searchService); this.indexJobScheduler = requireNonNull(indexJobScheduler); Set<Operator> operators = getQueryOperators(); operators.removeAll(delegate().getQueryOperators()); unsupportedOperators = Collections.unmodifiableSet(operators); } IndexedRepositoryDecorator( Repository<Entity> delegateRepository, SearchService searchService, IndexJobScheduler indexJobScheduler); @Override Entity findOne(Query<Entity> q); @Override Stream<Entity> findAll(Query<Entity> q); @Override Set<RepositoryCapability> getCapabilities(); @Override Set<Operator> getQueryOperators(); @Override long count(Query<Entity> q); @Override AggregateResult aggregate(AggregateQuery aggregateQuery); }### Answer: @SuppressWarnings("resource") @Test void indexedRepositoryDecorator() { assertThrows( NullPointerException.class, () -> new IndexedRepositoryDecorator(null, null, null)); }
### Question: IndexedRepositoryDecorator extends AbstractRepositoryDecorator<Entity> { @Override public AggregateResult aggregate(AggregateQuery aggregateQuery) { return tryTwice(() -> searchService.aggregate(getEntityType(), aggregateQuery)); } IndexedRepositoryDecorator( Repository<Entity> delegateRepository, SearchService searchService, IndexJobScheduler indexJobScheduler); @Override Entity findOne(Query<Entity> q); @Override Stream<Entity> findAll(Query<Entity> q); @Override Set<RepositoryCapability> getCapabilities(); @Override Set<Operator> getQueryOperators(); @Override long count(Query<Entity> q); @Override AggregateResult aggregate(AggregateQuery aggregateQuery); }### Answer: @Test void aggregate() { when(indexedRepositoryDecorator.getName()).thenReturn("entity"); Attribute xAttr = when(mock(Attribute.class).getName()).thenReturn("xAttr").getMock(); Attribute yAttr = when(mock(Attribute.class).getName()).thenReturn("yAttr").getMock(); Attribute distinctAttr = when(mock(Attribute.class).getName()).thenReturn("distinctAttr").getMock(); @SuppressWarnings("unchecked") Query<Entity> q = mock(Query.class); AggregateQuery aggregateQuery = new AggregateQueryImpl().attrX(xAttr).attrY(yAttr).attrDistinct(distinctAttr).query(q); indexedRepositoryDecorator.aggregate(aggregateQuery); verify(searchService).aggregate(repositoryEntityType, aggregateQuery); } @Test void aggregateUnknownIndexExceptionUnrecoverable() { AggregateQuery aggregateQuery = mock(AggregateQuery.class); when(searchService.aggregate(repositoryEntityType, aggregateQuery)) .thenThrow(new UnknownIndexException("msg")); Exception exception = assertThrows( MolgenisDataException.class, () -> indexedRepositoryDecorator.aggregate(aggregateQuery)); assertThat(exception.getMessage()) .containsPattern( "Error executing query, index for entity type 'My entity type' with id 'entity' does not exist"); }
### Question: IndexedRepositoryDecorator extends AbstractRepositoryDecorator<Entity> { @Override public Set<RepositoryCapability> getCapabilities() { Set<RepositoryCapability> capabilities = new HashSet<>(); capabilities.addAll(delegate().getCapabilities()); capabilities.addAll(EnumSet.of(QUERYABLE, AGGREGATEABLE)); return unmodifiableSet(capabilities); } IndexedRepositoryDecorator( Repository<Entity> delegateRepository, SearchService searchService, IndexJobScheduler indexJobScheduler); @Override Entity findOne(Query<Entity> q); @Override Stream<Entity> findAll(Query<Entity> q); @Override Set<RepositoryCapability> getCapabilities(); @Override Set<Operator> getQueryOperators(); @Override long count(Query<Entity> q); @Override AggregateResult aggregate(AggregateQuery aggregateQuery); }### Answer: @Test void getCapabilities() { assertEquals( of(AGGREGATEABLE, QUERYABLE, MANAGABLE, VALIDATE_NOTNULL_CONSTRAINT), indexedRepositoryDecorator.getCapabilities()); }
### Question: IndexedRepositoryDecorator extends AbstractRepositoryDecorator<Entity> { @Override public Set<Operator> getQueryOperators() { return EnumSet.allOf(Operator.class); } IndexedRepositoryDecorator( Repository<Entity> delegateRepository, SearchService searchService, IndexJobScheduler indexJobScheduler); @Override Entity findOne(Query<Entity> q); @Override Stream<Entity> findAll(Query<Entity> q); @Override Set<RepositoryCapability> getCapabilities(); @Override Set<Operator> getQueryOperators(); @Override long count(Query<Entity> q); @Override AggregateResult aggregate(AggregateQuery aggregateQuery); }### Answer: @Test void getQueryOperators() { assertEquals(allOf(Operator.class), indexedRepositoryDecorator.getQueryOperators()); }
### Question: IndexJobService { static Query<IndexAction> createQueryGetAllIndexActions(String transactionId) { QueryRule rule = new QueryRule(INDEX_ACTION_GROUP_ATTR, EQUALS, transactionId); QueryImpl<IndexAction> q = new QueryImpl<>(rule); q.setSort(new Sort(ACTION_ORDER)); return q; } IndexJobService( DataService dataService, IndexService indexService, EntityTypeFactory entityTypeFactory); @Timed( value = "service.index", description = "Timing information for the index service.", histogram = true) Void executeJob(Progress progress, String transactionId); }### Answer: @Test void testCreateQueryGetAllIndexActions() { Query<IndexAction> q = IndexJobService.createQueryGetAllIndexActions("testme"); assertEquals( "rules=['indexActionGroup' = 'testme'], sort=Sort [orders=[Order [attr=actionOrder, direction=ASC]]]", q.toString()); }
### Question: IndexActionRepositoryDecorator extends AbstractRepositoryDecorator<Entity> { @Override public Set<RepositoryCapability> getCapabilities() { Set<RepositoryCapability> capabilities = new HashSet<>(); capabilities.add(RepositoryCapability.INDEXABLE); capabilities.addAll(delegate().getCapabilities()); return capabilities; } IndexActionRepositoryDecorator( Repository<Entity> delegateRepository, IndexActionRegisterService indexActionRegisterService); @Override Set<RepositoryCapability> getCapabilities(); @Override void update(Entity entity); @Override void delete(Entity entity); @Override void deleteById(Object id); @Override void deleteAll(); @Override void add(Entity entity); @Override Integer add(Stream<Entity> entities); @Override void update(Stream<Entity> entities); @Override void delete(Stream<Entity> entities); @Override void deleteAll(Stream<Object> ids); }### Answer: @Test void getCapabilities() { assertEquals(of(INDEXABLE, MANAGABLE), indexActionRepositoryDecorator.getCapabilities()); }
### Question: IndexActionRepositoryDecorator extends AbstractRepositoryDecorator<Entity> { @Override public void deleteById(Object id) { indexActionRegisterService.register(getEntityType(), id); registerRefEntityIndexActions(); delegate().deleteById(id); } IndexActionRepositoryDecorator( Repository<Entity> delegateRepository, IndexActionRegisterService indexActionRegisterService); @Override Set<RepositoryCapability> getCapabilities(); @Override void update(Entity entity); @Override void delete(Entity entity); @Override void deleteById(Object id); @Override void deleteAll(); @Override void add(Entity entity); @Override Integer add(Stream<Entity> entities); @Override void update(Stream<Entity> entities); @Override void delete(Stream<Entity> entities); @Override void deleteAll(Stream<Object> ids); }### Answer: @Test void deleteEntityById() { initEntityMeta(); Entity entity0 = mock(Entity.class); when(entity0.getIdValue()).thenReturn(1); indexActionRepositoryDecorator.deleteById(1); verify(delegateRepository, times(1)).deleteById(1); verify(indexActionRegisterService).register(entityType, 1); verifyNoMoreInteractions(indexActionRegisterService); } @Test void deleteEntityByIdBidi() { initEntityMetaBidi(); Entity entity0 = mock(Entity.class); when(entity0.getIdValue()).thenReturn(1); indexActionRepositoryDecorator.deleteById(1); verify(delegateRepository, times(1)).deleteById(1); verify(indexActionRegisterService).register(entityType, 1); verify(indexActionRegisterService).register(mappedByEntity, null); verify(indexActionRegisterService).register(inversedByEntity, null); verifyNoMoreInteractions(indexActionRegisterService); }
### Question: IndexActionRepositoryCollectionDecorator extends AbstractRepositoryCollectionDecorator { @Override public void deleteRepository(EntityType entityType) { this.indexActionRegisterService.register(entityType, null); delegate().deleteRepository(entityType); } IndexActionRepositoryCollectionDecorator( RepositoryCollection delegateRepositoryCollection, IndexActionRegisterService indexActionRegisterService); @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); @Override Repository<Entity> createRepository(EntityType entityType); }### Answer: @Test void deleteRepository() { indexActionRepositoryCollectionDecorator.deleteRepository(entityType); verify(decoratedRepositoryCollection).deleteRepository(entityType); verify(indexActionRegisterService).register(entityType, null); }
### Question: IndexActionRepositoryCollectionDecorator extends AbstractRepositoryCollectionDecorator { @Override public void updateRepository(EntityType entityType, EntityType updatedEntityType) { this.indexActionRegisterService.register(entityType, null); delegate().updateRepository(entityType, updatedEntityType); } IndexActionRepositoryCollectionDecorator( RepositoryCollection delegateRepositoryCollection, IndexActionRegisterService indexActionRegisterService); @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); @Override Repository<Entity> createRepository(EntityType entityType); }### Answer: @Test void updateRepository() { EntityType entityType2 = mock(EntityType.class); indexActionRepositoryCollectionDecorator.updateRepository(entityType, entityType2); verify(decoratedRepositoryCollection).updateRepository(entityType, entityType2); verify(indexActionRegisterService).register(entityType, null); }
### Question: IndexActionRepositoryCollectionDecorator extends AbstractRepositoryCollectionDecorator { @Override public void addAttribute(EntityType entityType, Attribute attribute) { this.indexActionRegisterService.register(entityType, null); delegate().addAttribute(entityType, attribute); } IndexActionRepositoryCollectionDecorator( RepositoryCollection delegateRepositoryCollection, IndexActionRegisterService indexActionRegisterService); @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); @Override Repository<Entity> createRepository(EntityType entityType); }### Answer: @Test void addAttribute() { EntityType entityType = when(mock(EntityType.class).getId()).thenReturn(REPOSITORY_NAME).getMock(); Attribute attribute = when(mock(Attribute.class).getName()).thenReturn("attribute").getMock(); indexActionRepositoryCollectionDecorator.addAttribute(entityType, attribute); verify(decoratedRepositoryCollection).addAttribute(entityType, attribute); verify(indexActionRegisterService).register(entityType, null); }
### Question: IndexActionRepositoryCollectionDecorator extends AbstractRepositoryCollectionDecorator { @Override public void deleteAttribute(EntityType entityType, Attribute attr) { this.indexActionRegisterService.register(entityType, null); delegate().deleteAttribute(entityType, attr); } IndexActionRepositoryCollectionDecorator( RepositoryCollection delegateRepositoryCollection, IndexActionRegisterService indexActionRegisterService); @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); @Override Repository<Entity> createRepository(EntityType entityType); }### Answer: @Test void deleteAttribute() { EntityType entityType = when(mock(EntityType.class).getId()).thenReturn(REPOSITORY_NAME).getMock(); Attribute attribute = when(mock(Attribute.class).getName()).thenReturn("attribute").getMock(); indexActionRepositoryCollectionDecorator.deleteAttribute(entityType, attribute); verify(decoratedRepositoryCollection).deleteAttribute(entityType, attribute); verify(indexActionRegisterService).register(entityType, null); }
### Question: IndexActionRepositoryCollectionDecorator extends AbstractRepositoryCollectionDecorator { @Override public Repository<Entity> createRepository(EntityType entityType) { this.indexActionRegisterService.register(entityType, null); return delegate().createRepository(entityType); } IndexActionRepositoryCollectionDecorator( RepositoryCollection delegateRepositoryCollection, IndexActionRegisterService indexActionRegisterService); @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); @Override Repository<Entity> createRepository(EntityType entityType); }### Answer: @Test void addEntityType() { indexActionRepositoryCollectionDecorator.createRepository(entityType); verify(decoratedRepositoryCollection).createRepository(entityType); verify(indexActionRegisterService).register(entityType, null); }
### Question: CsvRepository extends AbstractRepository { public void addCellProcessor(CellProcessor cellProcessor) { if (cellProcessors == null) cellProcessors = new ArrayList<>(); cellProcessors.add(cellProcessor); } CsvRepository( File file, EntityTypeFactory entityTypeFactory, AttributeFactory attrMetaFactory, @Nullable @CheckForNull List<CellProcessor> cellProcessors, Character separator); CsvRepository( File file, EntityTypeFactory entityTypeFactory, AttributeFactory attrMetaFactory, @Nullable @CheckForNull List<CellProcessor> cellProcessors); CsvRepository( File file, EntityTypeFactory entityTypeFactory, AttributeFactory attrMetaFactory, String sheetName, @Nullable @CheckForNull List<CellProcessor> cellProcessors); @NotNull @Override Iterator<Entity> iterator(); EntityType getEntityType(); void addCellProcessor(CellProcessor cellProcessor); @Override Set<RepositoryCapability> getCapabilities(); @Override long count(); }### Answer: @SuppressWarnings("StatementWithEmptyBody") @Test public void addCellProcessorHeader() throws IOException { CellProcessor processor = when(mock(CellProcessor.class).processHeader()).thenReturn(true).getMock(); when(processor.process("col1")).thenReturn("col1"); when(processor.process("col2")).thenReturn("col2"); try (CsvRepository csvRepository = new CsvRepository(test, entityTypeFactory, attrMetaFactory, null)) { csvRepository.addCellProcessor(processor); for (@SuppressWarnings("unused") Entity entity : csvRepository) {} verify(processor).process("col1"); verify(processor).process("col2"); } } @SuppressWarnings("StatementWithEmptyBody") @Test public void addCellProcessorData() throws IOException { CellProcessor processor = when(mock(CellProcessor.class).processData()).thenReturn(true).getMock(); try (CsvRepository csvRepository = new CsvRepository(test, entityTypeFactory, attrMetaFactory, null)) { csvRepository.addCellProcessor(processor); for (@SuppressWarnings("unused") Entity entity : csvRepository) {} verify(processor).process("val1"); verify(processor).process("val2"); } }
### Question: CsvWriter extends AbstractWritable { public CsvWriter(Writer writer) { this(writer, ','); } CsvWriter(Writer writer); CsvWriter(Writer writer, char separator); CsvWriter(Writer writer, char separator, boolean noQuotes); CsvWriter(OutputStream os, char separator); CsvWriter(OutputStream os, char separator, boolean noQuotes); void addCellProcessor(CellProcessor cellProcessor); @Override void add(Entity entity); void writeAttributeNames(Iterable<String> attributeNames); void writeAttributes(Iterable<Attribute> attributes); void writeAttributes(Iterable<String> attributeNames, Iterable<String> attributeLabels); @Override void close(); @Override void flush(); @Override void clearCache(); }### Answer: @SuppressWarnings("resource") @Test void CsvWriter() { assertThrows(IllegalArgumentException.class, () -> new CsvWriter((Writer) null)); }
### Question: CsvWriter extends AbstractWritable { public void addCellProcessor(CellProcessor cellProcessor) { if (cellProcessors == null) cellProcessors = new ArrayList<>(); cellProcessors.add(cellProcessor); } CsvWriter(Writer writer); CsvWriter(Writer writer, char separator); CsvWriter(Writer writer, char separator, boolean noQuotes); CsvWriter(OutputStream os, char separator); CsvWriter(OutputStream os, char separator, boolean noQuotes); void addCellProcessor(CellProcessor cellProcessor); @Override void add(Entity entity); void writeAttributeNames(Iterable<String> attributeNames); void writeAttributes(Iterable<Attribute> attributes); void writeAttributes(Iterable<String> attributeNames, Iterable<String> attributeLabels); @Override void close(); @Override void flush(); @Override void clearCache(); }### Answer: @Test void addCellProcessor() throws IOException { CellProcessor processor = when(mock(CellProcessor.class).processHeader()).thenReturn(true).getMock(); try (CsvWriter csvWriter = new CsvWriter(new StringWriter())) { csvWriter.addCellProcessor(processor); csvWriter.writeAttributeNames(Arrays.asList("col1", "col2")); } verify(processor).process("col1"); verify(processor).process("col2"); }
### Question: CsvWriter extends AbstractWritable { @Override public void add(Entity entity) { if (cachedAttributeNames == null) throw new MolgenisDataException("No attribute names defined call writeAttributeNames first"); int i = 0; String[] values = new String[cachedAttributeNames.size()]; for (String colName : cachedAttributeNames) { values[i++] = toValue(entity.get(colName)); } csvWriter.writeNext(values); if (csvWriter.checkError()) throw new MolgenisDataException("An exception occured writing the csv file"); } CsvWriter(Writer writer); CsvWriter(Writer writer, char separator); CsvWriter(Writer writer, char separator, boolean noQuotes); CsvWriter(OutputStream os, char separator); CsvWriter(OutputStream os, char separator, boolean noQuotes); void addCellProcessor(CellProcessor cellProcessor); @Override void add(Entity entity); void writeAttributeNames(Iterable<String> attributeNames); void writeAttributes(Iterable<Attribute> attributes); void writeAttributes(Iterable<String> attributeNames, Iterable<String> attributeLabels); @Override void close(); @Override void flush(); @Override void clearCache(); }### Answer: @Test void add() throws IOException { StringWriter strWriter = new StringWriter(); try (CsvWriter csvWriter = new CsvWriter(strWriter)) { csvWriter.writeAttributeNames(Arrays.asList("col1", "col2")); Entity entity = new DynamicEntity(entityType); entity.set("col1", "val1"); entity.set("col2", "val2"); csvWriter.add(entity); assertEquals("\"col1\",\"col2\"\n\"val1\",\"val2\"\n", strWriter.toString()); } }
### Question: GlobalControllerExceptionHandler extends SpringExceptionHandler { @ExceptionHandler({ BadRequestException.class, DataConstraintViolationException.class, RepositoryConstraintViolationException.class }) public Object handleBadRequestException(Exception e, HandlerMethod handlerMethod) { return logAndHandleException(e, BAD_REQUEST, handlerMethod); } GlobalControllerExceptionHandler(ExceptionHandlerFacade exceptionHandlerFacade); @ExceptionHandler(UnknownDataException.class) Object handleNotFoundException(Exception e, HandlerMethod handlerMethod); @ExceptionHandler(DataAlreadyExistsException.class) Object handleConflictException(Exception e, HandlerMethod handlerMethod); @ExceptionHandler({ BadRequestException.class, DataConstraintViolationException.class, RepositoryConstraintViolationException.class }) Object handleBadRequestException(Exception e, HandlerMethod handlerMethod); @ExceptionHandler(ForbiddenException.class) Object handleForbiddenException(Exception e, HandlerMethod handlerMethod); @ExceptionHandler(PermissionDeniedException.class) Object handleUnauthorizedException(Exception e, HandlerMethod handlerMethod); }### Answer: @Test void testHandleBadRequestException() { Exception e = mock(Exception.class); HandlerMethod method = mock(HandlerMethod.class); globalControllerExceptionHandler.handleBadRequestException(e, method); verify(exceptionHandlerFacade).logAndHandleException(e, BAD_REQUEST, method); }
### Question: SchemaLoader implements LSResourceResolver { public Schema getSchema() { return schema; } SchemaLoader(String schemaName); SchemaLoader(InputStream is); Schema getSchema(); @Override LSInput resolveResource( String type, String namespaceURI, String publicId, String systemId, String baseURI); }### Answer: @Test void getSchemaFromInputStream() throws IOException { String schemaStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><xs:schema xmlns:xs=\"http: try (InputStream bis = new ByteArrayInputStream(schemaStr.getBytes("UTF-8"))) { SchemaLoader schemaLoader = new SchemaLoader(bis); assertNotNull(schemaLoader.getSchema()); } } @Test void getSchema() { SchemaLoader schemaLoader = new SchemaLoader("example.xsd"); assertNotNull(schemaLoader.getSchema()); }
### Question: FileUploadUtils { public static String getOriginalFileName(Part part) { String contentDisposition = part.getHeader("content-disposition"); if (contentDisposition != null) { for (String cd : contentDisposition.split(";")) { if (cd.trim().startsWith("filename")) { String path = cd.substring(cd.indexOf('=') + 1).replaceAll("\"", "").trim(); Path filename = Paths.get(path).getFileName(); return StringUtils.hasText(filename.toString()) ? filename.toString() : null; } } } return null; } private FileUploadUtils(); static File saveToTempFile(Part part); static File saveToTempFolder(Part part); static String getOriginalFileName(Part part); }### Answer: @Test void getOriginalFileName() { when(part.getHeader("content-disposition")) .thenReturn("form-data; name=\"upload\"; filename=\"example.xls\""); String filename = FileUploadUtils.getOriginalFileName(part); assertEquals("example.xls", filename); } @Test void getOriginalFileNameIE() { when(part.getHeader("content-disposition")) .thenReturn( "form-data; name=\"upload\"; filename=\"c:" + File.separator + "test" + File.separator + "path" + File.separator + "example.xls\""); String filename = FileUploadUtils.getOriginalFileName(part); assertEquals("example.xls", filename); } @Test void getOriginalFileNameWithMissingHeader() { when(part.getHeader("content-disposition")).thenReturn(null); assertNull(FileUploadUtils.getOriginalFileName(part)); } @Test void getOriginalFileNameNoFileSelected() { when(part.getHeader("content-disposition")) .thenReturn("form-data; name=\"upload\"; filename=\"\""); String filename = FileUploadUtils.getOriginalFileName(part); assertNull(filename); }
### Question: FileUploadUtils { public static File saveToTempFile(Part part) throws IOException { String filename = getOriginalFileName(part); if (filename == null) { return null; } File file = File.createTempFile("molgenis-", "." + StringUtils.getFilenameExtension(filename)); FileCopyUtils.copy(part.getInputStream(), new FileOutputStream(file)); return file; } private FileUploadUtils(); static File saveToTempFile(Part part); static File saveToTempFolder(Part part); static String getOriginalFileName(Part part); }### Answer: @Test void saveToTempFile() throws UnsupportedEncodingException, IOException { String fileContent = "Hey dude"; when(part.getHeader("content-disposition")) .thenReturn("form-data; name=\"upload\"; filename=\"example.txt\""); when(part.getInputStream()).thenReturn(new ByteArrayInputStream(fileContent.getBytes("UTF-8"))); File tempFile = FileUploadUtils.saveToTempFile(part); try { assertNotNull(tempFile); assertTrue(tempFile.exists()); assertEquals(fileContent, copyToString(new FileReader(tempFile))); } finally { tempFile.delete(); } }
### Question: ResourceFingerprintRegistry { @SuppressWarnings("unused") public String getFingerprint(String resourceName) throws IOException { return getFingerprint(this.getClass(), resourceName); } ResourceFingerprintRegistry(); @SuppressWarnings("unused") String getFingerprint(String resourceName); String getFingerprint(Class<?> contextClass, String resourceName); }### Answer: @Test void getFingerprint() throws IOException { assertEquals( "czpzLA", new ResourceFingerprintRegistry().getFingerprint(getClass(), "/resource.txt")); }
### Question: CountryCodes { public static Map<String, String> get() { return COUNTRIES; } private CountryCodes(); static Map<String, String> get(); static String get(String countryCode); }### Answer: @Test void testGetString() { assertEquals("Netherlands", get("NL")); } @Test void testGet() { assertEquals(250, get().size()); }
### Question: UnknownPermissionQueryParamException extends BadRequestException { @Override public String getMessage() { return String.format("key:%s", key); } UnknownPermissionQueryParamException(String key); @Override String getMessage(); }### Answer: @Test void testGetMessage() { CodedRuntimeException ex = new UnknownPermissionQueryParamException("type"); assertEquals("key:type", ex.getMessage()); }
### Question: PermissionRsqlVisitor extends NoArgRSQLVisitorAdapter<PermissionsQuery> { @Override public PermissionsQuery visit(AndNode andNode) { throw new UnsupportedPermissionQueryOperatorException(); } @Override PermissionsQuery visit(AndNode andNode); @Override PermissionsQuery visit(OrNode orNode); @Override PermissionsQuery visit(ComparisonNode comparisonNode); }### Answer: @Test void testVisitAnd() { Node node = mock(Node.class); AndNode andNode = new AndNode(Arrays.asList(node, node)); assertThrows(UnsupportedPermissionQueryOperatorException.class, () -> visitor.visit(andNode)); } @Test void testVisit() { ComparisonNode comparisonNode = new ComparisonNode( new ComparisonOperator("=="), "user", Collections.singletonList("user1")); assertEquals(new PermissionsQuery(asList("user1"), emptyList()), visitor.visit(comparisonNode)); } @Test void testVisit2() { ComparisonNode comparisonNode = new ComparisonNode( new ComparisonOperator("=in=", true), "role", Arrays.asList("role1", "role2")); assertEquals( new PermissionsQuery(emptyList(), asList("role1", "role2")), visitor.visit(comparisonNode)); } @Test void testVisitOr() { ComparisonNode comparisonNodeUser = new ComparisonNode( new ComparisonOperator("=="), "user", Collections.singletonList("user1")); ComparisonNode comparisonNodeRole = new ComparisonNode( new ComparisonOperator("=in=", true), "role", Arrays.asList("role1", "role2")); OrNode orNode = new OrNode(Arrays.asList(comparisonNodeUser, comparisonNodeRole)); assertEquals( new PermissionsQuery(asList("user1"), asList("role1", "role2")), visitor.visit(orNode)); }
### Question: UserAccountServiceImpl implements UserAccountService { @Override @Transactional(readOnly = true) public User getCurrentUser() { return userService.getUser(SecurityUtils.getCurrentUsername()); } @Override @Transactional(readOnly = true) User getCurrentUser(); @Override @PreAuthorize("hasAnyRole('ROLE_SU', 'ROLE_USER')") @Transactional void updateCurrentUser(User updatedCurrentUser); @Override @PreAuthorize("hasAnyRole('ROLE_SU', 'ROLE_USER')") @Transactional boolean validateCurrentUserPassword(String password); void setPasswordEncoder(PasswordEncoder passwordEncoder); }### Answer: @Test @WithMockUser(USERNAME_USER) void getCurrentUser() { User existingUser = mock(User.class); when(userService.getUser(USERNAME_USER)).thenReturn(existingUser); assertEquals(existingUser, userAccountServiceImpl.getCurrentUser()); }
### Question: UserAccountServiceImpl implements UserAccountService { @Override @PreAuthorize("hasAnyRole('ROLE_SU', 'ROLE_USER')") @Transactional public void updateCurrentUser(User updatedCurrentUser) { String currentUsername = SecurityUtils.getCurrentUsername(); if (!Objects.equals(currentUsername, updatedCurrentUser.getUsername())) { throw new RuntimeException("Updated user differs from the current user"); } User currentUser = userService.getUser(currentUsername); if (currentUser == null) { throw new RuntimeException("User does not exist [" + currentUsername + "]"); } userService.update(updatedCurrentUser); } @Override @Transactional(readOnly = true) User getCurrentUser(); @Override @PreAuthorize("hasAnyRole('ROLE_SU', 'ROLE_USER')") @Transactional void updateCurrentUser(User updatedCurrentUser); @Override @PreAuthorize("hasAnyRole('ROLE_SU', 'ROLE_USER')") @Transactional boolean validateCurrentUserPassword(String password); void setPasswordEncoder(PasswordEncoder passwordEncoder); }### Answer: @Test @WithMockUser(USERNAME_USER) void updateCurrentUser() { User existingUser = mock(User.class); when(userService.getUser(USERNAME_USER)).thenReturn(existingUser); User updatedUser = mock(User.class); when(updatedUser.getUsername()).thenReturn("username"); userAccountServiceImpl.updateCurrentUser(updatedUser); verify(passwordEncoder, never()).encode("encrypted-password"); } @Test @WithMockUser(USERNAME_USER) void updateCurrentUser_wrongUser() { User updatedUser = mock(User.class); when(updatedUser.getUsername()).thenReturn("wrong-username"); assertThrows( RuntimeException.class, () -> userAccountServiceImpl.updateCurrentUser(updatedUser)); } @Test @WithMockUser(USERNAME_USER) void updateCurrentUser_changePassword() { User existingUser = mock(User.class); when(userService.getUser(USERNAME_USER)).thenReturn(existingUser); User updatedUser = mock(User.class); when(updatedUser.getUsername()).thenReturn("username"); userAccountServiceImpl.updateCurrentUser(updatedUser); }
### Question: UserAccountServiceImpl implements UserAccountService { @Override @PreAuthorize("hasAnyRole('ROLE_SU', 'ROLE_USER')") @Transactional public boolean validateCurrentUserPassword(String password) { if (password == null || password.isEmpty()) return false; String currentUsername = SecurityUtils.getCurrentUsername(); User currentUser = userService.getUser(currentUsername); if (currentUser == null) { throw new RuntimeException( "User does not exist [" + SecurityUtils.getCurrentUsername() + "]"); } return passwordEncoder.matches(password, currentUser.getPassword()); } @Override @Transactional(readOnly = true) User getCurrentUser(); @Override @PreAuthorize("hasAnyRole('ROLE_SU', 'ROLE_USER')") @Transactional void updateCurrentUser(User updatedCurrentUser); @Override @PreAuthorize("hasAnyRole('ROLE_SU', 'ROLE_USER')") @Transactional boolean validateCurrentUserPassword(String password); void setPasswordEncoder(PasswordEncoder passwordEncoder); }### Answer: @Test @WithMockUser(USERNAME_USER) void validateCurrentUserPassword() { User existingUser = mock(User.class); when(existingUser.getPassword()).thenReturn("encrypted-password"); when(passwordEncoder.matches("password", "encrypted-password")).thenReturn(true); when(userService.getUser(USERNAME_USER)).thenReturn(existingUser); assertTrue(userAccountServiceImpl.validateCurrentUserPassword("password")); assertFalse(userAccountServiceImpl.validateCurrentUserPassword("wrong-password")); }
### Question: UserDetailsServiceImpl implements UserDetailsService { @Override @RunAsSystem public UserDetails loadUserByUsername(String username) { User user = dataService .query(UserMetadata.USER, User.class) .eq(UserMetadata.USERNAME, username) .findOne(); if (user == null) { throw new UsernameNotFoundException("unknown user '" + username + "'"); } Collection<? extends GrantedAuthority> authorities = getAuthorities(user); return new org.springframework.security.core.userdetails.User( user.getUsername(), user.getPassword(), user.isActive(), true, true, true, authorities); } UserDetailsServiceImpl( DataService dataService, GrantedAuthoritiesMapper grantedAuthoritiesMapper); @Override @RunAsSystem UserDetails loadUserByUsername(String username); @RunAsSystem Collection<? extends GrantedAuthority> getAuthorities(User user); }### Answer: @Test void testLoadUserByUsernameUnknownUser() { String username = "unknownUser"; @SuppressWarnings("unchecked") Query<User> userQuery = mock(Query.class, RETURNS_SELF); doReturn(userQuery).when(dataService).query(USER, User.class); when(userQuery.eq(USERNAME, username).findOne()).thenReturn(null); Exception exception = assertThrows( UsernameNotFoundException.class, () -> userDetailsServiceImpl.loadUserByUsername(username)); assertThat(exception.getMessage()).containsPattern("unknown user 'unknownUser'"); }
### Question: PasswordResetterImpl implements PasswordResetter { @Transactional(readOnly = true) @RunAsSystem @Override public void validatePasswordResetToken(String username, String token) { User user = getUser(username); passwordResetTokenService.validateToken(user, token); } PasswordResetterImpl( PasswordResetTokenRepository passwordResetTokenRepository, UserService userService, MailSender mailSender, AppSettings appSettings); @Transactional @RunAsSystem @Override void resetPassword(String emailAddress); @Transactional(readOnly = true) @RunAsSystem @Override void validatePasswordResetToken(String username, String token); @Transactional @RunAsSystem @Override void changePassword(String username, String token, String password); @Transactional @Override void changePasswordAuthenticatedUser(String password); }### Answer: @Test void testValidatePasswordResetToken() { String username = "MyUsername"; String token = "MyToken"; User user = mock(User.class); when(userService.getUser(username)).thenReturn(user); passwordResetServiceImpl.validatePasswordResetToken(username, token); verify(passwordResetTokenRepository).validateToken(user, token); } @Test void testValidatePasswordResetTokenUnknownUser() { String username = "MyUsername"; String token = "MyToken"; assertThrows( UnknownUserException.class, () -> passwordResetServiceImpl.validatePasswordResetToken(username, token)); }
### Question: PasswordResetterImpl implements PasswordResetter { @Transactional @RunAsSystem @Override public void changePassword(String username, String token, String password) { User user = getUser(username); passwordResetTokenService.validateToken(user, token); user.setPassword(password); userService.update(user); passwordResetTokenService.deleteToken(user, token); } PasswordResetterImpl( PasswordResetTokenRepository passwordResetTokenRepository, UserService userService, MailSender mailSender, AppSettings appSettings); @Transactional @RunAsSystem @Override void resetPassword(String emailAddress); @Transactional(readOnly = true) @RunAsSystem @Override void validatePasswordResetToken(String username, String token); @Transactional @RunAsSystem @Override void changePassword(String username, String token, String password); @Transactional @Override void changePasswordAuthenticatedUser(String password); }### Answer: @Test void testChangePassword() { String username = "MyUsername"; String token = "MyToken"; String password = "MyPassword"; User user = mock(User.class); when(userService.getUser(username)).thenReturn(user); passwordResetServiceImpl.changePassword(username, token, password); verify(passwordResetTokenRepository).validateToken(user, token); verify(user).setPassword(password); verify(userService).update(user); verify(passwordResetTokenRepository).deleteToken(user, token); } @Test void testChangePasswordUnknownUser() { String username = "MyUsername"; String token = "MyToken"; String password = "MyPassword"; assertThrows( UnknownUserException.class, () -> passwordResetServiceImpl.changePassword(username, token, password)); }
### Question: PasswordResetterImpl implements PasswordResetter { @Transactional @Override public void changePasswordAuthenticatedUser(String password) { String username = SecurityUtils.getCurrentUsername(); if (username == null) { throw new AuthenticationCredentialsNotFoundException("not authenticated"); } User user = getUser(username); user.setPassword(password); user.setChangePassword(false); RunAsSystemAspect.runAsSystem(() -> userService.update(user)); } PasswordResetterImpl( PasswordResetTokenRepository passwordResetTokenRepository, UserService userService, MailSender mailSender, AppSettings appSettings); @Transactional @RunAsSystem @Override void resetPassword(String emailAddress); @Transactional(readOnly = true) @RunAsSystem @Override void validatePasswordResetToken(String username, String token); @Transactional @RunAsSystem @Override void changePassword(String username, String token, String password); @Transactional @Override void changePasswordAuthenticatedUser(String password); }### Answer: @Test void testChangePasswordAuthenticatedUser() { String username = "MyUsername"; String password = "MyPassword"; SecurityContext securityContext = mock(SecurityContext.class); Authentication authentication = new UsernamePasswordAuthenticationToken(username, "MyCurrentPassword"); when(securityContext.getAuthentication()).thenReturn(authentication); SecurityContextHolder.setContext(securityContext); User user = mock(User.class); when(userService.getUser(username)).thenReturn(user); passwordResetServiceImpl.changePasswordAuthenticatedUser(password); verify(user).setChangePassword(false); verify(userService).update(user); } @Test void testChangePasswordAuthenticatedUserNoAuthenticedUser() { SecurityContext securityContext = mock(SecurityContext.class); SecurityContextHolder.setContext(securityContext); assertThrows( AuthenticationCredentialsNotFoundException.class, () -> passwordResetServiceImpl.changePasswordAuthenticatedUser("MyPassword")); }
### Question: AclCacheTransactionListener implements TransactionListener { public AclCacheTransactionListener(AclCache aclCache, MutableAclClassService aclClassService) { this.aclCache = requireNonNull(aclCache); this.aclClassService = requireNonNull(aclClassService); } AclCacheTransactionListener(AclCache aclCache, MutableAclClassService aclClassService); @Override void rollbackTransaction(String transactionId); }### Answer: @Test void testAclCacheTransactionListener() { assertThrows( NullPointerException.class, () -> new AclCacheTransactionListener(null, mutableAclClassService)); }
### Question: AclCacheTransactionListener implements TransactionListener { @Override public void rollbackTransaction(String transactionId) { aclCache.clearCache(); aclClassService.clearCache(); } AclCacheTransactionListener(AclCache aclCache, MutableAclClassService aclClassService); @Override void rollbackTransaction(String transactionId); }### Answer: @Test void testRollbackTransaction() { aclCacheTransactionListener.rollbackTransaction("transactionId"); verify(aclCache).clearCache(); verify(mutableAclClassService).clearCache(); }
### Question: MutableAclClassServiceImpl implements MutableAclClassService { @Transactional @Override public void createAclClass(String type, Class<?> idType) { LOGGER.debug("Create AclClass for type {}.", type); jdbcTemplate.update(SQL_INSERT_INTO_ACL_CLASS, type, idType.getCanonicalName()); aclClassCache.invalidate(type); } MutableAclClassServiceImpl(JdbcTemplate jdbcTemplate, AclCache aclCache); @Transactional @Override void createAclClass(String type, Class<?> idType); @Transactional @Override void deleteAclClass(String type); @Override void clearCache(); @SuppressWarnings("ConstantConditions") @Override boolean hasAclClass(String type); @Override Collection<String> getAclClassTypes(); }### Answer: @Test void testCreateAclClass() { String type = "MyType"; mutableAclClassService.createAclClass(type, String.class); verify(jdbcTemplate) .update( "insert into acl_class (class, class_id_type) values (?, ?)", type, "java.lang.String"); verifyZeroInteractions(aclCache); }
### Question: MutableAclClassServiceImpl implements MutableAclClassService { @Transactional @Override public void deleteAclClass(String type) { LOGGER.debug("Delete AclClass for type {}.", type); jdbcTemplate.update(SQL_DELETE_FROM_ACL_CLASS, type); aclClassCache.invalidate(type); aclCache.clearCache(); } MutableAclClassServiceImpl(JdbcTemplate jdbcTemplate, AclCache aclCache); @Transactional @Override void createAclClass(String type, Class<?> idType); @Transactional @Override void deleteAclClass(String type); @Override void clearCache(); @SuppressWarnings("ConstantConditions") @Override boolean hasAclClass(String type); @Override Collection<String> getAclClassTypes(); }### Answer: @Test void testDeleteAclClass() { String type = "MyType"; mutableAclClassService.deleteAclClass(type); verify(jdbcTemplate).update("delete from acl_class where class=?", type); verify(aclCache).clearCache(); }
### Question: MutableAclClassServiceImpl implements MutableAclClassService { @SuppressWarnings("ConstantConditions") @Override public boolean hasAclClass(String type) { boolean result = aclClassCache.get( type, t -> jdbcTemplate.queryForObject( SQL_COUNT_ACL_CLASS, new Object[] {t}, Integer.class)) > 0; LOGGER.trace("hasAclClass({}): {}", type, result); return result; } MutableAclClassServiceImpl(JdbcTemplate jdbcTemplate, AclCache aclCache); @Transactional @Override void createAclClass(String type, Class<?> idType); @Transactional @Override void deleteAclClass(String type); @Override void clearCache(); @SuppressWarnings("ConstantConditions") @Override boolean hasAclClass(String type); @Override Collection<String> getAclClassTypes(); }### Answer: @Test void testHasAclClassFalseCached() { String type = "MyType"; when(jdbcTemplate.queryForObject( "select count(*) from acl_class WHERE class = ?", new Object[] {type}, Integer.class)) .thenReturn(0); assertFalse(mutableAclClassService.hasAclClass(type)); assertFalse(mutableAclClassService.hasAclClass(type)); verifyZeroInteractions(aclCache); verify(jdbcTemplate, times(1)) .queryForObject( "select count(*) from acl_class WHERE class = ?", new Object[] {type}, Integer.class); }
### Question: MutableAclClassServiceImpl implements MutableAclClassService { @Override public Collection<String> getAclClassTypes() { return jdbcTemplate.queryForList(SQL_SELECT_ACL_CLASS, String.class); } MutableAclClassServiceImpl(JdbcTemplate jdbcTemplate, AclCache aclCache); @Transactional @Override void createAclClass(String type, Class<?> idType); @Transactional @Override void deleteAclClass(String type); @Override void clearCache(); @SuppressWarnings("ConstantConditions") @Override boolean hasAclClass(String type); @Override Collection<String> getAclClassTypes(); }### Answer: @Test void testGetAclClassTypes() { List<String> aclClassTypes = asList("MyType0", "MyType1"); when(jdbcTemplate.queryForList("select class from acl_class", String.class)) .thenReturn(aclClassTypes); assertEquals(aclClassTypes, mutableAclClassService.getAclClassTypes()); verifyZeroInteractions(aclCache); }
### Question: TokenAuthenticationFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; if (!httpRequest.getRequestURI().endsWith("login") && !httpRequest.getRequestURI().endsWith("logout")) { String token = TokenExtractor.getToken(httpRequest); if (StringUtils.isNotBlank(token)) { try { RestAuthenticationToken authToken = new RestAuthenticationToken(token); Authentication authentication = authenticationProvider.authenticate(authToken); if (authentication.isAuthenticated()) { SecurityContextHolder.getContext().setAuthentication(authentication); } } catch (AuthenticationException e) { } } } chain.doFilter(request, response); } TokenAuthenticationFilter(AuthenticationProvider authenticationProvider); @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); }### Answer: @Test void doFilter() throws IOException, ServletException { SecurityContext previous = SecurityContextHolder.getContext(); try { SecurityContext testContext = SecurityContextHolder.createEmptyContext(); SecurityContextHolder.setContext(testContext); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); RestAuthenticationToken auth = new RestAuthenticationToken( "admin", "admin", Arrays.asList(new SimpleGrantedAuthority("admin")), "token"); request.setRequestURI("/api/v1/dataset"); request.addHeader(TokenExtractor.TOKEN_HEADER, "token"); when(authenticationProvider.authenticate(new RestAuthenticationToken("token"))) .thenReturn(auth); filter.doFilter(request, response, chain); verify(chain).doFilter(request, response); assertEquals(auth, getContext().getAuthentication()); } finally { SecurityContextHolder.setContext(previous); } }
### Question: RunAsUserTokenFactory { public RunAsUserToken create( String key, UserDetails userDetails, Class<? extends Authentication> originalAuthentication) { userDetailsChecker.check(userDetails); return new RunAsUserToken( key, userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities(), originalAuthentication); } RunAsUserTokenFactory(UserDetailsChecker userDetailsChecker); RunAsUserToken create( String key, UserDetails userDetails, Class<? extends Authentication> originalAuthentication); }### Answer: @Test void testTokenForEnabledUser() { UserDetails userDetails = mock(UserDetails.class); runAsUserTokenFactory.create("test", userDetails, null); verify(userDetailsChecker).check(userDetails); } @Test void testTokenForDisabledUser() { UserDetails userDetails = mock(UserDetails.class); doThrow(new DisabledException("User is disabled.")).when(userDetailsChecker).check(userDetails); assertThrows( DisabledException.class, () -> runAsUserTokenFactory.create("test", userDetails, null)); }
### Question: TokenGenerator { public String generateToken() { return UUID.randomUUID().toString().replace("-", ""); } String generateToken(); }### Answer: @Test void generateToken() { TokenGenerator tg = new TokenGenerator(); String token = tg.generateToken(); assertNotNull(token); assertFalse(token.contains("-")); assertFalse(tg.generateToken().equals(token)); }
### Question: TokenAuthenticationProvider implements AuthenticationProvider { @Override @RunAsSystem public Authentication authenticate(Authentication authentication) { if (!supports(authentication.getClass())) throw new IllegalArgumentException("Only RestAuthenticationToken is supported"); RestAuthenticationToken authToken = (RestAuthenticationToken) authentication; if (authToken.getToken() != null) { UserDetails userDetails = tokenService.findUserByToken(authToken.getToken()); userDetailsChecker.check(userDetails); authToken = new RestAuthenticationToken( userDetails, userDetails.getPassword(), userDetails.getAuthorities(), authToken.getToken()); } return authToken; } TokenAuthenticationProvider( TokenService tokenService, UserDetailsChecker userDetailsChecker); @Override @RunAsSystem Authentication authenticate(Authentication authentication); @Override boolean supports(Class<?> authentication); }### Answer: @Test void authenticate() { RestAuthenticationToken authToken = new RestAuthenticationToken("token"); assertFalse(authToken.isAuthenticated()); when(tokenService.findUserByToken("token")) .thenReturn( new User("username", "password", Arrays.asList(new SimpleGrantedAuthority("admin")))); Authentication auth = tokenAuthenticationProvider.authenticate(authToken); assertNotNull(auth); assertTrue(auth.isAuthenticated()); assertEquals("username", auth.getName()); assertEquals(1, auth.getAuthorities().size()); assertEquals("admin", auth.getAuthorities().iterator().next().getAuthority()); } @Test void authenticateInvalidToken() { when(tokenService.findUserByToken("token")) .thenThrow(new UnknownTokenException("Invalid token")); assertThrows( AuthenticationException.class, () -> tokenAuthenticationProvider.authenticate(new RestAuthenticationToken("token"))); }
### Question: TokenExtractor implements HandlerMethodArgumentResolver { public static String getToken(HttpServletRequest request) { return getTokenInternal(request.getHeader(TOKEN_HEADER), request.getParameter(TOKEN_PARAMETER)); } static String getToken(HttpServletRequest request); @SuppressWarnings("java:S2259") // we use supportsParameter to check if the parameter is available @Override @Nullable @CheckForNull Object resolveArgument( MethodParameter parameter, @Nullable @CheckForNull ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @Nullable @CheckForNull WebDataBinderFactory binderFactory); @Override boolean supportsParameter(MethodParameter parameter); static final String TOKEN_HEADER; static final String TOKEN_PARAMETER; }### Answer: @Test void testGetTokenFromHeader() { when(request.getHeader(TOKEN_HEADER)).thenReturn(TEST_TOKEN); assertEquals(TEST_TOKEN, getToken(request)); } @Test void testGetTokenFromParam() { when(request.getParameter(TOKEN_PARAMETER)).thenReturn(TEST_TOKEN); assertEquals(TEST_TOKEN, getToken(request)); }
### Question: DataServiceTokenService implements TokenService { @Override @Transactional @RunAsSystem public String generateAndStoreToken(String username, String description) { User user = dataService.query(USER, User.class).eq(USERNAME, username).findOne(); if (user == null) { throw new IllegalArgumentException(format("Unknown username [%s]", username)); } String token = tokenGenerator.generateToken(); Token molgenisToken = tokenFactory.create(); molgenisToken.setUser(user); molgenisToken.setToken(token); molgenisToken.setDescription(description); molgenisToken.setExpirationDate(now().plus(2, HOURS)); dataService.add(TOKEN, molgenisToken); return token; } DataServiceTokenService( TokenGenerator tokenGenerator, DataService dataService, UserDetailsService userDetailsService, TokenFactory tokenFactory); @Override @Transactional(readOnly = true) @RunAsSystem UserDetails findUserByToken(String token); @Override @Transactional @RunAsSystem String generateAndStoreToken(String username, String description); @Override @Transactional @RunAsSystem void removeToken(String token); }### Answer: @Test void generateAndStoreToken() { User user = mock(User.class); @SuppressWarnings("unchecked") Query<User> q = mock(Query.class); when(q.eq(USERNAME, "admin")).thenReturn(q); when(q.findOne()).thenReturn(user); when(dataService.query(USER, User.class)).thenReturn(q); when(tokenGenerator.generateToken()).thenReturn("token"); assertEquals("token", tokenService.generateAndStoreToken("admin", "description")); ArgumentCaptor<Token> argumentCaptor = ArgumentCaptor.forClass(Token.class); verify(dataService).add(eq(TOKEN), argumentCaptor.capture()); Token token = argumentCaptor.getValue(); verify(token).setToken("token"); }
### Question: DataServiceTokenService implements TokenService { @Override @Transactional @RunAsSystem public void removeToken(String token) { Token molgenisToken = getMolgenisToken(token); dataService.delete(TOKEN, molgenisToken); } DataServiceTokenService( TokenGenerator tokenGenerator, DataService dataService, UserDetailsService userDetailsService, TokenFactory tokenFactory); @Override @Transactional(readOnly = true) @RunAsSystem UserDetails findUserByToken(String token); @Override @Transactional @RunAsSystem String generateAndStoreToken(String username, String description); @Override @Transactional @RunAsSystem void removeToken(String token); }### Answer: @Test void removeToken() { Token token = mock(Token.class); when(token.getToken()).thenReturn("token"); @SuppressWarnings("unchecked") Query<Token> q = mock(Query.class); when(q.eq(TOKEN_ATTR, "token")).thenReturn(q); when(q.findOne()).thenReturn(token); when(dataService.query(TOKEN, Token.class)).thenReturn(q); tokenService.removeToken("token"); verify(dataService).delete(TOKEN, token); }
### Question: GlobalControllerExceptionHandler extends SpringExceptionHandler { @ExceptionHandler(ForbiddenException.class) public Object handleForbiddenException(Exception e, HandlerMethod handlerMethod) { return logAndHandleException(e, FORBIDDEN, handlerMethod); } GlobalControllerExceptionHandler(ExceptionHandlerFacade exceptionHandlerFacade); @ExceptionHandler(UnknownDataException.class) Object handleNotFoundException(Exception e, HandlerMethod handlerMethod); @ExceptionHandler(DataAlreadyExistsException.class) Object handleConflictException(Exception e, HandlerMethod handlerMethod); @ExceptionHandler({ BadRequestException.class, DataConstraintViolationException.class, RepositoryConstraintViolationException.class }) Object handleBadRequestException(Exception e, HandlerMethod handlerMethod); @ExceptionHandler(ForbiddenException.class) Object handleForbiddenException(Exception e, HandlerMethod handlerMethod); @ExceptionHandler(PermissionDeniedException.class) Object handleUnauthorizedException(Exception e, HandlerMethod handlerMethod); }### Answer: @Test void testHandleForbiddenException() { Exception e = mock(Exception.class); HandlerMethod method = mock(HandlerMethod.class); globalControllerExceptionHandler.handleForbiddenException(e, method); verify(exceptionHandlerFacade).logAndHandleException(e, FORBIDDEN, method); }
### Question: MolgenisLoginController { @GetMapping(params = PARAM_SESSION_EXPIRED) public String getLoginErrorPage(Model model) { model.addAttribute(ERROR_MESSAGE_ATTRIBUTE, ERROR_MESSAGE_SESSION_AUTHENTICATION); return VIEW_LOGIN; } @GetMapping String getLoginPage(HttpServletRequest httpServletRequest, Model model); @GetMapping(params = PARAM_SESSION_EXPIRED) String getLoginErrorPage(Model model); @GetMapping(params = "error") String getLoginErrorPage(Model model, HttpServletRequest request); static final String PARAM_SESSION_EXPIRED; static final String URI; static final String ERROR_MESSAGE_ATTRIBUTE; static final String ERROR_MESSAGE_DISABLED; static final String SPRING_SECURITY_CONTEXT; static final String SPRING_SECURITY_SAVED_REQUEST; static final String JSESSIONID; }### Answer: @Test void getLoginErrorPage() throws Exception { this.mockMvc .perform(get("/login").param("error", "")) .andExpect(status().isOk()) .andExpect(view().name("view-login")) .andExpect(model().attributeExists("errorMessage")); }
### Question: TwoFactorAuthenticationController { @GetMapping(TWO_FACTOR_CONFIGURED_URI) public String configured() { return VIEW_2FA_CONFIGURED_MODAL; } TwoFactorAuthenticationController( TwoFactorAuthenticationProvider authenticationProvider, TwoFactorAuthenticationService twoFactorAuthenticationService, RecoveryAuthenticationProvider recoveryAuthenticationProvider, OtpService otpService); @GetMapping(TWO_FACTOR_CONFIGURED_URI) String configured(); @PostMapping(TWO_FACTOR_VALIDATION_URI) String validate(Model model, @RequestParam String verificationCode); @GetMapping(TWO_FACTOR_ACTIVATION_URI) String activation(Model model); @PostMapping(TWO_FACTOR_ACTIVATION_AUTHENTICATE_URI) String authenticate( Model model, @RequestParam String verificationCode, @RequestParam String secretKey); @PostMapping(TWO_FACTOR_RECOVER_URI) String recoverAccount(Model model, @RequestParam String recoveryCode); static final String URI; static final String TWO_FACTOR_ACTIVATION_URI; static final String ATTRIBUTE_2FA_SECRET_KEY; static final String TWO_FACTOR_CONFIGURED_URI; }### Answer: @Test void configuredExceptionTest() { String viewTemplate = twoFactorAuthenticationController.configured(); assertEquals("view-2fa-configured-modal", viewTemplate); }
### Question: TwoFactorAuthenticationController { @PostMapping(TWO_FACTOR_RECOVER_URI) public String recoverAccount(Model model, @RequestParam String recoveryCode) { String redirectUrl = "redirect:/"; try { RecoveryAuthenticationToken authToken = new RecoveryAuthenticationToken(recoveryCode); Authentication authentication = recoveryAuthenticationProvider.authenticate(authToken); SecurityContextHolder.getContext().setAuthentication(authentication); } catch (AuthenticationException e) { model.addAttribute(ATTRIBUTE_2FA_RECOVER_MODE, true); model.addAttribute(MolgenisLoginController.ERROR_MESSAGE_ATTRIBUTE, determineErrorMessage(e)); redirectUrl = VIEW_2FA_CONFIGURED_MODAL; } return redirectUrl; } TwoFactorAuthenticationController( TwoFactorAuthenticationProvider authenticationProvider, TwoFactorAuthenticationService twoFactorAuthenticationService, RecoveryAuthenticationProvider recoveryAuthenticationProvider, OtpService otpService); @GetMapping(TWO_FACTOR_CONFIGURED_URI) String configured(); @PostMapping(TWO_FACTOR_VALIDATION_URI) String validate(Model model, @RequestParam String verificationCode); @GetMapping(TWO_FACTOR_ACTIVATION_URI) String activation(Model model); @PostMapping(TWO_FACTOR_ACTIVATION_AUTHENTICATE_URI) String authenticate( Model model, @RequestParam String verificationCode, @RequestParam String secretKey); @PostMapping(TWO_FACTOR_RECOVER_URI) String recoverAccount(Model model, @RequestParam String recoveryCode); static final String URI; static final String TWO_FACTOR_ACTIVATION_URI; static final String ATTRIBUTE_2FA_SECRET_KEY; static final String TWO_FACTOR_CONFIGURED_URI; }### Answer: @Test @WithMockUser(value = USERNAME, roles = ROLE_SU) void testRecoverAccount() { String recoveryCodeId = "123456"; Model model = new ExtendedModelMap(); String viewTemplate = twoFactorAuthenticationController.recoverAccount(model, recoveryCodeId); assertEquals("redirect:/", viewTemplate); }
### Question: TwoFactorAuthenticationServiceImpl implements TwoFactorAuthenticationService { @Override public String generateSecretKey() { return idGenerator.generateId(SECURE_RANDOM); } TwoFactorAuthenticationServiceImpl( OtpService otpService, DataService dataService, UserService userService, IdGenerator idGenerator, UserSecretFactory userSecretFactory); @Override boolean isVerificationCodeValidForUser(String verificationCode); @Override boolean userIsBlocked(); @Override void saveSecretForUser(String secret); @Override void resetSecretForUser(); @Override void enableForUser(); @Override void disableForUser(); @Override String generateSecretKey(); @Override boolean isConfiguredForUser(); }### Answer: @Test void generateSecretKeyTest() { String key = twoFactorAuthenticationServiceImpl.generateSecretKey(); assertTrue(key.matches("^[a-z0-9]+$")); } @Test void generateWrongSecretKeyTest() { String key = twoFactorAuthenticationServiceImpl.generateSecretKey(); assertTrue(!key.matches("^[A-Z0-9]+$")); }
### Question: TwoFactorAuthenticationServiceImpl implements TwoFactorAuthenticationService { @Override public boolean isConfiguredForUser() { boolean isConfigured = false; try { UserSecret secret = getSecret(); if (StringUtils.hasText(secret.getSecret())) { isConfigured = true; } } catch (InternalAuthenticationServiceException err) { LOG.warn(err.getMessage()); } return isConfigured; } TwoFactorAuthenticationServiceImpl( OtpService otpService, DataService dataService, UserService userService, IdGenerator idGenerator, UserSecretFactory userSecretFactory); @Override boolean isVerificationCodeValidForUser(String verificationCode); @Override boolean userIsBlocked(); @Override void saveSecretForUser(String secret); @Override void resetSecretForUser(); @Override void enableForUser(); @Override void disableForUser(); @Override String generateSecretKey(); @Override boolean isConfiguredForUser(); }### Answer: @Test @WithMockUser(value = USERNAME, roles = ROLE_SU) void isConfiguredForUserTest() { User molgenisUser = mock(User.class); UserSecret userSecret = mock(UserSecret.class); when(molgenisUser.getId()).thenReturn("1324"); when(userService.getUser(USERNAME)).thenReturn(molgenisUser); Query<UserSecret> userSecretQuery = mock(Query.class, RETURNS_SELF); when(dataService.query(UserSecretMetadata.USER_SECRET, UserSecret.class)) .thenReturn(userSecretQuery); when(userSecretQuery.eq(UserSecretMetadata.USER_ID, molgenisUser.getId()).findOne()) .thenReturn(userSecret); when(userSecret.getSecret()).thenReturn("secretKey"); boolean isConfigured = twoFactorAuthenticationServiceImpl.isConfiguredForUser(); assertTrue(isConfigured); }
### Question: TwoFactorAuthenticationServiceImpl implements TwoFactorAuthenticationService { @Override public void disableForUser() { User user = getUser(); user.setTwoFactorAuthentication(false); userService.update(user); UserSecret userSecret = getSecret(); runAsSystem(() -> dataService.delete(USER_SECRET, userSecret)); } TwoFactorAuthenticationServiceImpl( OtpService otpService, DataService dataService, UserService userService, IdGenerator idGenerator, UserSecretFactory userSecretFactory); @Override boolean isVerificationCodeValidForUser(String verificationCode); @Override boolean userIsBlocked(); @Override void saveSecretForUser(String secret); @Override void resetSecretForUser(); @Override void enableForUser(); @Override void disableForUser(); @Override String generateSecretKey(); @Override boolean isConfiguredForUser(); }### Answer: @Test @WithMockUser(value = USERNAME, roles = ROLE_SU) void testDisableForUser() { User molgenisUser = mock(User.class); UserSecret userSecret = mock(UserSecret.class); when(molgenisUser.getUsername()).thenReturn(USERNAME); when(molgenisUser.getId()).thenReturn("1324"); when(userService.getUser(USERNAME)).thenReturn(molgenisUser); Query<UserSecret> userSecretQuery = mock(Query.class, RETURNS_SELF); when(dataService.query(UserSecretMetadata.USER_SECRET, UserSecret.class)) .thenReturn(userSecretQuery); when(userSecretQuery.eq(UserSecretMetadata.USER_ID, molgenisUser.getId()).findOne()) .thenReturn(userSecret); when(userService.getUser(molgenisUser.getUsername())).thenReturn(molgenisUser); when(dataService .query(UserSecretMetadata.USER_SECRET, UserSecret.class) .eq(UserSecretMetadata.USER_ID, molgenisUser.getId()) .findOne()) .thenReturn(userSecret); twoFactorAuthenticationServiceImpl.disableForUser(); }
### Question: RecoveryServiceImpl implements RecoveryService { @Override @Transactional public Stream<RecoveryCode> generateRecoveryCodes() { String userId = getUser().getId(); deleteOldRecoveryCodes(userId); List<RecoveryCode> newRecoveryCodes = generateRecoveryCodes(userId); runAsSystem((Runnable) () -> dataService.add(RECOVERY_CODE, newRecoveryCodes.stream())); return newRecoveryCodes.stream(); } RecoveryServiceImpl( DataService dataService, UserService userService, RecoveryCodeFactory recoveryCodeFactory, IdGenerator idGenerator); @Override @Transactional Stream<RecoveryCode> generateRecoveryCodes(); @Override @Transactional void useRecoveryCode(String recoveryCode); @Override Stream<RecoveryCode> getRecoveryCodes(); }### Answer: @Test @WithMockUser(value = USERNAME, roles = ROLE_SU) void testGenerateRecoveryCodes() { User molgenisUser = mock(User.class); RecoveryCode recoveryCode = mock(RecoveryCode.class); when(userService.getUser(USERNAME)).thenReturn(molgenisUser); when(molgenisUser.getId()).thenReturn("1234"); @SuppressWarnings("unchecked") Query<RecoveryCode> query = mock(Query.class, RETURNS_SELF); when(dataService.query(RecoveryCodeMetadata.RECOVERY_CODE, RecoveryCode.class)) .thenReturn(query); when(query.eq(USER_ID, molgenisUser.getId()).findAll()) .thenReturn(IntStream.range(0, 1).mapToObj(i -> recoveryCode)); when(recoveryCodeFactory.create()).thenReturn(recoveryCode); Stream<RecoveryCode> recoveryCodeStream = recoveryServiceImpl.generateRecoveryCodes(); assertEquals(recoveryCodeStream.count(), 10); }
### Question: RecoveryServiceImpl implements RecoveryService { @Override public Stream<RecoveryCode> getRecoveryCodes() { String userId = getUser().getId(); return runAsSystem( () -> dataService.query(RECOVERY_CODE, RecoveryCode.class).eq(USER_ID, userId).findAll()); } RecoveryServiceImpl( DataService dataService, UserService userService, RecoveryCodeFactory recoveryCodeFactory, IdGenerator idGenerator); @Override @Transactional Stream<RecoveryCode> generateRecoveryCodes(); @Override @Transactional void useRecoveryCode(String recoveryCode); @Override Stream<RecoveryCode> getRecoveryCodes(); }### Answer: @Test @WithMockUser(value = USERNAME, roles = ROLE_SU) void testGetRecoveryCodes() { User molgenisUser = mock(User.class); RecoveryCode recoveryCode = mock(RecoveryCode.class); when(userService.getUser(USERNAME)).thenReturn(molgenisUser); when(molgenisUser.getId()).thenReturn("1234"); @SuppressWarnings("unchecked") Query<RecoveryCode> query = mock(Query.class, RETURNS_SELF); when(dataService.query(RecoveryCodeMetadata.RECOVERY_CODE, RecoveryCode.class)) .thenReturn(query); when(query.eq(USER_ID, molgenisUser.getId()).findAll()) .thenReturn(IntStream.range(0, 1).mapToObj(i -> recoveryCode)); when(dataService .query(RECOVERY_CODE, RecoveryCode.class) .eq(USER_ID, molgenisUser.getId()) .findAll()) .thenReturn(Stream.of(recoveryCode)); Stream<RecoveryCode> recoveryCodeList = recoveryServiceImpl.getRecoveryCodes(); assertEquals(recoveryCodeList.count(), 1); }
### Question: OtpServiceImpl implements OtpService { @Override public boolean tryVerificationCode(String verificationCode, String secretKey) { boolean isValid; if (StringUtils.hasText(secretKey)) { if (verificationCode == null) { throw new InvalidVerificationCodeException("Verificationcode is mandatory"); } else { final Totp totp = new Totp(secretKey); if (isValidLong(verificationCode) && totp.verify(verificationCode)) { isValid = true; } else { throw new InvalidVerificationCodeException("Invalid verification code entered"); } } } else { throw new InvalidVerificationCodeException( "Two factor authentication secret key is not available"); } return isValid; } OtpServiceImpl(AppSettings appSettings); @Override boolean tryVerificationCode(String verificationCode, String secretKey); @Override String getAuthenticatorURI(String secretKey); }### Answer: @Test void testTryVerificationKeyFailed() { assertThrows( InvalidVerificationCodeException.class, () -> otpServiceImpl.tryVerificationCode("", "secretKey")); }
### Question: OtpServiceImpl implements OtpService { @Override public String getAuthenticatorURI(String secretKey) { String userName = SecurityUtils.getCurrentUsername(); String appName = appSettings.getTitle(); if (userName == null) { String errorMessage = "User is not available"; LOG.error(errorMessage); throw new IllegalStateException(errorMessage); } String normalizedBase32Key = secretKey.replace(" ", "").toUpperCase(); try { return String.format( "otpauth: URLEncoder.encode(appName + ":" + userName, "UTF-8").replace("+", "%20"), URLEncoder.encode(normalizedBase32Key, "UTF-8").replace("+", "%20"), URLEncoder.encode(appName, "UTF-8").replace("+", "%20")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } OtpServiceImpl(AppSettings appSettings); @Override boolean tryVerificationCode(String verificationCode, String secretKey); @Override String getAuthenticatorURI(String secretKey); }### Answer: @Test @WithMockUser(value = USERNAME, roles = ROLE_SU) void testGetAuthenticatorURI() { when(appSettings.getTitle()).thenReturn("MOLGENIS"); String uri = otpServiceImpl.getAuthenticatorURI("secretKey"); assertFalse(uri.isEmpty()); }
### Question: PrincipalSecurityContextRegistryImpl implements PrincipalSecurityContextRegistry { @Override public Stream<SecurityContext> getSecurityContexts(Object principal) { Set<SecurityContext> securityContexts = new HashSet<>(); SecurityContext currentExecutionThreadSecurityContext = getSecurityContextCurrentExecutionThread(principal); if (currentExecutionThreadSecurityContext != null) { securityContexts.add(currentExecutionThreadSecurityContext); } getSecurityContextsFromRegistry(principal).forEach(securityContexts::add); return securityContexts.stream(); } PrincipalSecurityContextRegistryImpl(SecurityContextRegistry securityContextRegistry); @Override Stream<SecurityContext> getSecurityContexts(Object principal); }### Answer: @WithMockUser(username = "user") @Test void testGetSecurityContextsUserThreadNoUserSessions() { SecurityContext securityContext = SecurityContextHolder.getContext(); Object user = securityContext.getAuthentication().getPrincipal(); assertEquals( singletonList(securityContext), principalSecurityContextRegistryImpl.getSecurityContexts(user).collect(toList())); }
### Question: MolgenisPermissionController { public MolgenisPermissionController(UserPermissionEvaluator permissionService) { this.permissionService = requireNonNull(permissionService); } MolgenisPermissionController(UserPermissionEvaluator permissionService); @GetMapping("/{entityTypeId}/read") @ResponseBody boolean hasReadPermission(@PathVariable("entityTypeId") String entityTypeId); @GetMapping("/{entityTypeId}/write") @ResponseBody boolean hasWritePermission(@PathVariable("entityTypeId") String entityTypeId); }### Answer: @Test void MolgenisPermissionController() { assertThrows(NullPointerException.class, () -> new MolgenisPermissionController(null)); }
### Question: MolgenisPermissionController { @GetMapping("/{entityTypeId}/read") @ResponseBody public boolean hasReadPermission(@PathVariable("entityTypeId") String entityTypeId) { return permissionService.hasPermission( new EntityTypeIdentity(entityTypeId), EntityTypePermission.READ_METADATA) && permissionService.hasPermission( new EntityTypeIdentity(entityTypeId), EntityTypePermission.READ_DATA); } MolgenisPermissionController(UserPermissionEvaluator permissionService); @GetMapping("/{entityTypeId}/read") @ResponseBody boolean hasReadPermission(@PathVariable("entityTypeId") String entityTypeId); @GetMapping("/{entityTypeId}/write") @ResponseBody boolean hasWritePermission(@PathVariable("entityTypeId") String entityTypeId); }### Answer: @Test void hasReadPermissionTrue() { String entityTypeId = "entity"; when(permissionService.hasPermission( new EntityTypeIdentity(entityTypeId), EntityTypePermission.READ_DATA)) .thenReturn(true); when(permissionService.hasPermission( new EntityTypeIdentity(entityTypeId), EntityTypePermission.READ_METADATA)) .thenReturn(true); assertTrue(molgenisPermissionController.hasReadPermission(entityTypeId)); } @Test void hasReadPermissionFalse() { String entityTypeId = "entity"; when(permissionService.hasPermission( new EntityTypeIdentity(entityTypeId), EntityTypePermission.READ_DATA)) .thenReturn(false); assertFalse(molgenisPermissionController.hasReadPermission(entityTypeId)); }
### Question: MolgenisPermissionController { @GetMapping("/{entityTypeId}/write") @ResponseBody public boolean hasWritePermission(@PathVariable("entityTypeId") String entityTypeId) { return permissionService.hasPermission( new EntityTypeIdentity(entityTypeId), EntityTypePermission.READ_METADATA) && permissionService.hasPermission( new EntityTypeIdentity(entityTypeId), EntityTypePermission.UPDATE_DATA); } MolgenisPermissionController(UserPermissionEvaluator permissionService); @GetMapping("/{entityTypeId}/read") @ResponseBody boolean hasReadPermission(@PathVariable("entityTypeId") String entityTypeId); @GetMapping("/{entityTypeId}/write") @ResponseBody boolean hasWritePermission(@PathVariable("entityTypeId") String entityTypeId); }### Answer: @Test void hasWritePermissionTrue() { String entityTypeId = "entity"; when(permissionService.hasPermission( new EntityTypeIdentity(entityTypeId), EntityTypePermission.UPDATE_DATA)) .thenReturn(true); when(permissionService.hasPermission( new EntityTypeIdentity(entityTypeId), EntityTypePermission.READ_METADATA)) .thenReturn(true); assertTrue(molgenisPermissionController.hasWritePermission(entityTypeId)); } @Test void hasWritePermissionFalse() { String entityTypeId = "entity"; when(permissionService.hasPermission( new EntityTypeIdentity(entityTypeId), EntityTypePermission.UPDATE_DATA)) .thenReturn(false); assertFalse(molgenisPermissionController.hasWritePermission(entityTypeId)); }
### Question: SecurityContextRegistryImpl implements SecurityContextRegistry { @Override public SecurityContext getSecurityContext(String sessionId) { HttpSession httpSession = httpSessionMap.get(sessionId); if (httpSession == null) { return null; } return getSecurityContext(httpSession); } SecurityContextRegistryImpl(); @Override SecurityContext getSecurityContext(String sessionId); @Override Stream<SecurityContext> getSecurityContexts(); @EventListener void handleHttpSessionCreatedEvent(HttpSessionCreatedEvent httpSessionCreatedEvent); @EventListener void handleHttpSessionDestroyedEvent(HttpSessionDestroyedEvent httpSessionDestroyedEvent); }### Answer: @Test void testGetSecurityContextFromSessionWithSecurityContext() { assertEquals( securityContext, securityContextRegistry.getSecurityContext(httpSessionWithSecurityContextId)); } @Test void testGetSecurityContextFromSessionWithoutSecurityContext() { assertNull(securityContextRegistry.getSecurityContext(httpSessionWithoutSecurityContextId)); } @Test void testGetSecurityContextUnknownSessionId() { assertNull(securityContextRegistry.getSecurityContext("unknownSessionId")); }
### Question: EntityReferenceResolverDecorator extends AbstractRepositoryDecorator<Entity> { public EntityReferenceResolverDecorator( Repository<Entity> delegateRepository, EntityManager entityManager) { super(delegateRepository); this.entityManager = requireNonNull(entityManager); } EntityReferenceResolverDecorator( Repository<Entity> delegateRepository, EntityManager entityManager); @Override Stream<Entity> findAll(Query<Entity> q); @Override Entity findOne(Query<Entity> q); @Override Iterator<Entity> iterator(); @Override void forEachBatched(Fetch fetch, Consumer<List<Entity>> consumer, int batchSize); @Override Entity findOneById(Object id); @Override Entity findOneById(Object id, Fetch fetch); @Override Stream<Entity> findAll(Stream<Object> ids); @Override Stream<Entity> findAll(Stream<Object> ids, Fetch fetch); }### Answer: @SuppressWarnings("resource") @Test void EntityReferenceResolverDecorator() { assertThrows( NullPointerException.class, () -> new EntityReferenceResolverDecorator(null, null)); }
### Question: SecurityContextRegistryImpl implements SecurityContextRegistry { @Override public Stream<SecurityContext> getSecurityContexts() { return httpSessionMap.values().stream().map(this::getSecurityContext).filter(Objects::nonNull); } SecurityContextRegistryImpl(); @Override SecurityContext getSecurityContext(String sessionId); @Override Stream<SecurityContext> getSecurityContexts(); @EventListener void handleHttpSessionCreatedEvent(HttpSessionCreatedEvent httpSessionCreatedEvent); @EventListener void handleHttpSessionDestroyedEvent(HttpSessionDestroyedEvent httpSessionDestroyedEvent); }### Answer: @Test void testGetSecurityContexts() { assertEquals( singletonList(securityContext), securityContextRegistry.getSecurityContexts().collect(toList())); }
### Question: SecurityContextRegistryImpl implements SecurityContextRegistry { @EventListener public void handleHttpSessionDestroyedEvent(HttpSessionDestroyedEvent httpSessionDestroyedEvent) { String sessionId = httpSessionDestroyedEvent.getId(); httpSessionMap.remove(sessionId); } SecurityContextRegistryImpl(); @Override SecurityContext getSecurityContext(String sessionId); @Override Stream<SecurityContext> getSecurityContexts(); @EventListener void handleHttpSessionCreatedEvent(HttpSessionCreatedEvent httpSessionCreatedEvent); @EventListener void handleHttpSessionDestroyedEvent(HttpSessionDestroyedEvent httpSessionDestroyedEvent); }### Answer: @Test void testHandleHttpSessionDestroyedEvent() { securityContextRegistry.handleHttpSessionDestroyedEvent( new HttpSessionDestroyedEvent(httpSessionWithSecurityContext)); }
### Question: PermissionSystemServiceImpl implements PermissionSystemService { @Override public void giveUserWriteMetaPermissions(EntityType entityType) { giveUserWriteMetaPermissions(singletonList(entityType)); } PermissionSystemServiceImpl(MutableAclService mutableAclService); @Override void giveUserWriteMetaPermissions(EntityType entityType); @Override void giveUserWriteMetaPermissions(Collection<EntityType> entityTypes); }### Answer: @Test @WithMockUser(username = "user") public void giveUserEntityPermissions() { String entityTypeId = "entityTypeId"; EntityType entityType = when(mock(EntityType.class).getId()).thenReturn(entityTypeId).getMock(); MutableAcl acl = mock(MutableAcl.class); when(mutableAclService.readAclById(new EntityTypeIdentity(entityTypeId))).thenReturn(acl); permissionSystemServiceImpl.giveUserWriteMetaPermissions(entityType); verify(mutableAclService).updateAcl(acl); verify(acl).insertAce(0, PermissionSet.WRITEMETA, new PrincipalSid("user"), true); }
### Question: OidcUserMapperImpl implements OidcUserMapper { public OidcUserMapperImpl( DataService dataService, OidcUserMappingFactory oidcUserMappingFactory, UserFactory userFactory) { this.dataService = requireNonNull(dataService); this.oidcUserMappingFactory = requireNonNull(oidcUserMappingFactory); this.userFactory = requireNonNull(userFactory); } OidcUserMapperImpl( DataService dataService, OidcUserMappingFactory oidcUserMappingFactory, UserFactory userFactory); @Transactional @Override User toUser(OidcUser oidcUser, OidcUserRequest userRequest); }### Answer: @Test void testOidcUserMapperImpl() { assertThrows(NullPointerException.class, () -> new OidcUserMapperImpl(null, null, null)); }
### Question: OidcClientRepositoryDecorator extends AbstractRepositoryDecorator<OidcClient> { OidcClientRepositoryDecorator( Repository<OidcClient> delegateRepository, ResettableOAuth2AuthorizedClientService oAuth2AuthorizedClientService) { super(delegateRepository); this.oAuth2AuthorizedClientService = requireNonNull(oAuth2AuthorizedClientService); } OidcClientRepositoryDecorator( Repository<OidcClient> delegateRepository, ResettableOAuth2AuthorizedClientService oAuth2AuthorizedClientService); @Override void update(OidcClient entity); @Override void update(Stream<OidcClient> entities); @Override void delete(OidcClient entity); @Override void deleteById(Object id); @Override void deleteAll(); @Override void delete(Stream<OidcClient> entities); @Override void deleteAll(Stream<Object> ids); }### Answer: @Test void testOidcClientRepositoryDecorator() { assertThrows(NullPointerException.class, () -> new OidcClientRepositoryDecorator(null, null)); }
### Question: OidcClientRepositoryDecorator extends AbstractRepositoryDecorator<OidcClient> { @Override public void update(OidcClient entity) { super.update(entity); oAuth2AuthorizedClientService.reset(); } OidcClientRepositoryDecorator( Repository<OidcClient> delegateRepository, ResettableOAuth2AuthorizedClientService oAuth2AuthorizedClientService); @Override void update(OidcClient entity); @Override void update(Stream<OidcClient> entities); @Override void delete(OidcClient entity); @Override void deleteById(Object id); @Override void deleteAll(); @Override void delete(Stream<OidcClient> entities); @Override void deleteAll(Stream<Object> ids); }### Answer: @Test void testUpdate() { OidcClient oidcClient = mock(OidcClient.class); oidcClientRepositoryDecorator.update(oidcClient); verify(delegateRepository).update(oidcClient); verify(oAuth2AuthorizedClientService).reset(); } @Test void testUpdateStream() { @SuppressWarnings("unchecked") Stream<OidcClient> oidcClientStream = mock(Stream.class); oidcClientRepositoryDecorator.update(oidcClientStream); verify(delegateRepository).update(oidcClientStream); verify(oAuth2AuthorizedClientService).reset(); }