method2testcases
stringlengths
118
6.63k
### Question: MBox extends AbstractEntity implements Serializable { public static boolean boxToUser(long bId, long uId) { MBox mb = Ebean.find(MBox.class, bId); return (mb != null && (mb.getUsr() != null) && (mb.getUsr().getId() == uId)); } MBox(); MBox(String local, String domain, long ts, boolean expired, User usr); String getAddress(); void setAddress(String address); @JsonProperty("expired") boolean isExpired(); @JsonIgnore boolean isActive(); @JsonIgnore boolean isExpiredByTimestamp(); @JsonIgnore void setExpired(boolean expired); @JsonIgnore User getUsr(); @JsonIgnore void setUsr(User usr); String getDomain(); void setDomain(String domain); boolean belongsTo(Long uid); @JsonProperty("forwards") int getForwards(); @JsonIgnore void setForwards(int forwards); void increaseForwards(); void resetForwards(); @JsonProperty("suppressions") int getSuppressions(); @JsonIgnore void setSuppressions(int suppressions); void increaseSuppressions(); void resetSuppressions(); @JsonProperty("ts_Active") long getTs_Active(); @JsonIgnore void setTs_Active(long ts_Active); @JsonProperty("datetime") void setDateTime(String dateTime); @JsonIgnore Long getVersion(); @JsonIgnore void setVersion(Long version); @JsonProperty("fullAddress") String getFullAddress(); @JsonIgnore void setFullAddress(String dummy); void increaseFwd(); void increaseSup(); static void delete(Long id); static MBox getById(Long id); static MBox getByName(String mail, String domain); static MBox getByAddress(final String mailAddress); static boolean boxToUser(long bId, long uId); static String getFwdByName(String mail, String domain); static List<MBox> all(); static List<MBox> allUser(Long id); static boolean mailExists(String mail, String domain); @JsonIgnore String getTSAsStringWithNull(); String getDatetime(); void resetIdAndCounterFields(); static List<MBox> getNextBoxes(int minutes); void enable(); void disable(); static List<MBox> findBoxLike(String input, long userId); static MBox find(String localPart, String domain); static String getMailsForTxt(long userId); static String getActiveMailsForTxt(Long userId); static String getSelectedMailsForTxt(Long userId, List<Long> boxIds); static int removeListOfBoxes(long userId, List<Long> boxIds); static int resetListOfBoxes(long userId, List<Long> boxIds); static int disableListOfBoxes(long userId, List<Long> boxIds); static int enableListOfBoxesIfPossible(long userId, List<Long> boxIds); static int setNewDateForListOfBoxes(long userId, List<Long> boxIds, long ts_Active); String toString(); boolean isForwardEmails(); void setForwardEmails(boolean forwardEmails); }### Answer: @Test public void boxToUserTest() { User user2 = new User("fname", "sName", "[email protected]", "pw", "en"); user2.save(); assertTrue(mailbox.belongsTo(user.getId())); assertFalse(mailbox.belongsTo(user2.getId())); assertTrue(MBox.boxToUser(mailbox.getId(), user.getId())); assertFalse(MBox.boxToUser(mailbox.getId(), user2.getId())); }
### Question: HelperUtils { public static boolean hasCorrectFormat(String input) { input = input.trim(); return PATTERN_DATEFORMAT.matcher(input).matches(); } private HelperUtils(); static Long parseTimeString(String input); static String parseStringTs(long ts_Active); static String addZero(int no); static boolean hasCorrectFormat(String input); static void parseEntryValue(Context context, Integer defaultNo); static List<String[]> getLanguageList(String[] availableLanguages, Context context, Result result, Messages msg); static boolean checkEmailAddressValidness(String[] mailAddressParts, String[] domainList); static String[] splitMailAddress(String mailAddress); static String getHeaderText(final MimeMessage message); static byte[] readLimitedAmount(InputStream data, int maxSize); }### Answer: @Test public void testHasCorrectFormat() { boolean correctFormat = HelperUtils.hasCorrectFormat("2013-12-12 12:12"); assertTrue(correctFormat); correctFormat = HelperUtils.hasCorrectFormat("2013-2-12 12:12"); assertTrue(correctFormat); correctFormat = HelperUtils.hasCorrectFormat("2013-12-2 12:12"); assertTrue(correctFormat); correctFormat = HelperUtils.hasCorrectFormat("2013-2-2 1:12"); assertTrue(correctFormat); correctFormat = HelperUtils.hasCorrectFormat("2013-12-12 12:2"); assertTrue(correctFormat); correctFormat = HelperUtils.hasCorrectFormat("13-12-12 12:21"); assertFalse(correctFormat); correctFormat = HelperUtils.hasCorrectFormat("2013-- 12:21"); assertFalse(correctFormat); correctFormat = HelperUtils.hasCorrectFormat("2013-12-12 :21"); assertFalse(correctFormat); correctFormat = HelperUtils.hasCorrectFormat("2013-12-12 12:21"); assertFalse(correctFormat); correctFormat = HelperUtils.hasCorrectFormat("2x, 2h"); assertFalse(correctFormat); }
### Question: HelperUtils { public static Long parseTimeString(String input) { if (input.equals("0") || input.equals("unlimited")) { return 0L; } if (!hasCorrectFormat(input)) { return -1L; } input = input.trim(); DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"); return formatter.parseDateTime(input).getMillis(); } private HelperUtils(); static Long parseTimeString(String input); static String parseStringTs(long ts_Active); static String addZero(int no); static boolean hasCorrectFormat(String input); static void parseEntryValue(Context context, Integer defaultNo); static List<String[]> getLanguageList(String[] availableLanguages, Context context, Result result, Messages msg); static boolean checkEmailAddressValidness(String[] mailAddressParts, String[] domainList); static String[] splitMailAddress(String mailAddress); static String getHeaderText(final MimeMessage message); static byte[] readLimitedAmount(InputStream data, int maxSize); }### Answer: @Test public void testParseTimeString() { long ts = HelperUtils.parseTimeString("2013-12-12 12:12"); DateTime dt = new DateTime(2013, 12, 12, 12, 12); assertEquals(dt.getMillis(), ts); ts = HelperUtils.parseTimeString(" 2013-12-12 12:12 "); assertEquals(dt.getMillis(), ts); ts = HelperUtils.parseTimeString("12:12:12 12:12"); assertEquals(-1L, ts); ts = HelperUtils.parseTimeString("2013-12-12 12:12"); assertEquals(-1L, ts); ts = HelperUtils.parseTimeString("2x, 2h"); assertEquals(-1L, ts); }
### Question: HelperUtils { public static String[] splitMailAddress(String mailAddress) { mailAddress = StringUtils.defaultString(mailAddress).trim(); if (mailAddress.length() > 0) { return mailAddress.split("@"); } return null; } private HelperUtils(); static Long parseTimeString(String input); static String parseStringTs(long ts_Active); static String addZero(int no); static boolean hasCorrectFormat(String input); static void parseEntryValue(Context context, Integer defaultNo); static List<String[]> getLanguageList(String[] availableLanguages, Context context, Result result, Messages msg); static boolean checkEmailAddressValidness(String[] mailAddressParts, String[] domainList); static String[] splitMailAddress(String mailAddress); static String getHeaderText(final MimeMessage message); static byte[] readLimitedAmount(InputStream data, int maxSize); }### Answer: @Test public void testSplitMailAddress() { assertNull(HelperUtils.splitMailAddress(null)); assertNull(HelperUtils.splitMailAddress("")); assertNull(HelperUtils.splitMailAddress(" ")); String[] parts = HelperUtils.splitMailAddress("foo"); assertNotNull(parts); assertEquals(1, parts.length); parts = HelperUtils.splitMailAddress("foo@bar"); assertNotNull(parts); assertEquals(2, parts.length); }
### Question: HelperUtils { public static boolean checkEmailAddressValidness(String[] mailAddressParts, String[] domainList) { if (mailAddressParts == null || domainList == null || mailAddressParts.length != 2) { return false; } boolean foundDomain = false; for (String domain : domainList) { if (domain.equalsIgnoreCase(mailAddressParts[1])) { foundDomain = true; break; } } return foundDomain; } private HelperUtils(); static Long parseTimeString(String input); static String parseStringTs(long ts_Active); static String addZero(int no); static boolean hasCorrectFormat(String input); static void parseEntryValue(Context context, Integer defaultNo); static List<String[]> getLanguageList(String[] availableLanguages, Context context, Result result, Messages msg); static boolean checkEmailAddressValidness(String[] mailAddressParts, String[] domainList); static String[] splitMailAddress(String mailAddress); static String getHeaderText(final MimeMessage message); static byte[] readLimitedAmount(InputStream data, int maxSize); }### Answer: @Test public void testCheckEmailAddressValidness() { assertFalse(HelperUtils.checkEmailAddressValidness(null, null)); assertFalse(HelperUtils.checkEmailAddressValidness(null, ArrayUtils.EMPTY_STRING_ARRAY)); assertFalse(HelperUtils.checkEmailAddressValidness(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.EMPTY_STRING_ARRAY)); String[] domainList = ArrayUtils.toArray("test.localhost"); String[] mailParts = ArrayUtils.toArray("foo"); assertFalse(HelperUtils.checkEmailAddressValidness(mailParts, domainList)); mailParts = ArrayUtils.add(mailParts, "bar"); assertFalse(HelperUtils.checkEmailAddressValidness(mailParts, domainList)); mailParts[1] = "test.localhost"; assertTrue(HelperUtils.checkEmailAddressValidness(mailParts, domainList)); mailParts[1] = "TesT.LOCALHosT"; assertTrue(HelperUtils.checkEmailAddressValidness(mailParts, domainList)); }
### Question: HelperUtils { public static byte[] readLimitedAmount(InputStream data, int maxSize) throws IOException { final ByteArrayOutputStream bos = new ByteArrayOutputStream(data.available()); final long count = IOUtils.copy(data, bos, 4096); if (count > maxSize) { throw new SizeLimitExceededException("Data stream exceeds size limit of " + maxSize + " bytes"); } return bos.toByteArray(); } private HelperUtils(); static Long parseTimeString(String input); static String parseStringTs(long ts_Active); static String addZero(int no); static boolean hasCorrectFormat(String input); static void parseEntryValue(Context context, Integer defaultNo); static List<String[]> getLanguageList(String[] availableLanguages, Context context, Result result, Messages msg); static boolean checkEmailAddressValidness(String[] mailAddressParts, String[] domainList); static String[] splitMailAddress(String mailAddress); static String getHeaderText(final MimeMessage message); static byte[] readLimitedAmount(InputStream data, int maxSize); }### Answer: @Test(expected = SizeLimitExceededException.class) public void testReadRawContent_LimitExceeded() throws Exception { final InputStream is = new ByteArrayInputStream(RandomUtils.nextBytes(30)); HelperUtils.readLimitedAmount(is, 25); }
### Question: MailboxApiController extends AbstractApiController { public Result listMailboxes(@Attribute("userId") @DbId final Long userId, final Context context) { final List<MBox> mailboxes = MBox.allUser(userId); final List<MailboxData> mailboxDatas = mailboxes.stream().map(mb -> new MailboxData(mb)) .collect(Collectors.toList()); return ApiResults.ok().render(mailboxDatas); } Result listMailboxes(@Attribute("userId") @DbId final Long userId, final Context context); Result createMailbox(@JSR303Validation final MailboxData mailboxData, @Attribute("user") final User user, final Context context); Result getMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress, @Attribute("userId") @DbId final Long userId, final Context context); Result updateMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress, @JSR303Validation final MailboxData mailboxData, @Attribute("userId") @DbId final Long userId, final Context context); Result deleteMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress, @Attribute("userId") @DbId final Long userId, final Context context); }### Answer: @Test public void listMailboxes_emptyList() throws Exception { final HttpResponse response = apiClient.listMailboxes(); RestApiTestUtils.validateStatusCode(response, 200); final MailboxData[] mailboxData = RestApiTestUtils.getResponseBodyAs(response, MailboxData[].class); Assert.assertEquals(0, mailboxData.length); }
### Question: UIController { @GetMapping( value = { "/", "/applications/**", "/clusters/**", "/commands/**", "/jobs/**", "/output/**" } ) public String getIndex() { return "index"; } @GetMapping( value = { "/", "/applications/**", "/clusters/**", "/commands/**", "/jobs/**", "/output/**" } ) String getIndex(); @GetMapping(value = "/file/{id}/**") String getFile( @PathVariable("id") final String id, final HttpServletRequest request ); }### Answer: @Test void canGetIndex() { Assertions.assertThat(this.controller.getIndex()).isEqualTo("index"); }
### Question: ClusterModelAssembler implements RepresentationModelAssembler<Cluster, EntityModel<Cluster>> { @Override @Nonnull public EntityModel<Cluster> toModel(final Cluster cluster) { final String id = cluster.getId().orElseThrow(IllegalArgumentException::new); final EntityModel<Cluster> clusterModel = new EntityModel<>(cluster); try { clusterModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(ClusterRestController.class) .getCluster(id) ).withSelfRel() ); clusterModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(ClusterRestController.class) .getCommandsForCluster(id, null) ).withRel(COMMANDS_LINK) ); } catch (final NotFoundException ge) { throw new RuntimeException(ge); } return clusterModel; } @Override @Nonnull EntityModel<Cluster> toModel(final Cluster cluster); }### Answer: @Test void canConvertToModel() { final EntityModel<Cluster> model = this.assembler.toModel(this.cluster); Assertions.assertThat(model.getLinks()).hasSize(2); Assertions.assertThat(model.getLink("self")).isPresent(); Assertions.assertThat(model.getLink("commands")).isPresent(); }
### Question: RootModelAssembler implements RepresentationModelAssembler<JsonNode, EntityModel<JsonNode>> { @Override @SuppressFBWarnings("NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS") @Nonnull public EntityModel<JsonNode> toModel(final JsonNode metadata) { final EntityModel<JsonNode> rootResource = new EntityModel<>(metadata); try { rootResource.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(RootRestController.class) .getRoot() ).withSelfRel() ); rootResource.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(ApplicationRestController.class) .createApplication(null) ).withRel(APPLICATIONS_LINK) ); rootResource.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(CommandRestController.class) .createCommand(null) ).withRel(COMMANDS_LINK) ); rootResource.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(ClusterRestController.class) .createCluster(null) ).withRel(CLUSTERS_LINK) ); rootResource.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .submitJob(null, null, null, null) ).withRel(JOBS_LINK) ); } catch (final GenieException | GenieCheckedException ge) { throw new RuntimeException(ge); } return rootResource; } @Override @SuppressFBWarnings("NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS") @Nonnull EntityModel<JsonNode> toModel(final JsonNode metadata); }### Answer: @Test void canConvertToResource() { final JsonNode node = JsonNodeFactory.instance.objectNode().set("description", JsonNodeFactory.instance.textNode("blah")); final EntityModel<JsonNode> model = this.assembler.toModel(node); Assertions.assertThat(model.getLinks()).hasSize(5); Assertions.assertThat(model.getContent()).isNotNull(); Assertions.assertThat(model.getLink("self")).isNotNull(); Assertions.assertThat(model.getLink("applications")).isNotNull(); Assertions.assertThat(model.getLink("commands")).isNotNull(); Assertions.assertThat(model.getLink("clusters")).isNotNull(); Assertions.assertThat(model.getLink("jobs")).isNotNull(); }
### Question: JobSearchResultModelAssembler implements RepresentationModelAssembler<JobSearchResult, EntityModel<JobSearchResult>> { @Override @Nonnull public EntityModel<JobSearchResult> toModel(final JobSearchResult job) { final EntityModel<JobSearchResult> jobSearchResultModel = new EntityModel<>(job); try { jobSearchResultModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJob(job.getId()) ).withSelfRel() ); } catch (final GenieException ge) { throw new RuntimeException(ge); } return jobSearchResultModel; } @Override @Nonnull EntityModel<JobSearchResult> toModel(final JobSearchResult job); }### Answer: @Test void canConvertToResource() { final EntityModel<JobSearchResult> model = this.assembler.toModel(this.jobSearchResult); Assertions.assertThat(model.getLinks()).hasSize(1); Assertions.assertThat(model.getLink("self")).isNotNull(); }
### Question: CommandModelAssembler implements RepresentationModelAssembler<Command, EntityModel<Command>> { @Override @Nonnull public EntityModel<Command> toModel(final Command command) { final String id = command.getId().orElseThrow(IllegalArgumentException::new); final EntityModel<Command> commandModel = new EntityModel<>(command); try { commandModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(CommandRestController.class) .getCommand(id) ).withSelfRel() ); commandModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(CommandRestController.class) .getApplicationsForCommand(id) ).withRel(APPLICATIONS_LINK) ); commandModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(CommandRestController.class) .getClustersForCommand(id, null) ).withRel(CLUSTERS_LINK) ); } catch (final GenieException | GenieCheckedException ge) { throw new RuntimeException(ge); } return commandModel; } @Override @Nonnull EntityModel<Command> toModel(final Command command); }### Answer: @Test void canConvertToResource() { final EntityModel<Command> model = this.assembler.toModel(this.command); Assertions.assertThat(model.getLinks()).hasSize(3); Assertions.assertThat(model.getLink("self")).isPresent(); Assertions.assertThat(model.getLink("applications")).isPresent(); Assertions.assertThat(model.getLink("clusters")).isPresent(); }
### Question: GenieExceptionMapper { @ExceptionHandler(GenieException.class) public ResponseEntity<GenieException> handleGenieException(final GenieException e) { this.countExceptionAndLog(e); HttpStatus status = HttpStatus.resolve(e.getErrorCode()); if (status == null) { status = HttpStatus.INTERNAL_SERVER_ERROR; } return new ResponseEntity<>(e, status); } @Autowired GenieExceptionMapper(final MeterRegistry registry); @ExceptionHandler(GenieException.class) ResponseEntity<GenieException> handleGenieException(final GenieException e); @ExceptionHandler(GenieRuntimeException.class) ResponseEntity<GenieRuntimeException> handleGenieRuntimeException(final GenieRuntimeException e); @ExceptionHandler(GenieCheckedException.class) ResponseEntity<GenieCheckedException> handleGenieCheckedException(final GenieCheckedException e); @ExceptionHandler(ConstraintViolationException.class) ResponseEntity<GeniePreconditionException> handleConstraintViolation( final ConstraintViolationException cve ); @ExceptionHandler(MethodArgumentNotValidException.class) ResponseEntity<GeniePreconditionException> handleMethodArgumentNotValidException( final MethodArgumentNotValidException e ); }### Answer: @Test void canHandleGenieExceptions() { final List<GenieException> exceptions = Arrays.asList( new GenieBadRequestException("bad"), new GenieNotFoundException("Not Found"), new GeniePreconditionException("Precondition"), new GenieServerException("server"), new GenieServerUnavailableException("Server Unavailable"), new GenieTimeoutException("Timeout"), new GenieException(568, "Other") ); for (final GenieException exception : exceptions) { final ResponseEntity<GenieException> response = this.mapper.handleGenieException(exception); final HttpStatus expectedStatus = HttpStatus.resolve(exception.getErrorCode()) != null ? HttpStatus.resolve(exception.getErrorCode()) : HttpStatus.INTERNAL_SERVER_ERROR; Assertions.assertThat(response.getStatusCode()).isEqualByComparingTo(expectedStatus); Mockito .verify(this.registry, Mockito.times(1)) .counter( GenieExceptionMapper.CONTROLLER_EXCEPTION_COUNTER_NAME, Sets.newHashSet( Tag.of(MetricsConstants.TagKeys.EXCEPTION_CLASS, exception.getClass().getCanonicalName()) ) ); } Mockito .verify(this.counter, Mockito.times(exceptions.size())) .increment(); }
### Question: PredicateUtils { public static String createTagSearchString(final Set<TagEntity> tags) { return TAG_DELIMITER + tags .stream() .map(TagEntity::getTag) .sorted(String.CASE_INSENSITIVE_ORDER) .reduce((one, two) -> one + TAG_DELIMITER + TAG_DELIMITER + two) .orElse("") + TAG_DELIMITER; } private PredicateUtils(); static String createTagSearchString(final Set<TagEntity> tags); }### Answer: @Test void canCreateTagSearchString() { final String one = "oNe"; final String two = "TwO"; final String three = "3"; final Set<TagEntity> tags = Sets.newHashSet(); Assertions .assertThat(PredicateUtils.createTagSearchString(tags)) .isEqualTo( PredicateUtils.TAG_DELIMITER + PredicateUtils.TAG_DELIMITER ); final TagEntity oneTag = new TagEntity(); oneTag.setTag(one); final TagEntity twoTag = new TagEntity(); twoTag.setTag(two); final TagEntity threeTag = new TagEntity(); threeTag.setTag(three); tags.add(oneTag); Assertions .assertThat(PredicateUtils.createTagSearchString(tags)) .isEqualTo( PredicateUtils.TAG_DELIMITER + one + PredicateUtils.TAG_DELIMITER ); tags.add(twoTag); Assertions.assertThat(PredicateUtils.createTagSearchString(tags)) .isEqualTo( PredicateUtils.TAG_DELIMITER + one + PredicateUtils.TAG_DELIMITER + PredicateUtils.TAG_DELIMITER + two + PredicateUtils.TAG_DELIMITER ); tags.add(threeTag); Assertions.assertThat(PredicateUtils.createTagSearchString(tags)) .isEqualTo( PredicateUtils.TAG_DELIMITER + three + PredicateUtils.TAG_DELIMITER + PredicateUtils.TAG_DELIMITER + one + PredicateUtils.TAG_DELIMITER + PredicateUtils.TAG_DELIMITER + two + PredicateUtils.TAG_DELIMITER ); }
### Question: GenieExceptionMapper { @ExceptionHandler(ConstraintViolationException.class) public ResponseEntity<GeniePreconditionException> handleConstraintViolation( final ConstraintViolationException cve ) { this.countExceptionAndLog(cve); return new ResponseEntity<>( new GeniePreconditionException(cve.getMessage(), cve), HttpStatus.PRECONDITION_FAILED ); } @Autowired GenieExceptionMapper(final MeterRegistry registry); @ExceptionHandler(GenieException.class) ResponseEntity<GenieException> handleGenieException(final GenieException e); @ExceptionHandler(GenieRuntimeException.class) ResponseEntity<GenieRuntimeException> handleGenieRuntimeException(final GenieRuntimeException e); @ExceptionHandler(GenieCheckedException.class) ResponseEntity<GenieCheckedException> handleGenieCheckedException(final GenieCheckedException e); @ExceptionHandler(ConstraintViolationException.class) ResponseEntity<GeniePreconditionException> handleConstraintViolation( final ConstraintViolationException cve ); @ExceptionHandler(MethodArgumentNotValidException.class) ResponseEntity<GeniePreconditionException> handleMethodArgumentNotValidException( final MethodArgumentNotValidException e ); }### Answer: @Test void canHandleConstraintViolationExceptions() { final ConstraintViolationException exception = new ConstraintViolationException("cve", null); final ResponseEntity<GeniePreconditionException> response = this.mapper.handleConstraintViolation(exception); Assertions.assertThat(response.getStatusCode()).isEqualByComparingTo(HttpStatus.PRECONDITION_FAILED); Mockito .verify(this.registry, Mockito.times(1)) .counter( GenieExceptionMapper.CONTROLLER_EXCEPTION_COUNTER_NAME, Sets.newHashSet( Tag.of(MetricsConstants.TagKeys.EXCEPTION_CLASS, exception.getClass().getCanonicalName()) ) ); Mockito .verify(this.counter, Mockito.times(1)) .increment(); }
### Question: GenieExceptionMapper { @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<GeniePreconditionException> handleMethodArgumentNotValidException( final MethodArgumentNotValidException e ) { this.countExceptionAndLog(e); return new ResponseEntity<>( new GeniePreconditionException(e.getMessage(), e), HttpStatus.PRECONDITION_FAILED ); } @Autowired GenieExceptionMapper(final MeterRegistry registry); @ExceptionHandler(GenieException.class) ResponseEntity<GenieException> handleGenieException(final GenieException e); @ExceptionHandler(GenieRuntimeException.class) ResponseEntity<GenieRuntimeException> handleGenieRuntimeException(final GenieRuntimeException e); @ExceptionHandler(GenieCheckedException.class) ResponseEntity<GenieCheckedException> handleGenieCheckedException(final GenieCheckedException e); @ExceptionHandler(ConstraintViolationException.class) ResponseEntity<GeniePreconditionException> handleConstraintViolation( final ConstraintViolationException cve ); @ExceptionHandler(MethodArgumentNotValidException.class) ResponseEntity<GeniePreconditionException> handleMethodArgumentNotValidException( final MethodArgumentNotValidException e ); }### Answer: @Test @SuppressFBWarnings(value = "DM_NEW_FOR_GETCLASS", justification = "It's needed for the test") void canHandleMethodArgumentNotValidExceptions() { final Method method = new Object() { }.getClass().getEnclosingMethod(); final MethodParameter parameter = Mockito.mock(MethodParameter.class); Mockito.when(parameter.getMethod()).thenReturn(method); final Executable executable = Mockito.mock(Executable.class); Mockito.when(parameter.getExecutable()).thenReturn(executable); Mockito.when(executable.toGenericString()).thenReturn(UUID.randomUUID().toString()); final BindingResult bindingResult = Mockito.mock(BindingResult.class); Mockito.when(bindingResult.getAllErrors()).thenReturn(Lists.newArrayList()); final MethodArgumentNotValidException exception = new MethodArgumentNotValidException( parameter, bindingResult ); final ResponseEntity<GeniePreconditionException> response = this.mapper.handleMethodArgumentNotValidException(exception); Assertions.assertThat(response.getStatusCode()).isEqualByComparingTo(HttpStatus.PRECONDITION_FAILED); Mockito .verify(this.registry, Mockito.times(1)) .counter( GenieExceptionMapper.CONTROLLER_EXCEPTION_COUNTER_NAME, Sets.newHashSet( Tag.of(MetricsConstants.TagKeys.EXCEPTION_CLASS, exception.getClass().getCanonicalName()) ) ); Mockito .verify(this.counter, Mockito.times(1)) .increment(); }
### Question: GenieExceptionMapper { @ExceptionHandler(GenieRuntimeException.class) public ResponseEntity<GenieRuntimeException> handleGenieRuntimeException(final GenieRuntimeException e) { this.countExceptionAndLog(e); if ( e instanceof GenieApplicationNotFoundException || e instanceof GenieCommandNotFoundException || e instanceof GenieClusterNotFoundException || e instanceof GenieJobNotFoundException || e instanceof GenieJobSpecificationNotFoundException ) { return new ResponseEntity<>(e, HttpStatus.NOT_FOUND); } else if (e instanceof GenieIdAlreadyExistsException) { return new ResponseEntity<>(e, HttpStatus.CONFLICT); } else { return new ResponseEntity<>(e, HttpStatus.INTERNAL_SERVER_ERROR); } } @Autowired GenieExceptionMapper(final MeterRegistry registry); @ExceptionHandler(GenieException.class) ResponseEntity<GenieException> handleGenieException(final GenieException e); @ExceptionHandler(GenieRuntimeException.class) ResponseEntity<GenieRuntimeException> handleGenieRuntimeException(final GenieRuntimeException e); @ExceptionHandler(GenieCheckedException.class) ResponseEntity<GenieCheckedException> handleGenieCheckedException(final GenieCheckedException e); @ExceptionHandler(ConstraintViolationException.class) ResponseEntity<GeniePreconditionException> handleConstraintViolation( final ConstraintViolationException cve ); @ExceptionHandler(MethodArgumentNotValidException.class) ResponseEntity<GeniePreconditionException> handleMethodArgumentNotValidException( final MethodArgumentNotValidException e ); }### Answer: @Test void canHandleGenieRuntimeExceptions() { final Map<GenieRuntimeException, HttpStatus> exceptions = Maps.newHashMap(); exceptions.put(new GenieApplicationNotFoundException(), HttpStatus.NOT_FOUND); exceptions.put(new GenieClusterNotFoundException(), HttpStatus.NOT_FOUND); exceptions.put(new GenieCommandNotFoundException(), HttpStatus.NOT_FOUND); exceptions.put(new GenieJobNotFoundException(), HttpStatus.NOT_FOUND); exceptions.put(new GenieJobSpecificationNotFoundException(), HttpStatus.NOT_FOUND); exceptions.put(new GenieIdAlreadyExistsException(), HttpStatus.CONFLICT); exceptions.put(new GenieRuntimeException(), HttpStatus.INTERNAL_SERVER_ERROR); for (final Map.Entry<GenieRuntimeException, HttpStatus> exception : exceptions.entrySet()) { final ResponseEntity<GenieRuntimeException> response = this.mapper.handleGenieRuntimeException(exception.getKey()); Assertions.assertThat(response.getStatusCode()).isEqualByComparingTo(exception.getValue()); } }
### Question: GenieExceptionMapper { @ExceptionHandler(GenieCheckedException.class) public ResponseEntity<GenieCheckedException> handleGenieCheckedException(final GenieCheckedException e) { this.countExceptionAndLog(e); if (e instanceof GenieJobResolutionException) { return new ResponseEntity<>(e, HttpStatus.PRECONDITION_FAILED); } else if (e instanceof IdAlreadyExistsException) { return new ResponseEntity<>(e, HttpStatus.CONFLICT); } else if (e instanceof JobNotFoundException | e instanceof NotFoundException) { return new ResponseEntity<>(e, HttpStatus.NOT_FOUND); } else if (e instanceof PreconditionFailedException) { return new ResponseEntity<>(e, HttpStatus.BAD_REQUEST); } else if (e instanceof AttachmentTooLargeException) { return new ResponseEntity<>(e, HttpStatus.PAYLOAD_TOO_LARGE); } else { return new ResponseEntity<>(e, HttpStatus.INTERNAL_SERVER_ERROR); } } @Autowired GenieExceptionMapper(final MeterRegistry registry); @ExceptionHandler(GenieException.class) ResponseEntity<GenieException> handleGenieException(final GenieException e); @ExceptionHandler(GenieRuntimeException.class) ResponseEntity<GenieRuntimeException> handleGenieRuntimeException(final GenieRuntimeException e); @ExceptionHandler(GenieCheckedException.class) ResponseEntity<GenieCheckedException> handleGenieCheckedException(final GenieCheckedException e); @ExceptionHandler(ConstraintViolationException.class) ResponseEntity<GeniePreconditionException> handleConstraintViolation( final ConstraintViolationException cve ); @ExceptionHandler(MethodArgumentNotValidException.class) ResponseEntity<GeniePreconditionException> handleMethodArgumentNotValidException( final MethodArgumentNotValidException e ); }### Answer: @Test void canHandleGenieCheckedExceptions() { final Map<GenieCheckedException, HttpStatus> exceptions = Maps.newHashMap(); exceptions.put(new GenieJobResolutionException(), HttpStatus.PRECONDITION_FAILED); exceptions.put(new JobArchiveException(), HttpStatus.INTERNAL_SERVER_ERROR); exceptions.put(new GenieConversionException(), HttpStatus.INTERNAL_SERVER_ERROR); exceptions.put(new GenieCheckedException(), HttpStatus.INTERNAL_SERVER_ERROR); exceptions.put(new IdAlreadyExistsException(), HttpStatus.CONFLICT); exceptions.put(new JobArchiveException(), HttpStatus.INTERNAL_SERVER_ERROR); exceptions.put(new SaveAttachmentException(), HttpStatus.INTERNAL_SERVER_ERROR); exceptions.put(new JobNotFoundException(), HttpStatus.NOT_FOUND); exceptions.put(new NotFoundException(), HttpStatus.NOT_FOUND); exceptions.put(new PreconditionFailedException(), HttpStatus.BAD_REQUEST); exceptions.put(new AttachmentTooLargeException(), HttpStatus.PAYLOAD_TOO_LARGE); for (final Map.Entry<GenieCheckedException, HttpStatus> exception : exceptions.entrySet()) { final ResponseEntity<GenieCheckedException> response = this.mapper.handleGenieCheckedException(exception.getKey()); Assertions.assertThat(response.getStatusCode()).isEqualByComparingTo(exception.getValue()); } }
### Question: ControllerUtils { public static String getRemainingPath(final HttpServletRequest request) { String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); if (path != null) { final String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); log.debug("bestMatchPattern = {}", bestMatchPattern); path = new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path); } path = path == null ? EMPTY_STRING : path; log.debug("Remaining path = {}", path); return path; } private ControllerUtils(); static String getRemainingPath(final HttpServletRequest request); }### Answer: @Test void canGetRemainingPath() { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).thenReturn(null); Assertions.assertThat(ControllerUtils.getRemainingPath(request)).isEqualTo(""); Mockito .when(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)) .thenReturn("/api/v3/jobs/1234/output/genie/log.out"); Mockito .when(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)) .thenReturn("/api/v3/jobs/{id}/output/**"); Assertions.assertThat(ControllerUtils.getRemainingPath(request)).isEqualTo("genie/log.out"); Mockito .when(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)) .thenReturn("/api/v3/jobs/1234/output"); Mockito .when(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)) .thenReturn("/api/v3/jobs/{id}/output"); Assertions.assertThat(ControllerUtils.getRemainingPath(request)).isEqualTo(""); Mockito .when(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)) .thenReturn("/api/v3/jobs/1234/output/"); Mockito .when(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)) .thenReturn("/api/v3/jobs/{id}/output/"); Assertions.assertThat(ControllerUtils.getRemainingPath(request)).isEqualTo(""); Mockito .when(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)) .thenReturn("/api/v3/jobs/1234/output/stdout"); Mockito .when(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)) .thenReturn("/api/v3/jobs/{id}/output/**"); Assertions.assertThat(ControllerUtils.getRemainingPath(request)).isEqualTo("stdout"); }
### Question: ControllerUtils { static URL getRequestRoot( final HttpServletRequest request, @Nullable final String path ) throws MalformedURLException { return getRequestRoot(new URL(request.getRequestURL().toString()), path); } private ControllerUtils(); static String getRemainingPath(final HttpServletRequest request); }### Answer: @Test void canGetRequestRoot() throws MalformedURLException { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final URL requestURL = new URL("https: final StringBuffer buffer = new StringBuffer(requestURL.toString()); Mockito.when(request.getRequestURL()).thenReturn(buffer); Assertions .assertThat(ControllerUtils.getRequestRoot(request, "")) .isEqualTo(new URL("https: Assertions .assertThat(ControllerUtils.getRequestRoot(request, null)) .isEqualTo(new URL("https: Assertions .assertThat(ControllerUtils.getRequestRoot(request, UUID.randomUUID().toString())) .isEqualTo(new URL("https: Assertions .assertThat(ControllerUtils.getRequestRoot(request, ".done")) .isEqualTo(new URL("https: Assertions .assertThat(ControllerUtils.getRequestRoot(request, "genie/genie.done")) .isEqualTo(new URL("https: }
### Question: GenieDefaultPropertiesPostProcessor implements EnvironmentPostProcessor { @Override public void postProcessEnvironment(final ConfigurableEnvironment environment, final SpringApplication application) { final Resource defaultProperties = new ClassPathResource(DEFAULT_PROPERTIES_FILE); final PropertySource<?> defaultSource = PropertySourceUtils.loadYamlPropertySource(DEFAULT_PROPERTY_SOURCE_NAME, defaultProperties); environment.getPropertySources().addLast(defaultSource); if (Arrays.asList(environment.getActiveProfiles()).contains(PROD_PROFILE)) { final Resource defaultProdProperties = new ClassPathResource(DEFAULT_PROD_PROPERTIES_FILE); final PropertySource<?> defaultProdSource = PropertySourceUtils.loadYamlPropertySource(DEFAULT_PROD_PROPERTY_SOURCE_NAME, defaultProdProperties); environment.getPropertySources().addBefore(DEFAULT_PROPERTY_SOURCE_NAME, defaultProdSource); } } @Override void postProcessEnvironment(final ConfigurableEnvironment environment, final SpringApplication application); }### Answer: @Test void testSmokeProperty() { this.contextRunner .run( context -> { final SpringApplication application = Mockito.mock(SpringApplication.class); final ConfigurableEnvironment environment = context.getEnvironment(); Assertions.assertThat( environment .getPropertySources() .contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROPERTY_SOURCE_NAME) ).isFalse(); Assertions.assertThat( environment .getPropertySources() .contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROD_PROPERTY_SOURCE_NAME) ).isFalse(); Assertions.assertThat(environment.getProperty("genie.smoke")).isNull(); this.processor.postProcessEnvironment(environment, application); Assertions.assertThat( environment .getPropertySources() .contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROPERTY_SOURCE_NAME) ).isTrue(); Assertions.assertThat( environment .getPropertySources() .contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROD_PROPERTY_SOURCE_NAME) ).isFalse(); Assertions .assertThat(environment.getProperty("genie.smoke", Boolean.class, false)) .isTrue(); } ); } @Test void testProdSmokeProperty() { this.contextRunner .withPropertyValues("spring.profiles.active=prod") .run( context -> { final SpringApplication application = Mockito.mock(SpringApplication.class); final ConfigurableEnvironment environment = context.getEnvironment(); final MutablePropertySources propertySources = environment.getPropertySources(); Assertions.assertThat( propertySources.contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROPERTY_SOURCE_NAME) ).isFalse(); Assertions.assertThat( propertySources.contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROD_PROPERTY_SOURCE_NAME) ).isFalse(); Assertions.assertThat(environment.getProperty("genie.smoke")).isNull(); this.processor.postProcessEnvironment(environment, application); Assertions.assertThat( propertySources.contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROPERTY_SOURCE_NAME) ).isTrue(); Assertions.assertThat( propertySources.contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROD_PROPERTY_SOURCE_NAME) ).isTrue(); final PropertySource<?> defaultPropertySource = propertySources.get(GenieDefaultPropertiesPostProcessor.DEFAULT_PROPERTY_SOURCE_NAME); final PropertySource<?> defaultProdPropertySource = propertySources.get(GenieDefaultPropertiesPostProcessor.DEFAULT_PROD_PROPERTY_SOURCE_NAME); Assertions.assertThat(defaultPropertySource).isNotNull(); Assertions.assertThat(defaultProdPropertySource).isNotNull(); Assertions .assertThat(propertySources.precedenceOf(defaultProdPropertySource)) .isLessThan(propertySources.precedenceOf(defaultPropertySource)); Assertions .assertThat(environment.getProperty("genie.smoke", Boolean.class, true)) .isFalse(); } ); }
### Question: ServicesAutoConfiguration { @Bean public JobsProperties jobsProperties( final JobsForwardingProperties forwarding, final JobsLocationsProperties locations, final JobsMemoryProperties memory, final JobsUsersProperties users, final JobsActiveLimitProperties activeLimit ) { return new JobsProperties( forwarding, locations, memory, users, activeLimit ); } @Bean JobsProperties jobsProperties( final JobsForwardingProperties forwarding, final JobsLocationsProperties locations, final JobsMemoryProperties memory, final JobsUsersProperties users, final JobsActiveLimitProperties activeLimit ); @Bean @ConditionalOnMissingBean(AttachmentService.class) AttachmentService attachmentService( final S3ClientFactory s3ClientFactory, final AttachmentServiceProperties attachmentServiceProperties, final MeterRegistry meterRegistry ); @Bean @ConditionalOnMissingBean(JobResolverService.class) JobResolverServiceImpl jobResolverService( final DataServices dataServices, @NotEmpty final List<ClusterSelector> clusterSelectors, final CommandSelector commandSelector, final MeterRegistry registry, final JobsProperties jobsProperties, final Environment environment ); @Bean @ConditionalOnMissingBean(JobDirectoryServerService.class) JobDirectoryServerServiceImpl jobDirectoryServerService( final ResourceLoader resourceLoader, final DataServices dataServices, final AgentFileStreamService agentFileStreamService, final ArchivedJobService archivedJobService, final MeterRegistry meterRegistry, final AgentRoutingService agentRoutingService ); @Bean @ConditionalOnMissingBean(JobLaunchService.class) JobLaunchServiceImpl jobLaunchService( final DataServices dataServices, final JobResolverService jobResolverService, final AgentLauncher agentLauncher, final MeterRegistry registry ); @Bean @ConditionalOnMissingBean(ArchivedJobService.class) ArchivedJobServiceImpl archivedJobService( final DataServices dataServices, final ResourceLoader resourceLoader, final MeterRegistry meterRegistry ); }### Answer: @Test void canGetJobPropertiesBean() { Assertions .assertThat( this.servicesAutoConfiguration.jobsProperties( Mockito.mock(JobsForwardingProperties.class), Mockito.mock(JobsLocationsProperties.class), Mockito.mock(JobsMemoryProperties.class), Mockito.mock(JobsUsersProperties.class), Mockito.mock(JobsActiveLimitProperties.class) ) ) .isNotNull(); }
### Question: ServicesAutoConfiguration { @Bean @ConditionalOnMissingBean(JobDirectoryServerService.class) public JobDirectoryServerServiceImpl jobDirectoryServerService( final ResourceLoader resourceLoader, final DataServices dataServices, final AgentFileStreamService agentFileStreamService, final ArchivedJobService archivedJobService, final MeterRegistry meterRegistry, final AgentRoutingService agentRoutingService ) { return new JobDirectoryServerServiceImpl( resourceLoader, dataServices, agentFileStreamService, archivedJobService, meterRegistry, agentRoutingService ); } @Bean JobsProperties jobsProperties( final JobsForwardingProperties forwarding, final JobsLocationsProperties locations, final JobsMemoryProperties memory, final JobsUsersProperties users, final JobsActiveLimitProperties activeLimit ); @Bean @ConditionalOnMissingBean(AttachmentService.class) AttachmentService attachmentService( final S3ClientFactory s3ClientFactory, final AttachmentServiceProperties attachmentServiceProperties, final MeterRegistry meterRegistry ); @Bean @ConditionalOnMissingBean(JobResolverService.class) JobResolverServiceImpl jobResolverService( final DataServices dataServices, @NotEmpty final List<ClusterSelector> clusterSelectors, final CommandSelector commandSelector, final MeterRegistry registry, final JobsProperties jobsProperties, final Environment environment ); @Bean @ConditionalOnMissingBean(JobDirectoryServerService.class) JobDirectoryServerServiceImpl jobDirectoryServerService( final ResourceLoader resourceLoader, final DataServices dataServices, final AgentFileStreamService agentFileStreamService, final ArchivedJobService archivedJobService, final MeterRegistry meterRegistry, final AgentRoutingService agentRoutingService ); @Bean @ConditionalOnMissingBean(JobLaunchService.class) JobLaunchServiceImpl jobLaunchService( final DataServices dataServices, final JobResolverService jobResolverService, final AgentLauncher agentLauncher, final MeterRegistry registry ); @Bean @ConditionalOnMissingBean(ArchivedJobService.class) ArchivedJobServiceImpl archivedJobService( final DataServices dataServices, final ResourceLoader resourceLoader, final MeterRegistry meterRegistry ); }### Answer: @Test void canGetJobDirectoryServerServiceBean() { Assertions .assertThat( this.servicesAutoConfiguration.jobDirectoryServerService( Mockito.mock(ResourceLoader.class), Mockito.mock(DataServices.class), Mockito.mock(AgentFileStreamService.class), Mockito.mock(ArchivedJobService.class), Mockito.mock(MeterRegistry.class), Mockito.mock(AgentRoutingService.class) ) ) .isNotNull(); }
### Question: PredicateUtils { static Predicate getStringLikeOrEqualPredicate( @NotNull final CriteriaBuilder cb, @NotNull final Expression<String> expression, @NotNull final String value ) { if (StringUtils.contains(value, PERCENT)) { return cb.like(expression, value); } else { return cb.equal(expression, value); } } private PredicateUtils(); static String createTagSearchString(final Set<TagEntity> tags); }### Answer: @SuppressWarnings("unchecked") @Test void canGetStringLikeOrEqualPredicate() { final CriteriaBuilder cb = Mockito.mock(CriteriaBuilder.class); final Expression<String> expression = (Expression<String>) Mockito.mock(Expression.class); final Predicate likePredicate = Mockito.mock(Predicate.class); final Predicate equalPredicate = Mockito.mock(Predicate.class); Mockito.when(cb.like(Mockito.eq(expression), Mockito.anyString())).thenReturn(likePredicate); Mockito.when(cb.equal(Mockito.eq(expression), Mockito.anyString())).thenReturn(equalPredicate); Assertions .assertThat(PredicateUtils.getStringLikeOrEqualPredicate(cb, expression, "equal")) .isEqualTo(equalPredicate); Assertions .assertThat(PredicateUtils.getStringLikeOrEqualPredicate(cb, expression, "lik%e")) .isEqualTo(likePredicate); }
### Question: ServicesAutoConfiguration { @Bean @ConditionalOnMissingBean(AttachmentService.class) public AttachmentService attachmentService( final S3ClientFactory s3ClientFactory, final AttachmentServiceProperties attachmentServiceProperties, final MeterRegistry meterRegistry ) throws IOException { final @NotNull URI location = attachmentServiceProperties.getLocationPrefix(); final String scheme = location.getScheme(); if ("s3".equals(scheme)) { return new S3AttachmentServiceImpl(s3ClientFactory, attachmentServiceProperties, meterRegistry); } else if ("file".equals(scheme)) { return new LocalFileSystemAttachmentServiceImpl(attachmentServiceProperties); } else { throw new IllegalStateException( "Unknown attachment service implementation to use for location: " + location ); } } @Bean JobsProperties jobsProperties( final JobsForwardingProperties forwarding, final JobsLocationsProperties locations, final JobsMemoryProperties memory, final JobsUsersProperties users, final JobsActiveLimitProperties activeLimit ); @Bean @ConditionalOnMissingBean(AttachmentService.class) AttachmentService attachmentService( final S3ClientFactory s3ClientFactory, final AttachmentServiceProperties attachmentServiceProperties, final MeterRegistry meterRegistry ); @Bean @ConditionalOnMissingBean(JobResolverService.class) JobResolverServiceImpl jobResolverService( final DataServices dataServices, @NotEmpty final List<ClusterSelector> clusterSelectors, final CommandSelector commandSelector, final MeterRegistry registry, final JobsProperties jobsProperties, final Environment environment ); @Bean @ConditionalOnMissingBean(JobDirectoryServerService.class) JobDirectoryServerServiceImpl jobDirectoryServerService( final ResourceLoader resourceLoader, final DataServices dataServices, final AgentFileStreamService agentFileStreamService, final ArchivedJobService archivedJobService, final MeterRegistry meterRegistry, final AgentRoutingService agentRoutingService ); @Bean @ConditionalOnMissingBean(JobLaunchService.class) JobLaunchServiceImpl jobLaunchService( final DataServices dataServices, final JobResolverService jobResolverService, final AgentLauncher agentLauncher, final MeterRegistry registry ); @Bean @ConditionalOnMissingBean(ArchivedJobService.class) ArchivedJobServiceImpl archivedJobService( final DataServices dataServices, final ResourceLoader resourceLoader, final MeterRegistry meterRegistry ); }### Answer: @Test void canGetS3AttachmentServiceServiceBean() throws IOException { final AttachmentServiceProperties properties = new AttachmentServiceProperties(); Assertions .assertThat( this.servicesAutoConfiguration.attachmentService( Mockito.mock(S3ClientFactory.class), properties, Mockito.mock(MeterRegistry.class) ) ) .isInstanceOf(LocalFileSystemAttachmentServiceImpl.class); properties.setLocationPrefix(URI.create("s3: Assertions .assertThat( this.servicesAutoConfiguration.attachmentService( Mockito.mock(S3ClientFactory.class), properties, Mockito.mock(MeterRegistry.class) ) ) .isInstanceOf(S3AttachmentServiceImpl.class); }
### Question: SwaggerAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "genieApi", value = Docket.class) public Docket genieApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo( new ApiInfo( "Genie REST API", "See our <a href=\"http: + "documentation.<br/>Post any issues found " + "<a href=\"https: "4.0.0", null, new Contact("Netflix, Inc.", "https: "Apache 2.0", "http: Lists.newArrayList() ) ) .select() .apis(RequestHandlerSelectors.basePackage("com.netflix.genie.web.apis.rest.v3.controllers")) .paths(PathSelectors.any()) .build() .pathMapping("/") .useDefaultResponseMessages(false); } @Bean @ConditionalOnMissingBean(name = "genieApi", value = Docket.class) Docket genieApi(); }### Answer: @Test void canCreateDocket() { final SwaggerAutoConfiguration config = new SwaggerAutoConfiguration(); final Docket docket = config.genieApi(); Assertions.assertThat(docket.getDocumentationType()).isEqualTo(DocumentationType.SWAGGER_2); }
### Question: ApisAutoConfiguration { @Bean @ConditionalOnMissingBean(ResourceLoader.class) public ResourceLoader resourceLoader() { return new DefaultResourceLoader(); } @Bean @ConditionalOnMissingBean(ResourceLoader.class) ResourceLoader resourceLoader(); @Bean @ConditionalOnMissingBean(name = "genieRestTemplate") RestTemplate genieRestTemplate( final HttpProperties httpProperties, final RestTemplateBuilder restTemplateBuilder ); @Bean @ConditionalOnMissingBean(name = "genieRetryTemplate") RetryTemplate genieRetryTemplate(final RetryProperties retryProperties); @Bean @ConditionalOnMissingBean(DirectoryWriter.class) DefaultDirectoryWriter directoryWriter(); @Bean @ConditionalOnMissingBean(name = "jobsDir", value = Resource.class) Resource jobsDir( final ResourceLoader resourceLoader, final JobsProperties jobsProperties ); @Bean CharacterEncodingFilter characterEncodingFilter(); @Bean Jackson2ObjectMapperBuilderCustomizer apisObjectMapperCustomizer(); }### Answer: @Test void canGetResourceLoader() { Assertions.assertThat(this.apisAutoConfiguration.resourceLoader()).isInstanceOf(DefaultResourceLoader.class); }
### Question: ApisAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "genieRestTemplate") public RestTemplate genieRestTemplate( final HttpProperties httpProperties, final RestTemplateBuilder restTemplateBuilder ) { return restTemplateBuilder .setConnectTimeout(Duration.of(httpProperties.getConnect().getTimeout(), ChronoUnit.MILLIS)) .setReadTimeout(Duration.of(httpProperties.getRead().getTimeout(), ChronoUnit.MILLIS)) .build(); } @Bean @ConditionalOnMissingBean(ResourceLoader.class) ResourceLoader resourceLoader(); @Bean @ConditionalOnMissingBean(name = "genieRestTemplate") RestTemplate genieRestTemplate( final HttpProperties httpProperties, final RestTemplateBuilder restTemplateBuilder ); @Bean @ConditionalOnMissingBean(name = "genieRetryTemplate") RetryTemplate genieRetryTemplate(final RetryProperties retryProperties); @Bean @ConditionalOnMissingBean(DirectoryWriter.class) DefaultDirectoryWriter directoryWriter(); @Bean @ConditionalOnMissingBean(name = "jobsDir", value = Resource.class) Resource jobsDir( final ResourceLoader resourceLoader, final JobsProperties jobsProperties ); @Bean CharacterEncodingFilter characterEncodingFilter(); @Bean Jackson2ObjectMapperBuilderCustomizer apisObjectMapperCustomizer(); }### Answer: @Test void canGetRestTemplate() { Assertions .assertThat(this.apisAutoConfiguration.genieRestTemplate(new HttpProperties(), new RestTemplateBuilder())) .isNotNull(); }
### Question: ApisAutoConfiguration { @Bean @ConditionalOnMissingBean(DirectoryWriter.class) public DefaultDirectoryWriter directoryWriter() { return new DefaultDirectoryWriter(); } @Bean @ConditionalOnMissingBean(ResourceLoader.class) ResourceLoader resourceLoader(); @Bean @ConditionalOnMissingBean(name = "genieRestTemplate") RestTemplate genieRestTemplate( final HttpProperties httpProperties, final RestTemplateBuilder restTemplateBuilder ); @Bean @ConditionalOnMissingBean(name = "genieRetryTemplate") RetryTemplate genieRetryTemplate(final RetryProperties retryProperties); @Bean @ConditionalOnMissingBean(DirectoryWriter.class) DefaultDirectoryWriter directoryWriter(); @Bean @ConditionalOnMissingBean(name = "jobsDir", value = Resource.class) Resource jobsDir( final ResourceLoader resourceLoader, final JobsProperties jobsProperties ); @Bean CharacterEncodingFilter characterEncodingFilter(); @Bean Jackson2ObjectMapperBuilderCustomizer apisObjectMapperCustomizer(); }### Answer: @Test void canGetDirectoryWriter() { Assertions.assertThat(this.apisAutoConfiguration.directoryWriter()).isNotNull(); }
### Question: FileLockFactory { public CloseableLock getLock(final File file) throws LockException { return new FileLock(file); } CloseableLock getLock(final File file); }### Answer: @Test void canGetTaskExecutor(@TempDir final Path tmpDir) throws IOException, LockException { Assertions .assertThat( this.fileLockFactory.getLock(Files.createFile(tmpDir.resolve(UUID.randomUUID().toString())).toFile()) ) .isInstanceOf(FileLock.class); }
### Question: GenieDefaultPropertiesPostProcessor implements EnvironmentPostProcessor { @Override public void postProcessEnvironment(final ConfigurableEnvironment environment, final SpringApplication application) { final Resource defaultProperties = new ClassPathResource(DEFAULT_PROPERTIES_FILE); final PropertySource<?> defaultSource = PropertySourceUtils.loadYamlPropertySource(DEFAULT_PROPERTY_SOURCE_NAME, defaultProperties); environment.getPropertySources().addLast(defaultSource); } @Override void postProcessEnvironment(final ConfigurableEnvironment environment, final SpringApplication application); }### Answer: @Test void testSmokeProperty() { this.contextRunner .run( context -> { final SpringApplication application = Mockito.mock(SpringApplication.class); final ConfigurableEnvironment environment = context.getEnvironment(); Assertions.assertThat( environment .getPropertySources() .contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROPERTY_SOURCE_NAME) ).isFalse(); Assertions.assertThat(environment.getProperty("genie.smoke")).isBlank(); this.processor.postProcessEnvironment(environment, application); Assertions .assertThat( environment .getPropertySources() .contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROPERTY_SOURCE_NAME) ) .isTrue(); Assertions .assertThat(environment.getProperty("genie.smoke", Boolean.class, false)) .isTrue(); } ); }
### Question: AgentAutoConfiguration { @Bean TaskExecutorCustomizer taskExecutorCustomizer(final AgentProperties agentProperties) { return taskExecutor -> { taskExecutor.setWaitForTasksToCompleteOnShutdown(true); taskExecutor.setAwaitTerminationSeconds( (int) agentProperties.getShutdown().getSystemExecutorLeeway().getSeconds() ); }; } @Bean @ConditionalOnMissingBean(GenieHostInfo.class) GenieHostInfo genieAgentHostInfo(); @Bean @Lazy @ConditionalOnMissingBean(AgentMetadata.class) AgentMetadataImpl agentMetadata(final GenieHostInfo genieHostInfo); @Bean @Lazy FileLockFactory fileLockFactory(); @Bean @Lazy @ConditionalOnMissingBean(name = "sharedAgentTaskExecutor", value = AsyncTaskExecutor.class) AsyncTaskExecutor sharedAgentTaskExecutor(final AgentProperties agentProperties); @Bean @Lazy @ConditionalOnMissingBean(name = "sharedAgentTaskScheduler") TaskScheduler sharedAgentTaskScheduler(final AgentProperties agentProperties); @Bean @Lazy @ConditionalOnMissingBean(name = "heartBeatServiceTaskScheduler") TaskScheduler heartBeatServiceTaskScheduler(final AgentProperties agentProperties); }### Answer: @Test void testTaskExecutorCustomizer() { final AgentProperties properties = new AgentProperties(); final TaskExecutorCustomizer customizer = new AgentAutoConfiguration().taskExecutorCustomizer(properties); final ThreadPoolTaskExecutor taskExecutor = Mockito.mock(ThreadPoolTaskExecutor.class); customizer.customize(taskExecutor); Mockito.verify(taskExecutor).setWaitForTasksToCompleteOnShutdown(true); Mockito.verify(taskExecutor).setAwaitTerminationSeconds(60); }
### Question: PredicateUtils { static String getTagLikeString(@NotNull final Set<String> tags) { final StringBuilder builder = new StringBuilder(); tags.stream() .filter(StringUtils::isNotBlank) .sorted(String.CASE_INSENSITIVE_ORDER) .forEach( tag -> builder .append(PERCENT) .append(TAG_DELIMITER) .append(tag) .append(TAG_DELIMITER) ); return builder.append(PERCENT).toString(); } private PredicateUtils(); static String createTagSearchString(final Set<TagEntity> tags); }### Answer: @Test void canGetTagLikeString() { Assertions .assertThat(PredicateUtils.getTagLikeString(Sets.newHashSet())) .isEqualTo( PredicateUtils.PERCENT ); Assertions .assertThat(PredicateUtils.getTagLikeString(Sets.newHashSet("tag"))) .isEqualTo( PredicateUtils.PERCENT + PredicateUtils.TAG_DELIMITER + "tag" + PredicateUtils.TAG_DELIMITER + PredicateUtils.PERCENT ); Assertions .assertThat(PredicateUtils.getTagLikeString(Sets.newHashSet("tag", "Stag", "rag"))) .isEqualTo( PredicateUtils.PERCENT + PredicateUtils.TAG_DELIMITER + "rag" + PredicateUtils.TAG_DELIMITER + "%" + PredicateUtils.TAG_DELIMITER + "Stag" + PredicateUtils.TAG_DELIMITER + "%" + PredicateUtils.TAG_DELIMITER + "tag" + PredicateUtils.TAG_DELIMITER + PredicateUtils.PERCENT ); }
### Question: AgentAutoConfiguration { @Bean TaskSchedulerCustomizer taskSchedulerCustomizer(final AgentProperties agentProperties) { return taskScheduler -> { taskScheduler.setWaitForTasksToCompleteOnShutdown(true); taskScheduler.setAwaitTerminationSeconds( (int) agentProperties.getShutdown().getSystemSchedulerLeeway().getSeconds() ); }; } @Bean @ConditionalOnMissingBean(GenieHostInfo.class) GenieHostInfo genieAgentHostInfo(); @Bean @Lazy @ConditionalOnMissingBean(AgentMetadata.class) AgentMetadataImpl agentMetadata(final GenieHostInfo genieHostInfo); @Bean @Lazy FileLockFactory fileLockFactory(); @Bean @Lazy @ConditionalOnMissingBean(name = "sharedAgentTaskExecutor", value = AsyncTaskExecutor.class) AsyncTaskExecutor sharedAgentTaskExecutor(final AgentProperties agentProperties); @Bean @Lazy @ConditionalOnMissingBean(name = "sharedAgentTaskScheduler") TaskScheduler sharedAgentTaskScheduler(final AgentProperties agentProperties); @Bean @Lazy @ConditionalOnMissingBean(name = "heartBeatServiceTaskScheduler") TaskScheduler heartBeatServiceTaskScheduler(final AgentProperties agentProperties); }### Answer: @Test void testTaskSchedulerCustomizer() { final AgentProperties properties = new AgentProperties(); final TaskSchedulerCustomizer customizer = new AgentAutoConfiguration().taskSchedulerCustomizer(properties); final ThreadPoolTaskScheduler taskScheduler = Mockito.mock(ThreadPoolTaskScheduler.class); customizer.customize(taskScheduler); Mockito.verify(taskScheduler).setWaitForTasksToCompleteOnShutdown(true); Mockito.verify(taskScheduler).setAwaitTerminationSeconds(60); }
### Question: FetchingCacheServiceImpl implements FetchingCacheService { @Override public void get(final URI sourceFileUri, final File destinationFile) throws DownloadException, IOException { lookupOrDownload(sourceFileUri, destinationFile); } FetchingCacheServiceImpl( final ResourceLoader resourceLoader, final ArgumentDelegates.CacheArguments cacheArguments, final FileLockFactory fileLockFactory, final TaskExecutor cleanUpTaskExecutor ); @Override void get(final URI sourceFileUri, final File destinationFile); @Override void get(final Set<Pair<URI, File>> sourceDestinationPairs); }### Answer: @Test void cacheConcurrentFetches() throws Exception { final AtomicInteger numOfCacheMisses = new AtomicInteger(0); final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class); final Resource resource = Mockito.mock(Resource.class); final ReentrantLock lockBackingMock = new ReentrantLock(); final CountDownLatch lockAcquisitionsAttempted = new CountDownLatch(2); final CloseableLock resourceLock = Mockito.mock(CloseableLock.class); Mockito.doAnswer(invocation -> { lockAcquisitionsAttempted.countDown(); lockBackingMock.lock(); return null; }).when(resourceLock).lock(); Mockito.doAnswer(invocation -> { lockBackingMock.unlock(); return null; }).when(resourceLock).close(); final FileLockFactory fileLockFactory = Mockito.mock(FileLockFactory.class); Mockito.when( fileLockFactory.getLock(Mockito.any()) ).thenReturn(resourceLock); final ResourceLoader resourceLoader2 = Mockito.mock(ResourceLoader.class); final Resource resource2 = Mockito.mock(Resource.class); Mockito.when( resourceLoader.getResource(Mockito.anyString()) ).thenReturn(resource); Mockito.when( resource.getInputStream() ).thenAnswer( (Answer<InputStream>) invocation -> { numOfCacheMisses.incrementAndGet(); return simulateDownloadWithWait(); } ); Mockito.when(resource.exists()).thenReturn(true); final FetchingCacheServiceImpl cache1 = new FetchingCacheServiceImpl( resourceLoader, cacheArguments, fileLockFactory, cleanUpTaskExecutor ); Mockito.when( resourceLoader2.getResource(Mockito.anyString()) ).thenReturn(resource2); Mockito.when( resource2.getInputStream() ).thenAnswer( (Answer<InputStream>) invocation -> { numOfCacheMisses.incrementAndGet(); return simulateDownloadWithWait(); } ); Mockito.when(resource2.exists()).thenReturn(true); final FetchingCacheServiceImpl cache2 = new FetchingCacheServiceImpl( resourceLoader2, cacheArguments, fileLockFactory, cleanUpTaskExecutor ); downloadCompleted.set(false); numOfCacheMisses.set(0); final CountDownLatch allFetchesDone = new CountDownLatch(2); executorService.submit(() -> { try { cache1.get(uri, targetFile); } catch (Exception e) { e.printStackTrace(); } finally { allFetchesDone.countDown(); } }); executorService.submit(() -> { try { cache2.get(uri, targetFile); } catch (Exception e) { e.printStackTrace(); } finally { allFetchesDone.countDown(); } }); lockAcquisitionsAttempted.await(); downloadCompleted.set(true); simulateDownloadLock.lock(); try { downloadComplete.signal(); } finally { simulateDownloadLock.unlock(); } allFetchesDone.await(); Assertions.assertThat(numOfCacheMisses.get()).isEqualTo(1); }
### Question: ExecutionAutoConfiguration { @Bean @Lazy @ConditionalOnMissingBean ExecutionContext executionContext(final AgentProperties agentProperties) { return new ExecutionContext(agentProperties); } @Bean @Lazy @ConditionalOnMissingBean(LoggingListener.class) LoggingListener loggingListener(); @Bean @Lazy @ConditionalOnMissingBean(ConsoleLogListener.class) ConsoleLogListener consoleLogLoggingListener(); }### Answer: @Test void executionContext() { contextRunner.run( context -> { Assertions.assertThat(context).hasSingleBean(LoggingListener.class); Assertions.assertThat(context).hasSingleBean(ConsoleLogListener.class); Assertions.assertThat(context).hasSingleBean(ExecutionContext.class); Assertions.assertThat(context).hasSingleBean(JobExecutionStateMachine.class); Assertions.assertThat(context).hasSingleBean(AgentProperties.class); uniqueExecutionStages.forEach( stageClass -> Assertions.assertThat(context).hasSingleBean(stageClass) ); repeatedExecutionStages.forEach( (clazz, count) -> Assertions.assertThat(context).getBeans(clazz).hasSize(count) ); } ); }
### Question: Job extends CommonDTO { public Optional<String> getCommandArgs() { return Optional.ofNullable(this.commandArgs); } protected Job(@Valid final Builder builder); Optional<String> getCommandArgs(); Optional<String> getStatusMsg(); Optional<String> getArchiveLocation(); Optional<String> getClusterName(); Optional<String> getCommandName(); Optional<String> getGrouping(); Optional<String> getGroupingInstance(); Optional<Instant> getStarted(); Optional<Instant> getFinished(); }### Answer: @Test void testCommandArgsEdgeCases() { final Job.Builder builder = new Job.Builder(NAME, USER, VERSION); String commandArgs = " blah "; builder.withCommandArgs(commandArgs); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(" blah "); commandArgs = " blah "; builder.withCommandArgs(commandArgs); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(" blah "); commandArgs = " blah blah blah\nblah\tblah \"blah\" blah "; builder.withCommandArgs(commandArgs); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(" blah blah blah\nblah\tblah \"blah\" blah "); builder.withCommandArgs(Lists.newArrayList("blah", "blah", " blah", "\nblah", "\"blah\"")); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo("blah blah blah \nblah \"blah\""); }
### Question: BaseSearchResult implements Serializable { @Override public String toString() { try { return GenieObjectMapper.getMapper().writeValueAsString(this); } catch (final JsonProcessingException ioe) { return ioe.getLocalizedMessage(); } } @JsonCreator BaseSearchResult( @NotBlank @JsonProperty(value = "id", required = true) final String id, @NotBlank @JsonProperty(value = "name", required = true) final String name, @NotBlank @JsonProperty(value = "user", required = true) final String user ); @Override String toString(); }### Answer: @Test void canConstruct() { final String id = UUID.randomUUID().toString(); final String name = UUID.randomUUID().toString(); final String user = UUID.randomUUID().toString(); final BaseSearchResult searchResult = new BaseSearchResult(id, name, user); Assertions.assertThat(searchResult.getId()).isEqualTo(id); Assertions.assertThat(searchResult.getName()).isEqualTo(name); Assertions.assertThat(searchResult.getUser()).isEqualTo(user); } @Test void canFindEquality() { final String id = UUID.randomUUID().toString(); final BaseSearchResult searchResult1 = new BaseSearchResult(id, UUID.randomUUID().toString(), UUID.randomUUID().toString()); final BaseSearchResult searchResult2 = new BaseSearchResult(id, UUID.randomUUID().toString(), UUID.randomUUID().toString()); final BaseSearchResult searchResult3 = new BaseSearchResult( UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString() ); Assertions.assertThat(searchResult1).isEqualTo(searchResult2); Assertions.assertThat(searchResult1).isNotEqualTo(searchResult3); Assertions.assertThat(searchResult1.hashCode()).isEqualTo(searchResult2.hashCode()); Assertions.assertThat(searchResult1.hashCode()).isNotEqualTo(searchResult3.hashCode()); } @Test void canCreateValidJsonString() { final BaseSearchResult searchResult = new BaseSearchResult( UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString() ); final String json = searchResult.toString(); Assertions.assertThatCode(() -> GenieObjectMapper.getMapper().readTree(json)).doesNotThrowAnyException(); }
### Question: BaseEntity extends UniqueIdEntity implements BaseProjection, SetupFileProjection { public void setDescription(@Nullable final String description) { this.description = description; } BaseEntity(); @Override Optional<String> getDescription(); void setDescription(@Nullable final String description); @Override Optional<JsonNode> getMetadata(); void setMetadata(@Nullable final JsonNode metadata); @Override Optional<FileEntity> getSetupFile(); void setSetupFile(@Nullable final FileEntity setupFile); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer: @Test void testSetDescription() { Assertions.assertThat(this.b.getDescription()).isNotPresent(); final String description = "Test description"; this.b.setDescription(description); Assertions.assertThat(this.b.getDescription()).isPresent().contains(description); }
### Question: BaseDTO implements Serializable { @Override public String toString() { try { return GenieObjectMapper.getMapper().writeValueAsString(this); } catch (final JsonProcessingException ioe) { return ioe.getLocalizedMessage(); } } BaseDTO(final Builder builder); Optional<String> getId(); Optional<Instant> getCreated(); Optional<Instant> getUpdated(); @Override String toString(); }### Answer: @Test void canCreateValidJsonString() { final Application application = new Application.Builder( UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), ApplicationStatus.ACTIVE ).build(); final String json = application.toString(); Assertions.assertThatCode(() -> GenieObjectMapper.getMapper().readTree(json)).doesNotThrowAnyException(); }
### Question: JobRequest extends ExecutionEnvironmentDTO { public Optional<String> getCommandArgs() { return Optional.ofNullable(this.commandArgs); } JobRequest(@Valid final Builder builder); Optional<String> getCommandArgs(); Optional<String> getGroup(); Optional<String> getEmail(); Optional<Integer> getCpu(); Optional<Integer> getMemory(); Optional<Integer> getTimeout(); Optional<String> getGrouping(); Optional<String> getGroupingInstance(); static final int DEFAULT_TIMEOUT_DURATION; }### Answer: @Test void testCommandArgsEdgeCases() { final JobRequest.Builder builder = new JobRequest.Builder(NAME, USER, VERSION, Lists.newArrayList(), Sets.newHashSet()); String commandArgs = " blah "; builder.withCommandArgs(commandArgs); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(" blah "); commandArgs = " blah "; builder.withCommandArgs(commandArgs); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(" blah "); commandArgs = " blah blah blah\nblah\tblah \"blah\" blah "; builder.withCommandArgs(commandArgs); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(" blah blah blah\nblah\tblah \"blah\" blah "); builder.withCommandArgs(Lists.newArrayList("blah", "blah", " blah", "\nblah", "\"blah\"")); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo("blah blah blah \nblah \"blah\""); }
### Question: TimeUtils { public static Duration getDuration(@Nullable final Instant started, @Nullable final Instant finished) { if (started == null || started.toEpochMilli() == 0L) { return Duration.ZERO; } else if (finished == null || finished.toEpochMilli() == 0L) { return Duration.ofMillis(Instant.now().toEpochMilli() - started.toEpochMilli()); } else { return Duration.ofMillis(finished.toEpochMilli() - started.toEpochMilli()); } } private TimeUtils(); static Duration getDuration(@Nullable final Instant started, @Nullable final Instant finished); }### Answer: @Test void canGetDuration() { final long durationMillis = 50823L; final Duration duration = Duration.ofMillis(durationMillis); final Instant started = Instant.now(); final Instant finished = started.plusMillis(durationMillis); Assertions.assertThat(TimeUtils.getDuration(null, finished)).isEqualByComparingTo(Duration.ZERO); Assertions.assertThat(TimeUtils.getDuration(Instant.EPOCH, finished)).isEqualByComparingTo(Duration.ZERO); Assertions.assertThat(TimeUtils.getDuration(started, null)).isNotNull(); Assertions.assertThat(TimeUtils.getDuration(started, Instant.EPOCH)).isNotNull(); Assertions.assertThat(TimeUtils.getDuration(started, finished)).isEqualByComparingTo(duration); }
### Question: JsonUtils { public static String marshall(final Object value) throws GenieException { try { return GenieObjectMapper.getMapper().writeValueAsString(value); } catch (final JsonProcessingException jpe) { throw new GenieServerException("Failed to marshall object", jpe); } } protected JsonUtils(); static String marshall(final Object value); static T unmarshall( final String source, final TypeReference<T> typeReference ); @Nonnull static List<String> splitArguments(final String commandArgs); @Nullable static String joinArguments(final List<String> commandArgs); }### Answer: @Test void canMarshall() throws GenieException { final List<String> strings = Lists.newArrayList("one", "two", "three"); Assertions.assertThat(JsonUtils.marshall(strings)).isEqualTo("[\"one\",\"two\",\"three\"]"); }
### Question: JsonUtils { public static <T extends Collection> T unmarshall( final String source, final TypeReference<T> typeReference ) throws GenieException { try { if (StringUtils.isNotBlank(source)) { return GenieObjectMapper.getMapper().readValue(source, typeReference); } else { return GenieObjectMapper.getMapper().readValue("[]", typeReference); } } catch (final IOException ioe) { throw new GenieServerException("Failed to read JSON value", ioe); } } protected JsonUtils(); static String marshall(final Object value); static T unmarshall( final String source, final TypeReference<T> typeReference ); @Nonnull static List<String> splitArguments(final String commandArgs); @Nullable static String joinArguments(final List<String> commandArgs); }### Answer: @Test void canUnmarshall() throws GenieException { final String source = "[\"one\",\"two\",\"three\"]"; final TypeReference<List<String>> list = new TypeReference<List<String>>() { }; Assertions .assertThat(JsonUtils.unmarshall(source, list)) .isEqualTo(Lists.newArrayList("one", "two", "three")); Assertions.assertThat(JsonUtils.unmarshall(null, list)).isEqualTo(Lists.newArrayList()); }
### Question: GenieException extends Exception { public int getErrorCode() { return errorCode; } GenieException(final int errorCode, final String msg, final Throwable cause); GenieException(final int errorCode, final String msg); int getErrorCode(); }### Answer: @Test void testThreeArgConstructor() { Assertions .assertThatExceptionOfType(GenieException.class) .isThrownBy( () -> { throw new GenieException(ERROR_CODE, ERROR_MESSAGE, IOE); } ) .withCause(IOE) .withMessage(ERROR_MESSAGE) .satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(HttpURLConnection.HTTP_NOT_FOUND)); } @Test void testTwoArgConstructorWithMessage() { Assertions .assertThatExceptionOfType(GenieException.class) .isThrownBy( () -> { throw new GenieException(ERROR_CODE, ERROR_MESSAGE); } ) .withNoCause() .withMessage(ERROR_MESSAGE) .satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(HttpURLConnection.HTTP_NOT_FOUND)); }
### Question: BaseEntity extends UniqueIdEntity implements BaseProjection, SetupFileProjection { public void setSetupFile(@Nullable final FileEntity setupFile) { this.setupFile = setupFile; } BaseEntity(); @Override Optional<String> getDescription(); void setDescription(@Nullable final String description); @Override Optional<JsonNode> getMetadata(); void setMetadata(@Nullable final JsonNode metadata); @Override Optional<FileEntity> getSetupFile(); void setSetupFile(@Nullable final FileEntity setupFile); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer: @Test void testSetSetupFile() { Assertions.assertThat(this.b.getSetupFile()).isNotPresent(); final FileEntity setupFile = new FileEntity(UUID.randomUUID().toString()); this.b.setSetupFile(setupFile); Assertions.assertThat(this.b.getSetupFile()).isPresent().contains(setupFile); this.b.setSetupFile(null); Assertions.assertThat(this.b.getSetupFile()).isNotPresent(); }
### Question: CommonServicesAutoConfiguration { @Bean(name = "jobDirectoryManifestCache") @ConditionalOnMissingBean(name = "jobDirectoryManifestCache") public Cache<Path, DirectoryManifest> jobDirectoryManifestCache() { return Caffeine.newBuilder() .maximumSize(100) .expireAfterWrite(30, TimeUnit.SECONDS) .build(); } @Bean @Order(FILE_SYSTEM_JOB_ARCHIVER_PRECEDENCE) FileSystemJobArchiverImpl fileSystemJobArchiver(); @Bean @ConditionalOnMissingBean(JobArchiveService.class) JobArchiveService jobArchiveService( final List<JobArchiver> jobArchivers, final DirectoryManifest.Factory directoryManifestFactory ); @Bean @ConditionalOnMissingBean(JobDirectoryManifestCreatorService.class) JobDirectoryManifestCreatorServiceImpl jobDirectoryManifestCreatorService( final DirectoryManifest.Factory directoryManifestFactory, @Qualifier("jobDirectoryManifestCache") final Cache<Path, DirectoryManifest> cache ); @Bean(name = "jobDirectoryManifestCache") @ConditionalOnMissingBean(name = "jobDirectoryManifestCache") Cache<Path, DirectoryManifest> jobDirectoryManifestCache(); @Bean @ConditionalOnMissingBean(DirectoryManifest.Factory.class) DirectoryManifest.Factory directoryManifestFactory( final DirectoryManifest.Filter directoryManifestFilter ); @Bean @ConditionalOnMissingBean(DirectoryManifest.Filter.class) DirectoryManifest.Filter directoryManifestFilter(final RegexDirectoryManifestProperties properties); static final int FILE_SYSTEM_JOB_ARCHIVER_PRECEDENCE; }### Answer: @Test void testJobDirectoryManifestCache() { this.contextRunner.run( context -> Assertions.assertThat(context).getBean("jobDirectoryManifestCache").isNotNull() ); }
### Question: CommonServicesAutoConfiguration { @Bean @ConditionalOnMissingBean(DirectoryManifest.Factory.class) public DirectoryManifest.Factory directoryManifestFactory( final DirectoryManifest.Filter directoryManifestFilter ) { return new DirectoryManifest.Factory(directoryManifestFilter); } @Bean @Order(FILE_SYSTEM_JOB_ARCHIVER_PRECEDENCE) FileSystemJobArchiverImpl fileSystemJobArchiver(); @Bean @ConditionalOnMissingBean(JobArchiveService.class) JobArchiveService jobArchiveService( final List<JobArchiver> jobArchivers, final DirectoryManifest.Factory directoryManifestFactory ); @Bean @ConditionalOnMissingBean(JobDirectoryManifestCreatorService.class) JobDirectoryManifestCreatorServiceImpl jobDirectoryManifestCreatorService( final DirectoryManifest.Factory directoryManifestFactory, @Qualifier("jobDirectoryManifestCache") final Cache<Path, DirectoryManifest> cache ); @Bean(name = "jobDirectoryManifestCache") @ConditionalOnMissingBean(name = "jobDirectoryManifestCache") Cache<Path, DirectoryManifest> jobDirectoryManifestCache(); @Bean @ConditionalOnMissingBean(DirectoryManifest.Factory.class) DirectoryManifest.Factory directoryManifestFactory( final DirectoryManifest.Filter directoryManifestFilter ); @Bean @ConditionalOnMissingBean(DirectoryManifest.Filter.class) DirectoryManifest.Filter directoryManifestFilter(final RegexDirectoryManifestProperties properties); static final int FILE_SYSTEM_JOB_ARCHIVER_PRECEDENCE; }### Answer: @Test void testDirectoryManifestFactory() { this.contextRunner.run( context -> Assertions.assertThat(context).hasSingleBean(DirectoryManifest.Factory.class) ); }
### Question: CommonServicesAutoConfiguration { @Bean @ConditionalOnMissingBean(DirectoryManifest.Filter.class) public DirectoryManifest.Filter directoryManifestFilter(final RegexDirectoryManifestProperties properties) { return new RegexDirectoryManifestFilter(properties); } @Bean @Order(FILE_SYSTEM_JOB_ARCHIVER_PRECEDENCE) FileSystemJobArchiverImpl fileSystemJobArchiver(); @Bean @ConditionalOnMissingBean(JobArchiveService.class) JobArchiveService jobArchiveService( final List<JobArchiver> jobArchivers, final DirectoryManifest.Factory directoryManifestFactory ); @Bean @ConditionalOnMissingBean(JobDirectoryManifestCreatorService.class) JobDirectoryManifestCreatorServiceImpl jobDirectoryManifestCreatorService( final DirectoryManifest.Factory directoryManifestFactory, @Qualifier("jobDirectoryManifestCache") final Cache<Path, DirectoryManifest> cache ); @Bean(name = "jobDirectoryManifestCache") @ConditionalOnMissingBean(name = "jobDirectoryManifestCache") Cache<Path, DirectoryManifest> jobDirectoryManifestCache(); @Bean @ConditionalOnMissingBean(DirectoryManifest.Factory.class) DirectoryManifest.Factory directoryManifestFactory( final DirectoryManifest.Filter directoryManifestFilter ); @Bean @ConditionalOnMissingBean(DirectoryManifest.Filter.class) DirectoryManifest.Filter directoryManifestFilter(final RegexDirectoryManifestProperties properties); static final int FILE_SYSTEM_JOB_ARCHIVER_PRECEDENCE; }### Answer: @Test void testDirectoryManifestFilter() { this.contextRunner.run( context -> Assertions.assertThat(context).hasSingleBean(DirectoryManifest.Filter.class) ); }
### Question: BaseEntity extends UniqueIdEntity implements BaseProjection, SetupFileProjection { public void setMetadata(@Nullable final JsonNode metadata) { this.metadata = metadata; } BaseEntity(); @Override Optional<String> getDescription(); void setDescription(@Nullable final String description); @Override Optional<JsonNode> getMetadata(); void setMetadata(@Nullable final JsonNode metadata); @Override Optional<FileEntity> getSetupFile(); void setSetupFile(@Nullable final FileEntity setupFile); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer: @Test void testSetMetadata() { Assertions.assertThat(this.b.getMetadata()).isNotPresent(); this.b.setMetadata(METADATA); Assertions.assertThat(this.b.getMetadata()).isPresent().contains(METADATA); this.b.setMetadata(null); Assertions.assertThat(this.b.getMetadata()).isNotPresent(); }
### Question: BaseEntity extends UniqueIdEntity implements BaseProjection, SetupFileProjection { @Override public int hashCode() { return super.hashCode(); } BaseEntity(); @Override Optional<String> getDescription(); void setDescription(@Nullable final String description); @Override Optional<JsonNode> getMetadata(); void setMetadata(@Nullable final JsonNode metadata); @Override Optional<FileEntity> getSetupFile(); void setSetupFile(@Nullable final FileEntity setupFile); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer: @Test void testEqualsAndHashCode() { final String id = UUID.randomUUID().toString(); final String name = UUID.randomUUID().toString(); final BaseEntity one = new BaseEntity(); one.setUniqueId(id); one.setName(UUID.randomUUID().toString()); final BaseEntity two = new BaseEntity(); two.setUniqueId(id); two.setName(name); final BaseEntity three = new BaseEntity(); three.setUniqueId(UUID.randomUUID().toString()); three.setName(name); Assertions.assertThat(one).isEqualTo(two); Assertions.assertThat(one).isNotEqualTo(three); Assertions.assertThat(two).isNotEqualTo(three); Assertions.assertThat(one.hashCode()).isEqualTo(two.hashCode()); Assertions.assertThat(one.hashCode()).isNotEqualTo(three.hashCode()); Assertions.assertThat(two.hashCode()).isNotEqualTo(three.hashCode()); }
### Question: UIController { @GetMapping(value = "/file/{id}/**") public String getFile( @PathVariable("id") final String id, final HttpServletRequest request ) throws UnsupportedEncodingException { final String encodedId = URLEncoder.encode(id, "UTF-8"); final String path = "/api/v3/jobs/" + encodedId + "/" + ControllerUtils.getRemainingPath(request); return "forward:" + path; } @GetMapping( value = { "/", "/applications/**", "/clusters/**", "/commands/**", "/jobs/**", "/output/**" } ) String getIndex(); @GetMapping(value = "/file/{id}/**") String getFile( @PathVariable("id") final String id, final HttpServletRequest request ); }### Answer: @Test void canGetFile() throws Exception { final String id = UUID.randomUUID().toString(); final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito .when(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)) .thenReturn("/file/" + id + "/output/genie/log.out"); Mockito .when(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)) .thenReturn("/file/{id}/**"); final String encodedId = URLEncoder.encode(id, "UTF-8"); final String expectedPath = "/api/v3/jobs/" + encodedId + "/output/genie/log.out"; Assertions.assertThat(this.controller.getFile(id, request)).isEqualTo("forward:" + expectedPath); }
### Question: TokenFetcher { public AccessToken getToken() throws GenieClientException { try { if (Instant.now().isAfter(this.expirationTime)) { final Response<AccessToken> response = tokenService.getToken(oauthUrl, credentialParams).execute(); if (response.isSuccessful()) { this.accessToken = response.body(); this.expirationTime = Instant .now() .plus(this.accessToken.getExpiresIn() - 300, ChronoUnit.SECONDS); return this.accessToken; } else { throw new GenieClientException(response.code(), "Could not fetch Token"); } } else { return this.accessToken; } } catch (final Exception e) { throw new GenieClientException("Could not get access tokens" + e); } } TokenFetcher( final String oauthUrl, final String clientId, final String clientSecret, final String grantType, final String scope ); AccessToken getToken(); }### Answer: @Test @Disabled("Fails from time to time non-deterministically") void testGetTokenFailure() { Assertions .assertThatExceptionOfType(GenieClientException.class) .isThrownBy( () -> { final TokenFetcher tokenFetcher = new TokenFetcher(URL, CLIENT_ID, CLIENT_SECRET, GRANT_TYPE, SCOPE); tokenFetcher.getToken(); } ) .satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(-1)); }
### Question: OAuth2SecurityInterceptor implements SecurityInterceptor { @Override public Response intercept( final Chain chain ) throws IOException { final AccessToken accessToken = this.tokenFetcher.getToken(); final Request newRequest = chain .request() .newBuilder() .addHeader(HttpHeaders.AUTHORIZATION, accessToken.getTokenType() + " " + accessToken.getAccessToken()) .build(); log.debug("Sending request {} on {} {}", newRequest.url(), chain.connection(), newRequest.headers()); return chain.proceed(newRequest); } OAuth2SecurityInterceptor( final String url, final String clientId, final String clientSecret, final String grantType, final String scope ); @Override Response intercept( final Chain chain ); }### Answer: @Disabled("fails randomly") @Test void testTokenFetchFailure() throws Exception { final Interceptor.Chain chain = Mockito.mock(Interceptor.Chain.class); final OAuth2SecurityInterceptor oAuth2SecurityInterceptor = new OAuth2SecurityInterceptor( URL, CLIENT_ID, CLIENT_SECRET, GRANT_TYPE, SCOPE ); Assertions.assertThatIOException().isThrownBy(() -> oAuth2SecurityInterceptor.intercept(chain)); }
### Question: ClusterEntity extends BaseEntity { public void setTags(@Nullable final Set<TagEntity> tags) { this.tags.clear(); if (tags != null) { this.tags.addAll(tags); } } ClusterEntity(); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); @Override boolean equals(final Object o); @Override int hashCode(); static final String DTO_ENTITY_GRAPH; }### Answer: @Test void testSetTags() { Assertions.assertThat(this.c.getTags()).isEmpty(); final TagEntity prodTag = new TagEntity(); prodTag.setTag("prod"); final TagEntity slaTag = new TagEntity(); slaTag.setTag("sla"); final Set<TagEntity> tags = Sets.newHashSet(prodTag, slaTag); this.c.setTags(tags); Assertions.assertThat(this.c.getTags()).isEqualTo(tags); this.c.setTags(null); Assertions.assertThat(this.c.getTags()).isEmpty(); } @Test void canSetClusterTags() { final TagEntity oneTag = new TagEntity(); oneTag.setTag("one"); final TagEntity twoTag = new TagEntity(); twoTag.setTag("tow"); final TagEntity preTag = new TagEntity(); preTag.setTag("Pre"); final Set<TagEntity> tags = Sets.newHashSet(oneTag, twoTag, preTag); this.c.setTags(tags); Assertions.assertThat(this.c.getTags()).isEqualTo(tags); this.c.setTags(Sets.newHashSet()); Assertions.assertThat(this.c.getTags()).isEmpty(); this.c.setTags(null); Assertions.assertThat(this.c.getTags()).isEmpty(); }
### Question: ClusterEntity extends BaseEntity { public void setConfigs(@Nullable final Set<FileEntity> configs) { this.configs.clear(); if (configs != null) { this.configs.addAll(configs); } } ClusterEntity(); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); @Override boolean equals(final Object o); @Override int hashCode(); static final String DTO_ENTITY_GRAPH; }### Answer: @Test void testSetConfigs() { Assertions.assertThat(this.c.getConfigs()).isEmpty(); this.c.setConfigs(this.configs); Assertions.assertThat(this.c.getConfigs()).isEqualTo(this.configs); this.c.setConfigs(null); Assertions.assertThat(c.getConfigs()).isEmpty(); }
### Question: ClusterEntity extends BaseEntity { public void setDependencies(@Nullable final Set<FileEntity> dependencies) { this.dependencies.clear(); if (dependencies != null) { this.dependencies.addAll(dependencies); } } ClusterEntity(); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); @Override boolean equals(final Object o); @Override int hashCode(); static final String DTO_ENTITY_GRAPH; }### Answer: @Test void testSetDependencies() { Assertions.assertThat(this.c.getDependencies()).isEmpty(); final FileEntity dependency = new FileEntity(); dependency.setFile("s3: final Set<FileEntity> dependencies = Sets.newHashSet(dependency); this.c.setDependencies(dependencies); Assertions.assertThat(this.c.getDependencies()).isEqualTo(dependencies); this.c.setDependencies(null); Assertions.assertThat(this.c.getDependencies()).isEmpty(); }
### Question: ApplicationEntity extends BaseEntity { public void setConfigs(@Nullable final Set<FileEntity> configs) { this.configs.clear(); if (configs != null) { this.configs.addAll(configs); } } ApplicationEntity(); Optional<String> getType(); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); @Override boolean equals(final Object o); @Override int hashCode(); static final String COMMANDS_ENTITY_GRAPH; static final String COMMANDS_DTO_ENTITY_GRAPH; static final String DTO_ENTITY_GRAPH; }### Answer: @Test void testSetConfigs() { final Set<FileEntity> configs = Sets.newHashSet(new FileEntity("s3: this.a.setConfigs(configs); Assertions.assertThat(this.a.getConfigs()).isEqualTo(configs); this.a.setConfigs(null); Assertions.assertThat(this.a.getConfigs()).isEmpty(); }
### Question: ApplicationEntity extends BaseEntity { public void setDependencies(@Nullable final Set<FileEntity> dependencies) { this.dependencies.clear(); if (dependencies != null) { this.dependencies.addAll(dependencies); } } ApplicationEntity(); Optional<String> getType(); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); @Override boolean equals(final Object o); @Override int hashCode(); static final String COMMANDS_ENTITY_GRAPH; static final String COMMANDS_DTO_ENTITY_GRAPH; static final String DTO_ENTITY_GRAPH; }### Answer: @Test void testSetDependencies() { final Set<FileEntity> dependencies = Sets.newHashSet(new FileEntity("s3: this.a.setDependencies(dependencies); Assertions.assertThat(this.a.getDependencies()).isEqualTo(dependencies); this.a.setDependencies(null); Assertions.assertThat(this.a.getDependencies()).isEmpty(); }
### Question: ApplicationEntity extends BaseEntity { public void setTags(@Nullable final Set<TagEntity> tags) { this.tags.clear(); if (tags != null) { this.tags.addAll(tags); } } ApplicationEntity(); Optional<String> getType(); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); @Override boolean equals(final Object o); @Override int hashCode(); static final String COMMANDS_ENTITY_GRAPH; static final String COMMANDS_DTO_ENTITY_GRAPH; static final String DTO_ENTITY_GRAPH; }### Answer: @Test void testSetTags() { final TagEntity tag1 = new TagEntity("tag1"); final TagEntity tag2 = new TagEntity("tag2"); final Set<TagEntity> tags = Sets.newHashSet(tag1, tag2); this.a.setTags(tags); Assertions.assertThat(this.a.getTags()).isEqualTo(tags); this.a.setTags(null); Assertions.assertThat(this.a.getTags()).isEmpty(); }
### Question: ApplicationEntity extends BaseEntity { void setCommands(@Nullable final Set<CommandEntity> commands) { this.commands.clear(); if (commands != null) { this.commands.addAll(commands); } } ApplicationEntity(); Optional<String> getType(); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); @Override boolean equals(final Object o); @Override int hashCode(); static final String COMMANDS_ENTITY_GRAPH; static final String COMMANDS_DTO_ENTITY_GRAPH; static final String DTO_ENTITY_GRAPH; }### Answer: @Test void testSetCommands() { final Set<CommandEntity> commandEntities = Sets.newHashSet(new CommandEntity()); this.a.setCommands(commandEntities); Assertions.assertThat(this.a.getCommands()).isEqualTo(commandEntities); this.a.setCommands(null); Assertions.assertThat(this.a.getCommands()).isEmpty(); }
### Question: CriterionEntity extends IdEntity { public void setTags(@Nullable final Set<TagEntity> tags) { this.tags.clear(); if (tags != null) { this.tags.addAll(tags); } } CriterionEntity( @Nullable final String uniqueId, @Nullable final String name, @Nullable final String version, @Nullable final String status, @Nullable final Set<TagEntity> tags ); Optional<String> getUniqueId(); void setUniqueId(@Nullable final String uniqueId); Optional<String> getName(); void setName(@Nullable final String name); Optional<String> getVersion(); void setVersion(@Nullable final String version); Optional<String> getStatus(); void setStatus(@Nullable final String status); void setTags(@Nullable final Set<TagEntity> tags); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer: @Test void canSetTags() { final CriterionEntity entity = new CriterionEntity(); Assertions.assertThat(entity.getTags()).isEmpty(); entity.setTags(null); Assertions.assertThat(entity.getTags()).isEmpty(); final Set<TagEntity> tags = Sets.newHashSet(); entity.setTags(tags); Assertions.assertThat(entity.getTags()).isEmpty(); tags.add(new TagEntity(UUID.randomUUID().toString())); entity.setTags(tags); Assertions.assertThat(entity.getTags()).isEqualTo(tags); }
### Question: CriterionEntity extends IdEntity { @Override public int hashCode() { return super.hashCode(); } CriterionEntity( @Nullable final String uniqueId, @Nullable final String name, @Nullable final String version, @Nullable final String status, @Nullable final Set<TagEntity> tags ); Optional<String> getUniqueId(); void setUniqueId(@Nullable final String uniqueId); Optional<String> getName(); void setName(@Nullable final String name); Optional<String> getVersion(); void setVersion(@Nullable final String version); Optional<String> getStatus(); void setStatus(@Nullable final String status); void setTags(@Nullable final Set<TagEntity> tags); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer: @Test void testEqualsAndHashCode() { final Set<TagEntity> tags = Sets.newHashSet( new TagEntity(UUID.randomUUID().toString()), new TagEntity(UUID.randomUUID().toString()) ); final CriterionEntity one = new CriterionEntity(null, null, null, null, tags); final CriterionEntity two = new CriterionEntity(null, null, null, null, tags); final CriterionEntity three = new CriterionEntity(); Assertions.assertThat(one).isEqualTo(two); Assertions.assertThat(one).isEqualTo(three); Assertions.assertThat(two).isEqualTo(three); Assertions.assertThat(one.hashCode()).isEqualTo(two.hashCode()); Assertions.assertThat(one.hashCode()).isEqualTo(three.hashCode()); Assertions.assertThat(two.hashCode()).isEqualTo(three.hashCode()); }
### Question: CommandEntity extends BaseEntity { public void setExecutable(@NotEmpty final List<@NotBlank @Size(max = 1024) String> executable) { this.executable.clear(); this.executable.addAll(executable); } CommandEntity(); void setExecutable(@NotEmpty final List<@NotBlank @Size(max = 1024) String> executable); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); Optional<Integer> getMemory(); Optional<JsonNode> getLauncherExt(); void setLauncherExt(@Nullable final JsonNode launcherExt); void setApplications( @Nullable final List<ApplicationEntity> applications ); void addApplication(@NotNull final ApplicationEntity application); void removeApplication(@NotNull final ApplicationEntity application); void setClusterCriteria(@Nullable final List<CriterionEntity> clusterCriteria); void addClusterCriterion(final CriterionEntity criterion); void addClusterCriterion(final CriterionEntity criterion, final int priority); CriterionEntity removeClusterCriterion(final int priority); @Override boolean equals(final Object o); @Override int hashCode(); static final String APPLICATIONS_ENTITY_GRAPH; static final String APPLICATIONS_DTO_ENTITY_GRAPH; static final String CLUSTER_CRITERIA_ENTITY_GRAPH; static final String DTO_ENTITY_GRAPH; }### Answer: @Test void testValidateEmptyExecutable() { this.c.setExecutable(Lists.newArrayList()); Assertions .assertThatExceptionOfType(ConstraintViolationException.class) .isThrownBy(() -> this.validate(this.c)); } @Test void testValidateBlankExecutable() { this.c.setExecutable(Lists.newArrayList(" ")); Assertions .assertThatExceptionOfType(ConstraintViolationException.class) .isThrownBy(() -> this.validate(this.c)); } @Test void testValidateExecutableArgumentTooLong() { this.c.setExecutable(Lists.newArrayList(StringUtils.leftPad("", 1025, 'e'))); Assertions .assertThatExceptionOfType(ConstraintViolationException.class) .isThrownBy(() -> this.validate(this.c)); } @Test void testSetExecutable() { this.c.setExecutable(EXECUTABLE); Assertions.assertThat(this.c.getExecutable()).isEqualTo(EXECUTABLE); }
### Question: CommandEntity extends BaseEntity { public Optional<Integer> getMemory() { return Optional.ofNullable(this.memory); } CommandEntity(); void setExecutable(@NotEmpty final List<@NotBlank @Size(max = 1024) String> executable); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); Optional<Integer> getMemory(); Optional<JsonNode> getLauncherExt(); void setLauncherExt(@Nullable final JsonNode launcherExt); void setApplications( @Nullable final List<ApplicationEntity> applications ); void addApplication(@NotNull final ApplicationEntity application); void removeApplication(@NotNull final ApplicationEntity application); void setClusterCriteria(@Nullable final List<CriterionEntity> clusterCriteria); void addClusterCriterion(final CriterionEntity criterion); void addClusterCriterion(final CriterionEntity criterion, final int priority); CriterionEntity removeClusterCriterion(final int priority); @Override boolean equals(final Object o); @Override int hashCode(); static final String APPLICATIONS_ENTITY_GRAPH; static final String APPLICATIONS_DTO_ENTITY_GRAPH; static final String CLUSTER_CRITERIA_ENTITY_GRAPH; static final String DTO_ENTITY_GRAPH; }### Answer: @Test void testSetMemory() { Assertions.assertThat(this.c.getMemory()).isPresent().contains(MEMORY); final int newMemory = MEMORY + 1; this.c.setMemory(newMemory); Assertions.assertThat(this.c.getMemory()).isPresent().contains(newMemory); }
### Question: CommandEntity extends BaseEntity { public void setConfigs(@Nullable final Set<FileEntity> configs) { this.configs.clear(); if (configs != null) { this.configs.addAll(configs); } } CommandEntity(); void setExecutable(@NotEmpty final List<@NotBlank @Size(max = 1024) String> executable); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); Optional<Integer> getMemory(); Optional<JsonNode> getLauncherExt(); void setLauncherExt(@Nullable final JsonNode launcherExt); void setApplications( @Nullable final List<ApplicationEntity> applications ); void addApplication(@NotNull final ApplicationEntity application); void removeApplication(@NotNull final ApplicationEntity application); void setClusterCriteria(@Nullable final List<CriterionEntity> clusterCriteria); void addClusterCriterion(final CriterionEntity criterion); void addClusterCriterion(final CriterionEntity criterion, final int priority); CriterionEntity removeClusterCriterion(final int priority); @Override boolean equals(final Object o); @Override int hashCode(); static final String APPLICATIONS_ENTITY_GRAPH; static final String APPLICATIONS_DTO_ENTITY_GRAPH; static final String CLUSTER_CRITERIA_ENTITY_GRAPH; static final String DTO_ENTITY_GRAPH; }### Answer: @Test void testSetConfigs() { Assertions.assertThat(this.c.getConfigs()).isEmpty(); final Set<FileEntity> configs = Sets.newHashSet(new FileEntity("s3: this.c.setConfigs(configs); Assertions.assertThat(this.c.getConfigs()).isEqualTo(configs); this.c.setConfigs(null); Assertions.assertThat(this.c.getConfigs()).isEmpty(); }
### Question: CommandEntity extends BaseEntity { public void setDependencies(@Nullable final Set<FileEntity> dependencies) { this.dependencies.clear(); if (dependencies != null) { this.dependencies.addAll(dependencies); } } CommandEntity(); void setExecutable(@NotEmpty final List<@NotBlank @Size(max = 1024) String> executable); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); Optional<Integer> getMemory(); Optional<JsonNode> getLauncherExt(); void setLauncherExt(@Nullable final JsonNode launcherExt); void setApplications( @Nullable final List<ApplicationEntity> applications ); void addApplication(@NotNull final ApplicationEntity application); void removeApplication(@NotNull final ApplicationEntity application); void setClusterCriteria(@Nullable final List<CriterionEntity> clusterCriteria); void addClusterCriterion(final CriterionEntity criterion); void addClusterCriterion(final CriterionEntity criterion, final int priority); CriterionEntity removeClusterCriterion(final int priority); @Override boolean equals(final Object o); @Override int hashCode(); static final String APPLICATIONS_ENTITY_GRAPH; static final String APPLICATIONS_DTO_ENTITY_GRAPH; static final String CLUSTER_CRITERIA_ENTITY_GRAPH; static final String DTO_ENTITY_GRAPH; }### Answer: @Test void testSetDependencies() { Assertions.assertThat(this.c.getDependencies()).isEmpty(); final Set<FileEntity> dependencies = Sets.newHashSet(new FileEntity("dep1")); this.c.setDependencies(dependencies); Assertions.assertThat(this.c.getDependencies()).isEqualTo(dependencies); this.c.setDependencies(null); Assertions.assertThat(this.c.getDependencies()).isEmpty(); }
### Question: CommandEntity extends BaseEntity { public void setTags(@Nullable final Set<TagEntity> tags) { this.tags.clear(); if (tags != null) { this.tags.addAll(tags); } } CommandEntity(); void setExecutable(@NotEmpty final List<@NotBlank @Size(max = 1024) String> executable); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); Optional<Integer> getMemory(); Optional<JsonNode> getLauncherExt(); void setLauncherExt(@Nullable final JsonNode launcherExt); void setApplications( @Nullable final List<ApplicationEntity> applications ); void addApplication(@NotNull final ApplicationEntity application); void removeApplication(@NotNull final ApplicationEntity application); void setClusterCriteria(@Nullable final List<CriterionEntity> clusterCriteria); void addClusterCriterion(final CriterionEntity criterion); void addClusterCriterion(final CriterionEntity criterion, final int priority); CriterionEntity removeClusterCriterion(final int priority); @Override boolean equals(final Object o); @Override int hashCode(); static final String APPLICATIONS_ENTITY_GRAPH; static final String APPLICATIONS_DTO_ENTITY_GRAPH; static final String CLUSTER_CRITERIA_ENTITY_GRAPH; static final String DTO_ENTITY_GRAPH; }### Answer: @Test void testSetTags() { Assertions.assertThat(this.c.getTags()).isEmpty(); final TagEntity one = new TagEntity("tag1"); final TagEntity two = new TagEntity("tag2"); final Set<TagEntity> tags = Sets.newHashSet(one, two); this.c.setTags(tags); Assertions.assertThat(this.c.getTags()).isEqualTo(tags); this.c.setTags(null); Assertions.assertThat(this.c.getTags()).isEmpty(); }
### Question: CommandEntity extends BaseEntity { public void setApplications( @Nullable final List<ApplicationEntity> applications ) throws PreconditionFailedException { if (applications != null && applications.stream().map(ApplicationEntity::getUniqueId).distinct().count() != applications.size()) { throw new PreconditionFailedException("List of applications to set cannot contain duplicates"); } for (final ApplicationEntity application : this.applications) { application.getCommands().remove(this); } this.applications.clear(); if (applications != null) { this.applications.addAll(applications); for (final ApplicationEntity application : this.applications) { application.getCommands().add(this); } } } CommandEntity(); void setExecutable(@NotEmpty final List<@NotBlank @Size(max = 1024) String> executable); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); Optional<Integer> getMemory(); Optional<JsonNode> getLauncherExt(); void setLauncherExt(@Nullable final JsonNode launcherExt); void setApplications( @Nullable final List<ApplicationEntity> applications ); void addApplication(@NotNull final ApplicationEntity application); void removeApplication(@NotNull final ApplicationEntity application); void setClusterCriteria(@Nullable final List<CriterionEntity> clusterCriteria); void addClusterCriterion(final CriterionEntity criterion); void addClusterCriterion(final CriterionEntity criterion, final int priority); CriterionEntity removeClusterCriterion(final int priority); @Override boolean equals(final Object o); @Override int hashCode(); static final String APPLICATIONS_ENTITY_GRAPH; static final String APPLICATIONS_DTO_ENTITY_GRAPH; static final String CLUSTER_CRITERIA_ENTITY_GRAPH; static final String DTO_ENTITY_GRAPH; }### Answer: @Test void testSetApplications() throws GenieCheckedException { Assertions.assertThat(this.c.getApplications()).isEmpty(); final ApplicationEntity one = new ApplicationEntity(); one.setUniqueId("one"); final ApplicationEntity two = new ApplicationEntity(); two.setUniqueId("two"); final List<ApplicationEntity> applicationEntities = Lists.newArrayList(one, two); this.c.setApplications(applicationEntities); Assertions.assertThat(this.c.getApplications()).isEqualTo(applicationEntities); Assertions.assertThat(one.getCommands()).contains(this.c); Assertions.assertThat(two.getCommands()).contains(this.c); applicationEntities.clear(); applicationEntities.add(two); this.c.setApplications(applicationEntities); Assertions.assertThat(this.c.getApplications()).isEqualTo(applicationEntities); Assertions.assertThat(one.getCommands()).doesNotContain(this.c); Assertions.assertThat(two.getCommands()).contains(this.c); this.c.setApplications(null); Assertions.assertThat(this.c.getApplications()).isEmpty(); Assertions.assertThat(one.getCommands()).isEmpty(); Assertions.assertThat(two.getCommands()).isEmpty(); } @Test void cantSetApplicationsIfDuplicates() { final ApplicationEntity one = Mockito.mock(ApplicationEntity.class); Mockito.when(one.getUniqueId()).thenReturn(UUID.randomUUID().toString()); final ApplicationEntity two = Mockito.mock(ApplicationEntity.class); Mockito.when(two.getUniqueId()).thenReturn(UUID.randomUUID().toString()); Assertions .assertThatExceptionOfType(PreconditionFailedException.class) .isThrownBy(() -> this.c.setApplications(Lists.newArrayList(one, two, one))); }
### Question: CommandEntity extends BaseEntity { public void addApplication(@NotNull final ApplicationEntity application) throws PreconditionFailedException { if (this.applications.contains(application)) { throw new PreconditionFailedException( "An application with id " + application.getUniqueId() + " is already added" ); } this.applications.add(application); application.getCommands().add(this); } CommandEntity(); void setExecutable(@NotEmpty final List<@NotBlank @Size(max = 1024) String> executable); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); Optional<Integer> getMemory(); Optional<JsonNode> getLauncherExt(); void setLauncherExt(@Nullable final JsonNode launcherExt); void setApplications( @Nullable final List<ApplicationEntity> applications ); void addApplication(@NotNull final ApplicationEntity application); void removeApplication(@NotNull final ApplicationEntity application); void setClusterCriteria(@Nullable final List<CriterionEntity> clusterCriteria); void addClusterCriterion(final CriterionEntity criterion); void addClusterCriterion(final CriterionEntity criterion, final int priority); CriterionEntity removeClusterCriterion(final int priority); @Override boolean equals(final Object o); @Override int hashCode(); static final String APPLICATIONS_ENTITY_GRAPH; static final String APPLICATIONS_DTO_ENTITY_GRAPH; static final String CLUSTER_CRITERIA_ENTITY_GRAPH; static final String DTO_ENTITY_GRAPH; }### Answer: @Test void canAddApplication() throws PreconditionFailedException { final String id = UUID.randomUUID().toString(); final ApplicationEntity app = new ApplicationEntity(); app.setUniqueId(id); this.c.addApplication(app); Assertions.assertThat(this.c.getApplications()).contains(app); Assertions.assertThat(app.getCommands()).contains(this.c); } @Test void cantAddApplicationThatAlreadyIsInList() throws PreconditionFailedException { final String id = UUID.randomUUID().toString(); final ApplicationEntity app = new ApplicationEntity(); app.setUniqueId(id); this.c.addApplication(app); Assertions .assertThatExceptionOfType(PreconditionFailedException.class) .isThrownBy(() -> this.c.addApplication(app)); }
### Question: UNIXUtils { public static void changeOwnershipOfDirectory( final String dir, final String user, final Executor executor ) throws IOException { final CommandLine commandLine = new CommandLine(SUDO) .addArgument("chown") .addArgument("-R") .addArgument(user) .addArgument(dir); executor.execute(commandLine); } private UNIXUtils(); static synchronized void createUser( final String user, @Nullable final String group, final Executor executor ); static void changeOwnershipOfDirectory( final String dir, final String user, final Executor executor ); }### Answer: @Test void testChangeOwnershipOfDirectoryMethodSuccess() throws IOException { final String user = "user"; final String dir = "dir"; final ArgumentCaptor<CommandLine> argumentCaptor = ArgumentCaptor.forClass(CommandLine.class); final List<String> command = Arrays.asList("sudo", "chown", "-R", user, dir); UNIXUtils.changeOwnershipOfDirectory(dir, user, executor); Mockito.verify(this.executor).execute(argumentCaptor.capture()); Assertions.assertThat(argumentCaptor.getValue().toStrings()).containsExactlyElementsOf(command); } @Test void testChangeOwnershipOfDirectoryMethodFailure() throws IOException { final String user = "user"; final String dir = "dir"; Mockito.when(this.executor.execute(Mockito.any(CommandLine.class))).thenThrow(new IOException()); Assertions.assertThatIOException().isThrownBy(() -> UNIXUtils.changeOwnershipOfDirectory(dir, user, executor)); }
### Question: UNIXUtils { public static synchronized void createUser( final String user, @Nullable final String group, final Executor executor ) throws IOException { final CommandLine idCheckCommandLine = new CommandLine("id") .addArgument("-u") .addArgument(user); try { executor.execute(idCheckCommandLine); log.debug("User already exists"); } catch (final IOException ioe) { log.debug("User does not exist. Creating it now."); final boolean isGroupValid = StringUtils.isNotBlank(group) && !group.equals(user); if (isGroupValid) { log.debug("Group and User are different so creating group now."); final CommandLine groupCreateCommandLine = new CommandLine(SUDO).addArgument("groupadd") .addArgument(group); try { log.debug("Running command to create group: [{}]", groupCreateCommandLine); executor.execute(groupCreateCommandLine); } catch (IOException ioexception) { log.debug("Group creation threw an error as it might already exist", ioexception); } } final CommandLine userCreateCommandLine = new CommandLine(SUDO) .addArgument("useradd") .addArgument(user); if (isGroupValid) { userCreateCommandLine .addArgument("-G") .addArgument(group); } userCreateCommandLine .addArgument("-M"); log.debug("Running command to create user: [{}]", userCreateCommandLine); executor.execute(userCreateCommandLine); } } private UNIXUtils(); static synchronized void createUser( final String user, @Nullable final String group, final Executor executor ); static void changeOwnershipOfDirectory( final String dir, final String user, final Executor executor ); }### Answer: @Test void testCreateUserMethodSuccessAlreadyExists() throws IOException { final String user = "user"; final String group = "group"; final ArgumentCaptor<CommandLine> argumentCaptor = ArgumentCaptor.forClass(CommandLine.class); final List<String> command = Arrays.asList("id", "-u", user); UNIXUtils.createUser(user, group, executor); Mockito.verify(this.executor).execute(argumentCaptor.capture()); Assertions.assertThat(argumentCaptor.getValue().toStrings()).containsExactlyElementsOf(command); } @Test void testCreateUserMethodSuccessDoesNotExist1() throws IOException { final String user = "user"; final String group = "group"; final CommandLine idCheckCommandLine = new CommandLine("id"); idCheckCommandLine.addArgument("-u"); idCheckCommandLine.addArgument(user); Mockito.when(this.executor.execute(Mockito.any(CommandLine.class))).thenThrow(new IOException()); final ArgumentCaptor<CommandLine> argumentCaptor = ArgumentCaptor.forClass(CommandLine.class); final List<String> command = Arrays.asList("sudo", "useradd", user, "-G", group, "-M"); try { UNIXUtils.createUser(user, group, executor); } catch (IOException ignored) { } Mockito.verify(this.executor, Mockito.times(3)).execute(argumentCaptor.capture()); Assertions.assertThat(argumentCaptor.getAllValues().get(2).toStrings()).containsExactlyElementsOf(command); } @Test void testCreateUserMethodSuccessDoesNotExist2() throws IOException { final String user = "user"; final String group = "group"; Mockito.when(this.executor.execute(Mockito.any(CommandLine.class))).thenThrow(new IOException()); Assertions.assertThatIOException().isThrownBy(() -> UNIXUtils.createUser(user, group, executor)); }
### Question: JobsActiveLimitProperties implements EnvironmentAware { public int getUserLimit(final String user) { final Environment env = this.environment.get(); if (env != null) { return env.getProperty( USER_LIMIT_OVERRIDE_PROPERTY_PREFIX + user, Integer.class, this.count ); } return this.count; } int getUserLimit(final String user); @Override void setEnvironment(final Environment environment); static final String PROPERTY_PREFIX; static final String ENABLED_PROPERTY; static final String USER_LIMIT_OVERRIDE_PROPERTY_PREFIX; static final boolean DEFAULT_ENABLED; static final int DEFAULT_COUNT; }### Answer: @Test void canConstruct() { Assertions.assertThat(this.properties.isEnabled()).isEqualTo(JobsActiveLimitProperties.DEFAULT_ENABLED); Assertions.assertThat(this.properties.getCount()).isEqualTo(JobsActiveLimitProperties.DEFAULT_COUNT); Assertions .assertThat(this.properties.getUserLimit("SomeUser")) .isEqualTo(JobsActiveLimitProperties.DEFAULT_COUNT); }
### Question: TaskUtils { public static Instant getMidnightUTC() { return ZonedDateTime.now(ZoneId.of("UTC")).withHour(0).withMinute(0).withSecond(0).withNano(0).toInstant(); } protected TaskUtils(); static Instant getMidnightUTC(); }### Answer: @Test void canGetMidnightUtc() { final Instant midnightUTC = TaskUtils.getMidnightUTC(); final ZonedDateTime cal = ZonedDateTime.ofInstant(midnightUTC, ZoneId.of("UTC")); Assertions.assertThat(cal.getNano()).isEqualTo(0); Assertions.assertThat(cal.getSecond()).isEqualTo(0); Assertions.assertThat(cal.getMinute()).isEqualTo(0); Assertions.assertThat(cal.getHour()).isEqualTo(0); }
### Question: DatabaseCleanupTask extends LeaderTask { @Override public GenieTaskScheduleType getScheduleType() { return GenieTaskScheduleType.TRIGGER; } DatabaseCleanupTask( @NotNull final DatabaseCleanupProperties cleanupProperties, @NotNull final Environment environment, @NotNull final DataServices dataServices, @NotNull final MeterRegistry registry ); @Override GenieTaskScheduleType getScheduleType(); @Override Trigger getTrigger(); @Override void run(); @Override void cleanup(); }### Answer: @Test void canGetScheduleType() { Assertions.assertThat(this.task.getScheduleType()).isEqualTo(GenieTaskScheduleType.TRIGGER); }
### Question: DatabaseCleanupTask extends LeaderTask { @Override public Trigger getTrigger() { final String expression = this.environment.getProperty( DatabaseCleanupProperties.EXPRESSION_PROPERTY, String.class, this.cleanupProperties.getExpression() ); return new CronTrigger(expression, JobConstants.UTC); } DatabaseCleanupTask( @NotNull final DatabaseCleanupProperties cleanupProperties, @NotNull final Environment environment, @NotNull final DataServices dataServices, @NotNull final MeterRegistry registry ); @Override GenieTaskScheduleType getScheduleType(); @Override Trigger getTrigger(); @Override void run(); @Override void cleanup(); }### Answer: @Test void canGetTrigger() { final String expression = "0 0 1 * * *"; this.environment.setProperty(DatabaseCleanupProperties.EXPRESSION_PROPERTY, expression); Mockito.when(this.cleanupProperties.getExpression()).thenReturn("0 0 0 * * *"); final Trigger trigger = this.task.getTrigger(); if (trigger instanceof CronTrigger) { final CronTrigger cronTrigger = (CronTrigger) trigger; Assertions.assertThat(cronTrigger.getExpression()).isEqualTo(expression); } else { Assertions.fail("Trigger was not of expected type: " + CronTrigger.class.getName()); } }
### Question: DefaultDirectoryWriter implements DirectoryWriter { @Override public String toHtml( @NotNull final File directory, @URL final String requestURL, final boolean includeParent ) throws IOException { final Directory dir = this.getDirectory(directory, requestURL, includeParent); return directoryToHTML(directory.getName(), dir); } static String directoryToHTML(final String directoryName, final Directory directory); @Override String toHtml( @NotNull final File directory, @URL final String requestURL, final boolean includeParent ); @Override String toJson( @NotNull final File directory, @URL final String requestURL, final boolean includeParent ); }### Answer: @Test void canConvertToHtml() throws Exception { this.setupWithParent(); final String html = this.writer.toHtml(this.directory, REQUEST_URL_WITH_PARENT, true); Assertions.assertThat(html).isNotNull(); final Tidy tidy = new Tidy(); final Writer stringWriter = new StringWriter(); tidy.parse(new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8)), stringWriter); Assertions.assertThat(tidy.getParseErrors()).isEqualTo(0); Assertions.assertThat(tidy.getParseWarnings()).isEqualTo(0); }
### Question: TasksCleanup { @EventListener public void onShutdown(final ContextClosedEvent event) { log.info("Shutting down the scheduler due to {}", event); this.scheduler.shutdown(); } @Autowired TasksCleanup(@Qualifier("genieTaskScheduler") @NotNull final ThreadPoolTaskScheduler scheduler); @EventListener void onShutdown(final ContextClosedEvent event); }### Answer: @Test void canShutdown() { final ContextClosedEvent event = Mockito.mock(ContextClosedEvent.class); final TasksCleanup cleanup = new TasksCleanup(this.scheduler); cleanup.onShutdown(event); Mockito.verify(this.scheduler, Mockito.times(1)).shutdown(); }
### Question: ApplicationModelAssembler implements RepresentationModelAssembler<Application, EntityModel<Application>> { @Override @Nonnull public EntityModel<Application> toModel(final Application application) { final String id = application.getId().orElseThrow(IllegalArgumentException::new); final EntityModel<Application> applicationModel = new EntityModel<>(application); try { applicationModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(ApplicationRestController.class) .getApplication(id) ).withSelfRel() ); applicationModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(ApplicationRestController.class) .getCommandsForApplication(id, null) ).withRel(COMMANDS_LINK) ); } catch (final GenieException | NotFoundException ge) { throw new RuntimeException(ge); } return applicationModel; } @Override @Nonnull EntityModel<Application> toModel(final Application application); }### Answer: @Test void canConvertToModel() { final EntityModel<Application> model = this.assembler.toModel(this.application); Assertions.assertThat(model.getLinks()).hasSize(2); Assertions.assertThat(model.getLink("self")).isPresent(); Assertions.assertThat(model.getLink("commands")).isPresent(); }
### Question: JobModelAssembler implements RepresentationModelAssembler<Job, EntityModel<Job>> { @Override @Nonnull public EntityModel<Job> toModel(final Job job) { final String id = job.getId().orElseThrow(IllegalArgumentException::new); final EntityModel<Job> jobModel = new EntityModel<>(job); try { jobModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJob(id) ).withSelfRel() ); jobModel.add( WebMvcLinkBuilder .linkTo(JobRestController.class) .slash(id) .slash(OUTPUT_LINK) .withRel(OUTPUT_LINK) ); jobModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobRequest(id) ).withRel(REQUEST_LINK) ); jobModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobExecution(id) ).withRel(EXECUTION_LINK) ); jobModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobMetadata(id) ).withRel(METADATA_LINK) ); jobModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobStatus(id) ).withRel(STATUS_LINK) ); jobModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobCluster(id) ).withRel(CLUSTER_LINK) ); jobModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobCommand(id) ).withRel(COMMAND_LINK) ); jobModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobApplications(id) ).withRel(APPLICATIONS_LINK) ); } catch (final GenieException | GenieCheckedException ge) { throw new RuntimeException(ge); } return jobModel; } @Override @Nonnull EntityModel<Job> toModel(final Job job); }### Answer: @Test public void canConvertToModel() { final EntityModel<Job> model = this.assembler.toModel(this.job); Assertions.assertThat(model.getLinks()).hasSize(9); Assertions.assertThat(model.getLink("self")).isPresent(); Assertions.assertThat(model.getLink("output")).isPresent(); Assertions.assertThat(model.getLink("request")).isPresent(); Assertions.assertThat(model.getLink("execution")).isPresent(); Assertions.assertThat(model.getLink("metadata")).isPresent(); Assertions.assertThat(model.getLink("status")).isPresent(); Assertions.assertThat(model.getLink("cluster")).isPresent(); Assertions.assertThat(model.getLink("command")).isPresent(); Assertions.assertThat(model.getLink("applications")).isPresent(); }
### Question: DefaultDirectoryWriter implements DirectoryWriter { @Override public String toJson( @NotNull final File directory, @URL final String requestURL, final boolean includeParent ) throws Exception { final Directory dir = this.getDirectory(directory, requestURL, includeParent); return GenieObjectMapper.getMapper().writeValueAsString(dir); } static String directoryToHTML(final String directoryName, final Directory directory); @Override String toHtml( @NotNull final File directory, @URL final String requestURL, final boolean includeParent ); @Override String toJson( @NotNull final File directory, @URL final String requestURL, final boolean includeParent ); }### Answer: @Test void canConvertToJson() throws Exception { this.setupWithParent(); final String json = this.writer.toJson(this.directory, REQUEST_URL_WITH_PARENT, true); Assertions.assertThat(json).isNotNull(); final DefaultDirectoryWriter.Directory dir = GenieObjectMapper.getMapper().readValue(json, DefaultDirectoryWriter.Directory.class); Assertions.assertThat(dir.getParent()).isNotNull(); Assertions.assertThat(dir.getParent().getName()).isEqualTo(PARENT_NAME); Assertions.assertThat(dir.getParent().getUrl()).isEqualTo(PARENT_URL); Assertions.assertThat(dir.getParent().getSize()).isEqualTo(PARENT_SIZE); Assertions.assertThat(dir.getParent().getLastModified()).isEqualTo(PARENT_LAST_MODIFIED); Assertions.assertThat(dir.getDirectories()).isNotNull(); Assertions .assertThat(dir.getDirectories()) .containsExactlyInAnyOrder(this.directoryEntry1, this.directoryEntry2); Assertions.assertThat(dir.getFiles()).isNotNull(); Assertions .assertThat(dir.getFiles()) .containsExactlyInAnyOrder(this.fileEntry1, this.fileEntry2); }
### Question: Entity_Feature { public String getAddress() { return address; } Entity_Feature(tracerengine Trac, Activity activity, String device_feature_model_id, int id, int devId, String device_usage_id, String address, String device_type_id, String description, String name, String state_key, String parameters, String value_type); int getId(); void setId(int id); JSONObject getDevice(); String getDescription(); void setDescription(String description); String getDevice_usage_id(); void setDevice_usage_id(String device_usage_id); String getAddress(); void setAddress(String address); int getDevId(); void setDevId(int devId); String getName(); void setName(String name); String getDevice_feature_model_id(); void setDevice_feature_model_id(String device_feature_model_id); String getState_key(); void setState_key(String state_key); String getParameters(); void setParameters(String parameters); String getValue_type(); void setValue_type(String value_type); int getRessources(); void setState(int state); String getDevice_type(); String getDevice_type_id(); void setDevice_type_id(String device_type_id); String getIcon_name(); }### Answer: @Test public void testGetAddress() throws Exception { String address = client.getAddress(); Assert.assertEquals(null, address); client.setAddress("Address"); address = client.getAddress(); Assert.assertEquals("Address", address); }
### Question: Entity_Feature_Association { public String getPlace_type() { return place_type; } Entity_Feature_Association(int place_id, String place_type, int device_feature_id, int id, String device_feature); int getPlace_id(); void setPlace_id(int placeId); String getPlace_type(); void setPlace_type(String placeType); int getDevice_feature_id(); void setDevice_feature_id(int deviceFeatureId); int getId(); void setId(int id); JSONObject getDevice_feature(); void setDevice_feature(JSONObject json_deviceFeature); String getFeat_model_id(); int getFeat_id(); int getFeat_device_id(); }### Answer: @Test public void testGetPlace_type() throws Exception { Entity_Feature_Association feature_association = new Entity_Feature_Association(0, null, 0, 0, null); }
### Question: Entity_Feature_Association { public int getDevice_feature_id() { return device_feature_id; } Entity_Feature_Association(int place_id, String place_type, int device_feature_id, int id, String device_feature); int getPlace_id(); void setPlace_id(int placeId); String getPlace_type(); void setPlace_type(String placeType); int getDevice_feature_id(); void setDevice_feature_id(int deviceFeatureId); int getId(); void setId(int id); JSONObject getDevice_feature(); void setDevice_feature(JSONObject json_deviceFeature); String getFeat_model_id(); int getFeat_id(); int getFeat_device_id(); }### Answer: @Test public void testGetDevice_feature_id() throws Exception { Entity_Feature_Association feature_association = new Entity_Feature_Association(0, null, 0, 0, null); int Device_feature_id = feature_association.getDevice_feature_id(); Assert.assertEquals(0, Device_feature_id); feature_association.setDevice_feature_id(125); Device_feature_id = feature_association.getDevice_feature_id(); Assert.assertEquals(125, Device_feature_id); }
### Question: Entity_Feature_Association { public int getId() { return id; } Entity_Feature_Association(int place_id, String place_type, int device_feature_id, int id, String device_feature); int getPlace_id(); void setPlace_id(int placeId); String getPlace_type(); void setPlace_type(String placeType); int getDevice_feature_id(); void setDevice_feature_id(int deviceFeatureId); int getId(); void setId(int id); JSONObject getDevice_feature(); void setDevice_feature(JSONObject json_deviceFeature); String getFeat_model_id(); int getFeat_id(); int getFeat_device_id(); }### Answer: @Test public void testGetId() throws Exception { Entity_Feature_Association feature_association = new Entity_Feature_Association(0, null, 0, 0, null); int id = feature_association.getId(); Assert.assertEquals(0, id); feature_association.setId(125); id = feature_association.getId(); Assert.assertEquals(125, id); }
### Question: Entity_Feature_Association { public JSONObject getDevice_feature() { return json_device_feature; } Entity_Feature_Association(int place_id, String place_type, int device_feature_id, int id, String device_feature); int getPlace_id(); void setPlace_id(int placeId); String getPlace_type(); void setPlace_type(String placeType); int getDevice_feature_id(); void setDevice_feature_id(int deviceFeatureId); int getId(); void setId(int id); JSONObject getDevice_feature(); void setDevice_feature(JSONObject json_deviceFeature); String getFeat_model_id(); int getFeat_id(); int getFeat_device_id(); }### Answer: @Test public void testGetDevice_feature() throws Exception { Entity_Feature_Association feature_association = new Entity_Feature_Association(0, null, 0, 0, null); JSONObject device_feature = feature_association.getDevice_feature(); feature_association.setDevice_feature(new JSONObject("")); device_feature = feature_association.getDevice_feature(); }
### Question: Entity_Feature_Association { public String getFeat_model_id() { return feat_model_id; } Entity_Feature_Association(int place_id, String place_type, int device_feature_id, int id, String device_feature); int getPlace_id(); void setPlace_id(int placeId); String getPlace_type(); void setPlace_type(String placeType); int getDevice_feature_id(); void setDevice_feature_id(int deviceFeatureId); int getId(); void setId(int id); JSONObject getDevice_feature(); void setDevice_feature(JSONObject json_deviceFeature); String getFeat_model_id(); int getFeat_id(); int getFeat_device_id(); }### Answer: @Test public void testGetFeat_model_id() throws Exception { Entity_Feature_Association feature_association = new Entity_Feature_Association(0, null, 0, 0, null); String feature_model_id = feature_association.getFeat_model_id(); Assert.assertEquals(null, feature_model_id); JSONObject device_feature_model_id = new JSONObject(); device_feature_model_id.put("device_feature_model_id", "125"); feature_association.setDevice_feature(device_feature_model_id); feature_model_id = feature_association.getFeat_model_id(); }
### Question: Entity_Feature_Association { public int getFeat_id() { return feat_id; } Entity_Feature_Association(int place_id, String place_type, int device_feature_id, int id, String device_feature); int getPlace_id(); void setPlace_id(int placeId); String getPlace_type(); void setPlace_type(String placeType); int getDevice_feature_id(); void setDevice_feature_id(int deviceFeatureId); int getId(); void setId(int id); JSONObject getDevice_feature(); void setDevice_feature(JSONObject json_deviceFeature); String getFeat_model_id(); int getFeat_id(); int getFeat_device_id(); }### Answer: @Test public void testGetFeat_id() throws Exception { Entity_Feature_Association feature_association = new Entity_Feature_Association(0, null, 0, 0, null); int feature_id = feature_association.getFeat_id(); Assert.assertEquals(0, feature_id); JSONObject device_feature_model_id = new JSONObject(); device_feature_model_id.put("id", "125"); feature_association.setDevice_feature(device_feature_model_id); feature_id = feature_association.getFeat_id(); }
### Question: Entity_Feature_Association { public int getFeat_device_id() { return feat_device_id; } Entity_Feature_Association(int place_id, String place_type, int device_feature_id, int id, String device_feature); int getPlace_id(); void setPlace_id(int placeId); String getPlace_type(); void setPlace_type(String placeType); int getDevice_feature_id(); void setDevice_feature_id(int deviceFeatureId); int getId(); void setId(int id); JSONObject getDevice_feature(); void setDevice_feature(JSONObject json_deviceFeature); String getFeat_model_id(); int getFeat_id(); int getFeat_device_id(); }### Answer: @Test public void testGetFeat_device_id() throws Exception { Entity_Feature_Association feature_association = new Entity_Feature_Association(0, null, 0, 0, null); int feature_device_id = feature_association.getFeat_device_id(); Assert.assertEquals(0, feature_device_id); JSONObject device_feature_model_id = new JSONObject(); device_feature_model_id.put("device_id", "125"); feature_device_id = feature_association.getFeat_device_id(); }
### Question: Entity_client { public int getClientType() { return client_type; } Entity_client(int devId, String skey, String Name, int session_type); void setClientType(int type); void setClientId(int id); void setcacheId(int Id); void setDevId(int devId); void setskey(String skey); void setValue(String Value); void setName(String Name); void setTimestamp(String Timestamp); void setType(Boolean type); int getClientType(); int getClientId(); int getcacheId(); int getDevId(); String getskey(); String getValue(); String getName(); String getTimestamp(); Boolean is_Miniwidget(); void client_value_update(String val, String valtimestamp); }### Answer: @Test public void testGetClientType() throws Exception { int type = client.getClientType(); Assert.assertEquals(0, type); client.setClientType(125); type = client.getClientType(); Assert.assertEquals(125, type); }
### Question: Entity_client { public int getClientId() { return client_id; } Entity_client(int devId, String skey, String Name, int session_type); void setClientType(int type); void setClientId(int id); void setcacheId(int Id); void setDevId(int devId); void setskey(String skey); void setValue(String Value); void setName(String Name); void setTimestamp(String Timestamp); void setType(Boolean type); int getClientType(); int getClientId(); int getcacheId(); int getDevId(); String getskey(); String getValue(); String getName(); String getTimestamp(); Boolean is_Miniwidget(); void client_value_update(String val, String valtimestamp); }### Answer: @Test public void testGetClientId() throws Exception { int id = client.getClientId(); Assert.assertEquals(-1, id); client.setClientId(125); id = client.getClientId(); Assert.assertEquals(125, id); }
### Question: Entity_client { public int getcacheId() { return cache_id; } Entity_client(int devId, String skey, String Name, int session_type); void setClientType(int type); void setClientId(int id); void setcacheId(int Id); void setDevId(int devId); void setskey(String skey); void setValue(String Value); void setName(String Name); void setTimestamp(String Timestamp); void setType(Boolean type); int getClientType(); int getClientId(); int getcacheId(); int getDevId(); String getskey(); String getValue(); String getName(); String getTimestamp(); Boolean is_Miniwidget(); void client_value_update(String val, String valtimestamp); }### Answer: @Test public void testGetcacheId() throws Exception { int cacheid = client.getcacheId(); Assert.assertEquals(0, cacheid); client.setcacheId(125); cacheid = client.getcacheId(); Assert.assertEquals(125, cacheid); }
### Question: Entity_Feature { public String getDevice_feature_model_id() { return device_feature_model_id; } Entity_Feature(tracerengine Trac, Activity activity, String device_feature_model_id, int id, int devId, String device_usage_id, String address, String device_type_id, String description, String name, String state_key, String parameters, String value_type); int getId(); void setId(int id); JSONObject getDevice(); String getDescription(); void setDescription(String description); String getDevice_usage_id(); void setDevice_usage_id(String device_usage_id); String getAddress(); void setAddress(String address); int getDevId(); void setDevId(int devId); String getName(); void setName(String name); String getDevice_feature_model_id(); void setDevice_feature_model_id(String device_feature_model_id); String getState_key(); void setState_key(String state_key); String getParameters(); void setParameters(String parameters); String getValue_type(); void setValue_type(String value_type); int getRessources(); void setState(int state); String getDevice_type(); String getDevice_type_id(); void setDevice_type_id(String device_type_id); String getIcon_name(); }### Answer: @Test public void testGetDevice_feature_model_id() throws Exception { String device_feature_model_id = client.getDevice_feature_model_id(); Assert.assertEquals(null, device_feature_model_id); client.setDevice_feature_model_id("Device_feature_model_id"); device_feature_model_id = client.getDevice_feature_model_id(); Assert.assertEquals("Device_feature_model_id", device_feature_model_id); }
### Question: Entity_client { public int getDevId() { return devId; } Entity_client(int devId, String skey, String Name, int session_type); void setClientType(int type); void setClientId(int id); void setcacheId(int Id); void setDevId(int devId); void setskey(String skey); void setValue(String Value); void setName(String Name); void setTimestamp(String Timestamp); void setType(Boolean type); int getClientType(); int getClientId(); int getcacheId(); int getDevId(); String getskey(); String getValue(); String getName(); String getTimestamp(); Boolean is_Miniwidget(); void client_value_update(String val, String valtimestamp); }### Answer: @Test public void testGetDevId() throws Exception { int DevId = client.getDevId(); Assert.assertEquals(0, DevId); client.setDevId(125); DevId = client.getDevId(); Assert.assertEquals(125, DevId); }
### Question: Entity_client { public String getskey() { return skey; } Entity_client(int devId, String skey, String Name, int session_type); void setClientType(int type); void setClientId(int id); void setcacheId(int Id); void setDevId(int devId); void setskey(String skey); void setValue(String Value); void setName(String Name); void setTimestamp(String Timestamp); void setType(Boolean type); int getClientType(); int getClientId(); int getcacheId(); int getDevId(); String getskey(); String getValue(); String getName(); String getTimestamp(); Boolean is_Miniwidget(); void client_value_update(String val, String valtimestamp); }### Answer: @Test public void testGetskey() throws Exception { String skey = client.getskey(); Assert.assertEquals(null, skey); client.setskey("Skey"); skey = client.getskey(); Assert.assertEquals("Skey", skey); }
### Question: Entity_client { public String getValue() { return currentState; } Entity_client(int devId, String skey, String Name, int session_type); void setClientType(int type); void setClientId(int id); void setcacheId(int Id); void setDevId(int devId); void setskey(String skey); void setValue(String Value); void setName(String Name); void setTimestamp(String Timestamp); void setType(Boolean type); int getClientType(); int getClientId(); int getcacheId(); int getDevId(); String getskey(); String getValue(); String getName(); String getTimestamp(); Boolean is_Miniwidget(); void client_value_update(String val, String valtimestamp); }### Answer: @Test public void testGetValue() throws Exception { String value = client.getValue(); Assert.assertEquals(null, value); client.setValue("Value"); value = client.getValue(); Assert.assertEquals("Value", value); }
### Question: Entity_client { public String getName() { return client_name; } Entity_client(int devId, String skey, String Name, int session_type); void setClientType(int type); void setClientId(int id); void setcacheId(int Id); void setDevId(int devId); void setskey(String skey); void setValue(String Value); void setName(String Name); void setTimestamp(String Timestamp); void setType(Boolean type); int getClientType(); int getClientId(); int getcacheId(); int getDevId(); String getskey(); String getValue(); String getName(); String getTimestamp(); Boolean is_Miniwidget(); void client_value_update(String val, String valtimestamp); }### Answer: @Test public void testGetName() throws Exception { String name = client.getName(); Assert.assertEquals(null, name); client.setName("Name"); name = client.getName(); Assert.assertEquals("Name", name); }
### Question: Entity_client { public String getTimestamp() { return timestamp; } Entity_client(int devId, String skey, String Name, int session_type); void setClientType(int type); void setClientId(int id); void setcacheId(int Id); void setDevId(int devId); void setskey(String skey); void setValue(String Value); void setName(String Name); void setTimestamp(String Timestamp); void setType(Boolean type); int getClientType(); int getClientId(); int getcacheId(); int getDevId(); String getskey(); String getValue(); String getName(); String getTimestamp(); Boolean is_Miniwidget(); void client_value_update(String val, String valtimestamp); }### Answer: @Test public void testGetTimestamp() throws Exception { String timestamp = client.getTimestamp(); Assert.assertEquals(null, timestamp); client.setTimestamp("Timestamp"); timestamp = client.getTimestamp(); Assert.assertEquals("Timestamp", timestamp); }
### Question: Entity_client { public Boolean is_Miniwidget() { return miniwidget; } Entity_client(int devId, String skey, String Name, int session_type); void setClientType(int type); void setClientId(int id); void setcacheId(int Id); void setDevId(int devId); void setskey(String skey); void setValue(String Value); void setName(String Name); void setTimestamp(String Timestamp); void setType(Boolean type); int getClientType(); int getClientId(); int getcacheId(); int getDevId(); String getskey(); String getValue(); String getName(); String getTimestamp(); Boolean is_Miniwidget(); void client_value_update(String val, String valtimestamp); }### Answer: @Test public void testIs_Miniwidget() throws Exception { Boolean type = client.is_Miniwidget(); Assert.assertEquals(false, type); client.setType(true); type = client.is_Miniwidget(); Assert.assertEquals(true, type); }
### Question: Entity_Feature { public String getState_key() { return state_key; } Entity_Feature(tracerengine Trac, Activity activity, String device_feature_model_id, int id, int devId, String device_usage_id, String address, String device_type_id, String description, String name, String state_key, String parameters, String value_type); int getId(); void setId(int id); JSONObject getDevice(); String getDescription(); void setDescription(String description); String getDevice_usage_id(); void setDevice_usage_id(String device_usage_id); String getAddress(); void setAddress(String address); int getDevId(); void setDevId(int devId); String getName(); void setName(String name); String getDevice_feature_model_id(); void setDevice_feature_model_id(String device_feature_model_id); String getState_key(); void setState_key(String state_key); String getParameters(); void setParameters(String parameters); String getValue_type(); void setValue_type(String value_type); int getRessources(); void setState(int state); String getDevice_type(); String getDevice_type_id(); void setDevice_type_id(String device_type_id); String getIcon_name(); }### Answer: @Test public void testGetState_key() throws Exception { String state_key = client.getState_key(); Assert.assertEquals(null, state_key); client.setState_key("State_key"); state_key = client.getState_key(); Assert.assertEquals("State_key", state_key); }