method2testcases stringlengths 118 3.08k |
|---|
### Question:
CDIBeanServiceDescriptor implements ServiceDescriptor { protected static Class<?> getServiceInterface(Class<?> beanClass) { Service serviceAnnotation = beanClass.getAnnotation(Service.class); Class<?> serviceInterface = serviceAnnotation.value(); if (serviceInterface == Service.class) { Class<?>[] interfaces = beanClass.getInterfaces(); if (interfaces.length == 1) { serviceInterface = interfaces[0]; } else { throw BeanMessages.MESSAGES.unexpectedExceptionTheServiceAnnotationHasNoValueItCannotBeOmmittedUnlessTheBeanImplementsExactlyOneInterface(); } } else if (!serviceInterface.isInterface()) { throw BeanMessages.MESSAGES.invalidServiceSpecificationService(serviceInterface.getName()); } return serviceInterface; } CDIBeanServiceDescriptor(CDIBean cdiBean, BeanDeploymentMetaData beanDeploymentMetaData); CDIBean getCDIBean(); @Override String getServiceName(); BeanServiceMetadata getServiceMetadata(); @Override ServiceProxyHandler getHandler(); @Override ServiceInterface getInterface(); }### Answer:
@Test public void test_IsInterface_OK() { CDIBeanServiceDescriptor.getServiceInterface(XImpl.class); }
@Test public void test_OmmitInterface_OK() { CDIBeanServiceDescriptor.getServiceInterface(ZImpl.class); }
@Test public void test_OmmitInterface_Fail_noInterface() { try { CDIBeanServiceDescriptor.getServiceInterface(TImpl.class); } catch (RuntimeException e) { String message = e.getMessage(); Assert.assertTrue(message.contains("SWITCHYARD030420")); } }
@Test public void test_OmmitInterface_Fail_multipleInterfaces() { try { CDIBeanServiceDescriptor.getServiceInterface(UImpl.class); } catch (RuntimeException e) { String message = e.getMessage(); Assert.assertTrue(message.contains("SWITCHYARD030420")); } }
@Test public void test_IsInterface_Fail() { try { CDIBeanServiceDescriptor.getServiceInterface(YImpl.class); } catch (RuntimeException e) { String message = e.getMessage(); Assert.assertTrue(message.contains("SWITCHYARD030421")); } } |
### Question:
CamelTransformer extends BaseTransformer { @Override public Object transform(final Object from) { if (from == null) { return null; } final Class<?> toType = QNameUtil.toJavaMessageType(getTo()); return _camelConverter.convert(toType, from); } CamelTransformer(); CamelTransformer(final QName from, final QName to); @Override Object transform(final Object from); }### Answer:
@Test public void genericFileToString() throws Exception { final QName genericFileType = new QName("java:org.apache.camel.component.file.GenericFile"); final QName stringType = JavaTypes.toMessageType(String.class); final CamelTransformer camelTransformer = new CamelTransformer(); camelTransformer.setFrom(genericFileType); camelTransformer.setTo(stringType); final GenericFile<File> genericFile = new GenericFile<File>(); genericFile.setBody("dummy file content"); final Object transform = camelTransformer.transform(genericFile); assertThat(transform, is(instanceOf(String.class))); } |
### Question:
CamelTypeConverterExtractor extends DefaultTypeConverter { public Map<QName, Set<QName>> getTransformTypes() { for (Entry<TypeMapping, TypeConverter> entry : typeMappings.entrySet()) { final TypeMapping mapping = entry.getKey(); final QName fromType = JavaTypes.toMessageType(mapping.getFromType()); final QName toType = JavaTypes.toMessageType(mapping.getToType()); getToTypesFor(fromType).add(toType); } return Collections.unmodifiableMap(_transformTypes); } CamelTypeConverterExtractor(final CamelContext camelContext); void init(); Map<QName, Set<QName>> getTransformTypes(); TransformsModel getTransformsModel(final TransformerRegistry transformerRegistry); TransformsModel getTransformsModel(); }### Answer:
@Test public void extractTypeConverterTypes() throws Exception { final Map<QName, Set<QName>> transformTypes = _extractor.getTransformTypes(); final Set<QName> toTypes = transformTypes.get(JavaTypes.toMessageType(String.class)); assertThat(toTypes, hasItems( new QName("java:java.io.InputStream"), new QName("java:java.io.StringReader"), new QName("java:java.io.File"), new QName("java:java.nio.ByteBuffer"), new QName("java:long"), new QName("java:char"), new QName("java:byte[]"), new QName("java:char[]"), new QName("java:javax.xml.transform.Source"), new QName("java:javax.xml.transform.dom.DOMSource"), new QName("java:javax.xml.transform.sax.SAXSource"), new QName("java:org.w3c.dom.Document"), new QName("java:org.apache.camel.StringSource"))); } |
### Question:
CamelTypeConverterExtractor extends DefaultTypeConverter { public TransformsModel getTransformsModel(final TransformerRegistry transformerRegistry) { final TransformsModel transforms = new V1TransformsModel(TransformNamespace.DEFAULT.uri()); for (Entry<QName, Set<QName>> entry : getTransformTypes().entrySet()) { final QName from = entry.getKey(); final Set<QName> toTypes = entry.getValue(); for (QName to : toTypes) { final V1JavaTransformModel transform = new V1JavaTransformModel(TransformNamespace.DEFAULT.uri()); transform.setFrom(from); transform.setTo(to); transform.setClazz(CamelTransformer.class.getName()); if (!isTransformRegistred(transform, transformerRegistry)) { transforms.addTransform(transform); } } } return transforms; } CamelTypeConverterExtractor(final CamelContext camelContext); void init(); Map<QName, Set<QName>> getTransformTypes(); TransformsModel getTransformsModel(final TransformerRegistry transformerRegistry); TransformsModel getTransformsModel(); }### Answer:
@Test public void generateTransformsModel() { final TransformsModel v1TransformsModel = _extractor.getTransformsModel(); assertThat(v1TransformsModel, is(not(nullValue()))); assertThat(v1TransformsModel.getTransforms().size(), is(greaterThan(161))); } |
### Question:
RouteFactory { public static List<RouteDefinition> createRoute(String className) { return createRoute(className, null); } private RouteFactory(); static List<RouteDefinition> getRoutes(CamelComponentImplementationModel model); static List<RouteDefinition> loadRoute(String xmlPath); static List<RouteDefinition> createRoute(String className); static List<RouteDefinition> createRoute(String className, String namespace); static List<RouteDefinition> createRoute(Class<?> routeClass); static List<RouteDefinition> createRoute(Class<?> routeClass, String namespace); }### Answer:
@Test public void createRouteFromClass() { List<RouteDefinition> routes = RouteFactory.createRoute(SingleRouteService.class.getName()); Assert.assertNotNull(routes); Assert.assertEquals(1, routes.size()); RouteDefinition route = routes.get(0); Assert.assertEquals(1, route.getInputs().size()); Assert.assertEquals(2, route.getOutputs().size()); }
@Test public void doesntExtendRouteBuilder() { try { RouteFactory.createRoute(DoesntExtendRouteBuilder.class.getName()); Assert.fail("Java DSL class does not extend RouteBuilder " + DoesntExtendRouteBuilder.class.getName()); } catch (RuntimeException ex) { System.err.println("Route class that does not extend RouteBuilder was rejected: " + ex.toString()); } }
@Test public void noRoutesDefined() { try { RouteFactory.createRoute(NoRoutesDefined.class.getName()); Assert.fail("No routes defined in Java DSL class " + NoRoutesDefined.class.getName()); } catch (RuntimeException ex) { System.err.println("Java DSL class without a route was rejected: " + ex.toString()); } } |
### Question:
ComponentNameComposer { public static Map<String, String> getQueryParamMap(final URI uri) { final Map<String, String> map = new HashMap<String, String>(); for (final String param : uri.getQuery().split("&")) { final String[] nameValue = param.split("="); if (nameValue.length == 2) { map.put(nameValue[0], nameValue[1]); } } return map; } private ComponentNameComposer(); static String composeComponentUri(final QName serviceName); static QName composeSwitchYardServiceName(
final String namespace, final String uri, final QName componentName); static Map<String, String> getQueryParamMap(final URI uri); }### Answer:
@Test public void getQueryParamMap() throws Exception { final Map<String, String> map = getQueryParamMap("switchyard: assertThat(map.size(), is(2)); assertThat(map.get("foo"), equalTo("bar")); assertThat(map.get("bar"), equalTo("baz")); }
@Test public void getQueryParamMap_no_params() throws Exception { assertThat(getQueryParamMap("switchyard: } |
### Question:
CamelResponseHandler implements ExchangeHandler { @Override public void handleMessage(final Exchange switchYardExchange) throws HandlerException { try { compose(switchYardExchange); } catch (Exception e) { throw new HandlerException(e); } } CamelResponseHandler(final org.apache.camel.Exchange camelExchange, final ServiceReference reference, final MessageComposer<CamelBindingData> messageComposer); @Override void handleMessage(final Exchange switchYardExchange); @Override void handleFault(final Exchange exchange); }### Answer:
@Test (expected = RuntimeException.class) public void constructor() throws Exception { final CamelResponseHandler responseHandler = new CamelResponseHandler(null, null, _messageComposer); responseHandler.handleMessage(null); }
@Test public void handleMessageWithOutputType() throws HandlerException { final Exchange camelExchange = createCamelExchange(); final ServiceReference serviceReference = createMockServiceRef(); final org.switchyard.Exchange switchYardExchange = createMockExchangeWithBody(new MessageCreator() { @Override public Message create() { Message message = mock(Message.class); when(message.getContext()).thenReturn(new DefaultContext(Scope.MESSAGE)); when(message.getContent(Integer.class)).thenReturn(10); return message; } }); final CamelResponseHandler responseHandler = new CamelResponseHandler(camelExchange, serviceReference, _messageComposer); responseHandler.handleMessage(switchYardExchange); assertThat(switchYardExchange.getMessage().getContent(Integer.class), is(equalTo(new Integer(10)))); } |
### Question:
RESTEasyUtil { public static List<String> getParamValues(Map<String, String> contextParams, String paramName) { if (contextParams != null) { String providers = contextParams.get(paramName); if (providers != null) { return Arrays.asList(providers.split(",")); } } return null; } private RESTEasyUtil(); static List<String> getParamValues(Map<String, String> contextParams, String paramName); static List<Class<?>> getProviderClasses(Map<String, String> contextParams); static Map<Class<?>, Class<?>> getExceptionProviderMap(Map<String, String> contextParams); static List<ClientErrorInterceptor> getClientErrorInterceptors(Map<String, String> contextParams); }### Answer:
@Test public void testGetProviders() throws Exception { Assert.assertNull(RESTEasyUtil.getParamValues(null, ResteasyContextParameters.RESTEASY_PROVIDERS)); Assert.assertNull(RESTEasyUtil.getParamValues(contextParams, ResteasyContextParameters.RESTEASY_PROVIDERS)); List<String> providers = RESTEasyUtil.getParamValues(contextParamsWithProviders, ResteasyContextParameters.RESTEASY_PROVIDERS); Assert.assertEquals(2, providers.size()); Assert.assertEquals(STRING_CLASS_NAME, providers.get(0)); Assert.assertEquals(BAD_CLASS_NAME, providers.get(1)); } |
### Question:
RESTEasyUtil { public static List<Class<?>> getProviderClasses(Map<String, String> contextParams) { List<String> providers = getParamValues(contextParams, ResteasyContextParameters.RESTEASY_PROVIDERS); if (providers != null) { List<Class<?>> providerClasses = new ArrayList<Class<?>>(providers.size()); for (String provider : providers) { Class<?> pc = Classes.forName(provider.trim()); if (pc != null) { providerClasses.add(pc); } } return providerClasses.isEmpty() ? null : providerClasses; } return null; } private RESTEasyUtil(); static List<String> getParamValues(Map<String, String> contextParams, String paramName); static List<Class<?>> getProviderClasses(Map<String, String> contextParams); static Map<Class<?>, Class<?>> getExceptionProviderMap(Map<String, String> contextParams); static List<ClientErrorInterceptor> getClientErrorInterceptors(Map<String, String> contextParams); }### Answer:
@Test public void testGetProviderClasses() throws Exception { Assert.assertNull(RESTEasyUtil.getProviderClasses(null)); Assert.assertNull(RESTEasyUtil.getProviderClasses(contextParams)); Assert.assertNull(RESTEasyUtil.getProviderClasses(contextParamsWithOnlyBadProviders)); List<Class<?>> providerClasses = RESTEasyUtil.getProviderClasses(contextParamsWithProviders); Assert.assertEquals(1, providerClasses.size()); Assert.assertEquals(String.class, providerClasses.get(0)); } |
### Question:
ClassUtil { public static List<Object> generateSingletons(String[] resourceIntfs, InboundHandler handler) throws Exception { List<Object> instances = new ArrayList<Object>(); for (String resourceIntf : resourceIntfs) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Generating instance for " + resourceIntf); } Class<?> clazz = Classes.forName(resourceIntf); Object instance = RESTEasyProxy.newInstance(handler, clazz); instances.add(instance); } return instances; } private ClassUtil(); static List<Object> generateSingletons(String[] resourceIntfs, InboundHandler handler); }### Answer:
@Test public void generateClassInstances() throws Exception { String[] intfs = {"org.switchyard.component.resteasy.util.support.WarehouseResource"}; Object instance = ClassUtil.generateSingletons(intfs, this).get(0); Method method = instance.getClass().getMethod("getItem", Integer.class); Item response = (Item)method.invoke(instance, 1); Item apple = new Item(1, "Apple"); Assert.assertTrue(response.equals(apple)); method = instance.getClass().getMethod("addItem", Item.class); Item orange = new Item(2, "Orange"); Assert.assertEquals("[2:Orange]", method.invoke(instance, orange)); method = instance.getClass().getMethod("updateItem", Item.class); Item grape = new Item(2, "Grape"); Assert.assertEquals("[2:Grape]", method.invoke(instance, grape)); method = instance.getClass().getMethod("removeItem", Integer.class); method = instance.getClass().getMethod("getItemCount"); Assert.assertEquals(0, method.invoke(instance)); method = instance.getClass().getMethod("testVoid"); method.invoke(instance); } |
### Question:
StandaloneResourcePublisher implements ResourcePublisher { static int getPort() { return Integer.getInteger(DEFAULT_PORT_PROPERTY, DEFAULT_PORT); } Endpoint publish(ServiceDomain domain, String context, List<Object> instances, Map<String, String> contextParams); }### Answer:
@Test public void useDefaultPort() { final int port = new NettyJaxrsServer().getPort(); assertThat(port, is(equalTo(ResourcePublisher.DEFAULT_PORT))); }
@Test public void useConfiguredPort() { System.setProperty(ResourcePublisher.DEFAULT_PORT_PROPERTY, Integer.toString(TEST_PORT)); final int port = new NettyJaxrsServer().getPort(); assertThat(port, is(equalTo(TEST_PORT))); } |
### Question:
ServiceInvoker { public static Map<String, Object> deepClone(Map<String, Object> sourceMap) { Map<String, Object> map = new LinkedHashMap<String, Object>(); Set<Map.Entry<String,Object>> mapEntries = sourceMap.entrySet(); for (Map.Entry<String,Object> entry : mapEntries) { map.put(entry.getKey(), deepClone(entry.getValue())); } return map; } ServiceInvoker(ServiceReference serviceReference); Object send(String operationName, RubyHash rubyHash); static Map<String, Object> deepClone(Map<String, Object> sourceMap); }### Answer:
@Test public void test_deepClone() { RubyHash rubyHash = (RubyHash) RubyUtil.evalScriptlet(getClass().getResourceAsStream("/order1.rb")); Map<String,Object> deepClone = ServiceInvoker.deepClone(rubyHash); Map header = (Map) deepClone.get("header"); Assert.assertFalse(header instanceof IRubyObject); Assert.assertEquals(1234L, header.get("orderId")); List items = (List) deepClone.get("items"); Assert.assertFalse(items instanceof IRubyObject); Assert.assertEquals(2, items.size()); } |
### Question:
SimpleTransactionExecutor implements TransactionExecutor { @Override public <T> T executeInTransaction(TransactionCallback<T> callback) { return executeInTransaction(callback, RethrowException.getInstance()); } SimpleTransactionExecutor(GraphDatabaseService database); @Override T executeInTransaction(TransactionCallback<T> callback); @Override T executeInTransaction(TransactionCallback<T> callback, ExceptionHandlingStrategy exceptionHandlingStrategy); }### Answer:
@Test public void nodeShouldBeSuccessfullyCreatedInTransaction() { executor.executeInTransaction(new VoidReturningCallback() { @Override public void doInTx(GraphDatabaseService database) { database.createNode(); } }); try (Transaction tx = database.beginTx()) { assertEquals(2, countNodes(database)); } }
@Test public void nodeShouldBeSuccessfullyDeletedInTransaction() { executor.executeInTransaction(new VoidReturningCallback() { @Override protected void doInTx(GraphDatabaseService database) { database.getNodeById(0).delete(); } }); try (Transaction tx = database.beginTx()) { assertEquals(0, countNodes(database)); } }
@Test(expected = ConstraintViolationException.class) public void deletingNodeWithRelationshipsShouldThrowException() { createNodeAndRelationship(); executor.executeInTransaction(database -> { database.getNodeById(0).delete(); return null; }); }
@Test public void deletingNodeWithRelationshipsShouldNotSucceed() { createNodeAndRelationship(); try (Transaction tx = database.beginTx()) { assertEquals(2, countNodes(database)); } executor.executeInTransaction(db -> { db.getNodeById(0).delete(); return null; }, KeepCalmAndCarryOn.getInstance()); try (Transaction tx = database.beginTx()) { assertEquals(2, countNodes(database)); } } |
### Question:
RelationshipUtils { public static boolean relationshipNotExists(Node node1, Node node2, RelationshipType type, Direction direction) { return !relationshipExists(node1, node2, type, direction); } private RelationshipUtils(); static Relationship getSingleRelationship(Node node1, Node node2, RelationshipType type, Direction direction); static Relationship getSingleRelationshipOrNull(Node node1, Node node2, RelationshipType type, Direction direction); static boolean relationshipNotExists(Node node1, Node node2, RelationshipType type, Direction direction); static boolean relationshipExists(Node node1, Node node2, RelationshipType type, Direction direction); static void deleteRelationshipIfExists(Node node1, Node node2, RelationshipType type, Direction direction); static Relationship createRelationshipIfNotExists(Node node1, Node node2, RelationshipType type, Direction direction); }### Answer:
@Test public void nonExistingRelationshipShouldBeCorrectlyIdentified() { try (Transaction tx = database.beginTx()) { Node node1 = database.getNodeById(0); Node node2 = database.getNodeById(1); assertTrue(relationshipNotExists(node2, node1, withName("TEST"), OUTGOING)); assertTrue(relationshipNotExists(node2, node1, withName("IDONTEXIST"), INCOMING)); assertFalse(relationshipNotExists(node2, node1, withName("TEST"), INCOMING)); assertFalse(relationshipNotExists(node2, node1, withName("TEST"), BOTH)); tx.success(); } } |
### Question:
RelationshipUtils { public static Relationship getSingleRelationship(Node node1, Node node2, RelationshipType type, Direction direction) { Relationship result = getSingleRelationshipOrNull(node1, node2, type, direction); if (result == null) { throw new NotFoundException("Relationship between " + node1 + " and " + node2 + " of type " + type + " and direction " + direction + " does not exist."); } return result; } private RelationshipUtils(); static Relationship getSingleRelationship(Node node1, Node node2, RelationshipType type, Direction direction); static Relationship getSingleRelationshipOrNull(Node node1, Node node2, RelationshipType type, Direction direction); static boolean relationshipNotExists(Node node1, Node node2, RelationshipType type, Direction direction); static boolean relationshipExists(Node node1, Node node2, RelationshipType type, Direction direction); static void deleteRelationshipIfExists(Node node1, Node node2, RelationshipType type, Direction direction); static Relationship createRelationshipIfNotExists(Node node1, Node node2, RelationshipType type, Direction direction); }### Answer:
@Test(expected = NotFoundException.class) public void nonExistingRelationshipShouldBeCorrectlyIdentified2() { try (Transaction tx = database.beginTx()) { Node node1 = database.getNodeById(0); Node node2 = database.getNodeById(1); getSingleRelationship(node2, node1, withName("IDONTEXIST"), INCOMING); tx.success(); } } |
### Question:
RelationshipUtils { public static Relationship createRelationshipIfNotExists(Node node1, Node node2, RelationshipType type, Direction direction) { Relationship existing = getSingleRelationshipOrNull(node1, node2, type, direction); if (existing == null) { if (Direction.INCOMING.equals(direction)) { return node2.createRelationshipTo(node1, type); } return node1.createRelationshipTo(node2, type); } return existing; } private RelationshipUtils(); static Relationship getSingleRelationship(Node node1, Node node2, RelationshipType type, Direction direction); static Relationship getSingleRelationshipOrNull(Node node1, Node node2, RelationshipType type, Direction direction); static boolean relationshipNotExists(Node node1, Node node2, RelationshipType type, Direction direction); static boolean relationshipExists(Node node1, Node node2, RelationshipType type, Direction direction); static void deleteRelationshipIfExists(Node node1, Node node2, RelationshipType type, Direction direction); static Relationship createRelationshipIfNotExists(Node node1, Node node2, RelationshipType type, Direction direction); }### Answer:
@Test public void existingRelationshipShouldNotBeRecreated() { try (Transaction tx = database.beginTx()) { Node node1 = database.getNodeById(0); Node node2 = database.getNodeById(1); Relationship r = createRelationshipIfNotExists(node1, node2, withName("TEST"), OUTGOING); assertEquals(0, r.getId()); assertEquals(1, IterableUtils.count(database.getAllRelationships())); tx.success(); } } |
### Question:
RelationshipUtils { public static void deleteRelationshipIfExists(Node node1, Node node2, RelationshipType type, Direction direction) { Relationship r = getSingleRelationshipOrNull(node1, node2, type, direction); if (r != null) { r.delete(); } } private RelationshipUtils(); static Relationship getSingleRelationship(Node node1, Node node2, RelationshipType type, Direction direction); static Relationship getSingleRelationshipOrNull(Node node1, Node node2, RelationshipType type, Direction direction); static boolean relationshipNotExists(Node node1, Node node2, RelationshipType type, Direction direction); static boolean relationshipExists(Node node1, Node node2, RelationshipType type, Direction direction); static void deleteRelationshipIfExists(Node node1, Node node2, RelationshipType type, Direction direction); static Relationship createRelationshipIfNotExists(Node node1, Node node2, RelationshipType type, Direction direction); }### Answer:
@Test public void existingRelationshipShouldBeDeleted() { try (Transaction tx = database.beginTx()) { Node node1 = database.getNodeById(0); Node node2 = database.getNodeById(1); deleteRelationshipIfExists(node1, node2, withName("TEST"), OUTGOING); assertEquals(0, IterableUtils.count(database.getAllRelationships())); tx.success(); } }
@Test public void nonExistingRelationshipDeletionShouldDoNothing() { try (Transaction tx = database.beginTx()) { Node node1 = database.getNodeById(0); Node node2 = database.getNodeById(1); deleteRelationshipIfExists(node2, node1, withName("TEST"), OUTGOING); assertEquals(1, IterableUtils.count(database.getAllRelationships())); tx.success(); } } |
### Question:
FileScanner { public static List<String> produceLines(File file, int skip) { try { return produceLines(new FileInputStream(file),skip); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } private FileScanner(); static List<String> produceLines(File file, int skip); static List<String> produceLines(InputStream inputStream, int skip); }### Answer:
@Test public void verifyCorrectNumberOfScannedLines() throws IOException { assertEquals(4, FileScanner.produceLines(FileScannerTest.class.getClassLoader().getResourceAsStream("scanner-test.csv"), 0).size()); }
@Test public void verifyCorrectlyScannedLines() throws IOException { List<String> lines = FileScanner.produceLines(FileScannerTest.class.getClassLoader().getResourceAsStream("scanner-test.csv"),1); assertEquals(3, lines.size()); assertEquals("line1;bla", lines.get(0)); assertEquals("line2;bla", lines.get(1)); assertEquals("line3;bla", lines.get(2)); } |
### Question:
Stopwatch { public Event stop(String eventName) { return stopEvent(eventName); } void start(String eventName); Event stop(String eventName); void lap(String eventName); }### Answer:
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenStopButNotStarted() { Stopwatch stopwatch = new Stopwatch(); stopwatch.stop("e"); } |
### Question:
Stopwatch { public void start(String eventName) { startEvent(eventName); } void start(String eventName); Event stop(String eventName); void lap(String eventName); }### Answer:
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenTryingToStartAlreadyStartedEvent() { Stopwatch stopwatch = new Stopwatch(); stopwatch.start("e"); stopwatch.start("e"); } |
### Question:
Period { public Long duration() { return end - start; } Period(Long start, Long end); Long startTime(); Long endTime(); Long duration(); @Override String toString(); }### Answer:
@Test public void shouldReturnDuration() { Long t = System.currentTimeMillis(); Long t2 = t + 1000; Period period = new Period(t, t2); assertEquals(1000, period.duration(), 0L); } |
### Question:
LiteralPropertiesDescription extends BaseDetachedPropertiesDescription { @Override protected Predicate undefined() { return Predicates.undefined(); } LiteralPropertiesDescription(Entity entity); LiteralPropertiesDescription(Map<String, Predicate> predicates); }### Answer:
@Test public void shouldReturnUndefinedForNonExistingKeys() { PropertiesDescription description = literal(); assertEquals(undefined(), description.get("non-existing")); } |
### Question:
LazyPropertiesDescription extends BasePropertiesDescription implements PropertiesDescription { @Override public Iterable<String> getKeys() { return entity.getPropertyKeys(); } LazyPropertiesDescription(Entity entity); @Override Predicate get(String key); @Override Iterable<String> getKeys(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void shouldContainCorrectKeys() { PropertiesDescription description = lazy(); List<String> keys = IterableUtils.toList(description.getKeys()); assertEquals(3, keys.size()); assertTrue(keys.contains("two")); assertTrue(keys.contains("three")); assertTrue(keys.contains("array")); } |
### Question:
LazyPropertiesDescription extends BasePropertiesDescription implements PropertiesDescription { @Override public Predicate get(String key) { Object value = entity.getProperty(key, null); if (value == null) { return undefined(); } return equalTo(value); } LazyPropertiesDescription(Entity entity); @Override Predicate get(String key); @Override Iterable<String> getKeys(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void shouldReturnEqualPredicatesForExistingKeys() { PropertiesDescription description = lazy(); assertEquals(equalTo(2), description.get("two")); assertEquals(equalTo("3"), description.get("three")); assertEquals(equalTo(new int[]{4, 5}), description.get("array")); }
@Test public void shouldReturnUndefinedForNonExistingKeys() { PropertiesDescription description = lazy(); assertEquals(undefined(), description.get("non-existing")); } |
### Question:
WildcardPropertiesDescription extends BaseDetachedPropertiesDescription { @Override public boolean isMoreGeneralThan(PropertiesDescription other) { if (predicates.isEmpty()) { return true; } for (String key : getKeys()) { if (!get(key).isMoreGeneralThan(other.get(key))) { return false; } } return true; } WildcardPropertiesDescription(Entity entity); WildcardPropertiesDescription(Map<String, Predicate> predicates); @Override boolean isMoreGeneralThan(PropertiesDescription other); }### Answer:
@Test public void shouldCorrectlyJudgeMoreGeneral() { assertTrue(wildcard().isMoreGeneralThan(wildcard())); assertTrue(wildcard().isMoreGeneralThan(literal())); assertTrue(wildcard().isMoreGeneralThan(lazy())); assertTrue(wildcard().isMoreGeneralThan(literal("two", equalTo(2), "three", equalTo("3"), "array", equalTo(new int[]{4, 5})))); assertFalse(wildcard().isMoreGeneralThan(literal("two", equalTo(2), "three", equalTo("4"), "array", equalTo(new int[]{4, 5})))); assertTrue(wildcard().with("three", any()).isMoreGeneralThan(literal("two", equalTo(2), "three", equalTo("4"), "array", equalTo(new int[]{4, 5})))); assertFalse(wildcard().isMoreGeneralThan(literal("two", equalTo(2), "three", equalTo("3")))); assertFalse(wildcard().isMoreGeneralThan(wildcard("two", equalTo(2), "three", equalTo("3")))); assertTrue(wildcard().isMoreGeneralThan(literal("two", equalTo(2), "three", equalTo("3"), "array", equalTo(new int[]{4, 5}), "four", equalTo(4)))); } |
### Question:
Undefined extends EqualTo { private Undefined() { super(UndefinedValue.getInstance()); } private Undefined(); static Undefined getInstance(); @Override String toString(); }### Answer:
@Test public void shouldComplainWhenProvidedWithIllegalValues() { try { undefined().evaluate(new Byte[]{}); fail(); } catch (IllegalArgumentException e) { } try { undefined().evaluate(null); fail(); } catch (IllegalArgumentException e) { } try { undefined().evaluate(new HashMap<>()); fail(); } catch (IllegalArgumentException e) { } } |
### Question:
CommunityRuntime implements TransactionEventHandler<Map<String, Object>>, GraphAwareRuntime, KernelEventHandler { @Override public final void waitUntilStarted() { if (!isStarted(null)) { throw new IllegalStateException("It appears that the thread starting the runtime called waitUntilStarted() before it's finished its job. This is a bug"); } } protected CommunityRuntime(RuntimeConfiguration configuration, GraphDatabaseService database, TxDrivenModuleManager<TxDrivenModule> txDrivenModuleManager, TimerDrivenModuleManager timerDrivenModuleManager, Neo4jWriter writer); @Override synchronized void registerModule(RuntimeModule module); @Override final synchronized void start(); @Override final void waitUntilStarted(); @Override Map<String, Object> beforeCommit(TransactionData data); @Override final void afterCommit(TransactionData data, Map<String, Object> states); @Override final void afterRollback(TransactionData data, Map<String, Object> states); @Override void beforeShutdown(); @Override M getModule(String moduleId, Class<M> clazz); @Override M getModule(Class<M> clazz); @Override final void kernelPanic(ErrorState error); @Override final Object getResource(); @Override final ExecutionOrder orderComparedTo(KernelEventHandler other); @Override RuntimeConfiguration getConfiguration(); @Override Neo4jWriter getDatabaseWriter(); }### Answer:
@Test(expected = IllegalStateException.class) public void shouldFailWaitingForRuntimeThatHasNotBeenStarted() { GraphAwareRuntime runtime = createRuntime(database); runtime.waitUntilStarted(); } |
### Question:
DetachedRelationshipDescriptionImpl extends BaseRelationshipDescription<DetachedPropertiesDescription> implements DetachedRelationshipDescription { @Override public String toString() { return getType() + "#" + getDirection() + "#" + getPropertiesDescription().toString(); } DetachedRelationshipDescriptionImpl(String relationshipType, Direction direction, DetachedPropertiesDescription propertiesDescription); @Override DetachedRelationshipDescription with(String propertyKey, Predicate predicate); @Override String toString(); }### Answer:
@Test public void verifySerialization() { try (Transaction tx = database.beginTx()) { RelationshipDescription description = literal(database.getRelationshipById(0), database.getNodeById(0)); String serialized = Serializer.toString(description, "testPrefix"); RelationshipDescription deserialized = Serializer.fromString(serialized, "testPrefix"); assertEquals(deserialized, description); } } |
### Question:
SpelRelationshipInclusionPolicy extends SpelInclusionPolicy implements RelationshipInclusionPolicy { @Override public Iterable<Relationship> getAll(GraphDatabaseService database) { return new FilteringIterable<>(database.getAllRelationships(), this::include); } SpelRelationshipInclusionPolicy(String expression); @Override boolean include(Relationship relationship); @Override boolean include(Relationship relationship, Node pointOfView); @Override Iterable<Relationship> getAll(GraphDatabaseService database); }### Answer:
@Test public void shouldIncludeAllCorrectRels() { try (Transaction tx = database.beginTx()) { assertEquals(1, Iterables.count(policy6.getAll(database))); assertEquals(vojtaWorksFor(), policy6.getAll(database).iterator().next()); tx.success(); } } |
### Question:
SpelNodeInclusionPolicy extends SpelInclusionPolicy implements NodeInclusionPolicy { @Override public boolean include(Node node) { return (Boolean) exp.getValue(new AttachedNode(node)); } SpelNodeInclusionPolicy(String expression); @Override boolean include(Node node); @Override Iterable<Node> getAll(GraphDatabaseService database); }### Answer:
@Test public void shouldIncludeCorrectNodes() { try (Transaction tx = database.beginTx()) { assertTrue(simplePolicy1.include(michal())); assertFalse(simplePolicy1.include(graphaware())); assertFalse(simplePolicy1.include(vojta())); assertFalse(simplePolicy1.include(london())); assertFalse(simplePolicy2.include(michal())); assertTrue(simplePolicy2.include(graphaware())); assertTrue(simplePolicy2.include(vojta())); assertTrue(simplePolicy2.include(london())); assertTrue(policy1.include(michal())); assertTrue(policy1.include(graphaware())); assertTrue(policy1.include(vojta())); assertFalse(policy1.include(london())); assertTrue(policy2.include(michal())); assertFalse(policy2.include(graphaware())); assertTrue(policy2.include(vojta())); assertFalse(policy2.include(london())); assertFalse(policy3.include(michal())); assertTrue(policy3.include(graphaware())); assertFalse(policy3.include(vojta())); assertFalse(policy3.include(london())); assertFalse(policy4.include(michal())); assertTrue(policy4.include(graphaware())); assertFalse(policy4.include(vojta())); assertFalse(policy4.include(london())); assertFalse(policy5.include(michal())); assertFalse(policy5.include(graphaware())); assertFalse(policy5.include(vojta())); assertFalse(policy5.include(london())); tx.success(); } } |
### Question:
SpelNodeInclusionPolicy extends SpelInclusionPolicy implements NodeInclusionPolicy { @Override public Iterable<Node> getAll(GraphDatabaseService database) { if(expressionNode.toStringAST().startsWith("hasLabel")) { String labelName = stripWrappingQuotes(expressionNode.getChild(0).toStringAST()); return () -> database.findNodes(Label.label(labelName)); } return new FilteringIterable<>(database.getAllNodes(), this::include); } SpelNodeInclusionPolicy(String expression); @Override boolean include(Node node); @Override Iterable<Node> getAll(GraphDatabaseService database); }### Answer:
@Test public void shouldCorrectlyGetAllNodes() { try (Transaction tx = database.beginTx()) { assertEquals(1, Iterables.count(simplePolicy1.getAll(database))); assertEquals(michal(), simplePolicy1.getAll(database).iterator().next()); assertEquals(3, Iterables.count(simplePolicy2.getAll(database))); assertEquals(3, Iterables.count(policy1.getAll(database))); assertEquals(2, Iterables.count(policy2.getAll(database))); assertEquals(1, Iterables.count(policy3.getAll(database))); assertEquals(graphaware(), policy3.getAll(database).iterator().next()); assertEquals(1, Iterables.count(policy4.getAll(database))); assertEquals(graphaware(), policy4.getAll(database).iterator().next()); assertEquals(0, Iterables.count(policy5.getAll(database))); assertEquals(2, Iterables.count(policy6.getAll(database))); assertEquals(2, Iterables.count(policy7.getAll(database))); tx.success(); } } |
### Question:
SpelRelationshipPropertyInclusionPolicy extends SpelInclusionPolicy implements RelationshipPropertyInclusionPolicy { @Override public boolean include(String key, Relationship relationship) { return (Boolean) exp.getValue(new AttachedRelationshipProperty(key, new AttachedRelationship(relationship))); } SpelRelationshipPropertyInclusionPolicy(String expression); @Override boolean include(String key, Relationship relationship); }### Answer:
@Test public void shouldIncludeCorrectProps() { RelationshipPropertyInclusionPolicy policy1 = new SpelRelationshipPropertyInclusionPolicy("key != 'since'"); RelationshipPropertyInclusionPolicy policy2 = new SpelRelationshipPropertyInclusionPolicy("relationship.isType('WORKS_FOR')"); try (Transaction tx = database.beginTx()) { assertFalse(policy1.include("since", vojtaWorksFor())); assertFalse(policy1.include("since", michalWorksFor())); assertTrue(policy1.include("until", michalWorksFor())); assertTrue(policy1.include("until", vojtaWorksFor())); assertTrue(policy2.include("since", michalWorksFor())); assertFalse(policy2.include("since", michalLivesIn())); assertTrue(policy2.include("since", vojtaWorksFor())); assertFalse(policy2.include("since", vojtaLivesIn())); tx.success(); } } |
### Question:
SpelNodePropertyInclusionPolicy extends SpelInclusionPolicy implements NodePropertyInclusionPolicy { @Override public boolean include(String key, Node node) { return (Boolean) exp.getValue(new AttachedNodeProperty(key, new AttachedNode(node))); } SpelNodePropertyInclusionPolicy(String expression); @Override boolean include(String key, Node node); }### Answer:
@Test public void shouldIncludeCorrectProps() { NodePropertyInclusionPolicy policy1 = new SpelNodePropertyInclusionPolicy("key != 'name'"); NodePropertyInclusionPolicy policy2 = new SpelNodePropertyInclusionPolicy("node.hasLabel('Employee') && key == 'name'"); try (Transaction tx = database.beginTx()) { assertFalse(policy1.include("name", michal())); assertFalse(policy1.include("name", vojta())); assertTrue(policy2.include("name", michal())); assertFalse(policy2.include("name", vojta())); assertFalse(policy2.include("name", graphaware())); tx.success(); } } |
### Question:
IncludeAllNodes extends BaseNodeInclusionPolicy { public static NodeInclusionPolicy getInstance() { return INSTANCE; } private IncludeAllNodes(); static NodeInclusionPolicy getInstance(); @Override boolean include(Node object); }### Answer:
@Test public void shouldGetAllNodes() { try (Transaction tx = database.beginTx()) { assertEquals(4, IterableUtils.count(IncludeAllNodes.getInstance().getAll(database))); tx.success(); } } |
### Question:
IncludeAllRelationships extends RelationshipInclusionPolicy.Adapter { public static RelationshipInclusionPolicy getInstance() { return INSTANCE; } private IncludeAllRelationships(); static RelationshipInclusionPolicy getInstance(); @Override boolean include(Relationship object); }### Answer:
@Test public void shouldGetAllRels() { try (Transaction tx = database.beginTx()) { assertEquals(4, IterableUtils.count(IncludeAllRelationships.getInstance().getAll(database))); tx.success(); } } |
### Question:
CompositePropertyInclusionPolicy implements PropertyInclusionPolicy<T> { @Override public boolean include(String key, T object) { for (PropertyInclusionPolicy<T> policy : policies) { if (!policy.include(key, object)) { return false; } } return true; } protected CompositePropertyInclusionPolicy(PropertyInclusionPolicy<T>[] policies); @Override boolean include(String key, T object); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void whenAllVoteYesThenTrueIsReturned() { assertTrue(CompositeNodePropertyInclusionPolicy.of(IncludeAllNodeProperties.getInstance(), IncludeAllNodeProperties.getInstance()).include("test", null)); assertTrue(CompositeRelationshipPropertyInclusionPolicy.of(IncludeAllRelationshipProperties.getInstance(), IncludeAllRelationshipProperties.getInstance()).include("test", null)); }
@Test public void whenOneVotesNoThenFalseIsReturned() { assertFalse(CompositeNodePropertyInclusionPolicy.of(IncludeNoNodeProperties.getInstance(), IncludeAllNodeProperties.getInstance()).include("test", null)); assertFalse(CompositeRelationshipPropertyInclusionPolicy.of(IncludeAllRelationshipProperties.getInstance(), IncludeNoRelationshipProperties.getInstance()).include("test", null)); } |
### Question:
CompositeEntityInclusionPolicy extends BaseEntityInclusionPolicy<E> implements EntityInclusionPolicy<E> { @Override public boolean include(E object) { for (T policy : policies) { if (!policy.include(object)) { return false; } } return true; } protected CompositeEntityInclusionPolicy(T[] policies); @Override boolean include(E object); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void whenAllVoteYesThenTrueIsReturned() { assertTrue(CompositeNodeInclusionPolicy.of(IncludeAllNodes.getInstance(), IncludeAllNodes.getInstance()).include(null)); assertTrue(CompositeRelationshipInclusionPolicy.of(IncludeAllRelationships.getInstance(), IncludeAllRelationships.getInstance()).include(null)); }
@Test public void whenOneVotesNoThenFalseIsReturned() { assertFalse(CompositeNodeInclusionPolicy.of(IncludeNoNodes.getInstance(), IncludeAllNodes.getInstance()).include(null)); assertFalse(CompositeRelationshipInclusionPolicy.of(IncludeAllRelationships.getInstance(), IncludeNoRelationships.getInstance()).include(null)); } |
### Question:
IncludeNoRelationships extends IncludeNoEntities<Relationship> implements RelationshipInclusionPolicy { public static RelationshipInclusionPolicy getInstance() { return INSTANCE; } private IncludeNoRelationships(); static RelationshipInclusionPolicy getInstance(); @Override boolean include(Relationship relationship, Node pointOfView); }### Answer:
@Test public void shouldGetNoRels() { try (Transaction tx = database.beginTx()) { assertEquals(0, IterableUtils.count(IncludeNoRelationships.getInstance().getAll(database))); tx.success(); } } |
### Question:
IncludeNoNodes extends IncludeNoEntities<Node> implements NodeInclusionPolicy { public static NodeInclusionPolicy getInstance() { return INSTANCE; } private IncludeNoNodes(); static NodeInclusionPolicy getInstance(); }### Answer:
@Test public void shouldIncludeNoNodes() { try (Transaction tx = database.beginTx()) { for (Node node : database.getAllNodes()) { assertFalse(IncludeNoNodes.getInstance().include(node)); } tx.success(); } }
@Test public void shouldGetNoNodes() { try (Transaction tx = database.beginTx()) { assertEquals(0, IterableUtils.count(IncludeNoNodes.getInstance().getAll(database))); tx.success(); } } |
### Question:
CommunityRuntime implements TransactionEventHandler<Map<String, Object>>, GraphAwareRuntime, KernelEventHandler { @Override public <M extends RuntimeModule> M getModule(String moduleId, Class<M> clazz) throws NotFoundException { M module = txDrivenModuleManager.getModule(moduleId, clazz); if (module != null) { return module; } module = timerDrivenModuleManager.getModule(moduleId, clazz); if (module != null) { return module; } throw new NotFoundException("No module of type " + clazz.getName() + " with ID " + moduleId + " has been registered"); } protected CommunityRuntime(RuntimeConfiguration configuration, GraphDatabaseService database, TxDrivenModuleManager<TxDrivenModule> txDrivenModuleManager, TimerDrivenModuleManager timerDrivenModuleManager, Neo4jWriter writer); @Override synchronized void registerModule(RuntimeModule module); @Override final synchronized void start(); @Override final void waitUntilStarted(); @Override Map<String, Object> beforeCommit(TransactionData data); @Override final void afterCommit(TransactionData data, Map<String, Object> states); @Override final void afterRollback(TransactionData data, Map<String, Object> states); @Override void beforeShutdown(); @Override M getModule(String moduleId, Class<M> clazz); @Override M getModule(Class<M> clazz); @Override final void kernelPanic(ErrorState error); @Override final Object getResource(); @Override final ExecutionOrder orderComparedTo(KernelEventHandler other); @Override RuntimeConfiguration getConfiguration(); @Override Neo4jWriter getDatabaseWriter(); }### Answer:
@Test(expected = NotFoundException.class) public void shouldThrowExceptionWhenAskedForNonExistingModule() { GraphAwareRuntime runtime = createRuntime(database, defaultConfiguration(database).withTimingStrategy(TIMING_STRATEGY)); runtime.getModule("non-existing", TxAndTimerDrivenModule.class); } |
### Question:
DefaultWriter extends BaseNeo4jWriter { @Override public <T> T write(Callable<T> task, String id, int waitMillis) { T result; try (Transaction tx = database.beginTx()) { result = task.call(); tx.success(); } catch (Exception e) { LOG.warn("Execution threw and exception.", e); if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new RuntimeException(e); } return result; } DefaultWriter(GraphDatabaseService database); @Override T write(Callable<T> task, String id, int waitMillis); }### Answer:
@Test public void shouldExecuteRunnable() { writer.write(new Runnable() { @Override public void run() { getDatabase().createNode(); } }); try (Transaction tx = getDatabase().beginTx()) { assertEquals(1, IterableUtils.countNodes(getDatabase())); tx.success(); } }
@Test public void shouldWaitForResult() { Boolean result = writer.write(new Callable<Boolean>() { @Override public Boolean call() throws Exception { getDatabase().createNode(); return true; } }, "test", 50); assertTrue(result); try (Transaction tx = getDatabase().beginTx()) { assertEquals(1, IterableUtils.countNodes(getDatabase())); tx.success(); } }
@Test(expected = RuntimeException.class) public void runtimeExceptionFromTaskGetsPropagated() { writer.write(new Callable<Boolean>() { @Override public Boolean call() throws Exception { throw new RuntimeException("Deliberate Testing Exception"); } }, "test", 50); }
@Test(expected = RuntimeException.class) public void checkedExceptionFromTaskGetsTranslated() { writer.write(new Callable<Boolean>() { @Override public Boolean call() throws Exception { throw new IOException("Deliberate Testing Exception"); } }, "test", 10); } |
### Question:
StartedTxBasedLoadMonitor implements DatabaseLoadMonitor { @Override public long getLoad() { runningWindowAverage.sample(System.currentTimeMillis(), txCounters.getNumberOfStartedTransactions()); return runningWindowAverage.getAverage(); } StartedTxBasedLoadMonitor(GraphDatabaseService database, RunningWindowAverage runningWindowAverage); @Override long getLoad(); }### Answer:
@Test public void readTransactionsShouldBeMonitored() throws InterruptedException { assertEquals(TimingStrategy.UNKNOWN, loadMonitor.getLoad()); for (int i = 0; i < 10; i++) { try (Transaction tx = database.beginTx()) { tx.success(); } Thread.sleep(1); assertTrue(loadMonitor.getLoad() > 0); } assertTrue(loadMonitor.getLoad() > 0); } |
### Question:
BoundedSortedList { public List<T> getItems() { List<T> result = new LinkedList<>(); lock.readLock().lock(); try { for (ComparableItem<T, C> comparableItem : items) { result.add(comparableItem.getItem()); if (result.size() >= capacity) { break; } } return result; } finally { lock.readLock().unlock(); } } BoundedSortedList(int capacity); BoundedSortedList(int capacity, final Comparator<C> comparator); BoundedSortedList(int capacity, int maxCapacity); BoundedSortedList(int capacity, int maxCapacity, final Comparator<C> comparator); List<T> getItems(); void add(T item, C quantity); }### Answer:
@Test public void emptyListShouldProduceEmptyList() { BoundedSortedList<String, Integer> list = new BoundedSortedList<>(10); assertTrue(list.getItems().isEmpty()); } |
### Question:
Change { @SuppressWarnings("RedundantIfStatement") @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Change change = (Change) o; if (!current.equals(change.current)) return false; if (!previous.equals(change.previous)) return false; return true; } Change(T previous, T current); T getPrevious(); T getCurrent(); @SuppressWarnings("RedundantIfStatement") @Override boolean equals(Object o); @Override int hashCode(); static Map<Long, Change<T>> changesToMap(Collection<Change<T>> changes); }### Answer:
@Test public void equalChangesShouldBeEqual() { try (Transaction tx = database.beginTx()) { Change<Node> nodeChange1 = new Change<>(database.getNodeById(0), database.getNodeById(0)); Change<Node> nodeChange2 = new Change<>(database.getNodeById(0), database.getNodeById(0)); Change<Node> nodeChange3 = new Change<>(database.getNodeById(1), database.getNodeById(1)); assertTrue(nodeChange1.equals(nodeChange2)); assertTrue(nodeChange2.equals(nodeChange1)); assertFalse(nodeChange3.equals(nodeChange1)); assertFalse(nodeChange1.equals(nodeChange3)); } } |
### Question:
Change { public static <T extends Entity> Map<Long, Change<T>> changesToMap(Collection<Change<T>> changes) { Map<Long, Change<T>> result = new HashMap<>(); for (Change<T> change : changes) { long id = change.getPrevious().getId(); if (id != change.getCurrent().getId()) { throw new IllegalArgumentException("IDs of the Entities in Change do not match!"); } result.put(id, change); } return result; } Change(T previous, T current); T getPrevious(); T getCurrent(); @SuppressWarnings("RedundantIfStatement") @Override boolean equals(Object o); @Override int hashCode(); static Map<Long, Change<T>> changesToMap(Collection<Change<T>> changes); }### Answer:
@Test(expected = IllegalArgumentException.class) public void invalidChangeShouldThrowException() { try (Transaction tx = database.beginTx()) { Change<Node> nodeChange1 = new Change<>(database.getNodeById(0), database.getNodeById(1)); changesToMap(Collections.singleton(nodeChange1)); } } |
### Question:
IterableUtils { public static long countNodes(GraphDatabaseService database) { return count(database.getAllNodes()); } private IterableUtils(); static long countNodes(GraphDatabaseService database); static long count(Iterable iterable); static boolean contains(Iterable<T> iterable, T object); static List<T> toList(Iterable<T> iterable); static T random(Iterable<T> iterable); static Iterable<T> random(Iterable<T> iterable, int numberOfSamples); static T getSingle(Iterator<T> iterator, String notFoundMessage); static T getSingle(Iterable<T> iterable, String notFoundMessage); static T getSingle(Iterator<T> iterator); static T getSingle(Iterable<T> iterable); static T getSingleOrNull(Iterator<T> iterator); static T getSingleOrNull(Iterable<T> iterable); static T getFirst(Iterator<T> iterator, String notFoundMessage); static T getFirst(Iterable<T> iterable, String notFoundMessage); static T getFirstOrNull(Iterator<T> iterator); static T getFirstOrNull(Iterable<T> iterable); }### Answer:
@Test public void newDatabaseShouldHaveNoNodes() { try (Transaction tx = database.beginTx()) { assertEquals(0, countNodes(database)); } }
@Test public void afterCreatingANodeDatabaseShouldHaveOneNode() { try (Transaction tx = database.beginTx()) { database.createNode(); tx.success(); } try (Transaction tx = database.beginTx()) { assertEquals(1, countNodes(database)); } } |
### Question:
IterableUtils { public static long count(Iterable iterable) { if (iterable instanceof Collection) { return ((Collection) iterable).size(); } return Iterables.count(iterable); } private IterableUtils(); static long countNodes(GraphDatabaseService database); static long count(Iterable iterable); static boolean contains(Iterable<T> iterable, T object); static List<T> toList(Iterable<T> iterable); static T random(Iterable<T> iterable); static Iterable<T> random(Iterable<T> iterable, int numberOfSamples); static T getSingle(Iterator<T> iterator, String notFoundMessage); static T getSingle(Iterable<T> iterable, String notFoundMessage); static T getSingle(Iterator<T> iterator); static T getSingle(Iterable<T> iterable); static T getSingleOrNull(Iterator<T> iterator); static T getSingleOrNull(Iterable<T> iterable); static T getFirst(Iterator<T> iterator, String notFoundMessage); static T getFirst(Iterable<T> iterable, String notFoundMessage); static T getFirstOrNull(Iterator<T> iterator); static T getFirstOrNull(Iterable<T> iterable); }### Answer:
@Test public void listWithOneItemShouldHaveOneItem() { assertEquals(1, count(asList("test"))); } |
### Question:
IterableUtils { public static <T> boolean contains(Iterable<T> iterable, T object) { if (iterable instanceof Collection) { return ((Collection) iterable).contains(object); } for (T t : iterable) { if (t.equals(object)) { return true; } } return false; } private IterableUtils(); static long countNodes(GraphDatabaseService database); static long count(Iterable iterable); static boolean contains(Iterable<T> iterable, T object); static List<T> toList(Iterable<T> iterable); static T random(Iterable<T> iterable); static Iterable<T> random(Iterable<T> iterable, int numberOfSamples); static T getSingle(Iterator<T> iterator, String notFoundMessage); static T getSingle(Iterable<T> iterable, String notFoundMessage); static T getSingle(Iterator<T> iterator); static T getSingle(Iterable<T> iterable); static T getSingleOrNull(Iterator<T> iterator); static T getSingleOrNull(Iterable<T> iterable); static T getFirst(Iterator<T> iterator, String notFoundMessage); static T getFirst(Iterable<T> iterable, String notFoundMessage); static T getFirstOrNull(Iterator<T> iterator); static T getFirstOrNull(Iterable<T> iterable); }### Answer:
@Test public void checkContainsCollections() { assertTrue(contains(asList("a", "b"), "b")); assertFalse(contains(asList("a", "b"), "c")); }
@Test public void checkContainsRealIterables() { Node node; try (Transaction tx = database.beginTx()) { node = database.createNode(); tx.success(); } try (Transaction tx = database.beginTx()) { assertTrue(contains(database.getAllNodes(), node)); } try (Transaction tx = database.beginTx()) { database.getNodeById(0).delete(); tx.success(); } try (Transaction tx = database.beginTx()) { assertFalse(contains(database.getAllNodes(), node)); } } |
### Question:
DisposableBatchTransactionExecutor implements BatchTransactionExecutor { @Override public final void execute() { if (alreadyExecuted.compareAndSet(false, true)) { doExecute(); } else { throw new IllegalStateException("DisposableBatchExecutor must only ever be executed once!"); } } @Override final void execute(); }### Answer:
@Test public void shouldExecuteForTheFirstTime() { DummyDisposableBatchTransactionExecutor executor = new DummyDisposableBatchTransactionExecutor(); executor.execute(); assertEquals(1, executor.getNoTimesExecuted()); }
@Test public void shouldNotExecuteMoreThanOnce() { DummyDisposableBatchTransactionExecutor executor = new DummyDisposableBatchTransactionExecutor(); executor.execute(); try { executor.execute(); fail(); } catch (IllegalStateException e) { } assertEquals(1, executor.getNoTimesExecuted()); } |
### Question:
IterableUtils { public static <T> T getSingleOrNull(Iterator<T> iterator) { T result = null; if (iterator.hasNext()) { result = iterator.next(); } if (iterator.hasNext()) { throw new IllegalStateException("Iterable has more than one element, which is unexpected"); } return result; } private IterableUtils(); static long countNodes(GraphDatabaseService database); static long count(Iterable iterable); static boolean contains(Iterable<T> iterable, T object); static List<T> toList(Iterable<T> iterable); static T random(Iterable<T> iterable); static Iterable<T> random(Iterable<T> iterable, int numberOfSamples); static T getSingle(Iterator<T> iterator, String notFoundMessage); static T getSingle(Iterable<T> iterable, String notFoundMessage); static T getSingle(Iterator<T> iterator); static T getSingle(Iterable<T> iterable); static T getSingleOrNull(Iterator<T> iterator); static T getSingleOrNull(Iterable<T> iterable); static T getFirst(Iterator<T> iterator, String notFoundMessage); static T getFirst(Iterable<T> iterable, String notFoundMessage); static T getFirstOrNull(Iterator<T> iterator); static T getFirstOrNull(Iterable<T> iterable); }### Answer:
@Test public void singleElementShouldBeReturnedWhenIterableHasOneElement() { assertEquals("test", getSingleOrNull(Collections.singletonList("test"))); }
@Test public void nullShouldBeReturnedWhenIterableHasNoElements() { assertNull(getSingleOrNull(Collections.emptyList())); }
@Test(expected = IllegalStateException.class) public void exceptionShouldBeThrownWhenIterableHasMoreThanOneElement() { getSingleOrNull(Arrays.asList("test1", "test2")); } |
### Question:
IterableUtils { public static <T> T getSingle(Iterator<T> iterator, String notFoundMessage) { T result = getSingleOrNull(iterator); if (result == null) { throw new NotFoundException(notFoundMessage); } return result; } private IterableUtils(); static long countNodes(GraphDatabaseService database); static long count(Iterable iterable); static boolean contains(Iterable<T> iterable, T object); static List<T> toList(Iterable<T> iterable); static T random(Iterable<T> iterable); static Iterable<T> random(Iterable<T> iterable, int numberOfSamples); static T getSingle(Iterator<T> iterator, String notFoundMessage); static T getSingle(Iterable<T> iterable, String notFoundMessage); static T getSingle(Iterator<T> iterator); static T getSingle(Iterable<T> iterable); static T getSingleOrNull(Iterator<T> iterator); static T getSingleOrNull(Iterable<T> iterable); static T getFirst(Iterator<T> iterator, String notFoundMessage); static T getFirst(Iterable<T> iterable, String notFoundMessage); static T getFirstOrNull(Iterator<T> iterator); static T getFirstOrNull(Iterable<T> iterable); }### Answer:
@Test public void singleElementShouldBeReturnedWhenIterableHasOneElement2() { assertEquals("test", getSingle(Collections.singletonList("test"))); }
@Test(expected = NotFoundException.class) public void exceptionShouldBeThrownWhenIterableHasNoElements() { getSingle(Collections.emptyList()); }
@Test public void exceptionShouldBeThrownWhenIterableHasNoElements2() { try { getSingle(Collections.emptyList(), "test"); } catch (NotFoundException e) { assertEquals("test", e.getMessage()); } }
@Test(expected = IllegalStateException.class) public void exceptionShouldBeThrownWhenIterableHasMoreThanOneElement2() { getSingle(Arrays.asList("test1", "test2")); } |
### Question:
IterableUtils { public static <T> T getFirstOrNull(Iterator<T> iterator) { T result = null; if (iterator.hasNext()) { result = iterator.next(); } return result; } private IterableUtils(); static long countNodes(GraphDatabaseService database); static long count(Iterable iterable); static boolean contains(Iterable<T> iterable, T object); static List<T> toList(Iterable<T> iterable); static T random(Iterable<T> iterable); static Iterable<T> random(Iterable<T> iterable, int numberOfSamples); static T getSingle(Iterator<T> iterator, String notFoundMessage); static T getSingle(Iterable<T> iterable, String notFoundMessage); static T getSingle(Iterator<T> iterator); static T getSingle(Iterable<T> iterable); static T getSingleOrNull(Iterator<T> iterator); static T getSingleOrNull(Iterable<T> iterable); static T getFirst(Iterator<T> iterator, String notFoundMessage); static T getFirst(Iterable<T> iterable, String notFoundMessage); static T getFirstOrNull(Iterator<T> iterator); static T getFirstOrNull(Iterable<T> iterable); }### Answer:
@Test public void firstElementShouldBeReturnedWhenIterableHasOneElement() { assertEquals("test", getFirstOrNull(Collections.singletonList("test"))); }
@Test public void nullShouldBeReturnedWhenIterableHasNoElementsWhenRequestingFirst() { assertNull(getFirstOrNull(Collections.emptyList())); }
@Test public void shouldReturnFirstWhenThereIsMoreThanOne() { assertEquals("test1", getFirstOrNull(Arrays.asList("test1", "test2"))); } |
### Question:
IterableUtils { public static <T> T getFirst(Iterator<T> iterator, String notFoundMessage) { T result = null; if (iterator.hasNext()) { result = iterator.next(); } if (result == null) { throw new NotFoundException(notFoundMessage); } return result; } private IterableUtils(); static long countNodes(GraphDatabaseService database); static long count(Iterable iterable); static boolean contains(Iterable<T> iterable, T object); static List<T> toList(Iterable<T> iterable); static T random(Iterable<T> iterable); static Iterable<T> random(Iterable<T> iterable, int numberOfSamples); static T getSingle(Iterator<T> iterator, String notFoundMessage); static T getSingle(Iterable<T> iterable, String notFoundMessage); static T getSingle(Iterator<T> iterator); static T getSingle(Iterable<T> iterable); static T getSingleOrNull(Iterator<T> iterator); static T getSingleOrNull(Iterable<T> iterable); static T getFirst(Iterator<T> iterator, String notFoundMessage); static T getFirst(Iterable<T> iterable, String notFoundMessage); static T getFirstOrNull(Iterator<T> iterator); static T getFirstOrNull(Iterable<T> iterable); }### Answer:
@Test public void firstElementShouldBeReturnedWhenIterableHasOneElement2() { assertEquals("test", getFirst(Collections.singletonList("test"), "test")); }
@Test(expected = NotFoundException.class) public void exceptionShouldBeThrownWhenIterableHasNoElementsWhenRequestingFirst() { getFirst(Collections.emptyList(), "test"); }
@Test public void exceptionShouldBeThrownWhenIterableHasNoElements2WhenRequestingFirst() { try { getFirst(Collections.emptyList(), "test"); } catch (NotFoundException e) { assertEquals("test", e.getMessage()); } }
@Test public void exceptionShouldBeThrownWhenIterableHasMoreThanOneElement2WhenRequestingFirst() { assertEquals("test1", getFirst(Arrays.asList("test1", "test2"), "test")); } |
### Question:
EntityUtils { public static <T extends Entity> Map<Long, T> entitiesToMap(Collection<T> entities) { Map<Long, T> result = new HashMap<>(); for (T entity : entities) { result.put(entity.getId(), entity); } return result; } private EntityUtils(); static Map<Long, T> entitiesToMap(Collection<T> entities); static Long[] ids(Iterable<? extends Entity> entities); static String valueToString(Object value); static Map<String, Object> propertiesToMap(Entity Entity); static Map<String, Object> propertiesToMap(Entity Entity, ObjectInclusionPolicy<String> propertyInclusionPolicy); static int deleteNodeAndRelationships(Node toDelete); static String nodeToString(Node node); static String relationshipToString(Relationship relationship); static String propertiesToString(Entity Entity); static int getInt(Entity Entity, String key); static int getInt(Entity Entity, String key, int defaultValue); static long getLong(Entity Entity, String key); static long getLong(Entity Entity, String key, long defaultValue); static float getFloat(Entity Entity, String key); static float getFloat(Entity Entity, String key, float defaultValue); }### Answer:
@Test public void shouldConvertEntitiesToMap() { try (Transaction tx = database.beginTx()) { Map<Long, Node> nodeMap = entitiesToMap(Iterables.asList(database.getAllNodes())); assertEquals(0, nodeMap.get(0L).getId()); assertEquals(1, nodeMap.get(1L).getId()); assertEquals(2, nodeMap.get(2L).getId()); assertEquals(3, nodeMap.size()); } } |
### Question:
EntityUtils { public static Long[] ids(Iterable<? extends Entity> entities) { List<Long> result = new LinkedList<>(); for (Entity entity : entities) { result.add(entity.getId()); } return result.toArray(new Long[result.size()]); } private EntityUtils(); static Map<Long, T> entitiesToMap(Collection<T> entities); static Long[] ids(Iterable<? extends Entity> entities); static String valueToString(Object value); static Map<String, Object> propertiesToMap(Entity Entity); static Map<String, Object> propertiesToMap(Entity Entity, ObjectInclusionPolicy<String> propertyInclusionPolicy); static int deleteNodeAndRelationships(Node toDelete); static String nodeToString(Node node); static String relationshipToString(Relationship relationship); static String propertiesToString(Entity Entity); static int getInt(Entity Entity, String key); static int getInt(Entity Entity, String key, int defaultValue); static long getLong(Entity Entity, String key); static long getLong(Entity Entity, String key, long defaultValue); static float getFloat(Entity Entity, String key); static float getFloat(Entity Entity, String key, float defaultValue); }### Answer:
@Test public void shouldFindNodeIds() { try (Transaction tx = database.beginTx()) { assertEquals("[0, 1, 2]", Arrays.toString(ids(database.getAllNodes()))); } }
@Test public void shouldFindRelationshipIds() { try (Transaction tx = database.beginTx()) { assertEquals("[0]", Arrays.toString((ids(database.getAllRelationships())))); } } |
### Question:
RotatingTaskScheduler implements TaskScheduler { protected boolean hasCorrectRole(TimerDrivenModule<?> module) { return true; } RotatingTaskScheduler(GraphDatabaseService database, ModuleMetadataRepository repository, TimingStrategy timingStrategy); @Override void registerModuleAndContext(T module, C context); @Override void start(); @Override void stop(); }### Answer:
@Test public void shouldIgnoreRole() { assertTrue(rotatingTaskScheduler.hasCorrectRole(MockTimerModuleContext.buildModule(MasterOnly.getInstance()))); assertTrue(rotatingTaskScheduler.hasCorrectRole(MockTimerModuleContext.buildModule(SlavesOnly.getInstance()))); assertTrue(rotatingTaskScheduler.hasCorrectRole(MockTimerModuleContext.buildModule(AnyRole.getInstance()))); assertTrue(rotatingTaskScheduler.hasCorrectRole(MockTimerModuleContext.buildModule(WritableRole.getInstance()))); } |
### Question:
EntityUtils { public static String valueToString(Object value) { if (value == null) { return ""; } if (isPrimitiveOrStringArray(value)) { return primitiveOrStringArrayToString(value); } return String.valueOf(value); } private EntityUtils(); static Map<Long, T> entitiesToMap(Collection<T> entities); static Long[] ids(Iterable<? extends Entity> entities); static String valueToString(Object value); static Map<String, Object> propertiesToMap(Entity Entity); static Map<String, Object> propertiesToMap(Entity Entity, ObjectInclusionPolicy<String> propertyInclusionPolicy); static int deleteNodeAndRelationships(Node toDelete); static String nodeToString(Node node); static String relationshipToString(Relationship relationship); static String propertiesToString(Entity Entity); static int getInt(Entity Entity, String key); static int getInt(Entity Entity, String key, int defaultValue); static long getLong(Entity Entity, String key); static long getLong(Entity Entity, String key, long defaultValue); static float getFloat(Entity Entity, String key); static float getFloat(Entity Entity, String key, float defaultValue); }### Answer:
@Test public void verifyValueToString() { assertEquals("", valueToString(null)); assertEquals("", valueToString("")); assertEquals("T", valueToString("T")); assertEquals("1", valueToString(1)); assertEquals("1", valueToString(1L)); assertEquals("[one, two]", valueToString(new String[]{"one", "two"})); assertEquals("[1, 2]", valueToString(new int[]{1, 2})); } |
### Question:
EntityUtils { public static Map<String, Object> propertiesToMap(Entity Entity) { return propertiesToMap(Entity, new IncludeAll<String>()); } private EntityUtils(); static Map<Long, T> entitiesToMap(Collection<T> entities); static Long[] ids(Iterable<? extends Entity> entities); static String valueToString(Object value); static Map<String, Object> propertiesToMap(Entity Entity); static Map<String, Object> propertiesToMap(Entity Entity, ObjectInclusionPolicy<String> propertyInclusionPolicy); static int deleteNodeAndRelationships(Node toDelete); static String nodeToString(Node node); static String relationshipToString(Relationship relationship); static String propertiesToString(Entity Entity); static int getInt(Entity Entity, String key); static int getInt(Entity Entity, String key, int defaultValue); static long getLong(Entity Entity, String key); static long getLong(Entity Entity, String key, long defaultValue); static float getFloat(Entity Entity, String key); static float getFloat(Entity Entity, String key, float defaultValue); }### Answer:
@Test public void verifyPropertiesToMap() { try (Transaction tx = database.beginTx()) { assertEquals(Collections.<String, Object>emptyMap(), propertiesToMap(database.getNodeById(1).getSingleRelationship(withName("test"), OUTGOING))); assertEquals(Collections.singletonMap("key", (Object) "value"), propertiesToMap(database.getNodeById(2))); assertEquals(Collections.<String, Object>emptyMap(), propertiesToMap(database.getNodeById(2), new ObjectInclusionPolicy<String>() { @Override public boolean include(String object) { return !"key".equals(object); } })); } } |
### Question:
EntityUtils { public static int deleteNodeAndRelationships(Node toDelete) { int result = 0; for (Relationship relationship : toDelete.getRelationships()) { relationship.delete(); result++; } toDelete.delete(); return result; } private EntityUtils(); static Map<Long, T> entitiesToMap(Collection<T> entities); static Long[] ids(Iterable<? extends Entity> entities); static String valueToString(Object value); static Map<String, Object> propertiesToMap(Entity Entity); static Map<String, Object> propertiesToMap(Entity Entity, ObjectInclusionPolicy<String> propertyInclusionPolicy); static int deleteNodeAndRelationships(Node toDelete); static String nodeToString(Node node); static String relationshipToString(Relationship relationship); static String propertiesToString(Entity Entity); static int getInt(Entity Entity, String key); static int getInt(Entity Entity, String key, int defaultValue); static long getLong(Entity Entity, String key); static long getLong(Entity Entity, String key, long defaultValue); static float getFloat(Entity Entity, String key); static float getFloat(Entity Entity, String key, float defaultValue); }### Answer:
@Test public void shouldDeleteNodeWithAllRelationships() { database.shutdown(); database = new TestGraphDatabaseFactory().newImpermanentDatabase(); registerShutdownHook(database); database.execute("CREATE " + "(a), " + "(b {name:'node1'})," + "(c {name:'node2'})," + "(c)-[:test {key1:'value1'}]->(b)," + "(c)-[:test {key1:'value1'}]->(a)"); try (Transaction tx = database.beginTx()) { assertEquals(2, deleteNodeAndRelationships(database.getNodeById(2))); tx.success(); } } |
### Question:
DirectionUtils { public static Direction reverse(Direction direction) { switch (direction) { case BOTH: return BOTH; case OUTGOING: return INCOMING; case INCOMING: return OUTGOING; default: throw new IllegalArgumentException("Unknown direction " + direction); } } private DirectionUtils(); static Direction resolveDirection(Relationship relationship, Node pointOfView); static Direction resolveDirection(Relationship relationship, Node pointOfView, Direction defaultDirection); static Direction resolveDirection(AttachedRelationshipExpressions<?> relationship, AttachedNodeExpressions pointOfView, Direction defaultDirection); static boolean matches(Relationship relationship, Node pointOfView, Direction direction); static boolean matches(Direction direction1, Direction direction2); static Direction reverse(Direction direction); }### Answer:
@Test public void shouldCorrectlyReverseDirection() { assertEquals(OUTGOING, reverse(INCOMING)); assertEquals(INCOMING, reverse(OUTGOING)); assertEquals(BOTH, reverse(BOTH)); } |
### Question:
ArrayUtils { public static boolean isPrimitiveArray(Object o) { if (o instanceof byte[]) { return true; } else if (o instanceof char[]) { return true; } else if (o instanceof boolean[]) { return true; } else if (o instanceof long[]) { return true; } else if (o instanceof double[]) { return true; } else if (o instanceof int[]) { return true; } else if (o instanceof short[]) { return true; } else if (o instanceof float[]) { return true; } return false; } private ArrayUtils(); static boolean isPrimitiveArray(Object o); static boolean isPrimitiveOrStringArray(Object o); static boolean isArray(Object o); static boolean arrayFriendlyEquals(Object o1, Object o2); static int arrayFriendlyHashCode(Object o); static String primitiveOrStringArrayToString(Object o); static boolean arrayFriendlyMapEquals(Map<String, T> map1, Map<String, T> map2); }### Answer:
@Test public void shouldCorrectlyIdentifyPrimitiveArray() { assertTrue(isPrimitiveArray(new byte[]{})); assertTrue(isPrimitiveArray(new char[]{})); assertTrue(isPrimitiveArray(new boolean[]{})); assertTrue(isPrimitiveArray(new long[]{})); assertTrue(isPrimitiveArray(new double[]{})); assertTrue(isPrimitiveArray(new int[]{})); assertTrue(isPrimitiveArray(new short[]{})); assertTrue(isPrimitiveArray(new float[]{})); assertFalse(isPrimitiveArray(new String[]{})); assertFalse(isPrimitiveArray(123)); assertFalse(isPrimitiveArray(new Object[]{})); } |
### Question:
ArrayUtils { public static boolean isPrimitiveOrStringArray(Object o) { if (isPrimitiveArray(o)) { return true; } else if (o instanceof String[]) { return true; } return false; } private ArrayUtils(); static boolean isPrimitiveArray(Object o); static boolean isPrimitiveOrStringArray(Object o); static boolean isArray(Object o); static boolean arrayFriendlyEquals(Object o1, Object o2); static int arrayFriendlyHashCode(Object o); static String primitiveOrStringArrayToString(Object o); static boolean arrayFriendlyMapEquals(Map<String, T> map1, Map<String, T> map2); }### Answer:
@Test public void shouldCorrectlyIdentifyPrimitiveOrStringArray() { assertTrue(isPrimitiveOrStringArray(new byte[]{})); assertTrue(isPrimitiveOrStringArray(new char[]{})); assertTrue(isPrimitiveOrStringArray(new boolean[]{})); assertTrue(isPrimitiveOrStringArray(new long[]{})); assertTrue(isPrimitiveOrStringArray(new double[]{})); assertTrue(isPrimitiveOrStringArray(new int[]{})); assertTrue(isPrimitiveOrStringArray(new short[]{})); assertTrue(isPrimitiveOrStringArray(new float[]{})); assertTrue(isPrimitiveOrStringArray(new String[]{})); assertFalse(isPrimitiveOrStringArray(123)); assertFalse(isPrimitiveOrStringArray(new Object[]{})); } |
### Question:
ArrayUtils { public static boolean isArray(Object o) { if (isPrimitiveArray(o)) { return true; } else if (o instanceof Object[]) { return true; } return false; } private ArrayUtils(); static boolean isPrimitiveArray(Object o); static boolean isPrimitiveOrStringArray(Object o); static boolean isArray(Object o); static boolean arrayFriendlyEquals(Object o1, Object o2); static int arrayFriendlyHashCode(Object o); static String primitiveOrStringArrayToString(Object o); static boolean arrayFriendlyMapEquals(Map<String, T> map1, Map<String, T> map2); }### Answer:
@Test public void shouldCorrectlyIdentifyArray() { assertTrue(isArray(new byte[]{})); assertTrue(isArray(new char[]{})); assertTrue(isArray(new boolean[]{})); assertTrue(isArray(new long[]{})); assertTrue(isArray(new double[]{})); assertTrue(isArray(new int[]{})); assertTrue(isArray(new short[]{})); assertTrue(isArray(new float[]{})); assertTrue(isArray(new String[]{})); assertTrue(isArray(new Object[]{})); assertFalse(isArray(123)); } |
### Question:
UnorderedPair extends SameTypePair<T> { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj instanceof UnorderedPair) { UnorderedPair that = (UnorderedPair) obj; return (Objects.equals(first(), that.first()) && Objects.equals(second(), that.second())) || (Objects.equals(first(), that.second()) && Objects.equals(second(), that.first())); } return false; } UnorderedPair(T first, T second); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void equalPairsShouldBeEqual() { assertTrue(new UnorderedPair<>("test", "test").equals(new UnorderedPair<>("test", "test"))); assertTrue(new UnorderedPair<>("test1", "test").equals(new UnorderedPair<>("test", "test1"))); assertTrue(new UnorderedPair<>(null, "test").equals(new UnorderedPair<>(null, "test"))); assertTrue(new UnorderedPair<>(null, "test").equals(new UnorderedPair<>("test", null))); assertTrue(new UnorderedPair<>("test", null).equals(new UnorderedPair<>("test", null))); assertTrue(new UnorderedPair<>("test", null).equals(new UnorderedPair<>(null, "test"))); assertTrue(new UnorderedPair<>(null, null).equals(new UnorderedPair<>(null, null))); }
@Test public void unEqualPairsShouldNotBeEqual() { assertFalse(new UnorderedPair<>("test1", "test2").equals(new UnorderedPair<>("test1", "test1"))); assertFalse(new UnorderedPair<>("test1", "test1").equals(new UnorderedPair<>(null, "test1"))); assertFalse(new UnorderedPair<>("test1", null).equals(new UnorderedPair<>("test1", "test1"))); assertFalse(new UnorderedPair<>(null, null).equals(new UnorderedPair<>("test1", "test1"))); assertFalse(new UnorderedPair<>("test1", "test1").equals(new UnorderedPair<>("test1", null))); assertFalse(new UnorderedPair<>("test1", "test1").equals(new UnorderedPair<>(null, null))); } |
### Question:
UnorderedPair extends SameTypePair<T> { @Override public int hashCode() { return Objects.hashCode(first()) + Objects.hashCode(second()); } UnorderedPair(T first, T second); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void equalObjectsShouldHaveSameHashCode() { assertEquals(new UnorderedPair<>("test", "test").hashCode(), new UnorderedPair<>("test", "test").hashCode()); assertEquals(new UnorderedPair<>("test1", "test").hashCode(), new UnorderedPair<>("test", "test1").hashCode()); assertEquals(new UnorderedPair<>(null, "test").hashCode(), new UnorderedPair<>(null, "test").hashCode()); assertEquals(new UnorderedPair<>(null, "test").hashCode(), new UnorderedPair<>("test", null).hashCode()); assertEquals(new UnorderedPair<>("test", null).hashCode(), new UnorderedPair<>("test", null).hashCode()); assertEquals(new UnorderedPair<>("test", null).hashCode(), new UnorderedPair<>(null, "test").hashCode()); assertEquals(new UnorderedPair<>(null, null).hashCode(), new UnorderedPair<>(null, null).hashCode()); } |
### Question:
Alumno { public Double deuda() { if (this.hermano == null) { return CUOTA; } if ( this.hermano != null && this.apellido.equals(this.hermano.apellido) ) { return .75 * CUOTA; } return CUOTA; } Alumno(); Alumno(String nombre, Alumno hermano); Alumno(String nombre, String apellido); Alumno(Alumno hermano); Double deuda(); }### Answer:
@Test public void unAlumnoPagaCuotaCompleta() { Alumno a = new Alumno(); assertEquals(100, a.deuda()); }
@Test public void unAlmnoTieneUnHermanoEntoncesElHermanoPaga75PdeCuota() { Alumno ova = new Alumno("ova", new Alumno("gabi", "sabatini")); assertEquals(75, ova.deuda()); } |
### Question:
Casa { public int getGastoTotal() { int gasto = 0; Iterator<ComponenteElectrico> iterador = estufas.iterator(); while (iterador.hasNext()){ ComponenteElectrico estufa = iterador.next(); gasto = gasto + estufa.getConsumo(); } iterador = cercos.iterator(); while (iterador.hasNext()){ ComponenteElectrico cerco = iterador.next(); gasto = gasto + cerco.getConsumo(); } iterador = losas.iterator(); while (iterador.hasNext()){ ComponenteElectrico losa = iterador.next(); gasto = gasto + losa.getConsumo(); } return gasto; } int getGastoTotal(); public List<ComponenteElectrico> estufas; public List<ComponenteElectrico> cercos; public List<ComponenteElectrico> losas; }### Answer:
@Test public void test() { Casa casa = new Casa(); ComponenteElectrico estufaDelBanio = new ComponenteElectrico("estufa"); estufaDelBanio.ambientes = 1; estufaDelBanio.precioKw = 10; estufaDelBanio.calorias = 1000; casa.estufas.add(estufaDelBanio); ComponenteElectrico losaComedor = new ComponenteElectrico("LOSA_RADIANTE"); losaComedor.metros = 10; losaComedor.precioKw = 10; casa.losas.add(losaComedor); ComponenteElectrico cercoFondo = new ComponenteElectrico("CeRcO-ElEcTrIcO"); cercoFondo.metros = 10; cercoFondo.precioKw = 10; casa.cercos.add(cercoFondo); org.junit.Assert.assertEquals(11100, casa.getGastoTotal()); } |
### Question:
CustomWorkflowValidation implements ValidationRule { @Override public ValidationInformation validate(ValidationInformation info) throws ValidationException { RequestParameters requestParameters = info.getSir().getRequestDetails().getRequestParameters(); if (requestParameters == null) { throw new ValidationException("requestParameters"); } return info; } @Override ValidationInformation validate(ValidationInformation info); }### Answer:
@Test public void testCustomWorkflowValidation() throws IOException, ValidationException { String requestJson = new String(Files.readAllBytes( Paths.get("src/test/resources/MsoRequestTest/SuccessfulValidation/v1ExecuteCustomWorkflow.json"))); ObjectMapper mapper = new ObjectMapper(); ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.inPlaceSoftwareUpdate, 1, false, sir.getRequestDetails().getRequestParameters()); info.setRequestScope("vnf"); CustomWorkflowValidation validation = new CustomWorkflowValidation(); validation.validate(info); assertEquals(info.getSir().getRequestDetails().getCloudConfiguration().getCloudOwner(), "att-aic"); } |
### Question:
DecomposeJsonUtil implements Serializable { public static AllottedResource jsonToAllottedResource(String jsonString) throws JsonDecomposingException { try { return OBJECT_MAPPER.readValue(jsonString, AllottedResource.class); } catch (IOException e) { throw new JsonDecomposingException("Exception while converting json to allotted resource", e); } } private DecomposeJsonUtil(); static ServiceDecomposition jsonToServiceDecomposition(String jsonString); static ServiceDecomposition jsonToServiceDecomposition(String jsonString, String serviceInstanceId); static VnfResource jsonToVnfResource(String jsonString); static NetworkResource jsonToNetworkResource(String jsonString); static AllottedResource jsonToAllottedResource(String jsonString); static ConfigResource jsonToConfigResource(String jsonString); }### Answer:
@Test public void testJsonToAllottedResource() throws JsonDecomposingException { allottedResource = createAllottedResourceData(); AllottedResource allottedResourceObj = DecomposeJsonUtil.jsonToAllottedResource(allottedResource.toString()); assertEquals(allottedResource.getResourceId(), allottedResourceObj.getResourceId()); }
@Test public void testJsonToAllottedResource_JsonDecomposingException() throws JsonDecomposingException { expectedException.expect(JsonDecomposingException.class); configResource = createConfigResourceData(); AllottedResource allottedResourceObj = DecomposeJsonUtil.jsonToAllottedResource(configResource.toString()); } |
### Question:
DecomposeJsonUtil implements Serializable { public static ConfigResource jsonToConfigResource(String jsonString) throws JsonDecomposingException { try { return OBJECT_MAPPER.readValue(jsonString, ConfigResource.class); } catch (IOException e) { throw new JsonDecomposingException("Exception while converting json to allotted resource", e); } } private DecomposeJsonUtil(); static ServiceDecomposition jsonToServiceDecomposition(String jsonString); static ServiceDecomposition jsonToServiceDecomposition(String jsonString, String serviceInstanceId); static VnfResource jsonToVnfResource(String jsonString); static NetworkResource jsonToNetworkResource(String jsonString); static AllottedResource jsonToAllottedResource(String jsonString); static ConfigResource jsonToConfigResource(String jsonString); }### Answer:
@Test public void testJsonToConfigResource() throws JsonDecomposingException { configResource = createConfigResourceData(); ConfigResource configResourceObj = DecomposeJsonUtil.jsonToConfigResource(configResource.toString()); assertEquals(configResource.getResourceId(), configResourceObj.getResourceId()); }
@Test public void testJsonToConfigResource_JsonDecomposingException() throws JsonDecomposingException { expectedException.expect(JsonDecomposingException.class); allottedResource = createAllottedResourceData(); ConfigResource configResourceObj = DecomposeJsonUtil.jsonToConfigResource(allottedResource.toString()); } |
### Question:
XmlTool { public static String normalize(Object xml) throws IOException, TransformerException, ParserConfigurationException, SAXException, XPathExpressionException { if (xml == null) { return null; } Source xsltSource = new StreamSource(new StringReader(readResourceFile("normalize-namespaces.xsl"))); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); dbFactory.setNamespaceAware(true); dbFactory.setFeature("http: dbFactory.setFeature("http: DocumentBuilder db = dbFactory.newDocumentBuilder(); InputSource source = new InputSource(new StringReader(String.valueOf(xml))); Document doc = db.parse(source); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xPath.evaluate(" for (int i = 0; i < nodeList.getLength(); ++i) { Node node = nodeList.item(i); node.getParentNode().removeChild(node); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); Transformer transformer = transformerFactory.newTransformer(xsltSource); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty("{http: StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); return writer.toString().trim(); } private XmlTool(); static String normalize(Object xml); static String encode(Object value); static String removePreamble(Object xml); static String removeNamespaces(Object xml); static Optional<String> modifyElement(String xml, String elementTag, String newValue); }### Answer:
@Test public void normalizeTest() throws Exception { String response = XmlTool.normalize(content); assertNotNull(response); } |
### Question:
XmlTool { public static Optional<String> modifyElement(String xml, String elementTag, String newValue) throws IOException, TransformerException, ParserConfigurationException, SAXException { if (xml == null || xml.isEmpty()) { return Optional.empty(); } DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); dbFactory.setNamespaceAware(true); dbFactory.setFeature("http: dbFactory.setFeature("http: DocumentBuilder db = dbFactory.newDocumentBuilder(); InputSource source = new InputSource(new StringReader(xml)); Document doc = db.parse(source); Node modNode = doc.getElementsByTagName(elementTag).item(0); if (modNode == null) { return Optional.empty(); } else { modNode.setTextContent(newValue); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); return Optional.of(writer.toString().trim()); } private XmlTool(); static String normalize(Object xml); static String encode(Object value); static String removePreamble(Object xml); static String removeNamespaces(Object xml); static Optional<String> modifyElement(String xml, String elementTag, String newValue); }### Answer:
@Test public void modifyElementTest() throws Exception { String response = XmlTool.modifyElement(content, "event-type", "uCPE-VMS").get(); assertNotNull(response); } |
### Question:
ResponseBuilder implements java.io.Serializable { public Object buildWorkflowResponse(DelegateExecution execution) { String method = getClass().getSimpleName() + ".buildWorkflowResponse(" + "execution=" + execution.getId() + ")"; logger.debug("Entered " + method); String prefix = (String) execution.getVariable("prefix"); String processKey = getProcessKey(execution); Object theResponse = null; WorkflowException theException = (WorkflowException) execution.getVariable(WORKFLOWEXCEPTION); String errorResponse = trimString(execution.getVariable(prefix + "ErrorResponse"), null); String responseCode = trimString(execution.getVariable(prefix + "ResponseCode"), null); if (theException == null && errorResponse == null && isOneOf(responseCode, null, "0", "200", "201", "202", "204")) { theResponse = execution.getVariable("WorkflowResponse"); if (theResponse == null) { theResponse = execution.getVariable(processKey + "Response"); } } logger.debug("Exited " + method); return theResponse; } WorkflowException buildWorkflowException(DelegateExecution execution); Object buildWorkflowResponse(DelegateExecution execution); }### Answer:
@Test public void buildWorkflowResponse_Object_Test() { String workflowResponse = "<WorkflowResponse>good</WorkflowResponse>"; when(mockExecution.getVariable("WorkflowResponse")).thenReturn(workflowResponse); obj = responseBuilder.buildWorkflowResponse(mockExecution); assertEquals(workflowResponse, obj); } |
### Question:
VariableNameExtractor { public Optional<String> extract() { Matcher matcher = VARIABLE_NAME_PATTERN.matcher(expression); if (!matcher.matches()) { return Optional.empty(); } return Optional.of(matcher.group(1)); } VariableNameExtractor(String expression); Optional<String> extract(); }### Answer:
@Test public void shouldExtractVariableName() throws Exception { String name = "A_different_NAME123"; String variable = "${A_different_NAME123}"; VariableNameExtractor extractor = new VariableNameExtractor(variable); Optional<String> extracted = extractor.extract(); assertTrue(extracted.isPresent()); assertThat(extracted.get(), containsString(name)); }
@Test public void shouldExtractVariableNameFromWhitespaces() throws Exception { String name = "name"; String variable = " \n\t$ \n\t{ \n\tname \n\t} \n\t"; VariableNameExtractor extractor = new VariableNameExtractor(variable); Optional<String> extracted = extractor.extract(); assertTrue(extracted.isPresent()); assertThat(extracted.get(), containsString(name)); }
@Test public void shouldReturnEmptyIfThereIsMoreThanVariable() throws Exception { String variable = "a ${test}"; VariableNameExtractor extractor = new VariableNameExtractor(variable); Optional<String> extracted = extractor.extract(); assertFalse(extracted.isPresent()); }
@Test public void shouldReturnEmptyIfVariableNameIsIncorrect() throws Exception { String variable = "${name with space}"; VariableNameExtractor extractor = new VariableNameExtractor(variable); Optional<String> extracted = extractor.extract(); assertFalse(extracted.isPresent()); }
@Test public void shouldReturnEmptyIfTwoVariablesPresent() throws Exception { String variable = "${var1} ${var2}"; VariableNameExtractor extractor = new VariableNameExtractor(variable); Optional<String> extracted = extractor.extract(); assertFalse(extracted.isPresent()); } |
### Question:
UrnPropertiesReader { public static String getVariable(String variableName, DelegateExecution execution) { Object value = execution.getVariable(variableName); if (value != null) { logger.trace("Retrieved value for the URN variable, {}, from the execution object: {}", variableName, String.valueOf(value)); return String.valueOf(value); } String variableValue = null; if (environment != null && environment.getProperty(variableName) != null) { variableValue = environment.getProperty(variableName); logger.trace("Retrieved value for the URN variable, {}, from the environment variable: {}", variableName, variableValue); execution.setVariable(variableName, variableValue); return variableValue; } return variableValue; } @Autowired void setEnvironment(Environment environment); static String getVariable(String variableName, DelegateExecution execution); static String getVariable(String variableName, DelegateExecution execution, String defaultValue); static String getVariable(String variableName); static String[] getVariablesArray(String variableName); static String getVariable(String variableName, String defaultValue); }### Answer:
@Test public void testGetVariableFromExecution() { ExecutionEntity mockExecution = mock(ExecutionEntity.class); when(mockExecution.getVariable("testKey")).thenReturn("testValue"); String value = UrnPropertiesReader.getVariable("testKey", mockExecution); Assert.assertEquals("testValue", value); verify(mockExecution).getVariable("testKey"); verify(mockExecution, never()).setVariable("testKey", value); }
@Test public void testGetVariableNotExist() { ExecutionEntity mockExecution = mock(ExecutionEntity.class); String value = UrnPropertiesReader.getVariable("notExist", mockExecution); Assert.assertEquals(null, value); verify(mockExecution).getVariable("notExist"); verify(mockExecution, never()).setVariable("notExist", value); } |
### Question:
NetworkResource extends Resource { public NetworkResource() { resourceType = ResourceType.NETWORK; setResourceId(UUID.randomUUID().toString()); } NetworkResource(); String getNetworkType(); void setNetworkType(String networkType); String getNetworkRole(); void setNetworkRole(String networkRole); String getNetworkTechnology(); void setNetworkTechnology(String networkTechnology); String getNetworkScope(); void setNetworkScope(String networkScope); String getResourceInput(); void setResourceInput(String resourceInput); }### Answer:
@Test public void testNetworkResource() { nr.setNetworkType("networkType"); nr.setNetworkRole("networkRole"); nr.setNetworkTechnology("networkTechnology"); nr.setNetworkScope("networkScope"); assertEquals(nr.getNetworkType(), "networkType"); assertEquals(nr.getNetworkRole(), "networkRole"); assertEquals(nr.getNetworkTechnology(), "networkTechnology"); assertEquals(nr.getNetworkScope(), "networkScope"); } |
### Question:
ModuleResource extends Resource { public ModuleResource() { resourceType = ResourceType.MODULE; } ModuleResource(); String getVfModuleName(); void setVfModuleName(String vfModuleName); String getHeatStackId(); void setHeatStackId(String heatStackId); boolean getIsBase(); void setIsBase(boolean isBase); String getVfModuleLabel(); void setVfModuleLabel(String vfModuleLabel); int getInitialCount(); void setInitialCount(int initialCount); String getVfModuleType(); void setVfModuleType(String vfModuleType); boolean isHasVolumeGroup(); void setHasVolumeGroup(boolean hasVolumeGroup); }### Answer:
@Test public void testModuleResource() { moduleresource.setVfModuleName("vfModuleName"); moduleresource.setHeatStackId("heatStackId"); moduleresource.setIsBase(true); moduleresource.setVfModuleLabel("vfModuleLabel"); moduleresource.setInitialCount(0); moduleresource.setVfModuleType("vfModuleType"); moduleresource.setHasVolumeGroup(true); assertEquals(moduleresource.getVfModuleName(), "vfModuleName"); assertEquals(moduleresource.getHeatStackId(), "heatStackId"); assertEquals(moduleresource.getIsBase(), true); assertEquals(moduleresource.getVfModuleLabel(), "vfModuleLabel"); assertEquals(moduleresource.getInitialCount(), 0); assertEquals(moduleresource.getVfModuleType(), "vfModuleType"); assertEquals(moduleresource.isHasVolumeGroup(), true); } |
### Question:
Subscriber implements Serializable { public Subscriber(String globalId, String name, String commonSiteId) { super(); this.globalId = globalId; this.name = name; this.commonSiteId = commonSiteId; } Subscriber(String globalId, String name, String commonSiteId); String getGlobalId(); void setGlobalId(String globalId); String getName(); void setName(String name); String getCommonSiteId(); void setCommonSiteId(String commonSiteId); }### Answer:
@Test public void testSubscriber() { subscriber.setGlobalId("globalId"); subscriber.setName("name"); subscriber.setCommonSiteId("commonSiteId"); assertEquals(subscriber.getGlobalId(), "globalId"); assertEquals(subscriber.getName(), "name"); assertEquals(subscriber.getCommonSiteId(), "commonSiteId"); } |
### Question:
ConfigResource extends Resource { public ConfigResource() { resourceType = ResourceType.CONFIGURATION; setResourceId(UUID.randomUUID().toString()); } ConfigResource(); }### Answer:
@Test public void testConfigResource() { configresource.setToscaNodeType("toscaNodeType"); assertEquals(configresource.getToscaNodeType(), "toscaNodeType"); } |
### Question:
CompareModelsResult extends JsonWrapper implements Serializable { public void setAddedResourceList(List<ResourceModelInfo> addedResourceList) { this.addedResourceList = addedResourceList; } List<ResourceModelInfo> getAddedResourceList(); void setAddedResourceList(List<ResourceModelInfo> addedResourceList); List<ResourceModelInfo> getDeletedResourceList(); void setDeletedResourceList(List<ResourceModelInfo> deletedResourceList); List<String> getRequestInputs(); void setRequestInputs(List<String> requestInputs); }### Answer:
@Test public void testSetAddedResourceList() { addedResourceList = new ArrayList<ResourceModelInfo>(); addedResourceList.add(resourceModelInfo1); addedResourceList.add(resourceModelInfo2); modelsResult = new CompareModelsResult(); modelsResult.setAddedResourceList(addedResourceList); assertEquals(addedResourceList, modelsResult.getAddedResourceList()); } |
### Question:
CompareModelsResult extends JsonWrapper implements Serializable { public void setDeletedResourceList(List<ResourceModelInfo> deletedResourceList) { this.deletedResourceList = deletedResourceList; } List<ResourceModelInfo> getAddedResourceList(); void setAddedResourceList(List<ResourceModelInfo> addedResourceList); List<ResourceModelInfo> getDeletedResourceList(); void setDeletedResourceList(List<ResourceModelInfo> deletedResourceList); List<String> getRequestInputs(); void setRequestInputs(List<String> requestInputs); }### Answer:
@Test public void testSetDeletedResourceList() { deletedResourceList = new ArrayList<ResourceModelInfo>(); deletedResourceList.add(resourceModelInfo1); deletedResourceList.add(resourceModelInfo2); modelsResult = new CompareModelsResult(); modelsResult.setDeletedResourceList(deletedResourceList); assertEquals(deletedResourceList, modelsResult.getDeletedResourceList()); } |
### Question:
CompareModelsResult extends JsonWrapper implements Serializable { public void setRequestInputs(List<String> requestInputs) { this.requestInputs = requestInputs; } List<ResourceModelInfo> getAddedResourceList(); void setAddedResourceList(List<ResourceModelInfo> addedResourceList); List<ResourceModelInfo> getDeletedResourceList(); void setDeletedResourceList(List<ResourceModelInfo> deletedResourceList); List<String> getRequestInputs(); void setRequestInputs(List<String> requestInputs); }### Answer:
@Test public void testSetRequestInputs() { requestInputs = new ArrayList<String>(); requestInputs.add("requestInput1"); requestInputs.add("requestInput2"); modelsResult = new CompareModelsResult(); modelsResult.setRequestInputs(requestInputs); assertEquals(requestInputs, modelsResult.getRequestInputs()); } |
### Question:
ActivateVnfOperationalEnvironment { public AAIResultWrapper getAAIOperationalEnvironment(String operationalEnvironmentId) { return aaiHelper.getAaiOperationalEnvironment(operationalEnvironmentId); } void execute(String requestId, CloudOrchestrationRequest request); void processActivateSDCRequest(String requestId, String operationalEnvironmentId,
List<ServiceModelList> serviceModelVersionIdList, String workloadContext,
String vnfOperationalEnvironmentId); AAIResultWrapper getAAIOperationalEnvironment(String operationalEnvironmentId); }### Answer:
@Test public void getAAIOperationalEnvironmentTest() { OperationalEnvironment aaiOpEnv; wireMockServer.stubFor( get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) .willReturn(aResponse().withHeader("Content-Type", "application/json") .withBodyFile("vnfoperenv/ecompOperationalEnvironmentWithRelationship.json") .withStatus(HttpStatus.SC_ACCEPTED))); AAIResultWrapper wrapper = clientHelper.getAaiOperationalEnvironment("EMOE-001"); aaiOpEnv = wrapper.asBean(OperationalEnvironment.class).get(); assertEquals("EMOE-001", aaiOpEnv.getOperationalEnvironmentId()); assertEquals("1dfe7154-eae0-44f2-8e7a-8e5e7882e55d", aaiOpEnv.getRelationshipList().getRelationship().get(0) .getRelationshipData().get(0).getRelationshipValue()); assertNotNull(activateVnf.getAAIOperationalEnvironment(operationalEnvironmentId)); assertEquals("EMOE-001", activateVnf.getAAIOperationalEnvironment(operationalEnvironmentId) .asBean(OperationalEnvironment.class).get().getOperationalEnvironmentId()); } |
### Question:
CreateNetwork { public void buildCreateNetworkRequest(BuildingBlockExecution execution) throws Exception { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); Map<String, String> userInput = gBBInput.getUserInput(); String cloudRegionPo = execution.getVariable("cloudRegionPo"); CreateNetworkRequest createNetworkRequest = networkAdapterObjectMapper.createNetworkRequestMapper( gBBInput.getRequestContext(), gBBInput.getCloudRegion(), gBBInput.getOrchContext(), serviceInstance, l3Network, userInput, cloudRegionPo, gBBInput.getCustomer()); execution.setVariable("createNetworkRequest", createNetworkRequest); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } } void buildCreateNetworkRequest(BuildingBlockExecution execution); }### Answer:
@Test public void buildCreateNetworkRequestTest() throws Exception { execution.setVariable("cloudRegionPo", cloudRegionPo); CreateNetworkRequest expectedCreateNetworkRequest = new CreateNetworkRequest(); doReturn(expectedCreateNetworkRequest).when(networkAdapterObjectMapper).createNetworkRequestMapper( requestContext, cloudRegion, orchestrationContext, serviceInstance, network, userInput, cloudRegionPo, customer); createNetwork.buildCreateNetworkRequest(execution); verify(networkAdapterObjectMapper, times(1)).createNetworkRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, network, userInput, cloudRegionPo, customer); assertThat(expectedCreateNetworkRequest, sameBeanAs(execution.getVariable("createNetworkRequest"))); } |
### Question:
CreateNetworkCollection { public void connectCollectionToInstanceGroup(BuildingBlockExecution execution) throws Exception { execution.setVariable("connectCollectionToInstanceGroupRollback", false); try { ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); Collection networkCollection = serviceInstance.getCollection(); aaiNetworkResources.connectNetworkCollectionInstanceGroupToNetworkCollection( networkCollection.getInstanceGroup(), networkCollection); execution.setVariable("connectCollectionToInstanceGroupRollback", true); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } } void buildNetworkCollectionName(BuildingBlockExecution execution); void connectCollectionToInstanceGroup(BuildingBlockExecution execution); void connectInstanceGroupToCloudRegion(BuildingBlockExecution execution); void connectCollectionToServiceInstance(BuildingBlockExecution execution); }### Answer:
@Test public void connectCollectionToInstanceGroupTest() throws Exception { doNothing().when(aaiNetworkResources).connectNetworkCollectionInstanceGroupToNetworkCollection( serviceInstance.getCollection().getInstanceGroup(), serviceInstance.getCollection()); createNetworkCollection.connectCollectionToInstanceGroup(execution); verify(aaiNetworkResources, times(1)).connectNetworkCollectionInstanceGroupToNetworkCollection( serviceInstance.getCollection().getInstanceGroup(), serviceInstance.getCollection()); } |
### Question:
CreateNetworkCollection { public void connectCollectionToServiceInstance(BuildingBlockExecution execution) throws Exception { execution.setVariable("connectCollectionToServiceInstanceRollback", false); try { ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); Collection networkCollection = serviceInstance.getCollection(); aaiNetworkResources.connectNetworkCollectionToServiceInstance(networkCollection, serviceInstance); execution.setVariable("connectCollectionToServiceInstanceRollback", true); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } } void buildNetworkCollectionName(BuildingBlockExecution execution); void connectCollectionToInstanceGroup(BuildingBlockExecution execution); void connectInstanceGroupToCloudRegion(BuildingBlockExecution execution); void connectCollectionToServiceInstance(BuildingBlockExecution execution); }### Answer:
@Test public void connectCollectionToServiceInstanceTest() throws Exception { doNothing().when(aaiNetworkResources).connectNetworkCollectionToServiceInstance(serviceInstance.getCollection(), serviceInstance); createNetworkCollection.connectCollectionToServiceInstance(execution); verify(aaiNetworkResources, times(1)).connectNetworkCollectionToServiceInstance(serviceInstance.getCollection(), serviceInstance); } |
### Question:
CreateNetworkCollection { public void connectInstanceGroupToCloudRegion(BuildingBlockExecution execution) throws Exception { execution.setVariable("connectInstanceGroupToCloudRegionRollback", false); try { ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); Collection networkCollection = serviceInstance.getCollection(); aaiNetworkResources.connectInstanceGroupToCloudRegion(networkCollection.getInstanceGroup(), execution.getGeneralBuildingBlock().getCloudRegion()); execution.setVariable("connectInstanceGroupToCloudRegionRollback", true); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } } void buildNetworkCollectionName(BuildingBlockExecution execution); void connectCollectionToInstanceGroup(BuildingBlockExecution execution); void connectInstanceGroupToCloudRegion(BuildingBlockExecution execution); void connectCollectionToServiceInstance(BuildingBlockExecution execution); }### Answer:
@Test public void connectInstanceGroupToCloudRegionTest() throws Exception { doNothing().when(aaiNetworkResources) .connectInstanceGroupToCloudRegion(serviceInstance.getCollection().getInstanceGroup(), cloudRegion); createNetworkCollection.connectInstanceGroupToCloudRegion(execution); verify(aaiNetworkResources, times(1)) .connectInstanceGroupToCloudRegion(serviceInstance.getCollection().getInstanceGroup(), cloudRegion); } |
### Question:
ControllerExecution { public void selectBB(BuildingBlockExecution execution) { try { String controllerActor = execution.getVariable(CONTROLLER_ACTOR); String action = Optional.of((String) execution.getVariable(ACTION)).get(); String scope = Optional.of((String) execution.getVariable(SCOPE)).get(); BBNameSelectionReference bbNameSelectionReference = catalogDbClient.getBBNameSelectionReference(controllerActor, scope, action); String bbName = bbNameSelectionReference.getBbName(); execution.setVariable(BBNAME, bbName); logger.debug(" Executing {} BPMN", bbName); } catch (Exception ex) { logger.error("An exception occurred while getting bbname from catalogdb ", ex); exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } } void setControllerActorScopeAction(BuildingBlockExecution execution); void selectBB(BuildingBlockExecution execution); }### Answer:
@Test public void testSelectBB() throws Exception { BBNameSelectionReference bbNameSelectionReference = new BBNameSelectionReference(); bbNameSelectionReference.setBbName(TEST_BBNAME); bbNameSelectionReference.setAction(TEST_ACTION); bbNameSelectionReference.setControllerActor(TEST_CONTROLLER_ACTOR); bbNameSelectionReference.setScope(TEST_SCOPE); doReturn(bbNameSelectionReference).when(catalogDbClient).getBBNameSelectionReference(TEST_CONTROLLER_ACTOR, TEST_SCOPE, TEST_ACTION); execution.setVariable("actor", TEST_CONTROLLER_ACTOR); execution.setVariable("scope", TEST_SCOPE); execution.setVariable("action", TEST_ACTION); controllerExecution.selectBB(execution); assertEquals(TEST_BBNAME, execution.getVariable("bbName")); } |
### Question:
ActivateVfModule { public void setTimerDuration(BuildingBlockExecution execution) { try { String waitDuration = this.environment.getProperty(VF_MODULE_TIMER_DURATION_PATH, DEFAULT_TIMER_DURATION); logger.debug("Sleeping before proceeding with SDNC activate. Timer duration: {}", waitDuration); execution.setVariable("vfModuleActivateTimerDuration", waitDuration); } catch (Exception e) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, e); } } void setTimerDuration(BuildingBlockExecution execution); }### Answer:
@Test public void setWaitBeforeDurationTest() throws Exception { when(env.getProperty(ActivateVfModule.VF_MODULE_TIMER_DURATION_PATH, ActivateVfModule.DEFAULT_TIMER_DURATION)) .thenReturn("PT300S"); activateVfModule.setTimerDuration(execution); verify(env, times(1)).getProperty(ActivateVfModule.VF_MODULE_TIMER_DURATION_PATH, ActivateVfModule.DEFAULT_TIMER_DURATION); assertEquals("PT300S", (String) execution.getVariable("vfModuleActivateTimerDuration")); } |
### Question:
ConfigDeployVnf { public void updateAAIConfigure(BuildingBlockExecution execution) { aaiUpdateTask.updateOrchestrationStatusConfigDeployConfigureVnf(execution); } void updateAAIConfigure(BuildingBlockExecution execution); void preProcessAbstractCDSProcessing(BuildingBlockExecution execution); void updateAAIConfigured(BuildingBlockExecution execution); }### Answer:
@Test public void updateAAIConfigureTaskTest() throws Exception { configDeployVnf.updateAAIConfigure(execution); assertTrue(true); } |
### Question:
ConfigDeployVnf { public void updateAAIConfigured(BuildingBlockExecution execution) { aaiUpdateTask.updateOrchestrationStatusConfigDeployConfiguredVnf(execution); } void updateAAIConfigure(BuildingBlockExecution execution); void preProcessAbstractCDSProcessing(BuildingBlockExecution execution); void updateAAIConfigured(BuildingBlockExecution execution); }### Answer:
@Test public void updateAAIConfiguredTaskTest() throws Exception { configDeployVnf.updateAAIConfigured(execution); assertTrue(true); } |
### Question:
UnassignVnf { public void deleteInstanceGroups(BuildingBlockExecution execution) { try { GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); List<InstanceGroup> instanceGroups = vnf.getInstanceGroups(); for (InstanceGroup instanceGroup : instanceGroups) { if (ModelInfoInstanceGroup.TYPE_VNFC .equalsIgnoreCase(instanceGroup.getModelInfoInstanceGroup().getType())) { aaiInstanceGroupResources.deleteInstanceGroup(instanceGroup); } } } catch (Exception ex) { logger.error("Exception occurred in UnassignVnf deleteInstanceGroups", ex); exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } } void deleteInstanceGroups(BuildingBlockExecution execution); }### Answer:
@Test public void deleteInstanceGroupsSunnyDayTest() throws Exception { GenericVnf genericVnf = setGenericVnf(); ModelInfoInstanceGroup modelVnfc = new ModelInfoInstanceGroup(); modelVnfc.setType("VNFC"); InstanceGroup instanceGroup1 = new InstanceGroup(); instanceGroup1.setId("test-001"); instanceGroup1.setModelInfoInstanceGroup(modelVnfc); genericVnf.getInstanceGroups().add(instanceGroup1); InstanceGroup instanceGroup2 = new InstanceGroup(); instanceGroup2.setId("test-002"); instanceGroup2.setModelInfoInstanceGroup(modelVnfc); genericVnf.getInstanceGroups().add(instanceGroup2); when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))) .thenReturn(genericVnf); unassignVnf.deleteInstanceGroups(execution); verify(aaiInstanceGroupResources, times(1)).deleteInstanceGroup(eq(instanceGroup1)); verify(aaiInstanceGroupResources, times(1)).deleteInstanceGroup(eq(instanceGroup2)); }
@Test public void deletecreateVnfcInstanceGroupExceptionTest() throws Exception { expectedException.expect(BpmnError.class); unassignVnf.deleteInstanceGroups(execution); } |
### Question:
CloudSiteCatalogUtils { protected Optional<CloudSite> getCloudSite(String id) { if (id == null) { return Optional.empty(); } CloudSite cloudSite = catalogDbClient.getCloudSite(id); if (cloudSite != null) { return Optional.of(cloudSite); } else { return (Optional.of(catalogDbClient.getCloudSiteByClliAndAicVersion(id, "2.5"))); } } void getIdentityUrlFromCloudSite(DelegateExecution execution); }### Answer:
@Test public void testGetCloudSiteGetVersion30Test() throws Exception { CloudSite cloudSite = new CloudSite(); String testCloudSiteId = "testCloudSiteId"; cloudSite.setClli(testCloudSiteId); doReturn(cloudSite).when(catalogDbClient).getCloudSite(testCloudSiteId); Optional<CloudSite> actualCloudSite = cloudSiteCatalogUtils.getCloudSite(testCloudSiteId); assertEquals(actualCloudSite.get().getClli(), testCloudSiteId); }
@Test public void testGetCloudSiteGetVersion25Test() throws Exception { CloudSite cloudSite = new CloudSite(); String testCloudSiteId = "testCloudSiteId"; cloudSite.setClli(testCloudSiteId); doReturn(null).when(catalogDbClient).getCloudSite(testCloudSiteId); doReturn(cloudSite).when(catalogDbClient).getCloudSiteByClliAndAicVersion(testCloudSiteId, "2.5"); Optional<CloudSite> actualCloudSite = cloudSiteCatalogUtils.getCloudSite(testCloudSiteId); assertEquals(actualCloudSite.get().getClli(), testCloudSiteId); } |
### Question:
AssignNetworkBBUtils { public void getCloudRegion(BuildingBlockExecution execution) { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); CloudRegion cloudRegion = gBBInput.getCloudRegion(); String cloudRegionSdnc; String cloudRegionPo = cloudRegion.getLcpCloudRegionId(); if ("2.5".equalsIgnoreCase(cloudRegion.getCloudRegionVersion())) { cloudRegionSdnc = "AAIAIC25"; } else { cloudRegionSdnc = cloudRegionPo; } execution.setVariable("cloudRegionPo", cloudRegionPo); execution.setVariable("cloudRegionSdnc", cloudRegionSdnc); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } } boolean networkFoundByName(BuildingBlockExecution execution); void getCloudRegion(BuildingBlockExecution execution); void processSilentSuccess(BuildingBlockExecution execution); void failOrchestrationStatus(BuildingBlockExecution execution); }### Answer:
@Test public void getCloudRegionTest25() throws Exception { cloudRegion.setCloudRegionVersion("2.5"); nonMockAssignNetworkBBUtils.getCloudRegion(execution); assertEquals(cloudRegion.getLcpCloudRegionId(), execution.getVariable("cloudRegionPo")); assertEquals("AAIAIC25", execution.getVariable("cloudRegionSdnc")); }
@Test public void getCloudRegionTest30() throws Exception { cloudRegion.setCloudRegionVersion("3.0"); nonMockAssignNetworkBBUtils.getCloudRegion(execution); assertEquals(cloudRegion.getLcpCloudRegionId(), execution.getVariable("cloudRegionPo")); assertEquals(cloudRegion.getLcpCloudRegionId(), execution.getVariable("cloudRegionSdnc")); } |
### Question:
NetworkBBUtils { public boolean isRelationshipRelatedToExists(Optional<org.onap.aai.domain.yang.L3Network> l3network, String relatedToValue) { boolean isRelatedToExists = false; if (l3network.isPresent()) { List<org.onap.aai.domain.yang.Relationship> relationshipList = l3network.get().getRelationshipList().getRelationship(); for (org.onap.aai.domain.yang.Relationship relationship : relationshipList) { if (relationship.getRelatedTo().equals(relatedToValue)) { isRelatedToExists = true; break; } } } return isRelatedToExists; } boolean isRelationshipRelatedToExists(Optional<org.onap.aai.domain.yang.L3Network> l3network,
String relatedToValue); String getCloudRegion(BuildingBlockExecution execution, SourceSystem sourceValue); }### Answer:
@Test public void isRelationshipRelatedToExistsTrueTest() throws Exception { final String aaiResponse = new String( Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "unassignNetworkBB_queryAAIResponse_.json"))); AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(aaiResponse); Optional<L3Network> l3network = aaiResultWrapper.asBean(L3Network.class); boolean isVfModule = networkBBUtils.isRelationshipRelatedToExists(l3network, "vf-module"); assertTrue(isVfModule); }
@Test public void isRelationshipRelatedToExistsFalseTest() throws Exception { final String aaiResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "queryAAIResponse.json"))); AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(aaiResponse); Optional<L3Network> l3network = aaiResultWrapper.asBean(L3Network.class); boolean isVfModule = networkBBUtils.isRelationshipRelatedToExists(l3network, "vf-module"); assertFalse(isVfModule); } |
### Question:
AssignNetwork { public boolean networkFoundByName(BuildingBlockExecution execution) { try { L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); if (!OrchestrationStatus.PRECREATED.equals(l3network.getOrchestrationStatus())) { logger.debug("network found in NOT PRECREATED status"); return true; } } catch (Exception ex) { return false; } return false; } boolean networkFoundByName(BuildingBlockExecution execution); }### Answer:
@Test public void networkNotFoundTest() throws Exception { try { network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); } catch (BBObjectNotFoundException e) { } network.setOrchestrationStatus(OrchestrationStatus.PRECREATED); boolean networkFound = assignNetwork.networkFoundByName(execution); assertEquals(false, networkFound); }
@Test public void networkFoundTest() throws Exception { try { network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); } catch (BBObjectNotFoundException e) { } boolean networkFound = assignNetwork.networkFoundByName(execution); assertEquals(true, networkFound); } |
### Question:
UnassignNetworkBB { public void getCloudSdncRegion(BuildingBlockExecution execution) { try { String cloudRegionSdnc = networkBBUtils.getCloudRegion(execution, SourceSystem.SDNC); execution.setVariable("cloudRegionSdnc", cloudRegionSdnc); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } } void checkRelationshipRelatedTo(BuildingBlockExecution execution, String relatedToValue); void getCloudSdncRegion(BuildingBlockExecution execution); void errorEncountered(BuildingBlockExecution execution); }### Answer:
@Test public void getCloudSdncRegion25Test() throws Exception { CloudRegion cloudRegion = setCloudRegion(); cloudRegion.setCloudRegionVersion("2.5"); doReturn("AAIAIC25").when(networkBBUtils).getCloudRegion(execution, SourceSystem.SDNC); unassignNetworkBB.getCloudSdncRegion(execution); assertEquals("AAIAIC25", execution.getVariable("cloudRegionSdnc")); }
@Test public void getCloudSdncRegion30Test() throws Exception { CloudRegion cloudRegion = setCloudRegion(); cloudRegion.setCloudRegionVersion("3.0"); gBBInput.setCloudRegion(cloudRegion); doReturn(cloudRegion.getLcpCloudRegionId()).when(networkBBUtils).getCloudRegion(execution, SourceSystem.SDNC); unassignNetworkBB.getCloudSdncRegion(execution); assertEquals(cloudRegion.getLcpCloudRegionId(), execution.getVariable("cloudRegionSdnc")); } |
### Question:
UnassignNetworkBB { public void errorEncountered(BuildingBlockExecution execution) { String msg; boolean isRollbackNeeded = execution.getVariable("isRollbackNeeded") != null ? execution.getVariable("isRollbackNeeded") : false; if (isRollbackNeeded) { msg = execution.getVariable("ErrorUnassignNetworkBB") + messageErrorRollback; } else { msg = execution.getVariable("ErrorUnassignNetworkBB"); } exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg); } void checkRelationshipRelatedTo(BuildingBlockExecution execution, String relatedToValue); void getCloudSdncRegion(BuildingBlockExecution execution); void errorEncountered(BuildingBlockExecution execution); }### Answer:
@Test public void errorEncounteredTest_rollback() throws Exception { expectedException.expect(BpmnError.class); execution.setVariable("ErrorUnassignNetworkBB", "Relationship's RelatedTo still exists in AAI, remove the relationship vf-module first."); execution.setVariable("isRollbackNeeded", true); unassignNetworkBB.errorEncountered(execution); }
@Test public void errorEncounteredTest_noRollback() throws Exception { expectedException.expect(BpmnError.class); execution.setVariable("ErrorUnassignNetworkBB", "Relationship's RelatedTo still exists in AAI, remove the relationship vf-module first."); unassignNetworkBB.errorEncountered(execution); } |
### Question:
GenericPnfCDSControllerRunnableBB implements ControllerRunnable<BuildingBlockExecution> { @Override public Boolean understand(ControllerContext<BuildingBlockExecution> controllerContext) { return PayloadConstants.CDS_ACTOR.equalsIgnoreCase(controllerContext.getControllerActor()) && PayloadConstants.PNF_SCOPE.equalsIgnoreCase(controllerContext.getControllerScope()); } @Autowired GenericPnfCDSControllerRunnableBB(AbstractCDSProcessingBBUtils abstractCDSProcessingBBUtils,
ExtractPojosForBB extractPojosForBB, ExceptionBuilder exceptionBuilder,
ConfigureInstanceParamsForPnf configureInstanceParamsForPnf); @Override Boolean understand(ControllerContext<BuildingBlockExecution> controllerContext); @Override Boolean ready(ControllerContext<BuildingBlockExecution> controllerContext); @Override void prepare(ControllerContext<BuildingBlockExecution> controllerContext); @Override void run(ControllerContext<BuildingBlockExecution> controllerContext); }### Answer:
@Test public void understandTest() { controllerContext.setControllerScope("pnf"); controllerContext.setControllerActor("cds"); assertTrue(genericPnfCDSControllerRunnableBB.understand(controllerContext)); } |
### Question:
GenericPnfCDSControllerRunnableBB implements ControllerRunnable<BuildingBlockExecution> { @Override public Boolean ready(ControllerContext<BuildingBlockExecution> controllerContext) { return true; } @Autowired GenericPnfCDSControllerRunnableBB(AbstractCDSProcessingBBUtils abstractCDSProcessingBBUtils,
ExtractPojosForBB extractPojosForBB, ExceptionBuilder exceptionBuilder,
ConfigureInstanceParamsForPnf configureInstanceParamsForPnf); @Override Boolean understand(ControllerContext<BuildingBlockExecution> controllerContext); @Override Boolean ready(ControllerContext<BuildingBlockExecution> controllerContext); @Override void prepare(ControllerContext<BuildingBlockExecution> controllerContext); @Override void run(ControllerContext<BuildingBlockExecution> controllerContext); }### Answer:
@Test public void readyTest() { assertTrue(genericPnfCDSControllerRunnableBB.ready(controllerContext)); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.