method2testcases
stringlengths
118
3.08k
### Question: RepositorySecurityDecorator extends AbstractRepositoryDecorator<Entity> { @Override public AggregateResult aggregate(AggregateQuery aggregateQuery) { EntityType entityType = delegate().getEntityType(); validatePermission(entityType, AGGREGATE_DATA); return delegate().aggregate(aggregateQuery); } RepositorySecurityDecorator( Repository<Entity> delegateRepository, UserPermissionEvaluator permissionService); @Override Iterator<Entity> iterator(); @Override void forEachBatched(Fetch fetch, Consumer<List<Entity>> consumer, int batchSize); @Override void close(); @Override long count(Query<Entity> q); @Override Stream<Entity> findAll(Query<Entity> q); @Override Entity findOne(Query<Entity> q); @Override Entity findOneById(Object id); @Override Entity findOneById(Object id, Fetch fetch); @Override Stream<Entity> findAll(Stream<Object> ids); @Override Stream<Entity> findAll(Stream<Object> ids, Fetch fetch); @Override long count(); @Override void update(Entity entity); @Override void update(Stream<Entity> entities); @Override void delete(Entity entity); @Override void delete(Stream<Entity> entities); @Override void deleteById(Object id); @Override void deleteAll(Stream<Object> ids); @Override void deleteAll(); @Override void add(Entity entity); @Override Integer add(Stream<Entity> entities); @Override AggregateResult aggregate(AggregateQuery aggregateQuery); }### Answer: @Test void testAggregatePermissionGranted() { initPermissionServiceMock(AGGREGATE_DATA, true); AggregateQuery aggregateQuery = mock(AggregateQuery.class); repositorySecurityDecorator.aggregate(aggregateQuery); verify(delegateRepository).aggregate(aggregateQuery); } @Test void testAggregatePermissionDenied() { initPermissionServiceMock(AGGREGATE_DATA, false); AggregateQuery aggregateQuery = mock(AggregateQuery.class); Exception exception = assertThrows( EntityTypePermissionDeniedException.class, () -> repositorySecurityDecorator.aggregate(aggregateQuery)); assertThat(exception.getMessage()) .containsPattern("permission:AGGREGATE_DATA entityTypeId:entityTypeId"); }
### Question: RepositorySecurityDecorator extends AbstractRepositoryDecorator<Entity> { @Override public void close() throws IOException { delegate().close(); } RepositorySecurityDecorator( Repository<Entity> delegateRepository, UserPermissionEvaluator permissionService); @Override Iterator<Entity> iterator(); @Override void forEachBatched(Fetch fetch, Consumer<List<Entity>> consumer, int batchSize); @Override void close(); @Override long count(Query<Entity> q); @Override Stream<Entity> findAll(Query<Entity> q); @Override Entity findOne(Query<Entity> q); @Override Entity findOneById(Object id); @Override Entity findOneById(Object id, Fetch fetch); @Override Stream<Entity> findAll(Stream<Object> ids); @Override Stream<Entity> findAll(Stream<Object> ids, Fetch fetch); @Override long count(); @Override void update(Entity entity); @Override void update(Stream<Entity> entities); @Override void delete(Entity entity); @Override void delete(Stream<Entity> entities); @Override void deleteById(Object id); @Override void deleteAll(Stream<Object> ids); @Override void deleteAll(); @Override void add(Entity entity); @Override Integer add(Stream<Entity> entities); @Override AggregateResult aggregate(AggregateQuery aggregateQuery); }### Answer: @Test void testCloseNoPermissionsNeeded() throws IOException { repositorySecurityDecorator.close(); verify(delegateRepository).close(); verifyZeroInteractions(permissionService); }
### Question: RepositorySecurityDecorator extends AbstractRepositoryDecorator<Entity> { @Override public void deleteById(Object id) { EntityType entityType = delegate().getEntityType(); validatePermission(entityType, DELETE_DATA); delegate().deleteById(id); } RepositorySecurityDecorator( Repository<Entity> delegateRepository, UserPermissionEvaluator permissionService); @Override Iterator<Entity> iterator(); @Override void forEachBatched(Fetch fetch, Consumer<List<Entity>> consumer, int batchSize); @Override void close(); @Override long count(Query<Entity> q); @Override Stream<Entity> findAll(Query<Entity> q); @Override Entity findOne(Query<Entity> q); @Override Entity findOneById(Object id); @Override Entity findOneById(Object id, Fetch fetch); @Override Stream<Entity> findAll(Stream<Object> ids); @Override Stream<Entity> findAll(Stream<Object> ids, Fetch fetch); @Override long count(); @Override void update(Entity entity); @Override void update(Stream<Entity> entities); @Override void delete(Entity entity); @Override void delete(Stream<Entity> entities); @Override void deleteById(Object id); @Override void deleteAll(Stream<Object> ids); @Override void deleteAll(); @Override void add(Entity entity); @Override Integer add(Stream<Entity> entities); @Override AggregateResult aggregate(AggregateQuery aggregateQuery); }### Answer: @Test void testDeleteByIdPermissionGranted() { initPermissionServiceMock(EntityTypePermission.DELETE_DATA, true); Object entityId = mock(Object.class); repositorySecurityDecorator.deleteById(entityId); verify(delegateRepository).deleteById(entityId); } @Test void testDeleteByIdPermissionDenied() { initPermissionServiceMock(EntityTypePermission.DELETE_DATA, false); Object entityId = mock(Object.class); Exception exception = assertThrows( EntityTypePermissionDeniedException.class, () -> repositorySecurityDecorator.deleteById(entityId)); assertThat(exception.getMessage()) .containsPattern("permission:DELETE_DATA entityTypeId:entityTypeId"); }
### Question: RepositorySecurityDecorator extends AbstractRepositoryDecorator<Entity> { @Override public Entity findOne(Query<Entity> q) { EntityType entityType = delegate().getEntityType(); validatePermission(entityType, READ_DATA); return delegate().findOne(q); } RepositorySecurityDecorator( Repository<Entity> delegateRepository, UserPermissionEvaluator permissionService); @Override Iterator<Entity> iterator(); @Override void forEachBatched(Fetch fetch, Consumer<List<Entity>> consumer, int batchSize); @Override void close(); @Override long count(Query<Entity> q); @Override Stream<Entity> findAll(Query<Entity> q); @Override Entity findOne(Query<Entity> q); @Override Entity findOneById(Object id); @Override Entity findOneById(Object id, Fetch fetch); @Override Stream<Entity> findAll(Stream<Object> ids); @Override Stream<Entity> findAll(Stream<Object> ids, Fetch fetch); @Override long count(); @Override void update(Entity entity); @Override void update(Stream<Entity> entities); @Override void delete(Entity entity); @Override void delete(Stream<Entity> entities); @Override void deleteById(Object id); @Override void deleteAll(Stream<Object> ids); @Override void deleteAll(); @Override void add(Entity entity); @Override Integer add(Stream<Entity> entities); @Override AggregateResult aggregate(AggregateQuery aggregateQuery); }### Answer: @Test void testFindOneQueryPermissionGranted() { initPermissionServiceMock(EntityTypePermission.READ_DATA, true); @SuppressWarnings("unchecked") Query<Entity> query = mock(Query.class); repositorySecurityDecorator.findOne(query); verify(delegateRepository).findOne(query); } @Test void testFindOneQueryPermissionDenied() { initPermissionServiceMock(EntityTypePermission.READ_DATA, false); @SuppressWarnings("unchecked") Query<Entity> query = mock(Query.class); Exception exception = assertThrows( EntityTypePermissionDeniedException.class, () -> repositorySecurityDecorator.findOne(query)); assertThat(exception.getMessage()) .containsPattern("permission:READ_DATA entityTypeId:entityTypeId"); }
### Question: RepositorySecurityDecorator extends AbstractRepositoryDecorator<Entity> { @Override public Iterator<Entity> iterator() { EntityType entityType = delegate().getEntityType(); validatePermission(entityType, READ_DATA); return delegate().iterator(); } RepositorySecurityDecorator( Repository<Entity> delegateRepository, UserPermissionEvaluator permissionService); @Override Iterator<Entity> iterator(); @Override void forEachBatched(Fetch fetch, Consumer<List<Entity>> consumer, int batchSize); @Override void close(); @Override long count(Query<Entity> q); @Override Stream<Entity> findAll(Query<Entity> q); @Override Entity findOne(Query<Entity> q); @Override Entity findOneById(Object id); @Override Entity findOneById(Object id, Fetch fetch); @Override Stream<Entity> findAll(Stream<Object> ids); @Override Stream<Entity> findAll(Stream<Object> ids, Fetch fetch); @Override long count(); @Override void update(Entity entity); @Override void update(Stream<Entity> entities); @Override void delete(Entity entity); @Override void delete(Stream<Entity> entities); @Override void deleteById(Object id); @Override void deleteAll(Stream<Object> ids); @Override void deleteAll(); @Override void add(Entity entity); @Override Integer add(Stream<Entity> entities); @Override AggregateResult aggregate(AggregateQuery aggregateQuery); }### Answer: @Test void testIteratorPermissionGranted() { initPermissionServiceMock(EntityTypePermission.READ_DATA, true); repositorySecurityDecorator.iterator(); verify(delegateRepository).iterator(); } @Test void testIteratorPermissionDenied() { initPermissionServiceMock(EntityTypePermission.READ_DATA, false); Exception exception = assertThrows( EntityTypePermissionDeniedException.class, () -> repositorySecurityDecorator.iterator()); assertThat(exception.getMessage()) .containsPattern("permission:READ_DATA entityTypeId:entityTypeId"); }
### Question: EntityIdentityUtils { public static String toType(EntityType entityType) { return toType(entityType.getId()); } private EntityIdentityUtils(); static String toType(EntityType entityType); static String toType(String entityTypeId); static Class<?> toIdType(EntityType entityType); static final String TYPE_PREFIX; }### Answer: @Test void testToTypeEntityType() { EntityType entityType = mock(EntityType.class); when(entityType.getId()).thenReturn("MyEntityTypeId"); assertEquals("entity-MyEntityTypeId", toType(entityType)); } @Test void testToTypeString() { assertEquals("entity-MyEntityTypeId", toType("MyEntityTypeId")); }
### Question: PackagePermissionUtils { public static boolean isWritablePackage( Package aPackage, UserPermissionEvaluator userPermissionEvaluator) { return isPermittedPackage(aPackage, userPermissionEvaluator, ADD_PACKAGE); } private PackagePermissionUtils(); static boolean isReadablePackage( Package aPackage, UserPermissionEvaluator userPermissionEvaluator); static boolean isWritablePackage( Package aPackage, UserPermissionEvaluator userPermissionEvaluator); }### Answer: @Test void testIsWritablePackageAddPackagePermission() { Package aPackage = when(mock(Package.class).getId()).thenReturn("packageId").getMock(); doReturn(true) .when(userPermissionEvaluator) .hasPermission(new PackageIdentity("packageId"), ADD_PACKAGE); doReturn(false) .when(userPermissionEvaluator) .hasPermission(new PackageIdentity("packageId"), ADD_ENTITY_TYPE); assertTrue(PackagePermissionUtils.isWritablePackage(aPackage, userPermissionEvaluator)); } @Test void testIsWritablePackageAddEntityTypePermission() { Package aPackage = when(mock(Package.class).getId()).thenReturn("packageId").getMock(); doReturn(true) .when(userPermissionEvaluator) .hasPermission(new PackageIdentity("packageId"), ADD_ENTITY_TYPE); assertTrue(PackagePermissionUtils.isWritablePackage(aPackage, userPermissionEvaluator)); } @Test void testIsWritablePackageFalse() { Package aPackage = when(mock(Package.class).getId()).thenReturn("packageId").getMock(); assertFalse(PackagePermissionUtils.isWritablePackage(aPackage, userPermissionEvaluator)); } @Test void testIsWritablePackageSystemPackage() { Package aPackage = when(mock(Package.class).getId()).thenReturn("packageId").getMock(); when(aPackage.getId()).thenReturn("sys"); assertFalse(PackagePermissionUtils.isWritablePackage(aPackage, userPermissionEvaluator)); }
### Question: EntityHelper { public ObjectIdentity getObjectIdentity(String classId, String objectIdentifier) { return new ObjectIdentityImpl(classId, getTypedValue(objectIdentifier, classId)); } EntityHelper(DataService dataService); ObjectIdentity getObjectIdentity(String classId, String objectIdentifier); String getLabel(String typeId, String untypedIdentifier); String getLabel(String typeId); LabelledObjectIdentity getLabelledObjectIdentity(ObjectIdentity objectIdentity); void checkEntityExists(ObjectIdentity objectIdentity); void checkEntityTypeExists(String typeId); void checkIsNotSystem(String typeId); static final String ENTITY_PREFIX; static final String PLUGIN; static final String SYS_PLUGIN; }### Answer: @Test void testGetObjectIdentity() { assertEquals( new ObjectIdentityImpl("typeId", "identifier"), entityHelper.getObjectIdentity("typeId", "identifier")); }
### Question: EntityHelper { public LabelledObjectIdentity getLabelledObjectIdentity(ObjectIdentity objectIdentity) { String typeLabel = getLabel(objectIdentity.getType()); String entityTypeId = getEntityTypeIdFromType(objectIdentity.getType()); String identifierLabel = getLabel(objectIdentity.getType(), objectIdentity.getIdentifier().toString()); return LabelledObjectIdentity.create( objectIdentity.getType(), entityTypeId, typeLabel, objectIdentity.getIdentifier().toString(), identifierLabel); } EntityHelper(DataService dataService); ObjectIdentity getObjectIdentity(String classId, String objectIdentifier); String getLabel(String typeId, String untypedIdentifier); String getLabel(String typeId); LabelledObjectIdentity getLabelledObjectIdentity(ObjectIdentity objectIdentity); void checkEntityExists(ObjectIdentity objectIdentity); void checkEntityTypeExists(String typeId); void checkIsNotSystem(String typeId); static final String ENTITY_PREFIX; static final String PLUGIN; static final String SYS_PLUGIN; }### Answer: @Test void testGetLabelledObjectIdentity() { Repository repository = mock(Repository.class); EntityType entityType = mock(EntityType.class); when(entityType.getLabel()).thenReturn("typeLabel"); Attribute idAttr = mock(Attribute.class); when(idAttr.getDataType()).thenReturn(STRING); when(entityType.getIdAttribute()).thenReturn(idAttr); when(repository.getEntityType()).thenReturn(entityType); Entity entity = mock(Entity.class); when(entity.getLabelValue()).thenReturn("label"); when(repository.findOneById("identifier")).thenReturn(entity); when(dataService.getRepository("typeId")).thenReturn(repository); when(dataService.getEntityType("typeId")).thenReturn(entityType); assertEquals( create("entity-typeId", "typeId", "typeLabel", "identifier", "label"), entityHelper.getLabelledObjectIdentity( new ObjectIdentityImpl("entity-typeId", "identifier"))); }
### Question: EntityHelper { public void checkEntityExists(ObjectIdentity objectIdentity) { checkEntityTypeExists(objectIdentity.getType()); String entityTypeId = getEntityTypeIdFromType(objectIdentity.getType()); if (getEntityByIdentifier(objectIdentity.getIdentifier(), entityTypeId) == null) { throw new UnknownEntityException(entityTypeId, objectIdentity.getIdentifier()); } } EntityHelper(DataService dataService); ObjectIdentity getObjectIdentity(String classId, String objectIdentifier); String getLabel(String typeId, String untypedIdentifier); String getLabel(String typeId); LabelledObjectIdentity getLabelledObjectIdentity(ObjectIdentity objectIdentity); void checkEntityExists(ObjectIdentity objectIdentity); void checkEntityTypeExists(String typeId); void checkIsNotSystem(String typeId); static final String ENTITY_PREFIX; static final String PLUGIN; static final String SYS_PLUGIN; }### Answer: @Test void testCheckEntityExistsFail() { when(dataService.hasEntityType("typeId")).thenReturn(true); when(dataService.getRepository("typeId")).thenReturn(repository); when(repository.findOneById("identifier")).thenReturn(null); assertThrows( UnknownEntityException.class, () -> entityHelper.checkEntityExists(new ObjectIdentityImpl("entity-typeId", "identifier"))); } @Test void testCheckEntityExists() { when(dataService.hasEntityType("typeId")).thenReturn(true); when(dataService.getRepository("typeId")).thenReturn(repository); when(repository.findOneById("identifier")).thenReturn(mock(Entity.class)); entityHelper.checkEntityExists(new ObjectIdentityImpl("entity-typeId", "identifier")); }
### Question: EntityHelper { public void checkEntityTypeExists(String typeId) { String entityTypeId = getEntityTypeIdFromType(typeId); if (!dataService.hasEntityType(entityTypeId)) { throw new UnknownEntityTypeException(typeId); } } EntityHelper(DataService dataService); ObjectIdentity getObjectIdentity(String classId, String objectIdentifier); String getLabel(String typeId, String untypedIdentifier); String getLabel(String typeId); LabelledObjectIdentity getLabelledObjectIdentity(ObjectIdentity objectIdentity); void checkEntityExists(ObjectIdentity objectIdentity); void checkEntityTypeExists(String typeId); void checkIsNotSystem(String typeId); static final String ENTITY_PREFIX; static final String PLUGIN; static final String SYS_PLUGIN; }### Answer: @Test void testCheckEntityTypeExistsFail() { when(dataService.hasEntityType("typeId")).thenReturn(false); assertThrows( UnknownEntityTypeException.class, () -> entityHelper.checkEntityTypeExists("entity-typeId")); } @Test void testCheckEntityTypeExists() { when(dataService.hasEntityType("typeId")).thenReturn(true); entityHelper.checkEntityTypeExists("entity-typeId"); }
### Question: Vectors { public static Vector append(Vector... vectors) { int totalSize = 0; for (Vector vec : vectors) { totalSize += vec.size(); } Vector result = new SequentialAccessSparseVector(totalSize); result.assign(0); int lastIndex = 0; for (Vector vector : vectors) { for (Element elem : vector) { result.setQuick(lastIndex + elem.index(), elem.get()); } lastIndex += vector.size(); } return result; } static Vector append(Vector... vectors); static SequentialAccessSparseVector newSequentialAccessSparseVector(double... ds); }### Answer: @Test @Repeat(iterations = 5) public void testAppendOne() { SequentialAccessSparseVector vec = randomVector(); Vector result = Vectors.append(vec); assertEquals("Appending a single vector should result that same vector.", vec, result); } @Test @Repeat(iterations = 10) public void testAppendTwo() { Vector vecA = randomVector(); Vector vecB = randomVector(); Vector result = Vectors.append(vecA, vecB); double sum = Math.pow(vecA.norm(2), 2) + Math.pow(vecB.norm(2), 2); double length = Math.sqrt(sum); assertEquals("Appending two vectors should result in a vector of added length.", length, result.norm(2), 0.00001); }
### Question: Vectors { public static SequentialAccessSparseVector newSequentialAccessSparseVector(double... ds) { SequentialAccessSparseVector result = new SequentialAccessSparseVector(ds.length); for (int i = 0; i < ds.length; i++) { result.setQuick(i, ds[i]); } return result; } static Vector append(Vector... vectors); static SequentialAccessSparseVector newSequentialAccessSparseVector(double... ds); }### Answer: @Test @Repeat(iterations = 10) public void testCreation() { Vector vec = randomVector(); double[] entries = new double[vec.getNumNondefaultElements()]; int index = 0; for (Vector.Element e : vec) { entries[index] = e.get(); index++; } Vector result = Vectors.newSequentialAccessSparseVector(entries); assertEquals("Original vector should have same length as the one created from its entries.", vec.norm(2), result.norm(2), 0.0001); }
### Question: Client { public List<Object> fetchAndProcessData(String dateTime) throws UnirestException { Optional<JsonNode> data = loadProviderJson(dateTime); System.out.println("data=" + data); if (data != null && data.isPresent()) { JSONObject jsonObject = data.get().getObject(); int value = 100 / jsonObject.getInt("count"); TemporalAccessor date = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXX") .parse(jsonObject.getString("validDate")); System.out.println("value=" + value); System.out.println("date=" + date); return Arrays.asList(value, OffsetDateTime.from(date)); } else { return Arrays.asList(0, null); } } Client(String url); List<Object> fetchAndProcessData(String dateTime); }### Answer: @Test public void canProcessTheJsonPayloadFromTheProvider() throws UnirestException { String date = "2013-08-16T15:31:20+1000"; stubFor(get(urlPathEqualTo("/provider.json")) .withQueryParam("validDate", matching(".+")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\"test\": \"NO\", \"validDate\": \"" + date + "\", \"count\": 100}"))); List<Object> data = new Client("http: assertThat(data, hasSize(2)); assertThat(data.get(0), is(1)); assertThat(data.get(1), is(equalTo(OffsetDateTime.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXX"))))); }
### Question: VerySimpleGroupSectionSpec { @OnEvent(ClickEvent.class) static void onImageClick(SectionContext c) { VerySimpleGroupSection.onUpdateStateSync(c, 3); } }### Answer: @Test public void testClickHandler() throws Exception { Section s = mTester.prepare( VerySimpleGroupSection.create(mTester.getContext()).numberOfDummy(4).build()); SectionsTestHelper.dispatchEvent( s, VerySimpleGroupSection.onImageClick(mTester.getScopedContext(s)), new ClickEvent()); VerySimpleGroupSection.VerySimpleGroupSectionStateContainer stateContainer = mTester.getStateContainer(s); assertThat(stateContainer.extra).isEqualTo(3); }
### Question: LithoPluginUtils { @Nullable @Contract("null -> null") public static String getLithoComponentNameFromSpec(@Nullable String specName) { if (isSpecName(specName)) { return specName.substring(0, specName.length() - SPEC_SUFFIX.length()); } return null; } static boolean isComponentClass(@Nullable PsiClass psiClass); static boolean isSectionClass(@Nullable PsiClass psiClass); static boolean isGeneratedClass(@Nullable PsiClass psiClass); static boolean isLithoSpec(@Nullable PsiFile psiFile); static boolean isLithoSpec(@Nullable PsiClass psiClass); static boolean isLayoutSpec(@Nullable PsiClass psiClass); static boolean isMountSpec(@Nullable PsiClass psiClass); static boolean hasLithoComponentSpecAnnotation(@Nullable PsiClass psiClass); static boolean hasLithoSectionSpecAnnotation(PsiClass psiClass); @Contract("null -> false") static boolean isSpecName(@Nullable String clsName); static boolean isPropOrState(PsiParameter parameter); static boolean isProp(PsiParameter parameter); static boolean isState(PsiParameter parameter); static boolean isParam(PsiParameter parameter); static boolean isPropDefault(PsiField field); static boolean isEvent(PsiClass psiClass); @Nullable @Contract("null -> null") static String getLithoComponentNameFromSpec(@Nullable String specName); @Nullable @Contract("null -> null; !null -> !null") static String getLithoComponentSpecNameFromComponent(@Nullable String componentName); static Stream<PsiParameter> getPsiParameterStream( @Nullable PsiMethod currentMethod, PsiMethod[] allMethods); static Optional<PsiClass> getFirstLayoutSpec(PsiFile psiFile); static Optional<PsiClass> getFirstClass(PsiFile psiFile, Predicate<PsiClass> classFilter); static void showInfo(String infoMessage, @Nullable Project project); static void showWarning(String infoMessage, @Nullable Project project); @Nullable static String resolveEventName(PsiMethodCallExpression methodCall); }### Answer: @Test public void getLithoComponentNameFromSpec() { Assert.assertEquals("Test", LithoPluginUtils.getLithoComponentNameFromSpec("TestSpec")); }
### Question: LithoPluginUtils { @Nullable @Contract("null -> null; !null -> !null") public static String getLithoComponentSpecNameFromComponent(@Nullable String componentName) { if (componentName != null) { return componentName + SPEC_SUFFIX; } return null; } static boolean isComponentClass(@Nullable PsiClass psiClass); static boolean isSectionClass(@Nullable PsiClass psiClass); static boolean isGeneratedClass(@Nullable PsiClass psiClass); static boolean isLithoSpec(@Nullable PsiFile psiFile); static boolean isLithoSpec(@Nullable PsiClass psiClass); static boolean isLayoutSpec(@Nullable PsiClass psiClass); static boolean isMountSpec(@Nullable PsiClass psiClass); static boolean hasLithoComponentSpecAnnotation(@Nullable PsiClass psiClass); static boolean hasLithoSectionSpecAnnotation(PsiClass psiClass); @Contract("null -> false") static boolean isSpecName(@Nullable String clsName); static boolean isPropOrState(PsiParameter parameter); static boolean isProp(PsiParameter parameter); static boolean isState(PsiParameter parameter); static boolean isParam(PsiParameter parameter); static boolean isPropDefault(PsiField field); static boolean isEvent(PsiClass psiClass); @Nullable @Contract("null -> null") static String getLithoComponentNameFromSpec(@Nullable String specName); @Nullable @Contract("null -> null; !null -> !null") static String getLithoComponentSpecNameFromComponent(@Nullable String componentName); static Stream<PsiParameter> getPsiParameterStream( @Nullable PsiMethod currentMethod, PsiMethod[] allMethods); static Optional<PsiClass> getFirstLayoutSpec(PsiFile psiFile); static Optional<PsiClass> getFirstClass(PsiFile psiFile, Predicate<PsiClass> classFilter); static void showInfo(String infoMessage, @Nullable Project project); static void showWarning(String infoMessage, @Nullable Project project); @Nullable static String resolveEventName(PsiMethodCallExpression methodCall); }### Answer: @Test public void getLithoComponentSpecNameFromComponent() { Assert.assertEquals( "NameSpec", LithoPluginUtils.getLithoComponentSpecNameFromComponent("Name")); }
### Question: ReplacingConsumer implements Consumer<CompletionResult> { void addRemainingCompletions(Project project) { for (String qualifiedName : replacedQualifiedNames) { result.addElement( PrioritizedLookupElement.withPriority( SpecLookupElement.create(qualifiedName, project, insertHandler), Integer.MAX_VALUE)); } } ReplacingConsumer( Collection<String> replacedQualifiedNames, CompletionResultSet result, InsertHandler<LookupElement> insertHandler); @Override void consume(CompletionResult completionResult); }### Answer: @Test public void addRemainingCompletions() { testHelper.runInReadAction( project -> { TestCompletionResultSet mutate = new TestCompletionResultSet(); List<String> namesToReplace = new ArrayList<>(); namesToReplace.add("one"); namesToReplace.add("other"); new ReplacingConsumer(namesToReplace, mutate, (context, item) -> {}) .addRemainingCompletions(project); assertThat(mutate.elements).hasSize(2); assertThat(mutate.elements.get(0).getLookupString()).isEqualTo("other"); assertThat(mutate.elements.get(1).getLookupString()).isEqualTo("one"); }); }
### Question: CompletionUtils { static Optional<PsiClass> findFirstParent(PsiElement element, Predicate<PsiClass> condition) { return Optional.ofNullable(PsiTreeUtil.findFirstParent(element, PsiClass.class::isInstance)) .map(PsiClass.class::cast) .filter(condition); } }### Answer: @Test public void findFirstParent() { testHelper.getPsiClass( psiClasses -> { Assert.assertNotNull(psiClasses); Assert.assertEquals(2, psiClasses.size()); PsiMethod layoutSpecMethod = psiClasses.get(0).getMethods()[0]; Optional<PsiClass> layoutSpec = CompletionUtils.findFirstParent(layoutSpecMethod, LithoPluginUtils::isLayoutSpec); Assert.assertTrue(layoutSpec.isPresent()); Optional<PsiClass> componentCls = CompletionUtils.findFirstParent(layoutSpecMethod, LithoPluginUtils::isComponentClass); Assert.assertFalse(componentCls.isPresent()); PsiMethod sectionSpecMethod = psiClasses.get(1).getMethods()[0]; Optional<PsiClass> layoutSpecInSection = CompletionUtils.findFirstParent(sectionSpecMethod, LithoPluginUtils::isLayoutSpec); Assert.assertFalse(layoutSpecInSection.isPresent()); Optional<PsiClass> lithoSpec = CompletionUtils.findFirstParent(sectionSpecMethod, LithoPluginUtils::isLithoSpec); Assert.assertTrue(lithoSpec.isPresent()); return true; }, "LayoutSpec.java", "SectionSpec.java"); }
### Question: LearningStateComponentSpec { @OnUpdateState static void incrementClickCount(StateValue<Integer> count) { count.set(count.get() + 1); } }### Answer: @Test public void testIncrementClickCount() { final StateValue<Integer> count = new StateValue<>(); count.set(0); LearningStateComponentSpec.incrementClickCount(count); LithoAssertions.assertThat(count).valueEqualTo(1); }
### Question: MethodChainLookupElement extends LookupElementDecorator<LookupElement> { @VisibleForTesting static PsiExpression createMethodChain( Project project, String firstName, List<? extends String> methodNames) { PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); StringBuilder expressionText = new StringBuilder(firstName + "(" + TEMPLATE_INSERT_PLACEHOLDER_C + ")"); methodNames.forEach( methodName -> expressionText .append("\n.") .append(methodName) .append("(") .append(TEMPLATE_INSERT_PLACEHOLDER) .append(")")); return factory.createExpressionFromText(expressionText.toString(), null); } @VisibleForTesting MethodChainLookupElement(LookupElement delegate, Template fromTemplate); static LookupElement create( LookupElement lookupPresentation, String firstMethodName, List<? extends String> otherMethodNames, PsiElement placeholder, Project project); @Override void handleInsert(InsertionContext context); @Override void renderElement(LookupElementPresentation presentation); }### Answer: @Test public void createMethodChain() { testHelper.runInReadAction( project -> { List<String> names = new ArrayList<>(2); names.add("methodName1"); names.add("otherName"); PsiExpression methodChain = MethodChainLookupElement.createMethodChain(project, "methodNameBase", names); assertEquals( "methodNameBase(insert_placeholder_c)\n" + ".methodName1(insert_placeholder)\n" + ".otherName(insert_placeholder)", methodChain.getText()); }); }
### Question: MethodChainLookupElement extends LookupElementDecorator<LookupElement> { @Override public void renderElement(LookupElementPresentation presentation) { super.renderElement(presentation); String tail = fromTemplate.getTemplateText(); int secondMethodIndex = tail.indexOf('.'); if (secondMethodIndex > 0) { String substring = tail.substring(secondMethodIndex).replaceAll("[^A-Za-z0-9$_.()]+", ""); presentation.appendTailText(substring, true); } } @VisibleForTesting MethodChainLookupElement(LookupElement delegate, Template fromTemplate); static LookupElement create( LookupElement lookupPresentation, String firstMethodName, List<? extends String> otherMethodNames, PsiElement placeholder, Project project); @Override void handleInsert(InsertionContext context); @Override void renderElement(LookupElementPresentation presentation); }### Answer: @Test public void renderElement() { LookupElement testDelegate = new TestLookupElement(""); Template testTemplate = new TestTemplate("beforeDot.afterDot.afterDot"); LookupElementPresentation testPresentation = new TestLookupElementPresentation(); testPresentation.setTailText("oldTail"); new MethodChainLookupElement(testDelegate, testTemplate).renderElement(testPresentation); assertEquals("oldTail.afterDot.afterDot", testPresentation.getTailText()); }
### Question: TemplateService implements Disposable { @Nullable public PsiMethod getMethodTemplate(String targetName, Project project) { final PsiMethod savedTemplate = templates.get(targetName); if (savedTemplate != null) return savedTemplate; final PsiMethod template = readMethodTemplate(targetName, project); if (template != null) { templates.putIfAbsent(targetName, template); } return template; } @Nullable PsiMethod getMethodTemplate(String targetName, Project project); @Override void dispose(); }### Answer: @Test public void getMethodTemplate() { ApplicationManager.getApplication() .invokeAndWait( () -> { final Project project = testHelper.getFixture().getProject(); final PsiMethod onAttached = ServiceManager.getService(project, TemplateService.class) .getMethodTemplate("OnAttached", project); assertThat(onAttached).isNotNull(); }); }
### Question: GeneratedFilesListener implements BulkFileListener, Disposable { @Override public void after(List<? extends VFileEvent> events) { IntervalLogger logger = new IntervalLogger(LOG); final boolean found = events.stream() .filter(VFileCreateEvent.class::isInstance) .map(VFileEvent::getFile) .filter(file -> file != null && file.isValid()) .map(file -> FileUtil.toSystemIndependentName(file.getPath())) .anyMatch(GeneratedFilesListener::isOutput); logger.logStep("finding created paths: " + found); if (!found) return; final Runnable job = () -> { logger.logStep("start of removing files"); ComponentsCacheService.getInstance(project).invalidate(); }; if (ApplicationManager.getApplication().isUnitTestMode()) { job.run(); } else { DumbService.getInstance(project).smartInvokeLater(job); } } GeneratedFilesListener(Project project); @Override void dispose(); @Override void after(List<? extends VFileEvent> events); }### Answer: @Test public void after_Remove() throws IOException { final Project project = testHelper.getFixture().getProject(); final GeneratedFilesListener listener = new GeneratedFilesListener(project); final PsiFile file = testHelper.configure("LayoutSpec.java"); ApplicationManager.getApplication() .invokeAndWait( () -> { final PsiClass cls = PsiTreeUtil.findChildOfType(file, PsiClass.class); ComponentGenerateService.getInstance().updateLayoutComponentAsync(cls); final ComponentsCacheService service = ComponentsCacheService.getInstance(project); final PsiClass component = service.getComponent("Layout"); assertThat(component).isNotNull(); final VFileEvent mockEvent = mockEvent(); PsiSearchUtils.addMock("Layout", cls); listener.after(Collections.singletonList(mockEvent)); final PsiClass component2 = service.getComponent("Layout"); assertThat(component2).isNull(); }); }
### Question: AnnotatorUtils { static void addError(AnnotationHolder holder, SpecModelValidationError error) { addError(holder, error, Collections.emptyList()); } private AnnotatorUtils(); }### Answer: @Test public void addError() { String message = "test message"; PsiElement element = Mockito.mock(PsiElement.class); TestHolder holder = new TestHolder(); AnnotatorUtils.addError(holder, new SpecModelValidationError(element, message)); assertEquals(1, holder.errorMessages.size()); assertEquals(message, holder.errorMessages.get(0)); assertEquals(1, holder.errorElements.size()); assertEquals(element, holder.errorElements.get(0)); }
### Question: RequiredPropLineMarkerProvider implements LineMarkerProvider { @Nullable @Override public LineMarkerInfo getLineMarkerInfo(PsiElement element) { final List<PsiReferenceExpression> methodCalls = new ArrayList<>(); final List<Collection<String>> missingPropNames = new ArrayList<>(); RequiredPropAnnotator.annotate( element, (missingRequiredPropNames, createMethodCall) -> { methodCalls.add(createMethodCall); missingPropNames.add(missingRequiredPropNames); }, generatedClassResolver); if (methodCalls.isEmpty()) { return null; } PsiElement leaf = methodCalls.get(0); final Collection<String> missingProps = missingPropNames.get(0); while (leaf.getFirstChild() != null) { leaf = leaf.getFirstChild(); } return new LineMarkerInfo<>( leaf, leaf.getTextRange(), LithoPluginIcons.ERROR_ACTION, 0, ignored -> RequiredPropAnnotator.createErrorMessage(missingProps), null, GutterIconRenderer.Alignment.CENTER); } RequiredPropLineMarkerProvider(); @VisibleForTesting RequiredPropLineMarkerProvider( Function<PsiMethodCallExpression, PsiClass> generatedClassResolver); @Nullable @Override LineMarkerInfo getLineMarkerInfo(PsiElement element); @Override void collectSlowLineMarkers( List<PsiElement> elements, Collection<LineMarkerInfo> result); }### Answer: @Test public void markStatement() { testHelper.getPsiClass( psiClasses -> { assertThat(psiClasses).hasSize(2); PsiClass underTest = psiClasses.get(0); PsiClass component = psiClasses.get(1); Function<PsiMethodCallExpression, PsiClass> resolver = ignored -> component; RequiredPropLineMarkerProvider provider = new RequiredPropLineMarkerProvider(resolver); List<PsiElement> statements = new ArrayList<>(PsiTreeUtil.findChildrenOfAnyType(underTest, PsiStatement.class)); assertThat(provider.getLineMarkerInfo(statements.get(0))).isNotNull(); assertThat(provider.getLineMarkerInfo(statements.get(1))).isNull(); return true; }, "RequiredPropAnnotatorTest.java", "RequiredPropAnnotatorComponent.java"); }
### Question: AddArgumentFix extends BaseIntentionAction implements HighPriorityAction { static IntentionAction createAddMethodCallFix( PsiMethodCallExpression originalMethodCall, String clsName, String methodName, PsiElementFactory elementFactory) { PsiExpressionList newArgumentList = createArgumentList(originalMethodCall.getContext(), clsName, methodName, elementFactory); String fixDescription = "Add ." + methodName + "() " + getCapitalizedMethoName(originalMethodCall); return new AddArgumentFix(originalMethodCall, newArgumentList, fixDescription); } private AddArgumentFix( PsiCall originalCall, PsiExpressionList newArgumentList, String description); @Nls(capitalization = Nls.Capitalization.Sentence) @Override String getFamilyName(); @Override boolean isAvailable(Project project, Editor editor, PsiFile file); @Override void invoke(Project project, Editor editor, PsiFile file); }### Answer: @Test public void createAddMethodCallFix() { testHelper.getPsiClass( classes -> { PsiClass cls = classes.get(0); PsiMethodCallExpression call = PsiTreeUtil.findChildOfType(cls, PsiMethodCallExpression.class); Project project = testHelper.getFixture().getProject(); PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); Editor editor = mock(Editor.class); when(editor.getCaretModel()).thenReturn(mock(CaretModel.class)); IntentionAction fix = AddArgumentFix.createAddMethodCallFix(call, "ClassName", "methodName", factory); assertThat(call.getArgumentList().getExpressions()[0].getText()) .isNotEqualTo("ClassName.methodName()"); fix.invoke(project, editor, testHelper.getFixture().getFile()); assertThat(call.getArgumentList().getExpressions()[0].getText()) .isEqualTo("ClassName.methodName()"); return true; }, "RequiredPropAnnotatorTest.java"); }
### Question: DebounceEventLogger implements EventLogger { @Override public void log(String event, Map<String, String> metadata) { boolean log = false; synchronized (this) { long currentTimeMillis = System.currentTimeMillis(); if (currentTimeMillis - lastTimeMillis > timespanMillis) { lastTimeMillis = currentTimeMillis; log = true; } } if (log) { eventLogger.log(event, metadata); } } DebounceEventLogger(long timespanMillis); @VisibleForTesting DebounceEventLogger(long timespanMillis, EventLogger logger); @Override void log(String event, Map<String, String> metadata); }### Answer: @Test public void logNoDebounce() { TestLogger testLogger = new TestLogger(); DebounceEventLogger debounceEventLogger = new DebounceEventLogger(-1, testLogger); int count = 100; for (int i = 0; i < count; i++) { debounceEventLogger.log(null); } Assert.assertEquals(count, testLogger.count); } @Test public void logDebounce() { TestLogger testLogger = new TestLogger(); DebounceEventLogger debounceEventLogger = new DebounceEventLogger(10, testLogger); for (int i = 0; i < 100; i++) { debounceEventLogger.log(null); } Assert.assertEquals(1, testLogger.count); } @Test public void logDebouncePaused() throws InterruptedException { TestLogger testLogger = new TestLogger(); DebounceEventLogger debounceEventLogger = new DebounceEventLogger(10, testLogger); int count = 5; for (int i = 0; i < count; i++) { debounceEventLogger.log(null); Thread.sleep(15); } Assert.assertEquals(count, testLogger.count); }
### Question: GenerateComponentAction extends AnAction { @VisibleForTesting static Optional<PsiClass> getValidSpec(AnActionEvent e) { return Optional.of(e) .map(event -> event.getData(CommonDataKeys.PSI_FILE)) .flatMap(LithoPluginUtils::getFirstLayoutSpec); } @Override void update(AnActionEvent e); @Override void actionPerformed(AnActionEvent e); }### Answer: @Test public void getValidSpec_layoutspec() { testHelper.getPsiClass( psiClasses -> { AnActionEvent mock = createEvent(psiClasses.get(0)); assertTrue(GenerateComponentAction.getValidSpec(mock).isPresent()); return true; }, "LayoutSpec.java"); } @Test public void getValidSpec_mountspec() { testHelper.getPsiClass( psiClasses -> { AnActionEvent mock = createEvent(psiClasses.get(0)); assertFalse(GenerateComponentAction.getValidSpec(mock).isPresent()); return true; }, "MountSpec.java"); } @Test public void getValidSpec_notspec() { testHelper.getPsiClass( psiClasses -> { AnActionEvent mock = createEvent(psiClasses.get(0)); assertFalse(GenerateComponentAction.getValidSpec(mock).isPresent()); return true; }, "NotSpec.java"); }
### Question: ComponentShortNamesCache extends PsiShortNamesCache { @Override public String[] getAllClassNames() { return Arrays.stream(ComponentsCacheService.getInstance(project).getAllComponents()) .map(cls -> StringUtil.getShortName(cls.getQualifiedName())) .toArray(String[]::new); } ComponentShortNamesCache(Project project); @Override PsiClass[] getClassesByName(String name, GlobalSearchScope scope); @Override String[] getAllClassNames(); @Override PsiMethod[] getMethodsByName(String name, GlobalSearchScope scope); @Override PsiMethod[] getMethodsByNameIfNotMoreThan( String name, GlobalSearchScope scope, int maxCount); @Override PsiField[] getFieldsByNameIfNotMoreThan( String name, GlobalSearchScope scope, int maxCount); @Override boolean processMethodsWithName( String name, GlobalSearchScope scope, Processor<PsiMethod> processor); @Override String[] getAllMethodNames(); @Override PsiField[] getFieldsByName(String name, GlobalSearchScope scope); @Override String[] getAllFieldNames(); }### Answer: @Ignore("T73932936") @Test public void getAllClassNames() throws IOException { final Project project = testHelper.getFixture().getProject(); final PsiFile file = testHelper.configure("LayoutSpec.java"); ApplicationManager.getApplication() .invokeAndWait( () -> { final ComponentShortNamesCache namesCache = new ComponentShortNamesCache(project); final PsiClass cls = PsiTreeUtil.findChildOfType(file, PsiClass.class); ComponentGenerateService.getInstance().updateLayoutComponentAsync(cls); final String[] allClassNames = namesCache.getAllClassNames(); assertThat(allClassNames.length).isOne(); assertThat(allClassNames[0]).isEqualTo("Layout"); }); }
### Question: ComponentFinder extends PsiElementFinder { @Nullable @Override public PsiClass findClass(String qualifiedName, GlobalSearchScope scope) { return findClassInternal(qualifiedName, scope, project); } ComponentFinder(Project project); @Override PsiClass[] findClasses(String qualifiedName, GlobalSearchScope scope); @Nullable @Override PsiClass findClass(String qualifiedName, GlobalSearchScope scope); @Override PsiClass[] getClasses(PsiPackage psiPackage, GlobalSearchScope scope); }### Answer: @Ignore("T73932936") @Test public void findClass() throws IOException { final Project project = testHelper.getFixture().getProject(); final PsiFile file = testHelper.configure("LayoutSpec.java"); ApplicationManager.getApplication() .invokeAndWait( () -> { final ComponentFinder finder = new ComponentFinder(project); final PsiClass cls = PsiTreeUtil.findChildOfType(file, PsiClass.class); ComponentGenerateService.getInstance().updateLayoutComponentAsync(cls); final PsiClass result1 = finder.findClass("Layout", GlobalSearchScope.projectScope(project)); assertThat(result1).isNull(); final PsiClass result2 = finder.findClass("Layout", ComponentScope.getInstance()); assertThat(result2).isNotNull(); }); }
### Question: ComponentFileListener implements FileDocumentManagerListener { @VisibleForTesting void beforeFileSaving(PsiFile psiFile) { LithoPluginUtils.getFirstLayoutSpec(psiFile).ifPresent(savingFileConsumer); } ComponentFileListener(); @VisibleForTesting ComponentFileListener(Consumer<PsiClass> savingFileConsumer); @Override void beforeAllDocumentsSaving(); @Override void beforeDocumentSaving(Document document); @Override void beforeFileContentReload(VirtualFile file, Document document); @Override void fileWithNoDocumentChanged(VirtualFile file); @Override void fileContentReloaded(VirtualFile file, Document document); @Override void fileContentLoaded(VirtualFile file, Document document); @Override void unsavedDocumentsDropped(); }### Answer: @Test public void beforeLayoutSpecSaving() { AtomicBoolean invoked = new AtomicBoolean(false); ComponentFileListener componentFileListener = new ComponentFileListener( psiClass -> { invoked.set(true); }); testHelper.getPsiClass( psiClasses -> { Assert.assertNotNull(psiClasses); PsiClass psiCls = psiClasses.get(0); PsiFile containingFile = psiCls.getContainingFile(); componentFileListener.beforeFileSaving(containingFile); return true; }, "LayoutSpec.java"); Assert.assertTrue(invoked.get()); } @Test public void beforeNotLayoutSpecSaving() { AtomicBoolean invoked = new AtomicBoolean(false); ComponentFileListener componentFileListener = new ComponentFileListener( psiClass -> { invoked.set(true); }); testHelper.getPsiClass( psiClasses -> { Assert.assertNotNull(psiClasses); PsiClass psiCls = psiClasses.get(0); PsiFile containingFile = psiCls.getContainingFile(); componentFileListener.beforeFileSaving(containingFile); return true; }, "MountSpec.java"); Assert.assertFalse(invoked.get()); }
### Question: SpecMethodFindUsagesHandler extends FindUsagesHandler { @Override public PsiElement[] getPrimaryElements() { return Optional.of(getPsiElement()) .filter(PsiMethod.class::isInstance) .map(PsiMethod.class::cast) .map(this::findComponentMethods) .map( methods -> { final Map<String, String> data = new HashMap<>(); data.put(EventLogger.KEY_TARGET, EventLogger.VALUE_NAVIGATION_TARGET_METHOD); data.put(EventLogger.KEY_TYPE, EventLogger.VALUE_NAVIGATION_TYPE_FIND_USAGES); LithoLoggerProvider.getEventLogger().log(EventLogger.EVENT_NAVIGATION, data); return ArrayUtil.mergeArrays(methods, super.getPrimaryElements()); }) .orElseGet(super::getPrimaryElements); } SpecMethodFindUsagesHandler( PsiElement psiElement, Function<PsiClass, PsiClass> findGeneratedClass); @Override PsiElement[] getPrimaryElements(); }### Answer: @Test public void getPrimaryElements() { testHelper.getPsiClass( psiClasses -> { final PsiClass targetCls = psiClasses.get(0); final PsiMethod[] methods = targetCls.getMethods(); final PsiMethod staticMethod = methods[0]; final PsiClass withMethodsClass = targetCls.getInnerClasses()[0]; final PsiElement[] primaryElements = new SpecMethodFindUsagesHandler(staticMethod, cls -> withMethodsClass) .getPrimaryElements(); assertThat(primaryElements.length).isEqualTo(2); assertThat(primaryElements[0].getParent()).isSameAs(withMethodsClass); assertThat(primaryElements[1].getParent()).isSameAs(targetCls); return true; }, "WithMethods.java"); }
### Question: GeneratedClassFindUsagesHandler extends FindUsagesHandler { @Override public PsiElement[] getPrimaryElements() { final Map<String, String> data = new HashMap<>(); data.put(EventLogger.KEY_RESULT, "fail"); final PsiElement[] results = Optional.of(getPsiElement()) .filter(PsiClass.class::isInstance) .map(PsiClass.class::cast) .map(findGeneratedClass) .map( psiClass -> { data.put(EventLogger.KEY_RESULT, "success"); return ArrayUtil.insert(super.getPrimaryElements(), 0, psiClass); }) .orElseGet(super::getPrimaryElements); data.put(EventLogger.KEY_TARGET, EventLogger.VALUE_NAVIGATION_TARGET_CLASS); data.put(EventLogger.KEY_TYPE, EventLogger.VALUE_NAVIGATION_TYPE_FIND_USAGES); LithoLoggerProvider.getEventLogger().log(EventLogger.EVENT_NAVIGATION, data); return results; } GeneratedClassFindUsagesHandler( PsiElement psiElement, Function<PsiClass, PsiClass> findGeneratedClass); @Override PsiElement[] getPrimaryElements(); @Override FindUsagesOptions getFindUsagesOptions(@Nullable DataContext dataContext); }### Answer: @Test public void getPrimaryElements() { PsiClass mockedElement = mock(PsiClass.class); PsiClass mockedResult = mock(PsiClass.class); Function<PsiClass, PsiClass> findGeneratedComponent = psiClass -> mockedResult; GeneratedClassFindUsagesHandler handler = new GeneratedClassFindUsagesHandler(mockedElement, findGeneratedComponent); PsiElement[] primaryElements = handler.getPrimaryElements(); assertThat(primaryElements.length).isEqualTo(2); assertThat(primaryElements[0]).isSameAs(mockedResult); assertThat(primaryElements[1]).isSameAs(mockedElement); }
### Question: GeneratedClassFindUsagesHandler extends FindUsagesHandler { @Override public FindUsagesOptions getFindUsagesOptions(@Nullable DataContext dataContext) { FindUsagesOptions findUsagesOptions = super.getFindUsagesOptions(dataContext); Optional.of(getPsiElement()) .filter(PsiClass.class::isInstance) .map(PsiClass.class::cast) .map(findGeneratedClass) .ifPresent( generatedCls -> { findUsagesOptions.searchScope = new ExcludingScope( findUsagesOptions.searchScope, ComponentScope.getVirtualFile(generatedCls.getContainingFile())); }); return findUsagesOptions; } GeneratedClassFindUsagesHandler( PsiElement psiElement, Function<PsiClass, PsiClass> findGeneratedClass); @Override PsiElement[] getPrimaryElements(); @Override FindUsagesOptions getFindUsagesOptions(@Nullable DataContext dataContext); }### Answer: @Test public void getFindUsagesOptions() { testHelper.getPsiClass( psiClasses -> { PsiClass layoutSpec = psiClasses.get(0); PsiClass mockedGeneratedComponentCls = mock(PsiClass.class); PsiFile mockedGeneratedComponentFile = mock(PsiFile.class); when(mockedGeneratedComponentCls.getContainingFile()) .thenReturn(mockedGeneratedComponentFile); VirtualFile generatedComponentVirtualFile = createPresentInScopeVirtualFile(); when(mockedGeneratedComponentFile.getVirtualFile()) .thenReturn(generatedComponentVirtualFile); VirtualFile presentInScopeVirtualFile = createPresentInScopeVirtualFile(); Function<PsiClass, PsiClass> findGeneratedComponent = psiClass -> mockedGeneratedComponentCls; GeneratedClassFindUsagesHandler handler = new GeneratedClassFindUsagesHandler(layoutSpec, findGeneratedComponent); SearchScope searchScope = handler.getFindUsagesOptions(null).searchScope; assertThat(searchScope.contains(presentInScopeVirtualFile)).isTrue(); assertThat(searchScope.contains(generatedComponentVirtualFile)).isFalse(); return true; }, "LayoutSpec.java"); }
### Question: LithoFindUsagesHandlerFactory extends FindUsagesHandlerFactory { @Override public boolean canFindUsages(PsiElement element) { return GeneratedClassFindUsagesHandler.canFindUsages(element) || SpecMethodFindUsagesHandler.canFindUsages(element); } LithoFindUsagesHandlerFactory(); @Override boolean canFindUsages(PsiElement element); @Nullable @Override FindUsagesHandler createFindUsagesHandler(PsiElement element, boolean forHighlightUsages); }### Answer: @Test public void canFindUsages_classes() { testHelper.getPsiClass( psiClasses -> { assertNotNull(psiClasses); PsiClass layoutSpec = psiClasses.get(0); PsiClass otherSpec = psiClasses.get(1); PsiClass notSpec = psiClasses.get(2); LithoFindUsagesHandlerFactory factory = new LithoFindUsagesHandlerFactory(); assertTrue(factory.canFindUsages(layoutSpec)); assertTrue(factory.canFindUsages(otherSpec)); assertFalse(factory.canFindUsages(notSpec)); return true; }, "LayoutSpec.java", "MountSpec.java", "NotSpec.java"); } @Test public void canFindUsages_methods() { testHelper.getPsiClass( psiClasses -> { final PsiMethod[] methods = psiClasses.get(0).getMethods(); final PsiMethod staticMethod = methods[0]; final PsiMethod nonStaticMethod = methods[1]; LithoFindUsagesHandlerFactory factory = new LithoFindUsagesHandlerFactory(); assertTrue(factory.canFindUsages(staticMethod)); assertFalse(factory.canFindUsages(nonStaticMethod)); return true; }, "WithMethods.java"); }
### Question: PsiTypeUtils { static ClassName guessClassName(String typeName) { return ClassName.bestGuess(typeName); } }### Answer: @Test public void guessClassName() { Assert.assertEquals("T", PsiTypeUtils.guessClassName("T").reflectionName()); Assert.assertEquals("com.Hello", PsiTypeUtils.guessClassName("com.Hello").reflectionName()); }
### Question: PsiTypeUtils { @VisibleForTesting static TypeName getWildcardTypeName(String wildcardTypeName) { if (wildcardTypeName.equals("?")) { return WildcardTypeName.subtypeOf(Object.class); } Matcher matcher = SUPER_PATTERN.matcher(wildcardTypeName); if (matcher.find()) { return WildcardTypeName.supertypeOf(guessClassName(matcher.group(1))); } matcher = EXTENDS_PATTERN.matcher(wildcardTypeName); if (matcher.find()) { return WildcardTypeName.subtypeOf(guessClassName(matcher.group(1))); } return guessClassName(wildcardTypeName); } }### Answer: @Test public void getWildcardTypeName() { Assert.assertEquals("?", PsiTypeUtils.getWildcardTypeName("?").toString()); Assert.assertEquals("? super T", PsiTypeUtils.getWildcardTypeName("? super T").toString()); Assert.assertEquals( "? extends com.some.Node", PsiTypeUtils.getWildcardTypeName("? extends com.some.Node").toString()); Assert.assertEquals( "? super com.A", PsiTypeUtils.getWildcardTypeName("? super com.A & com.B").toString()); }
### Question: PsiMethodExtractorUtils { static List<MethodParamModel> getMethodParams( PsiMethod method, List<Class<? extends Annotation>> permittedAnnotations, List<Class<? extends Annotation>> permittedInterStageInputAnnotations, List<Class<? extends Annotation>> delegateMethodAnnotationsThatSkipDiffModels) { final List<MethodParamModel> methodParamModels = new ArrayList<>(); PsiParameter[] params = method.getParameterList().getParameters(); for (final PsiParameter param : params) { methodParamModels.add( MethodParamModelFactory.create( PsiTypeUtils.generateTypeSpec(param.getType()), param.getName(), getLibraryAnnotations(param, permittedAnnotations), getExternalAnnotations(param), permittedInterStageInputAnnotations, canCreateDiffModels(method, delegateMethodAnnotationsThatSkipDiffModels), param)); } return methodParamModels; } }### Answer: @Test public void getMethodParams_forMethodWithNoParams_returnsEmptyList() { ApplicationManager.getApplication() .invokeAndWait( () -> { assertOnDetachedHasNoParams( getMethodParams( methods[1], Collections.emptyList(), Collections.emptyList(), Collections.emptyList())); }); } @Test public void getMethodParams_forMethodwithParams_returnsInfoForAllParams() { ApplicationManager.getApplication() .invokeAndWait( () -> { assertOnAttachedHasInfoForAllParams( getMethodParams( methods[0], Collections.singletonList(Prop.class), Collections.emptyList(), Collections.emptyList())); }); }
### Question: PsiMethodExtractorUtils { static List<TypeVariableName> getTypeVariables(PsiMethod method) { return Arrays.stream(method.getTypeParameters()) .map(PsiMethodExtractorUtils::toTypeVariableName) .collect(Collectors.toList()); } }### Answer: @Test public void getTypeVariables_forMethodWithNoTypeVars_returnsEmptyList() { ApplicationManager.getApplication() .invokeAndWait( () -> { assertOnAttachedHasNoTypeVars(getTypeVariables(methods[0])); }); } @Test public void getTypeVariables_forMethodWithTypeVars_returnsInfoForAllTypeVars() { ApplicationManager.getApplication() .invokeAndWait( () -> { assertOnDetachedHasInfoForAllTypeVars(getTypeVariables(methods[1])); }); }
### Question: PsiFieldsExtractor { static ImmutableList<FieldModel> extractFields(PsiClass psiClass) { return Optional.of(psiClass) .map(PsiClass::getFields) .map(Arrays::stream) .map( fields -> fields .filter(Objects::nonNull) .map(PsiFieldsExtractor::createFieldModel) .collect(Collectors.toCollection(ArrayList::new))) .map(ImmutableList::copyOf) .orElse(ImmutableList.of()); } }### Answer: @Test public void extractFields() { testHelper.getPsiClass( psiClasses -> { Assert.assertNotNull(psiClasses); PsiClass psiClass = psiClasses.get(0); ImmutableList<FieldModel> fieldModels = PsiFieldsExtractor.extractFields(psiClass); FieldsExtractorTestHelper.fieldExtraction(fieldModels); return true; }, "TwoFieldsClass.java"); } @Test public void extractNoFields() { testHelper.getPsiClass( psiClasses -> { Assert.assertNotNull(psiClasses); PsiClass psiClass = psiClasses.get(0); ImmutableList<FieldModel> fieldModels = PsiFieldsExtractor.extractFields(psiClass); FieldsExtractorTestHelper.noFieldExtraction(fieldModels); return true; }, "NoFieldsClass.java"); }
### Question: PsiEventMethodExtractor { static ImmutableList<SpecMethodModel<EventMethod, EventDeclarationModel>> getOnEventMethods( PsiClass psiClass, List<Class<? extends Annotation>> permittedInterStageInputAnnotations) { final List<SpecMethodModel<EventMethod, EventDeclarationModel>> delegateMethods = new ArrayList<>(); for (PsiMethod psiMethod : psiClass.getMethods()) { final PsiAnnotation onEventAnnotation = AnnotationUtil.findAnnotation(psiMethod, OnEvent.class.getName()); if (onEventAnnotation == null) { continue; } PsiClassObjectAccessExpression accessExpression = (PsiClassObjectAccessExpression) onEventAnnotation.findAttributeValue("value"); final List<MethodParamModel> methodParams = getMethodParams( psiMethod, EventMethodExtractor.getPermittedMethodParamAnnotations( permittedInterStageInputAnnotations), permittedInterStageInputAnnotations, ImmutableList.of()); final SpecMethodModel<EventMethod, EventDeclarationModel> eventMethod = new SpecMethodModel<>( ImmutableList.of(), PsiModifierExtractor.extractModifiers(psiMethod.getModifierList()), psiMethod.getName(), PsiTypeUtils.generateTypeSpec(psiMethod.getReturnType()), ImmutableList.copyOf(getTypeVariables(psiMethod)), ImmutableList.copyOf(methodParams), psiMethod, PsiEventDeclarationsExtractor.getEventDeclarationModel(accessExpression)); delegateMethods.add(eventMethod); } return ImmutableList.copyOf(delegateMethods); } }### Answer: @Test public void psiMethodExtraction() { testHelper.getPsiClass( psiClasses -> { Assert.assertNotNull(psiClasses); PsiClass psiClass = psiClasses.get(0); ImmutableList<SpecMethodModel<EventMethod, EventDeclarationModel>> methods = PsiEventMethodExtractor.getOnEventMethods(psiClass, INTER_STAGE_INPUT_ANNOTATIONS); EventMethodExtractorTestHelper.assertMethodExtraction(methods); return true; }, "PsiEventMethodExtractionClass.java"); }
### Question: PsiPropDefaultsExtractor { public static ImmutableList<PropDefaultModel> getPropDefaults(PsiClass psiClass) { final List<PropDefaultModel> propDefaults = new ArrayList<>(); for (PsiField psiField : psiClass.getFields()) { propDefaults.addAll(extractFromField(psiField)); } return ImmutableList.copyOf(propDefaults); } static ImmutableList<PropDefaultModel> getPropDefaults(PsiClass psiClass); }### Answer: @Test public void propDefaultExtractionWithField() { testHelper.getPsiClass( psiClasses -> { Assert.assertNotNull(psiClasses); PsiClass cls = psiClasses.get(0); final ImmutableList<PropDefaultModel> propDefaults = PsiPropDefaultsExtractor.getPropDefaults(cls); PropDefaultsExtractorTestHelper.assertPropDefaultsExtraction(propDefaults); return true; }, "PropDefaultExtractionWithField.java"); }
### Question: CertHelper { public static String getSubjectCommonName(X509Certificate cert) { return CertUtils.getSubjectCommonName(cert); } private CertHelper(); static String getSubjectCommonName(X509Certificate cert); static String getSubjectSerialNumber(X509Certificate cert); static ClientId getSubjectClientId(X509Certificate cert); static void verifyAuthCert(CertChain chain, List<OCSPResp> ocspResponses, ClientId member); static OCSPResp getOcspResponseForCert(X509Certificate cert, X509Certificate issuer, List<OCSPResp> ocspResponses); }### Answer: @Test public void getSubjectCommonName() { X509Certificate cert = TestCertUtil.getProducer().certChain[0]; String commonName = CertHelper.getSubjectCommonName(cert); assertEquals("producer", commonName); }
### Question: AsicContainerNameGenerator { public String createFilenameWithRandom(String queryId, String queryType) { String processedQueryId = AsicUtils.truncate(AsicUtils.escapeString(queryId), MAX_QUERY_LENGTH); return String.format("%s-%s", processedQueryId, queryType) + String.format("-%s.asice", randomGenerator.get()); } String getArchiveFilename(String queryId, String queryType); String createFilenameWithRandom(String queryId, String queryType); }### Answer: @Test public void testGeneratedFilename() { AsicContainerNameGenerator nameGenerator = new AsicContainerNameGenerator( AsicContainerNameGeneratorTest::generateRandomPart, 10); String s1 = nameGenerator.createFilenameWithRandom(LONG_QUERY_ID, QUERY_TYPE_REQUEST); assertTrue("The generated filename was too long", s1.length() <= FILENAME_MAX); String s2 = nameGenerator.createFilenameWithRandom(LONG_QUERY_ID, QUERY_TYPE_RESPONSE); assertTrue("The generated filename was too long", s2.length() <= FILENAME_MAX); String s3 = nameGenerator.createFilenameWithRandom(SHORT_QUERY_ID, QUERY_TYPE_REQUEST); assertTrue("The generated filename was too long", s3.length() <= FILENAME_MAX); String s4 = nameGenerator.createFilenameWithRandom(SHORT_QUERY_ID, QUERY_TYPE_RESPONSE); assertTrue("The generated filename was too long", s4.length() <= FILENAME_MAX); }
### Question: AsicContainer { public static AsicContainer read(InputStream is) throws Exception { return AsicHelper.read(is); } AsicContainer(Map<String, String> entries); AsicContainer(String message, SignatureData signature); AsicContainer(String message, SignatureData signature, TimestampData timestamp); String getMessage(); SignatureData getSignature(); TimestampData getTimestamp(); String getManifest(); String getAsicManifest(); byte[] getBytes(); boolean isAttachment(String fileName); boolean hasEntry(String fileName); InputStream getEntry(String fileName); String getEntryAsString(String fileName); static AsicContainer read(InputStream is); void write(OutputStream out); }### Answer: @Test public void test() throws Exception { thrown.expectError(errorCode); try (FileInputStream in = new FileInputStream("src/test/resources/" + containerFile)) { AsicContainer.read(in); } }
### Question: AsicUtils { public static String truncate(String s, int max) { if (s == null) { return null; } if (s.length() > max) { return s.substring(0, max); } else { return s; } } private AsicUtils(); @SneakyThrows static String escapeString(String str); static String buildFailureOutput(Throwable cause); static String buildSuccessOutput(AsicContainerVerifier verifier); static String truncate(String s, int max); }### Answer: @Test public void testTruncate() { assertEquals("Ham", AsicUtils.truncate("Hamburger", 3)); assertEquals("Olive", AsicUtils.truncate("Olive", 12)); assertEquals("", AsicUtils.truncate("", 1200)); assertEquals(null, AsicUtils.truncate(null, 0)); }
### Question: AtomicSave { public static void execute(String fileName, String tmpPrefix, Callback callback, CopyOption... options) throws Exception { Path target = Paths.get(fileName); Path parentPath = target.getParent(); Path tempFile = DefaultFilepaths.createTempFile(parentPath, tmpPrefix, null); try { SeekableByteChannel channel = Files.newByteChannel(tempFile, CREATE, WRITE, TRUNCATE_EXISTING, DSYNC); try (OutputStream out = Channels.newOutputStream(channel)) { callback.save(out); } if (options.length == 0) { Files.move(tempFile, target, StandardCopyOption.REPLACE_EXISTING); } else { Files.move(tempFile, target, options); } } finally { if (Files.exists(tempFile)) { Files.delete(tempFile); } } } private AtomicSave(); static void execute(String fileName, String tmpPrefix, Callback callback, CopyOption... options); static void execute(String fileName, String tmpPrefix, final byte[] data, CopyOption... options); static void moveBetweenFilesystems(String sourceFileName, String targetFileName); }### Answer: @Test public void tmpFileRemoved() throws Exception { try { AtomicSave.execute(DESTINATION_FILE, "AtomicSaveTest", out -> { throw new CodedException(ErrorCodes.X_IO_ERROR); }); } catch (CodedException e) { Assert.assertFalse("Temporary file not deleted", tmpFileExists()); return; } finally { Files.deleteIfExists(Paths.get(DESTINATION_FILE)); } fail(); }
### Question: CertUtils { public static X509Certificate[] readCertificateChain(String filename) throws CertificateException, IOException { CertificateFactory fact = CertificateFactory.getInstance("X.509"); try (FileInputStream is = new FileInputStream(filename)) { final Collection<? extends Certificate> certs = fact.generateCertificates(is); return certs.toArray(new X509Certificate[0]); } } private CertUtils(); static String getSubjectCommonName(X509Certificate cert); static String getSubjectSerialNumber(X509Certificate cert); static ClientId getSubjectClientId(X509Certificate cert); static boolean isAuthCert(X509Certificate cert); static boolean isSigningCert(X509Certificate cert); static boolean isValid(X509Certificate cert); static boolean isSelfSigned(X509Certificate cert); static String getOcspResponderUriFromCert(X509Certificate subject); static String[] getCertHashes(List<X509Certificate> certs); static String getRDNValue(X500Name name, ASN1ObjectIdentifier id); static byte[] generateCertRequest(PrivateKey privateKey, PublicKey publicKey, String principal); static KeyPair readKeyPairFromPemFile(String filename); static void writePemToFile(byte[] certBytes, String filename); static X509Certificate[] readCertificateChain(String filename); static void createPkcs12(String filenameKey, String filenamePem, String filenameP12); static String identify(X509Certificate certificate); }### Answer: @Test public void testReadCertificate() throws CertificateException, IOException { X509Certificate[] certificate = CertUtils.readCertificateChain("src/test/resources/internal.crt"); assertNotNull(certificate); assertEquals(certificate[0].getSubjectDN().getName(), "CN=ubuntu-xroad-securityserver-dev"); }
### Question: SchemaValidator { protected static void validate(Schema schema, Source source, String errorCode) throws Exception { if (schema == null) { throw new IllegalStateException("Schema is not initialized"); } try { Validator validator = schema.newValidator(); validator.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); validator.validate(source); } catch (SAXException e) { throw new CodedException(errorCode, e); } } }### Answer: @Test public void testOkValidation() throws Exception { StreamSource source = new StreamSource(ResourceUtils.getClasspathResourceStream("test-part.xml")); TestValidator.validate(source); } @Test public void testXxeFailsValidation() throws Exception { thrown.expectError(ErrorCodes.X_MALFORMED_OPTIONAL_PARTS_CONF); StreamSource source = new StreamSource(ResourceUtils.getClasspathResourceStream("test-part-with-xxe.xml")); TestValidator.validate(source); fail("Should fail to parse XML containing XXE. But it passed validation."); }
### Question: SystemPropertiesLoader { static List<Path> getFilePaths(Path dir, String glob) throws IOException { try (DirectoryStream<Path> dStream = Files.newDirectoryStream(dir, glob)) { List<Path> filePaths = new ArrayList<>(); dStream.forEach(filePaths::add); return filePaths; } } protected SystemPropertiesLoader(String prefix); static SystemPropertiesLoader create(); static SystemPropertiesLoader create(String prefix); SystemPropertiesLoader withCommon(); SystemPropertiesLoader withoutOverrides(); SystemPropertiesLoader withLocal(); SystemPropertiesLoader withAddOn(); SystemPropertiesLoader withCommonAndLocal(); SystemPropertiesLoader with(String fileName, String... sectionNames); SystemPropertiesLoader withLocalOptional(String fileName, String... sectionNames); SystemPropertiesLoader withAtLeastOneOf(String... filePaths); void load(); }### Answer: @Test public void listFilePathsBasedOnGlob() throws IOException { String testGlob = "*.ini"; List<Path> testFilePaths = SystemPropertiesLoader.getFilePaths( Paths.get("src/test/resources/loading_order_inis"), testGlob); assertEquals(testFilePaths.size(), testFilePaths.size()); assertTrue(testFilePaths.containsAll(testFiles)); }
### Question: ConfigurationLocation { public static URLConnection getDownloadURLConnection(String urlStr) throws IOException { URL url = new URL(urlStr); URLConnection connection = url.openConnection(); connection.setReadTimeout(READ_TIMEOUT); return connection; } InputStream getInputStream(); static URLConnection getDownloadURLConnection(String urlStr); X509Certificate getVerificationCert(String certHashBase64, String hashAlgoId); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static final int READ_TIMEOUT; }### Answer: @Test public void connectionsTimeout() throws IOException { URLConnection connection = ConfigurationLocation.getDownloadURLConnection("http: assertEquals(connection.getReadTimeout(), ConfigurationLocation.READ_TIMEOUT); assertTrue(connection.getReadTimeout() > 0); }
### Question: IdentifierTypeConverter { static ServiceId parseServiceId(XRoadIdentifierType v) { return ServiceId.create(v.getXRoadInstance(), v.getMemberClass(), v.getMemberCode(), v.getSubsystemCode(), v.getServiceCode(), v.getServiceVersion()); } private IdentifierTypeConverter(); }### Answer: @Test public void readServiceIdentifier() throws Exception { ServiceId id = parseServiceId( fileToType("serviceid.xml", SERVICE, XRoadServiceIdentifierType.class)); assertEquals("EE", id.getXRoadInstance()); assertEquals("BUSINESS", id.getMemberClass()); assertEquals("JODA", id.getMemberCode()); assertEquals("getState", id.getServiceCode()); assertEquals("SERVICE:EE/BUSINESS/JODA/getState", id.toString()); assertNull(id.getServiceVersion()); } @Test public void readServiceIdentifierWithVersion() throws Exception { ServiceId id = parseServiceId( fileToType("serviceid-version.xml", SERVICE, XRoadServiceIdentifierType.class)); assertEquals("EE", id.getXRoadInstance()); assertEquals("BUSINESS", id.getMemberClass()); assertEquals("JODA", id.getMemberCode()); assertEquals("getState", id.getServiceCode()); assertEquals("SERVICE:EE/BUSINESS/JODA/getState/v1", id.toString()); assertEquals("v1", id.getServiceVersion()); }
### Question: IdentifierTypeConverter { static SecurityCategoryId parseSecurityCategoryId(XRoadIdentifierType v) { return SecurityCategoryId.create(v.getXRoadInstance(), v.getSecurityCategoryCode()); } private IdentifierTypeConverter(); }### Answer: @Test public void readSecurityCategoryIdentifier() throws Exception { SecurityCategoryId id = parseSecurityCategoryId( fileToType("securitycategoryid.xml", SECURITYCATEGORY, XRoadSecurityCategoryIdentifierType.class)); assertEquals("EE", id.getXRoadInstance()); assertEquals("ISKE_H", id.getCategoryCode()); assertEquals("SECURITYCATEGORY:EE/ISKE_H", id.toString()); }
### Question: IdentifierTypeConverter { static CentralServiceId parseCentralServiceId(XRoadIdentifierType v) { return CentralServiceId.create(v.getXRoadInstance(), v.getServiceCode()); } private IdentifierTypeConverter(); }### Answer: @Test public void readCentralServiceIdentifier() throws Exception { CentralServiceId id = parseCentralServiceId( fileToType("centralserviceid.xml", CENTRALSERVICE, XRoadCentralServiceIdentifierType.class)); assertEquals("EE", id.getXRoadInstance()); assertEquals("rahvastikuregister_isikuandmed", id.getServiceCode()); assertEquals("CENTRALSERVICE:EE/rahvastikuregister_isikuandmed", id.toString()); }
### Question: IdentifierTypeConverter { static SecurityServerId parseSecurityServerId(XRoadIdentifierType v) { return SecurityServerId.create(v.getXRoadInstance(), v.getMemberClass(), v.getMemberCode(), v.getServerCode()); } private IdentifierTypeConverter(); }### Answer: @Test public void readSecurityServerIdentifier() throws Exception { SecurityServerId id = parseSecurityServerId( fileToType("securityserverid.xml", SERVER, XRoadSecurityServerIdentifierType.class)); assertEquals("EE", id.getXRoadInstance()); assertEquals("BUSINESS", id.getMemberClass()); assertEquals("123456789", id.getMemberCode()); assertEquals("bambi", id.getServerCode()); assertEquals("SERVER:EE/BUSINESS/123456789/bambi", id.toString()); }
### Question: IdentifierTypeConverter { static GlobalGroupId parseGlobalGroupId(XRoadIdentifierType v) { return GlobalGroupId.create(v.getXRoadInstance(), v.getGroupCode()); } private IdentifierTypeConverter(); }### Answer: @Test public void readGlobalGroupIdentifier() throws Exception { GlobalGroupId id = parseGlobalGroupId( fileToType("globalgroupid.xml", GLOBALGROUP, XRoadGlobalGroupIdentifierType.class)); assertEquals("EE", id.getXRoadInstance()); assertEquals("perearstid", id.getGroupCode()); assertEquals("GLOBALGROUP:EE/perearstid", id.toString()); }
### Question: IdentifierTypeConverter { static LocalGroupId parseLocalGroupId(XRoadIdentifierType v) { return LocalGroupId.create(v.getGroupCode()); } private IdentifierTypeConverter(); }### Answer: @Test public void readLocalGroupIdentifier() throws Exception { LocalGroupId id = parseLocalGroupId( fileToType("localgroupid.xml", LOCALGROUP, XRoadLocalGroupIdentifierType.class)); assertNull(id.getXRoadInstance()); assertEquals("lokaalgrupp", id.getGroupCode()); assertEquals("LOCALGROUP:lokaalgrupp", id.toString()); }
### Question: ProcessLister extends AbstractExecLister<ProcessInfo> { @Override protected String getCommand() { return LIST_PROCESSES_COMMAND; } static void main(String[] args); }### Answer: @Test public void testProcessList() throws Exception { ProcessLister testProcessLister = new ProcessLister() { @Override ProcessOutputs executeProcess() throws IOException, InterruptedException { ProcessOutputs fakeOutputs = new ProcessOutputs(); fakeOutputs.setOut(processOutputString); return fakeOutputs; } }; JmxStringifiedData<ProcessInfo> data = testProcessLister.list(); assertEquals(11, data.getDtoData().size()); assertEquals(12, data.getJmxStringData().size()); ProcessInfo info = data.getDtoData().iterator().next(); assertEquals("root", info.getUserId()); assertEquals("7.0", info.getCpuLoad()); assertEquals("marras05", info.getStartTime()); assertEquals("0.2", info.getMemUsed()); assertEquals("1", info.getProcessId()); assertEquals("init", info.getCommand()); String jmxData = data.getJmxStringData().get(1); assertEquals("root 7.0 marras05 0.2 1 init", jmxData); }
### Question: MetricRegistryHolder { @SuppressWarnings("unchecked") public <T extends Serializable> SimpleSensor<T> getOrCreateSimpleSensor(String metricName) { final Gauge sensor = metrics.gauge(metricName, SimpleSensor::new); if (sensor instanceof SimpleSensor) { return (SimpleSensor<T>) sensor; } throw new IllegalArgumentException(metricName + " is already used for a different type of metric"); } private MetricRegistryHolder(); static MetricRegistryHolder getInstance(); MetricRegistry getMetrics(); void setMetrics(MetricRegistry metricRegistry); @SuppressWarnings("unchecked") SimpleSensor<T> getOrCreateSimpleSensor(String metricName); Histogram getOrCreateHistogram(String metricName); }### Answer: @Test public void testGetOrCreateSimpleSensor() { try { MetricRegistryHolder holder = MetricRegistryHolder.getInstance(); assertEquals(holder.getOrCreateSimpleSensor("Sensor"), holder.getOrCreateSimpleSensor("Sensor")); } catch (Exception e) { fail("Exception should not have been thrwon!"); } }
### Question: MetricRegistryHolder { public Histogram getOrCreateHistogram(String metricName) { return metrics.histogram(metricName, this::createDefaultHistogram); } private MetricRegistryHolder(); static MetricRegistryHolder getInstance(); MetricRegistry getMetrics(); void setMetrics(MetricRegistry metricRegistry); @SuppressWarnings("unchecked") SimpleSensor<T> getOrCreateSimpleSensor(String metricName); Histogram getOrCreateHistogram(String metricName); }### Answer: @Test public void testGetOrCreateHistogram() { try { MetricRegistryHolder holder = MetricRegistryHolder.getInstance(); assertEquals(holder.getOrCreateHistogram("Histogram"), holder.getOrCreateHistogram("Histogram")); } catch (Exception e) { fail("Exception should not have been thrown!"); } }
### Question: ManagementRequestSender { static Integer getRequestId( SoapMessageImpl responseMessage) throws SOAPException { NodeList nodes = responseMessage .getSoap() .getSOAPBody() .getElementsByTagNameNS(SoapHeader.NS_XROAD, "requestId"); if (nodes.getLength() == 0) { return null; } Node node = nodes.item(0); try { return Integer.parseInt(node.getTextContent()); } catch (NumberFormatException e) { return null; } } ManagementRequestSender(ClientId sender, ClientId receiver); Integer sendAuthCertRegRequest(SecurityServerId securityServer, String address, byte[] authCert); Integer sendAuthCertDeletionRequest(SecurityServerId securityServer, byte[] authCert); Integer sendClientRegRequest(SecurityServerId securityServer, ClientId clientId); Integer sendClientDeletionRequest(SecurityServerId securityServer, ClientId clientId); }### Answer: @Test public void getRequestIdFromManagementServiceResponse() throws Exception { SoapMessageImpl response = createResponse("response-with-requestId.answer"); Integer requestId = ManagementRequestSender.getRequestId(response); Integer expectedRequestId = 413; assertEquals(expectedRequestId, requestId); }
### Question: CertificateProfileInfoValidator { public static void validate(String className) { try { new GetCertificateProfile(className).klass(); } catch (Exception e) { log.error("Error getting profile info for class '{}'", className, e); throw new RuntimeException("Certificate profile with name '" + className + "' does not exist."); } } private CertificateProfileInfoValidator(); static void validate(String className); }### Answer: @Test public void passWhenClassNameCorrect() throws ClassNotFoundException { CertificateProfileInfoValidator.validate( "ee.ria.xroad.common.certificateprofile.impl." + "EjbcaCertificateProfileInfoProvider"); } @Test(expected = RuntimeException.class) public void failWhenClassDoesNotImplementProfileInfoInterface() throws ClassNotFoundException { CertificateProfileInfoValidator.validate("java.lang.String"); } @Test(expected = RuntimeException.class) public void failWhenClassDoesNotExist() throws ClassNotFoundException { CertificateProfileInfoValidator.validate("a.b.C"); }
### Question: ManagementRequestUtil { public static SoapMessageImpl toResponse( SoapMessageImpl request, int requestId) throws Exception { return SoapUtils.toResponse( request, soap -> addRequestId(requestId, soap)); } private ManagementRequestUtil(); static SoapMessageImpl toResponse( SoapMessageImpl request, int requestId); }### Answer: @Test public void addIdToResponse() throws Exception { SoapMessageImpl request = createRequest("simple.query"); int id = 10; SoapMessageImpl response = ManagementRequestUtil.toResponse(request, id); assertThat(response.getXml(), containsRequestId()); }
### Question: OperationalDataRequestHandler extends QueryRequestHandler { protected static void checkOutputFields(Set<String> outputFields) { for (String field : outputFields) { if (!OUTPUT_FIELDS.contains(field)) { throw new CodedException(X_INVALID_REQUEST, "Unknown output field in search criteria: " + field) .withPrefix(CLIENT_X); } } } @Override void handle(SoapMessageImpl requestSoap, OutputStream out, Consumer<String> contentTypeCallback); }### Answer: @Test public void checkOkSearchCriteriaOutputFields() throws Exception { OperationalDataRequestHandler.checkOutputFields(Collections.emptySet()); OperationalDataRequestHandler.checkOutputFields(Sets.newHashSet( "monitoringDataTs", "securityServerInternalIp")); } @Test public void checkInvalidSearchCriteriaOutputFields() throws Exception { thrown.expect(CodedException.class); thrown.expectMessage( "Unknown output field in search criteria: UNKNOWN-FIELD"); OperationalDataRequestHandler.checkOutputFields(Sets.newHashSet( "monitoringDataTs", "UNKNOWN-FIELD")); }
### Question: OperationalDataRequestHandler extends QueryRequestHandler { protected GetSecurityServerOperationalDataResponseType buildOperationalDataResponse(ClientId filterByClient, long recordsFrom, long recordsTo, ClientId filterByServiceProvider, Set<String> outputFields, long recordsAvailableBefore) throws IOException { OperationalDataRecords responseRecords; GetSecurityServerOperationalDataResponseType opDataResponse = OBJECT_FACTORY .createGetSecurityServerOperationalDataResponseType(); if (recordsTo >= recordsAvailableBefore) { log.debug("recordsTo({}) >= recordsAvailableBefore({})," + " set nextRecordsFrom to {}", recordsTo, recordsAvailableBefore, recordsAvailableBefore); recordsTo = recordsAvailableBefore - 1; opDataResponse.setNextRecordsFrom(recordsAvailableBefore); } responseRecords = getOperationalDataRecords(filterByClient, recordsFrom, recordsTo, filterByServiceProvider, outputFields); opDataResponse.setRecordsCount(responseRecords.size()); String payload = responseRecords.getPayload(GSON); responseRecords.getRecords().clear(); opDataResponse.setRecords(createAttachmentDataSource(compress(payload), CID, MimeTypes.GZIP)); if (responseRecords.getNextRecordsFrom() != null) { opDataResponse.setNextRecordsFrom( responseRecords.getNextRecordsFrom()); } return opDataResponse; } @Override void handle(SoapMessageImpl requestSoap, OutputStream out, Consumer<String> contentTypeCallback); }### Answer: @Test public void buildOperationalDataResponseWithNotAvailableRecordsTo() throws Exception { ClientId client = ClientId.create( "XTEE-CI-XM", "00000001", "GOV", "System1"); OperationalDataRequestHandler handler = new OperationalDataRequestHandler(); long recordsAvailableBefore = TimeUtils.getEpochSecond(); GetSecurityServerOperationalDataResponseType response = handler .buildOperationalDataResponse(client, 1474968960L, recordsAvailableBefore + 10, null, Collections.emptySet(), recordsAvailableBefore); assertNotNull(response.getNextRecordsFrom()); }
### Question: OperationalDataRequestHandler extends QueryRequestHandler { static void checkTimestamps(long recordsFrom, long recordsTo, long recordsAvailableBefore) { if (recordsFrom < 0) { throw new CodedException(X_INVALID_REQUEST, "Records from timestamp is a negative number") .withPrefix(CLIENT_X); } if (recordsTo < 0) { throw new CodedException(X_INVALID_REQUEST, "Records to timestamp is a negative number") .withPrefix(CLIENT_X); } if (recordsTo < recordsFrom) { throw new CodedException(X_INVALID_REQUEST, "Records to timestamp is earlier than records from" + " timestamp").withPrefix(CLIENT_X); } if (recordsFrom >= recordsAvailableBefore) { throw new CodedException(X_INVALID_REQUEST, "Records not available from " + recordsFrom + " yet") .withPrefix(CLIENT_X); } } @Override void handle(SoapMessageImpl requestSoap, OutputStream out, Consumer<String> contentTypeCallback); }### Answer: @Test public void checkNegativeRecordsFromTimestamps() throws Exception { thrown.expect(CodedException.class); thrown.expectMessage("Records from timestamp is a negative number"); OperationalDataRequestHandler.checkTimestamps(-10, 10, 10); } @Test public void checkNegativeRecordsToTimestamps() throws Exception { thrown.expect(CodedException.class); thrown.expectMessage("Records to timestamp is a negative number"); OperationalDataRequestHandler.checkTimestamps(10, -10, 10); } @Test public void checkEarlierRecordsToTimestamps() throws Exception { thrown.expect(CodedException.class); thrown.expectMessage("Records to timestamp is earlier than records" + " from timestamp"); OperationalDataRequestHandler.checkTimestamps(10, 5, 10); } @Test public void checkRecordsNotAvailable() throws Exception { thrown.expect(CodedException.class); thrown.expectMessage("Records not available from " + 10 + " yet"); OperationalDataRequestHandler.checkTimestamps(10, 10, 5); }
### Question: OcspFetchIntervalSchemaValidator extends SchemaValidator { public void validateFile(String fileName) throws Exception { String xml = FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8.toString()); validate(xml); } static void main(String[] args); void validateFile(String fileName); static void validate(String xml); static void validate(Source source); }### Answer: @Test public void testValidConfiguration() throws Exception { OcspFetchIntervalSchemaValidator validator = new OcspFetchIntervalSchemaValidator(); validator.validateFile(getClasspathFilename(VALID_FILE)); } @Test public void testEmptyConfigurationIsInvalid() throws Exception { OcspFetchIntervalSchemaValidator validator = new OcspFetchIntervalSchemaValidator(); exception.expect(Exception.class); validator.validateFile(getClasspathFilename(EMPTY_FILE)); } @Test public void testInvalidConfiguration() throws Exception { OcspFetchIntervalSchemaValidator validator = new OcspFetchIntervalSchemaValidator(); exception.expect(Exception.class); validator.validateFile(getClasspathFilename(INVALID_FILE)); }
### Question: QueryRequestHandler { abstract void handle(SoapMessageImpl requestSoap, OutputStream out, Consumer<String> contentTypeCallback) throws Exception; }### Answer: @Test public void handleOperationalDataRequest() throws Exception { InputStream is = new FileInputStream(OPERATIONAL_DATA_REQUEST); SoapParser parser = new SoapParserImpl(); SoapMessageImpl request = (SoapMessageImpl) parser.parse( MimeTypes.TEXT_XML_UTF8, is); QueryRequestHandler handler = new OperationalDataRequestHandler() { @Override protected OperationalDataRecords getOperationalDataRecords( ClientId filterByClient, long recordsFrom, long recordsTo, ClientId filterByServiceProvider, Set<String> outputFields) { return new OperationalDataRecords(Collections.emptyList()); } @Override protected ClientId getClientForFilter(ClientId clientId, SecurityServerId serverId) throws Exception { return null; } }; OutputStream out = new ByteArrayOutputStream(); handler.handle(request, out, ct -> testContentType = ct); String baseContentType = MimeUtils.getBaseContentType(testContentType); assertEquals(MimeTypes.MULTIPART_RELATED, baseContentType); SoapMessageDecoder decoder = new SoapMessageDecoder(testContentType, new SoapMessageDecoder.Callback() { @Override public void soap(SoapMessage message, Map<String, String> headers) throws Exception { assertEquals("cid:" + OperationalDataRequestHandler.CID, findRecordsContentId(message)); } @Override public void attachment(String contentType, InputStream content, Map<String, String> additionalHeaders) throws Exception { String expectedCid = "<" + OperationalDataRequestHandler.CID + ">"; assertEquals(expectedCid, additionalHeaders.get("content-id")); } @Override public void onCompleted() { } @Override public void onError(Exception t) throws Exception { throw t; } @Override public void fault(SoapFault fault) throws Exception { throw fault.toCodedException(); } }); decoder.parse(IOUtils.toInputStream(out.toString())); }
### Question: OperationalDataRecords { String getPayload(Gson gson) { return gson.toJson(this); } OperationalDataRecords(List<OperationalDataRecord> records); }### Answer: @Test public void emptyRecordsPayload() throws Exception { List<OperationalDataRecord> recordList = new ArrayList<>(); OperationalDataRecords records = new OperationalDataRecords(recordList); recordList.add(new OperationalDataRecord()); recordList.add(new OperationalDataRecord()); assertEquals("{\"records\":[{},{}]}", records.getPayload(GSON)); }
### Question: WSDLParser { public static Collection<ServiceInfo> parseWSDL(String wsdlUrl) throws Exception { try { return internalParseWSDL(wsdlUrl); } catch (Exception e) { throw translateException(clarifyWsdlParsingException(e)); } } private WSDLParser(); static Collection<ServiceInfo> parseWSDL(String wsdlUrl); }### Answer: @Test public void readValidWsdl() throws Exception { Collection<ServiceInfo> si = WSDLParser.parseWSDL("file:src/test/resources/valid.wsdl"); assertEquals(3, si.size()); } @Test(expected = CodedException.class) public void readInvalidWsdl() throws Exception { WSDLParser.parseWSDL("file:src/test/resources/invalid.wsdl"); } @Test(expected = CodedException.class) public void readWsdlFromInvalidUrl() throws Exception { WSDLParser.parseWSDL("http: } @Test(expected = CodedException.class) public void readFaultInsteadOfWsdl() throws Exception { WSDLParser.parseWSDL("file:src/test/resources/fault.xml"); }
### Question: MonitoringParametersSchemaValidator extends SchemaValidator { public void validateFile(String fileName) throws Exception { String xml = FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8.toString()); validate(xml); } static void main(String[] args); void validateFile(String fileName); static void validate(String xml); static void validate(Source source); }### Answer: @Test public void testValidConfiguration() throws Exception { MonitoringParametersSchemaValidator validator = new MonitoringParametersSchemaValidator(); validator.validateFile(getClasspathFilename(VALID_FILE)); } @Test public void testValidEmptyConfiguration() throws Exception { MonitoringParametersSchemaValidator validator = new MonitoringParametersSchemaValidator(); validator.validateFile(getClasspathFilename(VALID_EMPTY_FILE)); } @Test public void testInvalidConfiguration() throws Exception { MonitoringParametersSchemaValidator validator = new MonitoringParametersSchemaValidator(); exception.expect(Exception.class); validator.validateFile(getClasspathFilename(INVALID_FILE)); }
### Question: OcspNextUpdateSchemaValidator extends SchemaValidator { public void validateFile(String fileName) throws Exception { String xml = FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8.toString()); validate(xml); } static void main(String[] args); void validateFile(String fileName); static void validate(String xml); static void validate(Source source); }### Answer: @Test public void testValidConfiguration() throws Exception { OcspNextUpdateSchemaValidator validator = new OcspNextUpdateSchemaValidator(); validator.validateFile(getClasspathFilename(VALID_FILE)); } @Test public void testEmptyConfigurationIsInvalid() throws Exception { OcspNextUpdateSchemaValidator validator = new OcspNextUpdateSchemaValidator(); exception.expect(Exception.class); validator.validateFile(getClasspathFilename(EMPTY_FILE)); } @Test public void testInvalidConfiguration() throws Exception { OcspNextUpdateSchemaValidator validator = new OcspNextUpdateSchemaValidator(); exception.expect(Exception.class); validator.validateFile(getClasspathFilename(INVALID_FILE)); }
### Question: CertHelper { public static String getSubjectSerialNumber(X509Certificate cert) { return CertUtils.getSubjectSerialNumber(cert); } private CertHelper(); static String getSubjectCommonName(X509Certificate cert); static String getSubjectSerialNumber(X509Certificate cert); static ClientId getSubjectClientId(X509Certificate cert); static void verifyAuthCert(CertChain chain, List<OCSPResp> ocspResponses, ClientId member); static OCSPResp getOcspResponseForCert(X509Certificate cert, X509Certificate issuer, List<OCSPResp> ocspResponses); }### Answer: @Test public void getSubjectSerialNumber() throws Exception { String base64data = IOUtils.toString(new FileInputStream( "../common-test/src/test/certs/test-esteid.txt")); X509Certificate cert = CryptoUtils.readCertificate(base64data); String serialNumber = CertHelper.getSubjectSerialNumber(cert); assertEquals("47101010033", serialNumber); } @Test public void subjectSerialNumberNotAvailable() throws Exception { X509Certificate cert = TestCertUtil.getProducer().certChain[0]; String serialNumber = CertHelper.getSubjectSerialNumber(cert); assertNull(serialNumber); }
### Question: ConfigurationDownloader { DownloadResult download(ConfigurationSource source, String... contentIdentifiers) { DownloadResult result = new DownloadResult(); for (ConfigurationLocation location : getLocations(source)) { try { Configuration config = download(location, contentIdentifiers); rememberLastSuccessfulLocation(location); return result.success(config); } catch (Exception e) { result.addFailure(location, e); } } return result.failure(); } ConfigurationDownloader(FileNameProvider fileNameProvider, int version, String... instanceIdentifiers); static URL getDownloadURL(ConfigurationLocation location, ConfigurationFile file); static URLConnection getDownloadURLConnection(URL url); static final int READ_TIMEOUT; }### Answer: @Test public void rememberLastSuccessfulDownloadLocation() { for (int i = 0; i < MAX_ATTEMPTS; i++) { ConfigurationDownloader downloader = getDownloader(LOCATION_URL_SUCCESS); List<String> locationUrls = getMixedLocationUrls(); downloader.download(getSource(locationUrls)); resetParser(downloader); downloader.download(getSource(locationUrls)); verifyLastSuccessfulLocationUsedSecondTime(downloader); } }
### Question: ConfigurationDownloader { public static URLConnection getDownloadURLConnection(URL url) throws IOException { URLConnection connection = url.openConnection(); connection.setReadTimeout(READ_TIMEOUT); return connection; } ConfigurationDownloader(FileNameProvider fileNameProvider, int version, String... instanceIdentifiers); static URL getDownloadURL(ConfigurationLocation location, ConfigurationFile file); static URLConnection getDownloadURLConnection(URL url); static final int READ_TIMEOUT; }### Answer: @Test public void downloaderConnectionsTimeout() throws IOException { URLConnection connection = ConfigurationDownloader.getDownloadURLConnection( new URL("http: assertEquals(connection.getReadTimeout(), ConfigurationDownloader.READ_TIMEOUT); assertTrue(connection.getReadTimeout() > 0); }
### Question: LogArchiveCache implements Closeable { void add(MessageRecord messageRecord) throws Exception { try { validateMessageRecord(messageRecord); handleRotation(); cacheRecord(messageRecord); updateState(); } catch (Exception e) { handleCacheError(e); } } LogArchiveCache(Supplier<String> randomGenerator, LinkingInfoBuilder linkingInfoBuilder, Path workingDir); @Override void close(); }### Answer: @Test public void doNotAllowNullMessageRecords() throws Exception { thrown.expect(IllegalArgumentException.class); cache.add(null); thrown.expectMessage("Message record to be archived must not be null"); } @Test public void avoidNameClashWhenFileWithSameNameIsAlreadyInSameZip() throws Exception { setMaxArchiveSizeDefault(); cache = createCache(new TestRandomGenerator()); cache.add(createRequestRecordNormal()); assertZip(expectedNormalSizeRequestEntryName(), getArchiveBytes()); cache.add(createRequestRecordNormal()); assertZip(expectedConflictingEntryNames(), getArchiveBytes()); }
### Question: Hash { @Override public String toString() { return algoId + SEPARATOR + hashValue; } Hash(String hashString); Hash(String algoId, String hashValue); @Override String toString(); }### Answer: @Test public void parseSuccessfully() { String hashString = "SHA-256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4" + "649b934ca495991b7852b855"; Hash h = new Hash(hashString); assertEquals("SHA-256", h.getAlgoId()); assertEquals("e3b0c44298fc1c149afbf4c8996fb92427ae41e4" + "649b934ca495991b7852b855", h.getHashValue()); assertEquals(hashString, h.toString()); }
### Question: OpMonitoringBuffer extends AbstractOpMonitoringBuffer { @Override protected void store(OpMonitoringData data) throws Exception { if (ignoreOpMonitoringData()) { return; } data.setSecurityServerInternalIp(getIpAddress()); buffer.put(getNextBufferIndex(), data); send(); } OpMonitoringBuffer(); @Override void preStart(); @Override void postStop(); static final String OP_MONITORING_DAEMON_SENDER; }### Answer: @Test public void bufferOverflow() throws Exception { System.setProperty("xroad.op-monitor-buffer.size", "2"); final Props props = Props.create(TestOpMonitoringBuffer.class); final TestActorRef<TestOpMonitoringBuffer> testActorRef = TestActorRef.create(ACTOR_SYSTEM, props, "testActorRef"); TestOpMonitoringBuffer opMonitoringBuffer = testActorRef.underlyingActor(); OpMonitoringData opMonitoringData = new OpMonitoringData( OpMonitoringData.SecurityServerType.CLIENT, 100); opMonitoringBuffer.store(opMonitoringData); opMonitoringBuffer.store(opMonitoringData); opMonitoringBuffer.store(opMonitoringData); assertEquals(2, opMonitoringBuffer.buffer.size()); assertEquals(true, opMonitoringBuffer.buffer.containsKey(2L)); assertEquals(true, opMonitoringBuffer.buffer.containsKey(3L)); }
### Question: SoapMessageBodyManipulator { public boolean isClientInCollection(ClientId searchParam, Iterable<ClientId> searched) { ClientId searchResult = Iterables.find(searched, input -> (input.memberEquals(searchParam) && Objects.equals(input.getSubsystemCode(), searchParam.getSubsystemCode())), null); return (searchResult != null); } String getLoggableMessageText(SoapMessageImpl message, boolean clientSide); boolean isSoapBodyLogged(SoapMessageImpl message, boolean clientSide); boolean isClientInCollection(ClientId searchParam, Iterable<ClientId> searched); }### Answer: @Test public void clientIdSearching() throws Exception { SoapMessageBodyManipulator manipulator = new SoapMessageBodyManipulator(); ClientId ss1 = ClientId.create("instance", "memberclass", "membercode", "ss1"); ClientId cmember = ClientId.create("instance", "memberclass", "membercode", null); ClientId ss2 = ClientId.create("instance", "memberclass", "membercode", "ss2"); ClientId cmember2 = ClientId.create("instance", "memberclass", "membercode2", null); List<ClientId> coll1 = Arrays.asList(ss1, cmember); assertTrue(manipulator.isClientInCollection(ss1, coll1)); assertTrue(manipulator.isClientInCollection( ClientId.create("instance", "memberclass", "membercode", "ss1"), coll1)); assertFalse(manipulator.isClientInCollection(ss2, coll1)); assertTrue(manipulator.isClientInCollection(cmember, coll1)); assertFalse(manipulator.isClientInCollection(cmember2, coll1)); assertFalse(manipulator.isClientInCollection( ClientId.create("-", "memberclass", "membercode", "ss1"), coll1)); assertFalse(manipulator.isClientInCollection(ss1, Arrays.asList(cmember))); }
### Question: MetadataClientRequestProcessor extends MessageProcessorBase { public boolean canProcess() { switch (target) { case LIST_CLIENTS: case LIST_CENTRAL_SERVICES: return true; case WSDL: return SystemProperties.isAllowGetWsdlRequest(); default: return false; } } MetadataClientRequestProcessor(String target, HttpServletRequest request, HttpServletResponse response); boolean canProcess(); @Override void process(); @Override MessageInfo createRequestMessageInfo(); }### Answer: @Test public void shouldBeAbleToProcessListClients() { MetadataClientRequestProcessor processorToTest = new MetadataClientRequestProcessor(LIST_CLIENTS, mockRequest, mockResponse); assertTrue("Wasn't able to process list clients", processorToTest.canProcess()); } @Test public void shouldBeAbleToProcessListCentralServices() { MetadataClientRequestProcessor processorToTest = new MetadataClientRequestProcessor(LIST_CENTRAL_SERVICES, mockRequest, mockResponse); assertTrue("Wasn't able to process central services", processorToTest.canProcess()); } @Test public void shouldBeAbleToProcessGetWsdl() { System.setProperty(SystemProperties.ALLOW_GET_WSDL_REQUEST, "true"); MetadataClientRequestProcessor processorToTest = new MetadataClientRequestProcessor(WSDL, mockRequest, mockResponse); assertTrue("Wasn't able to process get wsdl request", processorToTest.canProcess()); } @Test public void shouldNotBeAbleToProcessGetWsdl() { System.setProperty(SystemProperties.ALLOW_GET_WSDL_REQUEST, "false"); MetadataClientRequestProcessor processorToTest = new MetadataClientRequestProcessor(WSDL, mockRequest, mockResponse); assertFalse("Was able to process get wsdl request", processorToTest.canProcess()); } @Test public void shouldNotBeAbleToProcessRandomRequest() { MetadataClientRequestProcessor processorToTest = new MetadataClientRequestProcessor("getRandom", mockRequest, mockResponse); assertFalse("Was able to process a random target", processorToTest.canProcess()); }
### Question: ProxyMessageDecoder { private void parseFault(InputStream is) throws Exception { Soap soap = new SaxSoapParserImpl().parse(MimeTypes.TEXT_XML_UTF8, is); if (!(soap instanceof SoapFault)) { throw new CodedException(X_INVALID_MESSAGE, "Expected fault message, but got reqular SOAP message"); } callback.fault((SoapFault) soap); } ProxyMessageDecoder(ProxyMessageConsumer callback, String contentType, String hashAlgoId); ProxyMessageDecoder(ProxyMessageConsumer callback, String contentType, boolean faultAllowed, String hashAlgoId); void parse(InputStream is); void verify(ClientId sender, SignatureData signatureData); int getAttachmentCount(); }### Answer: @Test public void parseFault() throws Exception { ProxyMessageDecoder decoder = createDecoder(MimeTypes.TEXT_XML); decoder.parse(getQuery("fault.query")); assertNotNull(callback.getFault()); }
### Question: AntiDosConnectionManager { synchronized void accept(T connection) { syncDatabase(); HostData currentPartner = getHostData(connection.getHostAddress()); currentPartner.connections.addFirst(connection); if (!activePartners.contains(currentPartner)) { activePartners.add(currentPartner); } } AntiDosConnectionManager(AntiDosConfiguration configuration); }### Answer: @Test public void normalLoad() throws Exception { TestConfiguration conf = new TestConfiguration(15, 0.5); TestSystemMetrics sm = new TestSystemMetrics(); sm.addLoad(20, 0.1); TestSocketChannel member1 = createConnection("test1"); TestSocketChannel member2 = createConnection("test2"); TestSocketChannel member3 = createConnection("test3"); TestConnectionManager cm = createConnectionManager(conf, sm); cm.accept(member1, member2, member2, member3); cm.assertConnections(member1, member2, member3, member2); cm.assertEmpty(); } @Test public void knownMembersCanConnectUnderDosAttack() throws Exception { TestConfiguration conf = new TestConfiguration(5, 1.1); TestSystemMetrics sm = new TestSystemMetrics(); sm.addLoad(7, 0.1); TestSocketChannel member1 = createConnection("test1"); TestSocketChannel member2 = createConnection("test2"); TestSocketChannel attacker1 = createConnection("attacker1"); TestSocketChannel attacker2 = createConnection("attacker2"); TestConnectionManager cm = createConnectionManager(conf, sm); cm.accept( member1, attacker1, member2, attacker1, attacker2, attacker2, member2); cm.assertConnections( member1, attacker1, member2, attacker1, member2, attacker2, attacker2); cm.assertEmpty(); }
### Question: HealthChecks { public static HealthCheckProvider cacheResultOnce(HealthCheckProvider provider, HealthCheckResult cachedOnceResult) { return new HealthCheckProvider() { private HealthCheckResult cachedResult = cachedOnceResult; @Override public HealthCheckResult get() { HealthCheckResult result = Optional.ofNullable(cachedResult).orElseGet(provider); cachedResult = null; return result; } }; } private HealthChecks(); static HealthCheckProvider checkAuthKeyOcspStatus(); static HealthCheckProvider checkServerConfDatabaseStatus(); static Function<HealthCheckProvider, HealthCheckProvider> cacheResultFor( int resultValidFor, int errorResultValidFor, TimeUnit timeUnit); static HealthCheckProvider cacheResultOnce(HealthCheckProvider provider, HealthCheckResult cachedOnceResult); }### Answer: @Test public void cacheResultOnceShouldCacheOnce() { final HealthCheckResult expectedFirstResult = failure("message for failure"); final HealthCheckResult expectedSecondResult = failure("some other message"); final HealthCheckProvider mockProvider = mock(HealthCheckProvider.class); when(mockProvider.get()).thenReturn(expectedSecondResult); final HealthCheckProvider testedProvider = HealthChecks.cacheResultOnce(mockProvider, expectedFirstResult); assertEquals("first result does not match", expectedFirstResult, testedProvider.get()); assertEquals("second result does not match", expectedSecondResult, testedProvider.get()); assertEquals("third result does not match", expectedSecondResult, testedProvider.get()); }
### Question: HealthChecks { public static HealthCheckProvider checkServerConfDatabaseStatus() { return () -> { try { ServerConf.getIdentifier(); } catch (RuntimeException e) { log.error("Got exception while checking server configuration db status", e); return failure("Server Conf database did not respond as expected"); } return OK; }; } private HealthChecks(); static HealthCheckProvider checkAuthKeyOcspStatus(); static HealthCheckProvider checkServerConfDatabaseStatus(); static Function<HealthCheckProvider, HealthCheckProvider> cacheResultFor( int resultValidFor, int errorResultValidFor, TimeUnit timeUnit); static HealthCheckProvider cacheResultOnce(HealthCheckProvider provider, HealthCheckResult cachedOnceResult); }### Answer: @Test public void checkServerConfShouldReturnOkStatusWhenServerConfReturnsInfo() { ServerConfProvider mockProvider = mock(ServerConfProvider.class); when(mockProvider.getIdentifier()).thenReturn( SecurityServerId.create("XE", "member", "code", "servercode")); ServerConf.reload(mockProvider); HealthCheckProvider testedProvider = HealthChecks.checkServerConfDatabaseStatus(); assertTrue("result should be OK", testedProvider.get().isOk()); } @Test public void checkServerConfShouldReturnNotOkWhenServerConfThrows() { ServerConfProvider mockProvider = mock(ServerConfProvider.class); when(mockProvider.getIdentifier()).thenThrow(new RuntimeException("broken conf!")); ServerConf.reload(mockProvider); HealthCheckProvider testedProvider = HealthChecks.checkServerConfDatabaseStatus(); HealthCheckResult checkedResult = testedProvider.get(); assertTrue("health check result should be a failure", !checkedResult.isOk()); assertThat(checkedResult.getErrorMessage(), containsString("Server Conf database did not respond as expected")); }
### Question: BackupFileService extends ServiceDispatcher<I, O> implements BackupFileServiceApi<I, O> { @Override public boolean isValidBackupFilename(String filename) { return isValidZipBackupFilename(filename) || isValidEncryptedBackupFilename(filename); } @Override boolean isValidBackupFilename(String filename); @Override boolean isValidZipBackupFilename(String filename); @Override boolean isValidEncryptedBackupFilename(String filename); }### Answer: @Test public void testIsValidBackupFilename_withValidZipBackupFilename_succeeds() { String givenFilename = "/example/filename.zip"; boolean result = this.target.isValidBackupFilename(givenFilename); assertTrue(result); } @Test public void testIsValidBackupFilename_withValidEncryptedBackupFilename_succeeds() { String givenFilename = "/example/filename.dbb"; boolean result = this.target.isValidBackupFilename(givenFilename); assertTrue(result); } @Test public void testIsValidBackupFilename_withInvalidBackupFilename_fails() { String givenFilename = "/example/filename.zip1"; boolean result = this.target.isValidBackupFilename(givenFilename); assertFalse(result); }
### Question: BackupFileService extends ServiceDispatcher<I, O> implements BackupFileServiceApi<I, O> { @Override public boolean isValidZipBackupFilename(String filename) { return ("." + FilenameUtils.getExtension(filename)).equals(EXT_ZIP_BACKUP); } @Override boolean isValidBackupFilename(String filename); @Override boolean isValidZipBackupFilename(String filename); @Override boolean isValidEncryptedBackupFilename(String filename); }### Answer: @Test public void testIsValidZipBackupFilename_withValidFilename_succeeds() { String givenFilename = "/example/filename.zip"; boolean result = this.target.isValidZipBackupFilename(givenFilename); assertTrue(result); } @Test public void testIsValidZipBackupFilename_withInvalidFilename_fails() { String givenFilename = "/example/filename.zip2"; boolean result = this.target.isValidZipBackupFilename(givenFilename); assertFalse(result); }
### Question: BackupFileService extends ServiceDispatcher<I, O> implements BackupFileServiceApi<I, O> { @Override public boolean isValidEncryptedBackupFilename(String filename) { return ("." + FilenameUtils.getExtension(filename)).equals(EXT_ENCRYPTED_BACKUP); } @Override boolean isValidBackupFilename(String filename); @Override boolean isValidZipBackupFilename(String filename); @Override boolean isValidEncryptedBackupFilename(String filename); }### Answer: @Test public void testIsValidEncryptedBackupFilename_withValidFilename_succeeds() { String givenFilename = "/example/filename.dbb"; boolean result = this.target.isValidEncryptedBackupFilename(givenFilename); assertTrue(result); } @Test public void testIsValidEncryptedBackupFilename_withInvalidFilename_fails() { String givenFilename = "/example/filename.dbb123"; boolean result = this.target.isValidEncryptedBackupFilename(givenFilename); assertFalse(result); }
### Question: SyncDistributedApplianceService extends ServiceDispatcher<BaseIdRequest, BaseJobResponse> implements SyncDistributedApplianceServiceApi { @Override protected BaseJobResponse exec(BaseIdRequest request, EntityManager em) throws Exception { this.da = em.find(DistributedAppliance.class, request.getId()); validate(em, request.getId()); Long jobId = this.daConformJobFactory.startDAConformJob(em, this.da); BaseJobResponse response = new BaseJobResponse(); response.setJobId(jobId); return response; } }### Answer: @Test public void testExec_WithVariousIds() throws Exception { BaseIdRequest request = new BaseIdRequest(this.daId); BaseJobResponse response = this.service.exec(request, this.em); Assert.assertNotNull(response); assertEquals(this.jobId, response.getJobId()); }
### Question: CleanK8sDAITask extends TransactionalTask { public CleanK8sDAITask create(DistributedApplianceInstance daiForDeletion) { return create(daiForDeletion, null); } CleanK8sDAITask create(DistributedApplianceInstance daiForDeletion); @Override void executeTransaction(EntityManager em); @Override String getName(); @Override Set<LockObjectReference> getObjects(); }### Answer: @Test public void testExecute_WithDAIAssignedToInspectionElement_DAICleanedOfNetworkInformation() throws Exception { DistributedApplianceInstance dai = createAndRegisterDAI(true, 100L); CleanK8sDAITask task = this.factory.create(dai); task.execute(); verify(this.em, Mockito.times(1)).merge(Mockito.argThat(new CleanNetworkInfoDAIMatcher())); verify(this.em, Mockito.never()).remove(Mockito.any(DistributedApplianceInstance.class)); }
### Question: ConformK8sDeploymentSpecInspectionPortsMetaTask extends TransactionalMetaTask { public ConformK8sDeploymentSpecInspectionPortsMetaTask create(DeploymentSpec ds) { ConformK8sDeploymentSpecInspectionPortsMetaTask task = new ConformK8sDeploymentSpecInspectionPortsMetaTask(); task.deleteK8sDAIInspectionPortTask = this.deleteK8sDAIInspectionPortTask; task.registerK8sDAIInspectionPortTask = this.registerK8sDAIInspectionPortTask; task.ds = ds; task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } ConformK8sDeploymentSpecInspectionPortsMetaTask create(DeploymentSpec ds); @Override void executeTransaction(EntityManager em); @Override String getName(); @Override TaskGraph getTaskGraph(); @Override Set<LockObjectReference> getObjects(); }### Answer: @Test public void testExecuteTransaction_WithVariousDeploymentSpecs_ExpectsCorrectTaskGraph() throws Exception { this.factoryTask.deleteK8sDAIInspectionPortTask = new DeleteK8sDAIInspectionPortTask(); this.factoryTask.registerK8sDAIInspectionPortTask = new RegisterK8sDAIInspectionPortTask(); ConformK8sDeploymentSpecInspectionPortsMetaTask task = this.factoryTask.create(this.ds); task.execute(); TaskGraphHelper.validateTaskGraph(task, this.expectedGraph); }
### Question: CreateK8sDeploymentTask extends TransactionalTask { CreateK8sDeploymentTask create(DeploymentSpec ds, KubernetesDeploymentApi k8sDeploymentApi) { CreateK8sDeploymentTask task = new CreateK8sDeploymentTask(); task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; task.ds = ds; task.k8sDeploymentApi = k8sDeploymentApi; return task; } CreateK8sDeploymentTask create(DeploymentSpec ds); @Override void executeTransaction(EntityManager em); @Override String getName(); @Override Set<LockObjectReference> getObjects(); }### Answer: @Test public void testExecute_WhenCreateDeploymentSucceeds_DSIsUpdatedWithK8sDeploymentID() throws Exception { VirtualizationConnector vc = new VirtualizationConnector(); vc.setProviderIpAddress("1.1.1.1"); VirtualSystem vs = new VirtualSystem(null); vs.setVirtualizationConnector(vc); vs.setId(102L); ApplianceSoftwareVersion avs = new ApplianceSoftwareVersion(); avs.setImageUrl("ds-image-url"); avs.setImagePullSecretName("ds-pull-secret-name"); vs.setApplianceSoftwareVersion(avs); DeploymentSpec ds = new DeploymentSpec(vs, null, null, null, null, null); ds.setId(101L); ds.setName("ds-name"); ds.setNamespace("ds-namespace"); ds.setInstanceCount(5); when(this.em.find(DeploymentSpec.class, ds.getId())).thenReturn(ds); String k8sDeploymentId = UUID.randomUUID().toString(); mockCreateK8sDeployment(ds, k8sDeploymentId); CreateK8sDeploymentTask task = this.factory.create(ds, this.k8sDeploymentApi); task.execute(); Assert.assertEquals("The deployment spec external id was different than expected", k8sDeploymentId, ds.getExternalId()); verify(this.em, Mockito.times(1)).merge(ds); }
### Question: DeleteK8sDAIInspectionPortTask extends TransactionalTask { public DeleteK8sDAIInspectionPortTask create(DistributedApplianceInstance dai) { DeleteK8sDAIInspectionPortTask task = new DeleteK8sDAIInspectionPortTask(); task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; task.apiFactoryService = this.apiFactoryService; task.dai = dai; return task; } DeleteK8sDAIInspectionPortTask create(DistributedApplianceInstance dai); @Override void executeTransaction(EntityManager em); @Override String getName(); @Override Set<LockObjectReference> getObjects(); }### Answer: @Test public void testExecute_WhenSDNThrowsException_ThrowsUnhandledException() throws Exception { DistributedApplianceInstance dai = createAndRegisterDAI(); DeleteK8sDAIInspectionPortTask task = this.factory.create(dai); doThrow(new IllegalStateException()) .when(this.redirectionApi) .removeInspectionPort(argThat(new InspectionPortElementMatcher(dai.getInspectionElementId(), dai.getInspectionElementParentId()))); when(this.apiFactoryServiceMock.createNetworkRedirectionApi(dai.getVirtualSystem())).thenReturn(this.redirectionApi); this.exception.expect(IllegalStateException.class); task.execute(); verify(this.em, never()).remove(any(DistributedApplianceInstance.class)); } @Test public void testExecute_WhenInspectionPortIsRemoved_DAIIsDeleted() throws Exception { DistributedApplianceInstance dai = createAndRegisterDAI(); DeleteK8sDAIInspectionPortTask task = this.factory.create(dai); when(this.apiFactoryServiceMock.createNetworkRedirectionApi(dai.getVirtualSystem())).thenReturn(this.redirectionApi); task.execute(); verify(this.redirectionApi, times(1)) .removeInspectionPort(argThat(new InspectionPortElementMatcher(dai.getInspectionElementId(), dai.getInspectionElementParentId()))); verify(this.em, times(1)).remove(dai); }
### Question: ConformK8sDeploymentSpecMetaTask extends TransactionalMetaTask { public ConformK8sDeploymentSpecMetaTask create(DeploymentSpec ds) { ConformK8sDeploymentSpecMetaTask task = new ConformK8sDeploymentSpecMetaTask(); task.deleteK8sDAIInspectionPortTask = this.deleteK8sDAIInspectionPortTask; task.deleteK8sDeploymentTask = this.deleteK8sDeploymentTask; task.createOrUpdateK8sDeploymentSpecMetaTask = this.createOrUpdateK8sDeploymentSpecMetaTask; task.mgrCheckDevicesMetaTask = this.mgrCheckDevicesMetaTask; task.deleteDSFromDbTask = this.deleteDSFromDbTask; task.ds = ds; task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } ConformK8sDeploymentSpecMetaTask create(DeploymentSpec ds); @Override void executeTransaction(EntityManager em); @Override String getName(); @Override TaskGraph getTaskGraph(); @Override Set<LockObjectReference> getObjects(); }### Answer: @Test public void testExecuteTransaction_WithVariousDeploymentSpecs_ExpectsCorrectTaskGraph() throws Exception { this.factoryTask.deleteDSFromDbTask = new DeleteDSFromDbTask(); this.factoryTask.mgrCheckDevicesMetaTask = new MgrCheckDevicesMetaTask(); this.factoryTask.deleteK8sDAIInspectionPortTask = new DeleteK8sDAIInspectionPortTask(); this.factoryTask.createOrUpdateK8sDeploymentSpecMetaTask = new CreateOrUpdateK8sDeploymentSpecMetaTask(); this.factoryTask.deleteK8sDeploymentTask = new DeleteK8sDeploymentTask(); ConformK8sDeploymentSpecMetaTask task = this.factoryTask.create(this.ds); task.execute(); TaskGraphHelper.validateTaskGraph(task, this.expectedGraph); }
### Question: CreateOrUpdateK8sDeploymentSpecMetaTask extends TransactionalMetaTask { CreateOrUpdateK8sDeploymentSpecMetaTask create(DeploymentSpec ds, KubernetesDeploymentApi k8sDeploymentApi) { CreateOrUpdateK8sDeploymentSpecMetaTask task = new CreateOrUpdateK8sDeploymentSpecMetaTask(); task.createK8sDeploymentTask = this.createK8sDeploymentTask; task.updateK8sDeploymentTask = this.updateK8sDeploymentTask; task.checkK8sDeploymentStateTask = this.checkK8sDeploymentStateTask; task.conformK8sDeploymentPodsMetaTask = this.conformK8sDeploymentPodsMetaTask; task.k8sDeploymentApi = k8sDeploymentApi; task.ds = ds; task.k8sDeploymentApi = this.k8sDeploymentApi; task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } CreateOrUpdateK8sDeploymentSpecMetaTask create(DeploymentSpec ds); @Override void executeTransaction(EntityManager em); @Override String getName(); @Override TaskGraph getTaskGraph(); @Override Set<LockObjectReference> getObjects(); }### Answer: @Test public void testExecuteTransaction_WithVariousDeploymentSpecs_ExpectsCorrectTaskGraph() throws Exception { this.factoryTask.createK8sDeploymentTask = new CreateK8sDeploymentTask(); this.factoryTask.updateK8sDeploymentTask = new UpdateK8sDeploymentTask(); this.factoryTask.checkK8sDeploymentStateTask = new CheckK8sDeploymentStateTask(); this.factoryTask.conformK8sDeploymentPodsMetaTask = new ConformK8sDeploymentPodsMetaTask(); CreateOrUpdateK8sDeploymentSpecMetaTask task = this.factoryTask.create(this.ds, this.k8sDeploymentApi); task.execute(); TaskGraphHelper.validateTaskGraph(task, this.expectedGraph); }
### Question: ConformK8sDeploymentPodsMetaTask extends TransactionalMetaTask { public ConformK8sDeploymentPodsMetaTask create(DeploymentSpec ds, KubernetesPodApi k8sPodApi) { ConformK8sDeploymentPodsMetaTask task = new ConformK8sDeploymentPodsMetaTask(); task.deleteOrCleanK8sDAITask = this.deleteOrCleanK8sDAITask; task.createOrUpdateK8sDAITask = this.createOrUpdateK8sDAITask; task.conformK8sInspectionPortMetaTask = this.conformK8sInspectionPortMetaTask; task.managerCheckDevicesMetaTask = this.managerCheckDevicesMetaTask; task.ds = ds; task.k8sPodApi = this.k8sPodApi; task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } ConformK8sDeploymentPodsMetaTask create(DeploymentSpec ds, KubernetesPodApi k8sPodApi); ConformK8sDeploymentPodsMetaTask create(DeploymentSpec ds); @Override void executeTransaction(EntityManager em); @Override String getName(); @Override TaskGraph getTaskGraph(); @Override Set<LockObjectReference> getObjects(); }### Answer: @Test public void testExecuteTransaction_WithVariousDeploymentSpecs_ExpectsCorrectTaskGraph() throws Exception { this.factoryTask.deleteOrCleanK8sDAITask = new CleanK8sDAITask(); this.factoryTask.createOrUpdateK8sDAITask = new CreateOrUpdateK8sDAITask(); this.factoryTask.conformK8sInspectionPortMetaTask = new ConformK8sDeploymentSpecInspectionPortsMetaTask(); this.factoryTask.managerCheckDevicesMetaTask = new MgrCheckDevicesMetaTask(); ConformK8sDeploymentPodsMetaTask task = this.factoryTask.create(this.ds, this.k8sPodApi); task.execute(); TaskGraphHelper.validateTaskGraph(task, this.expectedGraph); }
### Question: DeleteK8sDeploymentTask extends TransactionalTask { public DeleteK8sDeploymentTask create(DeploymentSpec ds) { return create(ds, null); } DeleteK8sDeploymentTask create(DeploymentSpec ds); @Override void executeTransaction(EntityManager em); @Override String getName(); @Override Set<LockObjectReference> getObjects(); }### Answer: @Test public void testExecute_WithExistingDS_K8sDSIsDeleted() throws Exception { VirtualizationConnector vc = new VirtualizationConnector(); vc.setProviderIpAddress("1.1.1.1"); VirtualSystem vs = new VirtualSystem(null); vs.setVirtualizationConnector(vc); vs.setId(102L); ApplianceSoftwareVersion asv = new ApplianceSoftwareVersion(); asv.setImageUrl("ds-image-url"); asv.setImagePullSecretName("ds-pull-secret-name"); vs.setApplianceSoftwareVersion(asv); DeploymentSpec ds = new DeploymentSpec(vs, null, null, null, null, null); ds.setId(101L); ds.setName("ds-name"); ds.setNamespace("ds-namespace"); ds.setInstanceCount(8); ds.setExternalId(UUID.randomUUID().toString()); when(this.em.find(DeploymentSpec.class, ds.getId())).thenReturn(ds); DeleteK8sDeploymentTask task = this.factory.create(ds, this.k8sDeploymentApi); task.execute(); verify(this.k8sDeploymentApi, Mockito.times(1)).deleteDeployment( ds.getExternalId(), ds.getNamespace(), K8sUtil.getK8sName(ds)); }
### Question: RegisterK8sDAIInspectionPortTask extends TransactionalTask { public RegisterK8sDAIInspectionPortTask create(DistributedApplianceInstance dai) { RegisterK8sDAIInspectionPortTask task = new RegisterK8sDAIInspectionPortTask(); task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; task.apiFactoryService = this.apiFactoryService; task.dai = dai; return task; } RegisterK8sDAIInspectionPortTask create(DistributedApplianceInstance dai); @Override void executeTransaction(EntityManager em); @Override String getName(); @Override Set<LockObjectReference> getObjects(); }### Answer: @Test public void testExecute_WhenSDNThrowsException_ThrowsUnhandledException() throws Exception { DistributedApplianceInstance dai = createAndRegisterDAI(); RegisterK8sDAIInspectionPortTask task = this.factory.create(dai); mockRegisterInspectionPortNetworkElement(dai, new IllegalStateException()); this.exception.expect(IllegalStateException.class); task.execute(); verify(this.em, never()).merge(any(DistributedApplianceInstance.class)); } @Test public void testExecute_WhenInspectionPortIsRegistered_DAIIsUpdated() throws Exception { DistributedApplianceInstance dai = createAndRegisterDAI(); RegisterK8sDAIInspectionPortTask task = this.factory.create(dai); String inspectionPortId = mockRegisterInspectionPortNetworkElement(dai); task.execute(); Assert.assertEquals("The inspection element id was different than expected.", inspectionPortId, dai.getInspectionElementId()); verify(this.em, times(1)).merge(dai); }
### Question: UpdateK8sDeploymentTask extends TransactionalTask { UpdateK8sDeploymentTask create(DeploymentSpec ds, KubernetesDeploymentApi k8sDeploymentApi) { UpdateK8sDeploymentTask task = new UpdateK8sDeploymentTask(); task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; task.ds = ds; task.k8sDeploymentApi = k8sDeploymentApi; return task; } UpdateK8sDeploymentTask create(DeploymentSpec ds); @Override void executeTransaction(EntityManager em); @Override String getName(); @Override Set<LockObjectReference> getObjects(); }### Answer: @Test public void testExecute_WhenUpdatingSucceeds_K8sDeploymentIsUpdatedWithNewInstanceCount() throws Exception { VirtualizationConnector vc = new VirtualizationConnector(); vc.setProviderIpAddress("1.1.1.1"); VirtualSystem vs = new VirtualSystem(null); vs.setVirtualizationConnector(vc); vs.setId(102L); ApplianceSoftwareVersion asv = new ApplianceSoftwareVersion(); asv.setImageUrl("ds-image-url"); asv.setImagePullSecretName("ds-pull-secret-name"); vs.setApplianceSoftwareVersion(asv); DeploymentSpec ds = new DeploymentSpec(vs, null, null, null, null, null); ds.setId(101L); ds.setName("ds-name"); ds.setNamespace("ds-namespace"); ds.setInstanceCount(8); ds.setExternalId(UUID.randomUUID().toString()); when(this.em.find(DeploymentSpec.class, ds.getId())).thenReturn(ds); UpdateK8sDeploymentTask task = this.factory.create(ds, this.k8sDeploymentApi); task.execute(); verify(this.k8sDeploymentApi, Mockito.times(1)).updateDeploymentReplicaCount( ds.getExternalId(), ds.getNamespace(), K8sUtil.getK8sName(ds), ds.getInstanceCount()); }
### Question: DeleteK8sLabelPodTask extends TransactionalTask { public DeleteK8sLabelPodTask create(Pod pod, Label label) { DeleteK8sLabelPodTask task = new DeleteK8sLabelPodTask(); task.pod = pod; task.label = label; task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } @Override void executeTransaction(EntityManager em); DeleteK8sLabelPodTask create(Pod pod, Label label); @Override String getName(); @Override Set<LockObjectReference> getObjects(); }### Answer: @Test public void testExecute_WithPodAssignedToAnotherMember_NothingIsRemoved() throws Exception { Pod pod = createAndRegisterPod(100L); pod.getLabels().add(new Label(UUID.randomUUID().toString(), UUID.randomUUID().toString())); Label memberLabel = new Label(UUID.randomUUID().toString(), UUID.randomUUID().toString()); DeleteK8sLabelPodTask task = this.factory.create(pod, memberLabel); task.execute(); verify(this.em, Mockito.never()).remove(Mockito.any(PodPort.class)); verify(this.em, Mockito.never()).remove(Mockito.any(Pod.class)); } @Test public void testExecute_WithPodAssignedToTargetedMember_PodAndPortRemoved() throws Exception { Pod pod = createAndRegisterPod(100L); String sameLabel = UUID.randomUUID().toString(); pod.getLabels().add(new Label(UUID.randomUUID().toString(), sameLabel)); Label memberLabel = new Label(UUID.randomUUID().toString(), sameLabel); DeleteK8sLabelPodTask task = this.factory.create(pod, memberLabel); task.execute(); verify(this.em, Mockito.times(1)).remove(pod.getPorts().iterator().next()); verify(this.em, Mockito.times(1)).remove(pod); }