method2testcases
stringlengths
118
3.08k
### Question: MapResolverCustomizer extends CheckedLispCustomizer implements InitializingListReaderCustomizer<MapResolver, MapResolverKey, MapResolverBuilder>, AddressTranslator, JvppReplyConsumer, LispInitPathsMapper { @Override public List<MapResolverKey> getAllIds(InstanceIdentifier<MapResolver> id, ReadContext context) throws ReadFailedException { if (!lispStateCheckService.lispEnabled(context)) { LOG.debug("Failed to read {}. Lisp feature must be enabled first", id); return Collections.emptyList(); } LOG.debug("Dumping MapResolver..."); final Optional<OneMapResolverDetailsReplyDump> dumpOptional = dumpManager.getDump(id, context.getModificationCache()); if (!dumpOptional.isPresent() || dumpOptional.get().oneMapResolverDetails.isEmpty()) { return Collections.emptyList(); } return dumpOptional.get().oneMapResolverDetails.stream() .map(resolver -> new MapResolverKey( arrayToIpAddress(byteToBoolean(resolver.isIpv6), resolver.ipAddress))) .collect(Collectors.toList()); } MapResolverCustomizer(@Nonnull final FutureJVppCore futureJvpp, @Nonnull final LispStateCheckService lispStateCheckService); @Override MapResolverBuilder getBuilder(InstanceIdentifier<MapResolver> id); @Override void readCurrentAttributes(InstanceIdentifier<MapResolver> id, MapResolverBuilder builder, ReadContext ctx); @Override List<MapResolverKey> getAllIds(InstanceIdentifier<MapResolver> id, ReadContext context); @Override void merge(Builder<? extends DataObject> builder, List<MapResolver> readData); @Nonnull @Override Initialized<? extends DataObject> init(@Nonnull InstanceIdentifier<MapResolver> instanceIdentifier, @Nonnull MapResolver mapResolver, @Nonnull ReadContext readContext); }### Answer: @Test public void getAllIds() throws Exception { final List<MapResolverKey> keys = getCustomizer().getAllIds(emptyId, ctx); assertEquals(1, keys.size()); final MapResolverKey key = keys.get(0); assertNotNull(key); assertEquals("1.2.168.192", key.getIpAddress().stringValue()); }
### Question: CliInbandService implements RpcService<CliInbandInput, CliInbandOutput>, JvppReplyConsumer { @Override @Nonnull public CompletionStage<CliInbandOutput> invoke(@Nonnull final CliInbandInput input) { final CliInband request = new CliInband(); request.cmd = input.getCmd(); return jvpp.cliInband(request) .thenApply(reply -> new CliInbandOutputBuilder().setReply(reply.reply).build()); } @Inject CliInbandService(@Nonnull final FutureJVppCore jvpp); @Override @Nonnull CompletionStage<CliInbandOutput> invoke(@Nonnull final CliInbandInput input); @Nonnull @Override SchemaPath getManagedNode(); }### Answer: @Test public void testInvoke() throws Exception { initMocks(this); final String replyString = "CLI output"; final CliInbandService service = new CliInbandService(api); final CliInbandReply reply = new CliInbandReply(); reply.reply = replyString; when(api.cliInband(any())).thenReturn(future(reply)); final CliInbandInput request = new CliInbandInputBuilder().setCmd("cmd").build(); final CliInbandOutput response = service.invoke(request).toCompletableFuture().get(); assertEquals(replyString, response.getReply()); }
### Question: NamingContext implements AutoCloseable { public synchronized int getIndex(final String name, final MappingContext mappingContext) { final Optional<Mapping> read = mappingContext.read(getMappingIid(name)); checkArgument(read.isPresent(), "No mapping stored for name: %s", name); return read.get().getIndex(); } NamingContext(@Nonnull final String artificialNamePrefix, @Nonnull final String instanceName); @Nonnull synchronized String getName(final int index, @Nonnull final MappingContext mappingContext); @Nonnull synchronized Optional<String> getNameIfPresent(final int index, @Nonnull final MappingContext mappingContext); synchronized boolean containsName(final int index, @Nonnull final MappingContext mappingContext); synchronized void addName(final int index, final String name, final MappingContext mappingContext); synchronized void addName(final String name, final MappingContext mappingContext); synchronized void removeName(final String name, final MappingContext mappingContext); synchronized int getIndex(final String name, final MappingContext mappingContext); synchronized int getIndex(final String name, final MappingContext mappingContext, final Supplier<T> throwIfNonExisting); synchronized boolean containsIndex(final String name, final MappingContext mappingContext); @Override void close(); }### Answer: @Test(expected = IllegalArgumentException.class) public void getAndThrow() { when(mappingContext.read(any())).thenReturn(Optional.empty()); namingContext .getIndex("non-existing", mappingContext, () -> new IllegalArgumentException("Non existing index")); }
### Question: VppStatusListener implements KeepaliveReaderWrapper.KeepaliveFailureListener { @Override public void onKeepaliveFailure() { LOG.error("Keepalive failed. VPP is probably DOWN! Restarting Honeycomb"); this.down = true; System.exit(RESTART_ERROR_CODE); } boolean isDown(); @Override void onKeepaliveFailure(); static final int RESTART_ERROR_CODE; }### Answer: @Test public void testOnKeepaliveFailure() throws Exception { final VppStatusListener vppStatus = new VppStatusListener(); exit.expectSystemExitWithStatus(VppStatusListener.RESTART_ERROR_CODE); exit.checkAssertionAfterwards(() -> assertTrue(vppStatus.isDown())); vppStatus.onKeepaliveFailure(); }
### Question: MultiNamingContext { public synchronized String getChildName(@Nonnull final String parentName, @Nonnull final int childIndex, @Nonnull final MappingContext mappingContext) { final Optional<Mapping> read = mappingContext.read(getMappingIid(parentName)); checkState(read.isPresent(), "Mapping not present"); return read.get().getValue().stream() .filter(value -> value.getIndex().equals(childIndex)) .collect(RWUtils.singleItemCollector()).getName(); } MultiNamingContext(@Nonnull final String instanceName, final int startIndex); synchronized void addChild(@Nonnull final String parentName, final int childIndex, @Nonnull final String childName, @Nonnull final MappingContext mappingContext); synchronized void addChild(@Nonnull final String parentName, @Nonnull final String childName, @Nonnull final MappingContext mappingContext); synchronized String getChildName(@Nonnull final String parentName, @Nonnull final int childIndex, @Nonnull final MappingContext mappingContext); synchronized int getChildIndex(@Nonnull final String parentName, @Nonnull final String childName, @Nonnull final MappingContext mappingContext); synchronized void removeChild(@Nonnull final String parentName, @Nonnull final String childName, @Nonnull final MappingContext mappingContext); }### Answer: @Test public void getChildName() throws Exception { assertEquals(CHILD_1, namingContext.getChildName(PARENT_1, 1, mappingContext)); }
### Question: MultiNamingContext { public synchronized int getChildIndex(@Nonnull final String parentName, @Nonnull final String childName, @Nonnull final MappingContext mappingContext) { final Optional<Mapping> read = mappingContext.read(getMappingIid(parentName)); checkState(read.isPresent(), "Mapping not present"); return read.get().getValue().stream() .filter(value -> value.getName().equals(childName)) .collect(RWUtils.singleItemCollector()).getIndex(); } MultiNamingContext(@Nonnull final String instanceName, final int startIndex); synchronized void addChild(@Nonnull final String parentName, final int childIndex, @Nonnull final String childName, @Nonnull final MappingContext mappingContext); synchronized void addChild(@Nonnull final String parentName, @Nonnull final String childName, @Nonnull final MappingContext mappingContext); synchronized String getChildName(@Nonnull final String parentName, @Nonnull final int childIndex, @Nonnull final MappingContext mappingContext); synchronized int getChildIndex(@Nonnull final String parentName, @Nonnull final String childName, @Nonnull final MappingContext mappingContext); synchronized void removeChild(@Nonnull final String parentName, @Nonnull final String childName, @Nonnull final MappingContext mappingContext); }### Answer: @Test public void getChildIndex() throws Exception { assertEquals(1, namingContext.getChildIndex(PARENT_1, CHILD_1, mappingContext)); }
### Question: VppCommonModule extends AbstractModule { @Override protected void configure() { install(ConfigurationModule.create()); requestInjection(VppConfigAttributes.class); bind(VppStatusListener.class).toInstance(new VppStatusListener()); bind(JVppRegistry.class).toProvider(JVppRegistryProvider.class).in(Singleton.class); bind(FutureJVppCore.class).toProvider(JVppCoreProvider.class).in(Singleton.class); bind(JVppTimeoutProvider.JVppTimeoutInit.class).toProvider(JVppTimeoutProvider.class).asEagerSingleton(); final Multibinder<ReaderFactory> readerBinder = Multibinder.newSetBinder(binder(), ReaderFactory.class); readerBinder.addBinding().toProvider(ContextsReaderFactoryProvider.class).in(Singleton.class); } }### Answer: @Test public void testConfigure() throws Exception { initMocks(this); Guice.createInjector(new VppCommonModule(), BoundFieldModule.of(this)).injectMembers(this); assertThat(readerFactories, is(not(empty()))); assertEquals(15, JvppReplyConsumer.JvppReplyTimeoutHolder.getTimeout()); }
### Question: ClassifySessionValidator implements Validator<ClassifySession>, ClassifyWriter { @Override public void validateWrite(@Nonnull final InstanceIdentifier<ClassifySession> id, @Nonnull final ClassifySession session, @Nonnull final WriteContext writeContext) throws DataValidationFailedException.CreateValidationFailedException { try { validateSession(id, writeContext); } catch (RuntimeException e) { throw new DataValidationFailedException.CreateValidationFailedException(id, session, e); } } ClassifySessionValidator(@Nonnull final VppClassifierContextManager classifyTableContext, @Nonnull final NamingContext policerContext); @Override void validateWrite(@Nonnull final InstanceIdentifier<ClassifySession> id, @Nonnull final ClassifySession session, @Nonnull final WriteContext writeContext); @Override void validateDelete(@Nonnull final InstanceIdentifier<ClassifySession> id, @Nonnull final ClassifySession dataBefore, @Nonnull final WriteContext writeContext); }### Answer: @Test public void testWriteSuccessfull() throws CreateValidationFailedException { when(classifyTableContext.containsTable(eq(TABLE_NAME), any())).thenReturn(true); validator.validateWrite(ClassifySessionWriterTest.getClassifySessionId(TABLE_NAME, MATCH), session, writeContext); }
### Question: ClassifySessionValidator implements Validator<ClassifySession>, ClassifyWriter { @Override public void validateDelete(@Nonnull final InstanceIdentifier<ClassifySession> id, @Nonnull final ClassifySession dataBefore, @Nonnull final WriteContext writeContext) throws DataValidationFailedException.DeleteValidationFailedException { try { validateSession(id, writeContext); } catch (RuntimeException e) { throw new DataValidationFailedException.DeleteValidationFailedException(id, e); } } ClassifySessionValidator(@Nonnull final VppClassifierContextManager classifyTableContext, @Nonnull final NamingContext policerContext); @Override void validateWrite(@Nonnull final InstanceIdentifier<ClassifySession> id, @Nonnull final ClassifySession session, @Nonnull final WriteContext writeContext); @Override void validateDelete(@Nonnull final InstanceIdentifier<ClassifySession> id, @Nonnull final ClassifySession dataBefore, @Nonnull final WriteContext writeContext); }### Answer: @Test(expected = DeleteValidationFailedException.class) public void testDeleteFailedContextMissingTable() throws DeleteValidationFailedException { when(classifyTableContext.containsTable(eq(TABLE_NAME), any())).thenReturn(Boolean.FALSE); validator.validateDelete(ClassifySessionWriterTest.getClassifySessionId(TABLE_NAME, MATCH), session, writeContext); }
### Question: SubInterfaceAclCustomizer extends FutureJVppCustomizer implements WriterCustomizer<Ingress>, AclWriter { @Override public void writeCurrentAttributes(@Nonnull final InstanceIdentifier<Ingress> id, @Nonnull final Ingress dataAfter, @Nonnull final WriteContext writeContext) throws WriteFailedException { setAcl(true, id, dataAfter, writeContext); } SubInterfaceAclCustomizer(@Nonnull final FutureJVppCore vppApi, @Nonnull final NamingContext interfaceContext, @Nonnull final VppClassifierContextManager classifyTableContext); @Override void writeCurrentAttributes(@Nonnull final InstanceIdentifier<Ingress> id, @Nonnull final Ingress dataAfter, @Nonnull final WriteContext writeContext); @Override void updateCurrentAttributes(@Nonnull final InstanceIdentifier<Ingress> id, @Nonnull final Ingress dataBefore, @Nonnull final Ingress dataAfter, @Nonnull final WriteContext writeContext); @Override void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<Ingress> id, @Nonnull final Ingress dataBefore, @Nonnull final WriteContext writeContext); }### Answer: @Test public void testCreate() throws WriteFailedException { when(api.inputAclSetInterface(any())).thenReturn(future(new InputAclSetInterfaceReply())); customizer.writeCurrentAttributes(IID, ip4Acl(), writeContext); verify(api).inputAclSetInterface(expectedIp4AclRequest()); } @Test(expected = WriteFailedException.class) public void testCreateFailed() throws WriteFailedException { when(api.inputAclSetInterface(any())).thenReturn(failedFuture()); customizer.writeCurrentAttributes(IID, ip4Acl(), writeContext); }
### Question: SubInterfaceAclCustomizer extends FutureJVppCustomizer implements WriterCustomizer<Ingress>, AclWriter { @Override public void updateCurrentAttributes(@Nonnull final InstanceIdentifier<Ingress> id, @Nonnull final Ingress dataBefore, @Nonnull final Ingress dataAfter, @Nonnull final WriteContext writeContext) throws WriteFailedException { throw new UnsupportedOperationException("Acl update is not supported. Please delete Acl container first."); } SubInterfaceAclCustomizer(@Nonnull final FutureJVppCore vppApi, @Nonnull final NamingContext interfaceContext, @Nonnull final VppClassifierContextManager classifyTableContext); @Override void writeCurrentAttributes(@Nonnull final InstanceIdentifier<Ingress> id, @Nonnull final Ingress dataAfter, @Nonnull final WriteContext writeContext); @Override void updateCurrentAttributes(@Nonnull final InstanceIdentifier<Ingress> id, @Nonnull final Ingress dataBefore, @Nonnull final Ingress dataAfter, @Nonnull final WriteContext writeContext); @Override void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<Ingress> id, @Nonnull final Ingress dataBefore, @Nonnull final WriteContext writeContext); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testUpdate() throws WriteFailedException { customizer.updateCurrentAttributes(IID, ip4Acl(), ip6Acl(), writeContext); }
### Question: SubInterfaceAclCustomizer extends FutureJVppCustomizer implements WriterCustomizer<Ingress>, AclWriter { @Override public void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<Ingress> id, @Nonnull final Ingress dataBefore, @Nonnull final WriteContext writeContext) throws WriteFailedException { setAcl(false, id, dataBefore, writeContext); } SubInterfaceAclCustomizer(@Nonnull final FutureJVppCore vppApi, @Nonnull final NamingContext interfaceContext, @Nonnull final VppClassifierContextManager classifyTableContext); @Override void writeCurrentAttributes(@Nonnull final InstanceIdentifier<Ingress> id, @Nonnull final Ingress dataAfter, @Nonnull final WriteContext writeContext); @Override void updateCurrentAttributes(@Nonnull final InstanceIdentifier<Ingress> id, @Nonnull final Ingress dataBefore, @Nonnull final Ingress dataAfter, @Nonnull final WriteContext writeContext); @Override void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<Ingress> id, @Nonnull final Ingress dataBefore, @Nonnull final WriteContext writeContext); }### Answer: @Test public void testDelete() throws Exception { when(api.inputAclSetInterface(any())).thenReturn(future(new InputAclSetInterfaceReply())); customizer.deleteCurrentAttributes(IID, ip6Acl(), writeContext); verify(api).inputAclSetInterface(expectedIp6AclRequest()); } @Test(expected = WriteFailedException.class) public void testDeleteFailed() throws WriteFailedException { when(api.inputAclSetInterface(any())).thenReturn(failedFuture()); customizer.deleteCurrentAttributes(IID, ip4Acl(), writeContext); }
### Question: ClassifyTableValidator implements Validator<ClassifyTable>, ClassifyWriter { @Override public void validateWrite(@Nonnull final InstanceIdentifier<ClassifyTable> id, @Nonnull final ClassifyTable table, @Nonnull final WriteContext writeContext) throws CreateValidationFailedException { try { validateTable(id, table); } catch (RuntimeException e) { throw new CreateValidationFailedException(id, table, e); } } @Override void validateWrite(@Nonnull final InstanceIdentifier<ClassifyTable> id, @Nonnull final ClassifyTable table, @Nonnull final WriteContext writeContext); @Override void validateDelete(@Nonnull final InstanceIdentifier<ClassifyTable> id, @Nonnull final ClassifyTable dataBefore, @Nonnull final WriteContext writeContext); }### Answer: @Test public void testWriteSuccessfull() throws CreateValidationFailedException { ClassifyTableBuilder builder = generatePrePopulatedClassifyTableBuilder(TABLE_NAME); validator.validateWrite(tableIID, builder.build(), writeContext); } @Test(expected = CreateValidationFailedException.class) public void testWriteFailedOnEmptyNBuckets() throws CreateValidationFailedException { ClassifyTableBuilder builder = generatePrePopulatedClassifyTableBuilder(TABLE_NAME); builder.setNbuckets(null); validator.validateWrite(tableIID, builder.build(), writeContext); } @Test(expected = CreateValidationFailedException.class) public void testWriteFailedOnEmptyMemorySize() throws CreateValidationFailedException { ClassifyTableBuilder builder = generatePrePopulatedClassifyTableBuilder(TABLE_NAME); builder.setMemorySize(null); validator.validateWrite(tableIID, builder.build(), writeContext); }
### Question: ClassifyTableValidator implements Validator<ClassifyTable>, ClassifyWriter { @Override public void validateDelete(@Nonnull final InstanceIdentifier<ClassifyTable> id, @Nonnull final ClassifyTable dataBefore, @Nonnull final WriteContext writeContext) throws DeleteValidationFailedException { try { validateTable(id, dataBefore); } catch (RuntimeException e) { throw new DeleteValidationFailedException(id, e); } } @Override void validateWrite(@Nonnull final InstanceIdentifier<ClassifyTable> id, @Nonnull final ClassifyTable table, @Nonnull final WriteContext writeContext); @Override void validateDelete(@Nonnull final InstanceIdentifier<ClassifyTable> id, @Nonnull final ClassifyTable dataBefore, @Nonnull final WriteContext writeContext); }### Answer: @Test(expected = DeleteValidationFailedException.class) public void testDeleteFailedOnEmptySkipNVectors() throws DeleteValidationFailedException { ClassifyTableBuilder builder = generatePrePopulatedClassifyTableBuilder(TABLE_NAME); builder.setSkipNVectors(null); validator.validateDelete(tableIID, builder.build(), writeContext); }
### Question: ClassifySessionWriter extends VppNodeWriter implements ListWriterCustomizer<ClassifySession, ClassifySessionKey>, ByteDataTranslator, ClassifyWriter, JvppReplyConsumer { @Override public void updateCurrentAttributes(@Nonnull final InstanceIdentifier<ClassifySession> id, @Nonnull final ClassifySession dataBefore, @Nonnull final ClassifySession dataAfter, @Nonnull final WriteContext writeContext) throws WriteFailedException { throw new UnsupportedOperationException("Classify session update is not supported"); } ClassifySessionWriter(@Nonnull final FutureJVppCore futureJVppCore, @Nonnull final VppClassifierContextManager classifyTableContext, @Nonnull final NamingContext policerContext); @Override void writeCurrentAttributes(@Nonnull final InstanceIdentifier<ClassifySession> id, @Nonnull final ClassifySession dataAfter, @Nonnull final WriteContext writeContext); @Override void updateCurrentAttributes(@Nonnull final InstanceIdentifier<ClassifySession> id, @Nonnull final ClassifySession dataBefore, @Nonnull final ClassifySession dataAfter, @Nonnull final WriteContext writeContext); @Override void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<ClassifySession> id, @Nonnull final ClassifySession dataBefore, @Nonnull final WriteContext writeContext); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testUpdate() throws Exception { customizer.updateCurrentAttributes(null, null, null, writeContext); }
### Question: ClassifyTableWriter extends VppNodeWriter implements ListWriterCustomizer<ClassifyTable, ClassifyTableKey>, ByteDataTranslator, ClassifyWriter, JvppReplyConsumer { @Override public void updateCurrentAttributes(@Nonnull final InstanceIdentifier<ClassifyTable> id, @Nonnull final ClassifyTable dataBefore, @Nonnull final ClassifyTable dataAfter, @Nonnull final WriteContext writeContext) throws WriteFailedException { LOG.error("Classify table update is not supported, ignoring config"); } ClassifyTableWriter(@Nonnull final FutureJVppCore futureJVppCore, @Nonnull final VppClassifierContextManager classifyTableContext); @Override void writeCurrentAttributes(@Nonnull final InstanceIdentifier<ClassifyTable> id, @Nonnull final ClassifyTable dataAfter, @Nonnull final WriteContext writeContext); @Override void updateCurrentAttributes(@Nonnull final InstanceIdentifier<ClassifyTable> id, @Nonnull final ClassifyTable dataBefore, @Nonnull final ClassifyTable dataAfter, @Nonnull final WriteContext writeContext); @Override void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<ClassifyTable> id, @Nonnull final ClassifyTable dataBefore, @Nonnull final WriteContext writeContext); }### Answer: @Test public void testUpdate() throws Exception { final ClassifyTable classifyTableBefore = generateClassifyTable(TABLE_NAME); final InstanceIdentifier<ClassifyTable> id = getClassifyTableId(TABLE_NAME); customizer.updateCurrentAttributes(id, classifyTableBefore, new ClassifyTableBuilder().build(), writeContext); verifyZeroInteractions(api); }
### Question: VppClassifierContextManagerImpl implements VppClassifierContextManager { @Override public void addTable(final int id, @Nonnull final String name, @Nullable final VppNodeName classifierNode, @Nonnull final MappingContext ctx) { final KeyedInstanceIdentifier<ClassifyTableContext, ClassifyTableContextKey> mappingIid = getMappingIid(name); final ClassifyTableContextBuilder tableCtx = new ClassifyTableContextBuilder().setIndex(id).setName(name); if (classifierNode != null) { tableCtx.setClassifierNodeName(classifierNode.getValue()); } ctx.put(mappingIid, tableCtx.build()); } VppClassifierContextManagerImpl(@Nonnull final String artificialNamePrefix); @Override void addTable(final int id, @Nonnull final String name, @Nullable final VppNodeName classifierNode, @Nonnull final MappingContext ctx); @Override boolean containsTable(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override int getTableIndex(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override String getTableName(final int id, @Nonnull final MappingContext ctx); @Override Optional<String> getTableBaseNode(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override void removeTable(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override void addNodeName(@Nonnull final String tableName, final int nodeIndex, @Nonnull final String nodeName, @Nonnull final MappingContext ctx); @Override Optional<String> getNodeName(final int tableIndex, final int nodeIndex, @Nonnull final MappingContext ctx); }### Answer: @Test public void testAddTable() throws Exception { final String classfierNodeName = "node123"; vppClassfierContext.addTable(TABLE_ID_0, TABLE_NAME_0, new VppNodeName(classfierNodeName), ctx); verify(ctx).put(TABLE_IID_0, table(TABLE_ID_0, TABLE_NAME_0, classfierNodeName)); }
### Question: VppClassifierContextManagerImpl implements VppClassifierContextManager { @Override public boolean containsTable(@Nonnull final String name, @Nonnull final MappingContext ctx) { final Optional<ClassifyTableContext> read = ctx.read(getMappingIid(name)); return read.isPresent(); } VppClassifierContextManagerImpl(@Nonnull final String artificialNamePrefix); @Override void addTable(final int id, @Nonnull final String name, @Nullable final VppNodeName classifierNode, @Nonnull final MappingContext ctx); @Override boolean containsTable(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override int getTableIndex(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override String getTableName(final int id, @Nonnull final MappingContext ctx); @Override Optional<String> getTableBaseNode(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override void removeTable(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override void addNodeName(@Nonnull final String tableName, final int nodeIndex, @Nonnull final String nodeName, @Nonnull final MappingContext ctx); @Override Optional<String> getNodeName(final int tableIndex, final int nodeIndex, @Nonnull final MappingContext ctx); }### Answer: @Test public void testContainsTable() throws Exception { when(ctx.read(TABLE_IID_0)).thenReturn(Optional.empty()); assertFalse(vppClassfierContext.containsTable(TABLE_NAME_0, ctx)); }
### Question: VppClassifierContextManagerImpl implements VppClassifierContextManager { @Override public int getTableIndex(@Nonnull final String name, @Nonnull final MappingContext ctx) { final Optional<ClassifyTableContext> read = ctx.read(getMappingIid(name)); checkArgument(read.isPresent(), "No mapping stored for name: %s", name); return read.get().getIndex(); } VppClassifierContextManagerImpl(@Nonnull final String artificialNamePrefix); @Override void addTable(final int id, @Nonnull final String name, @Nullable final VppNodeName classifierNode, @Nonnull final MappingContext ctx); @Override boolean containsTable(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override int getTableIndex(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override String getTableName(final int id, @Nonnull final MappingContext ctx); @Override Optional<String> getTableBaseNode(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override void removeTable(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override void addNodeName(@Nonnull final String tableName, final int nodeIndex, @Nonnull final String nodeName, @Nonnull final MappingContext ctx); @Override Optional<String> getNodeName(final int tableIndex, final int nodeIndex, @Nonnull final MappingContext ctx); }### Answer: @Test public void testGetTableIndex() throws Exception { when(ctx.read(TABLE_IID_0)).thenReturn(Optional.of(table(TABLE_ID_0, TABLE_NAME_0))); assertEquals(TABLE_ID_0, vppClassfierContext.getTableIndex(TABLE_NAME_0, ctx)); }
### Question: VppClassifierContextManagerImpl implements VppClassifierContextManager { @Override public Optional<String> getTableBaseNode(@Nonnull final String name, @Nonnull final MappingContext ctx) { final Optional<ClassifyTableContext> read = ctx.read(getMappingIid(name)); if (read.isPresent()) { return Optional.ofNullable(read.get().getClassifierNodeName()); } return Optional.empty(); } VppClassifierContextManagerImpl(@Nonnull final String artificialNamePrefix); @Override void addTable(final int id, @Nonnull final String name, @Nullable final VppNodeName classifierNode, @Nonnull final MappingContext ctx); @Override boolean containsTable(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override int getTableIndex(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override String getTableName(final int id, @Nonnull final MappingContext ctx); @Override Optional<String> getTableBaseNode(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override void removeTable(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override void addNodeName(@Nonnull final String tableName, final int nodeIndex, @Nonnull final String nodeName, @Nonnull final MappingContext ctx); @Override Optional<String> getNodeName(final int tableIndex, final int nodeIndex, @Nonnull final MappingContext ctx); }### Answer: @Test public void testGetTableBaseNode() throws Exception { final String classfierNodeName = "node123"; when(ctx.read(TABLE_IID_0)).thenReturn(Optional.of(table(TABLE_ID_0, TABLE_NAME_0, classfierNodeName))); vppClassfierContext.getTableBaseNode(TABLE_NAME_0, ctx); assertEquals(Optional.of(classfierNodeName), (vppClassfierContext.getTableBaseNode(TABLE_NAME_0, ctx))); }
### Question: VppClassifierContextManagerImpl implements VppClassifierContextManager { @Override public void removeTable(@Nonnull final String name, @Nonnull final MappingContext ctx) { ctx.delete(getMappingIid(name)); } VppClassifierContextManagerImpl(@Nonnull final String artificialNamePrefix); @Override void addTable(final int id, @Nonnull final String name, @Nullable final VppNodeName classifierNode, @Nonnull final MappingContext ctx); @Override boolean containsTable(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override int getTableIndex(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override String getTableName(final int id, @Nonnull final MappingContext ctx); @Override Optional<String> getTableBaseNode(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override void removeTable(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override void addNodeName(@Nonnull final String tableName, final int nodeIndex, @Nonnull final String nodeName, @Nonnull final MappingContext ctx); @Override Optional<String> getNodeName(final int tableIndex, final int nodeIndex, @Nonnull final MappingContext ctx); }### Answer: @Test public void testRemoveTable() throws Exception { vppClassfierContext.removeTable(TABLE_NAME_0, ctx); verify(ctx).delete(TABLE_IID_0); }
### Question: VppClassifierContextManagerImpl implements VppClassifierContextManager { @Override public void addNodeName(@Nonnull final String tableName, final int nodeIndex, @Nonnull final String nodeName, @Nonnull final MappingContext ctx) { final KeyedInstanceIdentifier<NodeContext, NodeContextKey> iid = getMappingIid(tableName).child(NodeContext.class, new NodeContextKey(nodeName)); ctx.put(iid, new NodeContextBuilder().setName(nodeName).setIndex(nodeIndex).build()); } VppClassifierContextManagerImpl(@Nonnull final String artificialNamePrefix); @Override void addTable(final int id, @Nonnull final String name, @Nullable final VppNodeName classifierNode, @Nonnull final MappingContext ctx); @Override boolean containsTable(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override int getTableIndex(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override String getTableName(final int id, @Nonnull final MappingContext ctx); @Override Optional<String> getTableBaseNode(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override void removeTable(@Nonnull final String name, @Nonnull final MappingContext ctx); @Override void addNodeName(@Nonnull final String tableName, final int nodeIndex, @Nonnull final String nodeName, @Nonnull final MappingContext ctx); @Override Optional<String> getNodeName(final int tableIndex, final int nodeIndex, @Nonnull final MappingContext ctx); }### Answer: @Test public void testAddNodeName() throws Exception { final String nodeName = "node123"; final int nodeIndex = 1; vppClassfierContext.addNodeName(TABLE_NAME_0, nodeIndex, nodeName, ctx); verify(ctx).put( TABLE_IID_0.child(NodeContext.class, new NodeContextKey(nodeName)), node(nodeName, nodeIndex) ); }
### Question: PolicerValidator implements Validator<Policer> { @Override public void validateWrite(@Nonnull final InstanceIdentifier<Policer> id, @Nonnull final Policer policer, @Nonnull final WriteContext writeContext) throws DataValidationFailedException.CreateValidationFailedException { try { validatePolicer(policer); } catch (RuntimeException e) { throw new DataValidationFailedException.CreateValidationFailedException(id, policer, e); } } PolicerValidator(final NamingContext policerContext); @Override void validateWrite(@Nonnull final InstanceIdentifier<Policer> id, @Nonnull final Policer policer, @Nonnull final WriteContext writeContext); @Override void validateDelete(@Nonnull final InstanceIdentifier<Policer> id, @Nonnull final Policer policer, @Nonnull final WriteContext writeContext); }### Answer: @Test public void testWriteSuccessfull() throws CreateValidationFailedException { PolicerBuilder builder = generatePrePopulatedPolicerBuilder(); validator.validateWrite(POLICER_IID, builder.build(), writeContext); } @Test(expected = CreateValidationFailedException.class) public void testWriteFailedDscp() throws CreateValidationFailedException { PolicerBuilder builder = generatePrePopulatedPolicerBuilder(); builder.setConformAction(generateConformAction(true, MeterActionDrop.class)); validator.validateWrite(POLICER_IID, builder.build(), writeContext); }
### Question: PolicerValidator implements Validator<Policer> { @Override public void validateDelete(@Nonnull final InstanceIdentifier<Policer> id, @Nonnull final Policer policer, @Nonnull final WriteContext writeContext) throws DataValidationFailedException.DeleteValidationFailedException { try { validatePolicer(policer); } catch (RuntimeException e) { throw new DataValidationFailedException.DeleteValidationFailedException(id, e); } } PolicerValidator(final NamingContext policerContext); @Override void validateWrite(@Nonnull final InstanceIdentifier<Policer> id, @Nonnull final Policer policer, @Nonnull final WriteContext writeContext); @Override void validateDelete(@Nonnull final InstanceIdentifier<Policer> id, @Nonnull final Policer policer, @Nonnull final WriteContext writeContext); }### Answer: @Test(expected = DeleteValidationFailedException.class) public void testDeleteFailedDscp() throws DeleteValidationFailedException { PolicerBuilder builder = generatePrePopulatedPolicerBuilder(); builder.setExceedAction(generateExceedAction(true, MeterActionTransmit.class)); validator.validateDelete(POLICER_IID, builder.build(), writeContext); }
### Question: Ikev2PolicyCustomizer extends FutureJVppIkev2Customizer implements ListWriterCustomizer<Policy, PolicyKey>, JvppReplyConsumer, ByteDataTranslator, Ipv4Translator { @Override public void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<Policy> id, @Nonnull final Policy dataBefore, @Nonnull final WriteContext writeContext) throws WriteFailedException { final Ikev2ProfileAddDel request = new Ikev2ProfileAddDel(); request.isAdd = BYTE_FALSE; request.name = dataBefore.getName().getBytes(); getReplyForWrite(getjVppIkev2Facade().ikev2ProfileAddDel(request).toCompletableFuture(), id); } Ikev2PolicyCustomizer(final FutureJVppIkev2Facade vppApi); @Override void writeCurrentAttributes(@Nonnull final InstanceIdentifier<Policy> id, @Nonnull final Policy dataAfter, @Nonnull final WriteContext writeContext); @Override void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<Policy> id, @Nonnull final Policy dataBefore, @Nonnull final WriteContext writeContext); @Override void updateCurrentAttributes(@Nonnull final InstanceIdentifier<Policy> id, @Nonnull final Policy dataBefore, @Nonnull final Policy dataAfter, @Nonnull final WriteContext writeContext); }### Answer: @Test public void testDelete(@InjectTestData(resourcePath = "/ikev2/addIkev2Profile.json", id = IKEV2_PATH) Ikev2 ikev2) throws WriteFailedException { Policy policy = ikev2.getPolicy().get(0); customizer.deleteCurrentAttributes(getId(policy.getName()), policy, writeContext); final Ikev2ProfileAddDel request = new Ikev2ProfileAddDel(); request.name = policy.getName().getBytes(); request.isAdd = BYTE_FALSE; verify(ikev2api).ikev2ProfileAddDel(request); verify(ikev2api, times(0)).ikev2ProfileSetTs(any()); verify(ikev2api, times(0)).ikev2ProfileSetAuth(any()); }
### Question: IpsecSadEntryCustomizer extends FutureJVppCustomizer implements ListWriterCustomizer<SadEntries, SadEntriesKey>, JvppReplyConsumer, ByteDataTranslator, Ipv6Translator, Ipv4Translator { @Override public void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<SadEntries> id, @Nonnull final SadEntries dataBefore, @Nonnull final WriteContext writeContext) throws WriteFailedException { addDelEntry(id, dataBefore, writeContext, false); } IpsecSadEntryCustomizer(final FutureJVppCore vppApi); @Override void writeCurrentAttributes(@Nonnull final InstanceIdentifier<SadEntries> id, @Nonnull final SadEntries dataAfter, @Nonnull final WriteContext writeContext); @Override void updateCurrentAttributes(@Nonnull final InstanceIdentifier<SadEntries> id, @Nonnull final SadEntries dataBefore, @Nonnull final SadEntries dataAfter, @Nonnull final WriteContext writeContext); @Override void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<SadEntries> id, @Nonnull final SadEntries dataBefore, @Nonnull final WriteContext writeContext); }### Answer: @Test public void testDelete(@InjectTestData(resourcePath = "/sadEntries/delSadEntry.json", id = SAD_PATH) Sad sad) throws WriteFailedException { final SadEntries data = sad.getSadEntries().get(0); final Long spi = data.getSpi(); customizer.deleteCurrentAttributes(getId(IpsecTrafficDirection.Outbound, spi), data, writeContext); final IpsecSadEntryAddDel request = new IpsecSadEntryAddDel(); request.isAdd = BYTE_FALSE; request.entry = new IpsecSadEntry(); request.entry.spi = SPI_1002; request.entry.sadId = SAD_ID; request.entry.flags = new IpsecSadFlags(); verify(api).ipsecSadEntryAddDel(request); }
### Question: AclValidator implements Validator<Acl>, AclDataExtractor { @Override public void validateWrite(final InstanceIdentifier<Acl> id, final Acl dataAfter, final WriteContext ctx) throws CreateValidationFailedException { try { validateAcl(dataAfter); } catch (RuntimeException e) { throw new CreateValidationFailedException(id, dataAfter, e); } } @Override void validateWrite(final InstanceIdentifier<Acl> id, final Acl dataAfter, final WriteContext ctx); @Override void validateUpdate(final InstanceIdentifier<Acl> id, final Acl dataBefore, final Acl dataAfter, final WriteContext ctx); @Override void validateDelete(final InstanceIdentifier<Acl> id, final Acl dataBefore, final WriteContext ctx); }### Answer: @Test public void testValidateWrite( @InjectTestData(resourcePath = "/acl/standard/standard-acl-icmp.json") Acls acls) throws DataValidationFailedException.CreateValidationFailedException { validator.validateWrite(ID, acls.getAcl().get(0), writeContext); } @Test(expected = DataValidationFailedException.CreateValidationFailedException.class) public void testValidateWriteEmptyAcl() throws DataValidationFailedException.CreateValidationFailedException { validator.validateWrite(ID, new AclBuilder().build(), writeContext); }
### Question: Ikev2PolicyIdentityCustomizer extends FutureJVppIkev2Customizer implements WriterCustomizer<Identity>, JvppReplyConsumer, ByteDataTranslator, Ipv4Translator, Ipv6Translator { @Override public void updateCurrentAttributes(@Nonnull final InstanceIdentifier<Identity> id, @Nonnull final Identity dataBefore, @Nonnull final Identity dataAfter, @Nonnull final WriteContext writeContext) throws WriteFailedException { writeCurrentAttributes(id, dataAfter, writeContext); } Ikev2PolicyIdentityCustomizer(final FutureJVppIkev2Facade vppApi); @Override void writeCurrentAttributes(@Nonnull final InstanceIdentifier<Identity> id, @Nonnull final Identity dataAfter, @Nonnull final WriteContext writeContext); @Override void updateCurrentAttributes(@Nonnull final InstanceIdentifier<Identity> id, @Nonnull final Identity dataBefore, @Nonnull final Identity dataAfter, @Nonnull final WriteContext writeContext); @Override void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<Identity> id, @Nonnull final Identity dataBefore, @Nonnull final WriteContext writeContext); }### Answer: @Test public void testUpdate( @InjectTestData(resourcePath = "/ikev2/identity/identity_local_ipv4.json", id = IDENTITY_PATH) Identity before, @InjectTestData(resourcePath = "/ikev2/identity/identity_local_rfc822.json", id = IDENTITY_PATH) Identity after) throws WriteFailedException { customizer.updateCurrentAttributes(getId(), before, after, writeContext); Ikev2ProfileSetId request = new Ikev2ProfileSetId(); request.name = POLICY_NAME.getBytes(); request.idType = (byte) 3; request.isLocal = BYTE_TRUE; request.data = RFC822_TYPE_DATA.getBytes(); request.dataLen = request.data.length; verify(ikev2api).ikev2ProfileSetId(request); }
### Question: IpsecSpdCustomizer extends FutureJVppCustomizer implements ListWriterCustomizer<Spd, SpdKey>, JvppReplyConsumer, ByteDataTranslator, Ipv6Translator, Ipv4Translator { @Override public void updateCurrentAttributes(@Nonnull final InstanceIdentifier<Spd> id, @Nonnull final Spd dataBefore, @Nonnull final Spd dataAfter, @Nonnull final WriteContext writeContext) throws WriteFailedException { if (dataAfter.getSpdEntries() != null) { for (SpdEntries entry : dataAfter.getSpdEntries()) { addSpdEntry(id, dataAfter.getSpdId(), entry); } } } IpsecSpdCustomizer(final FutureJVppCore vppApi); @Override void writeCurrentAttributes(@Nonnull final InstanceIdentifier<Spd> id, @Nonnull final Spd dataAfter, @Nonnull final WriteContext writeContext); @Override void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<Spd> id, @Nonnull final Spd dataBefore, @Nonnull final WriteContext writeContext); @Override void updateCurrentAttributes(@Nonnull final InstanceIdentifier<Spd> id, @Nonnull final Spd dataBefore, @Nonnull final Spd dataAfter, @Nonnull final WriteContext writeContext); }### Answer: @Test public void testUpdate( @InjectTestData(resourcePath = "/spdEntries/addDelSpd_before.json", id = IPSEC_PATH) Ipsec ipsecBefore, @InjectTestData(resourcePath = "/spdEntries/addDelSpd_after.json", id = IPSEC_PATH) Ipsec ipsecAfter) throws WriteFailedException { Spd before = ipsecBefore.getSpd().get(0); Spd after = ipsecAfter.getSpd().get(0); customizer.updateCurrentAttributes(getSpdId(SPD_ID), before, after, writeContext); verify(api).ipsecSpdEntryAddDel(translateSpdEntry(after.getSpdEntries().get(0), SPD_ID, true)); }
### Question: IpsecSpdCustomizer extends FutureJVppCustomizer implements ListWriterCustomizer<Spd, SpdKey>, JvppReplyConsumer, ByteDataTranslator, Ipv6Translator, Ipv4Translator { @Override public void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<Spd> id, @Nonnull final Spd dataBefore, @Nonnull final WriteContext writeContext) throws WriteFailedException { IpsecSpdAddDel spdDelete = new IpsecSpdAddDel(); spdDelete.isAdd = ByteDataTranslator.BYTE_FALSE; spdDelete.spdId = dataBefore.getSpdId(); getReplyForWrite(getFutureJVpp().ipsecSpdAddDel(spdDelete).toCompletableFuture(), id); } IpsecSpdCustomizer(final FutureJVppCore vppApi); @Override void writeCurrentAttributes(@Nonnull final InstanceIdentifier<Spd> id, @Nonnull final Spd dataAfter, @Nonnull final WriteContext writeContext); @Override void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<Spd> id, @Nonnull final Spd dataBefore, @Nonnull final WriteContext writeContext); @Override void updateCurrentAttributes(@Nonnull final InstanceIdentifier<Spd> id, @Nonnull final Spd dataBefore, @Nonnull final Spd dataAfter, @Nonnull final WriteContext writeContext); }### Answer: @Test public void testDelete() throws WriteFailedException { SpdBuilder spdBuilder = new SpdBuilder(); spdBuilder.setSpdId(SPD_ID) .withKey(new SpdKey(SPD_ID)) .setSpdEntries(Collections.singletonList(new SpdEntriesBuilder().build())); customizer.deleteCurrentAttributes(getSpdId(SPD_ID), spdBuilder.build(), writeContext); IpsecSpdAddDel request = new IpsecSpdAddDel(); request.spdId = SPD_ID; request.isAdd = BYTE_FALSE; verify(api).ipsecSpdAddDel(request); }
### Question: IpsecStateCustomizer extends FutureJVppCustomizer implements JvppReplyConsumer, InitializingReaderCustomizer<IpsecState, IpsecStateBuilder>, Ipv4Translator, Ipv6Translator { @Override public void merge(@Nonnull final Builder<? extends DataObject> parentBuilder, @Nonnull final IpsecState readValue) { IpsecStateBuilder ipsecParentBuilder = (IpsecStateBuilder) parentBuilder; ipsecParentBuilder.setHoldDown(readValue.getHoldDown()) .setPolicy(readValue.getPolicy()) .setProposal(readValue.getProposal()) .setRedundancy(readValue.getRedundancy()) .setSa(readValue.getSa()) .addAugmentation(IpsecStateSpdAugmentation.class, readValue.augmentation(IpsecStateSpdAugmentation.class)); } IpsecStateCustomizer(final FutureJVppCore vppApi); @Nonnull @Override Initialized<? extends DataObject> init(@Nonnull final InstanceIdentifier<IpsecState> id, @Nonnull final IpsecState readValue, @Nonnull final ReadContext ctx); @Nonnull @Override IpsecStateBuilder getBuilder(@Nonnull final InstanceIdentifier<IpsecState> id); @Override void readCurrentAttributes(@Nonnull final InstanceIdentifier<IpsecState> id, @Nonnull final IpsecStateBuilder builder, @Nonnull final ReadContext ctx); @Override void merge(@Nonnull final Builder<? extends DataObject> parentBuilder, @Nonnull final IpsecState readValue); }### Answer: @Test public void testMerge() { final IpsecStateBuilder parentBuilder = new IpsecStateBuilder(); final IpsecStateBuilder builderForNewdata = new IpsecStateBuilder(); builderForNewdata.setHoldDown((long) HOLD_DOWN); getCustomizer().merge(parentBuilder, builderForNewdata.build()); assertEquals(parentBuilder.getHoldDown().intValue(), HOLD_DOWN); }
### Question: IpsecStateSpdCustomizer extends FutureJVppCustomizer implements JvppReplyConsumer, InitializingListReaderCustomizer<Spd, SpdKey, SpdBuilder>, Ipv4Translator, Ipv6Translator { @Override public void merge(@Nonnull final Builder<? extends DataObject> builder, @Nonnull final List<Spd> readData) { ((IpsecStateSpdAugmentationBuilder) builder).setSpd(readData); } IpsecStateSpdCustomizer(final FutureJVppCore vppApi); @Nonnull @Override Initialized<? extends DataObject> init(@Nonnull final InstanceIdentifier<Spd> id, @Nonnull final Spd readValue, @Nonnull final ReadContext ctx); @Nonnull @Override SpdBuilder getBuilder(@Nonnull final InstanceIdentifier<Spd> id); @Override void readCurrentAttributes(@Nonnull final InstanceIdentifier<Spd> id, @Nonnull final SpdBuilder builder, @Nonnull final ReadContext ctx); @Nonnull @Override List<SpdKey> getAllIds(@Nonnull final InstanceIdentifier<Spd> id, @Nonnull final ReadContext context); @Override void merge(@Nonnull final Builder<? extends DataObject> builder, @Nonnull final List<Spd> readData); }### Answer: @Test public void testMerge() throws Exception { final IpsecStateSpdAugmentationBuilder parentBuilder = new IpsecStateSpdAugmentationBuilder(); final IpsecStateSpdAugmentationBuilder builderForNewData = new IpsecStateSpdAugmentationBuilder(); SpdBuilder spdBuilder = new SpdBuilder(); spdBuilder.setSpdId(SPD_ID); getCustomizer().merge(parentBuilder, spdBuilder.build()); assertEquals(parentBuilder.getSpd().size(), 1); assertEquals(parentBuilder.getSpd().get(0).getSpdId().intValue(), SPD_ID); }
### Question: DhcpRelayValidator implements Validator<Relay> { @Override public void validateWrite(@Nonnull final InstanceIdentifier<Relay> id, @Nonnull final Relay relay, @Nonnull final WriteContext writeContext) throws CreateValidationFailedException { try { validateRelay(relay); } catch (RuntimeException e) { throw new CreateValidationFailedException(id, relay, e); } } @Override void validateWrite(@Nonnull final InstanceIdentifier<Relay> id, @Nonnull final Relay relay, @Nonnull final WriteContext writeContext); @Override void validateUpdate(@Nonnull final InstanceIdentifier<Relay> id, @Nonnull final Relay dataBefore, @Nonnull final Relay dataAfter, @Nonnull final WriteContext writeContext); @Override void validateDelete(@Nonnull final InstanceIdentifier<Relay> id, @Nonnull final Relay dataBefore, @Nonnull final WriteContext writeContext); }### Answer: @Test public void testWrite(@InjectTestData(resourcePath = "/relay/ipv4DhcpRelay.json", id = RELAYS_PATH) Relays relays) throws DataValidationFailedException.CreateValidationFailedException { final int rxVrfId = 0; validator.validateWrite(getId(rxVrfId, Ipv4.class), extractRelay(relays), writeContext); }
### Question: DhcpRelayValidator implements Validator<Relay> { @Override public void validateUpdate(@Nonnull final InstanceIdentifier<Relay> id, @Nonnull final Relay dataBefore, @Nonnull final Relay dataAfter, @Nonnull final WriteContext writeContext) throws UpdateValidationFailedException { try { validateRelay(dataBefore); validateRelay(dataAfter); } catch (RuntimeException e) { throw new UpdateValidationFailedException(id, dataBefore, dataAfter, e); } } @Override void validateWrite(@Nonnull final InstanceIdentifier<Relay> id, @Nonnull final Relay relay, @Nonnull final WriteContext writeContext); @Override void validateUpdate(@Nonnull final InstanceIdentifier<Relay> id, @Nonnull final Relay dataBefore, @Nonnull final Relay dataAfter, @Nonnull final WriteContext writeContext); @Override void validateDelete(@Nonnull final InstanceIdentifier<Relay> id, @Nonnull final Relay dataBefore, @Nonnull final WriteContext writeContext); }### Answer: @Test public void testUpdate( @InjectTestData(resourcePath = "/relay/ipv6DhcpRelayBefore.json", id = RELAYS_PATH) Relays relaysBefore, @InjectTestData(resourcePath = "/relay/ipv6DhcpRelayAfter.json", id = RELAYS_PATH) Relays relayAfter) throws DataValidationFailedException.UpdateValidationFailedException { final int rxVrfId = 1; validator.validateUpdate(getId(rxVrfId, Ipv6.class), extractRelay(relaysBefore), extractRelay(relayAfter), writeContext); }
### Question: DhcpRelayValidator implements Validator<Relay> { @Override public void validateDelete(@Nonnull final InstanceIdentifier<Relay> id, @Nonnull final Relay dataBefore, @Nonnull final WriteContext writeContext) throws DeleteValidationFailedException { try { validateRelay(dataBefore); } catch (RuntimeException e) { throw new DeleteValidationFailedException(id, e); } } @Override void validateWrite(@Nonnull final InstanceIdentifier<Relay> id, @Nonnull final Relay relay, @Nonnull final WriteContext writeContext); @Override void validateUpdate(@Nonnull final InstanceIdentifier<Relay> id, @Nonnull final Relay dataBefore, @Nonnull final Relay dataAfter, @Nonnull final WriteContext writeContext); @Override void validateDelete(@Nonnull final InstanceIdentifier<Relay> id, @Nonnull final Relay dataBefore, @Nonnull final WriteContext writeContext); }### Answer: @Test public void testDelete(@InjectTestData(resourcePath = "/relay/ipv4DhcpRelay.json", id = RELAYS_PATH) Relays relays) throws DataValidationFailedException.DeleteValidationFailedException { final int rxVrfId = 0; validator.validateDelete(getId(rxVrfId, Ipv4.class), extractRelay(relays), writeContext); }
### Question: DhcpRelayValidator implements Validator<Relay> { @VisibleForTesting void validateRelay(final Relay relay) { final boolean isIpv6 = Ipv6.class == relay.getAddressFamily(); try { isAddressCorrect(relay.getGatewayAddress(), isIpv6); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("Gateway address validation error: %s", e.getMessage())); } checkArgument(relay.getServer() != null && !relay.getServer().isEmpty(), "At least one DHCP server needs to be configured"); for (final Server server : relay.getServer()) { validateServer(server, isIpv6); } } @Override void validateWrite(@Nonnull final InstanceIdentifier<Relay> id, @Nonnull final Relay relay, @Nonnull final WriteContext writeContext); @Override void validateUpdate(@Nonnull final InstanceIdentifier<Relay> id, @Nonnull final Relay dataBefore, @Nonnull final Relay dataAfter, @Nonnull final WriteContext writeContext); @Override void validateDelete(@Nonnull final InstanceIdentifier<Relay> id, @Nonnull final Relay dataBefore, @Nonnull final WriteContext writeContext); }### Answer: @Test(expected = IllegalArgumentException.class) public void testMixedIpAddressFamilies( @InjectTestData(resourcePath = "/relay/ipv4DhcpRelay.json", id = RELAYS_PATH) Relays relays) { RelayBuilder builder = new RelayBuilder(); builder.fieldsFrom(extractRelay(relays)); builder.setGatewayAddress(IpAddressNoZoneBuilder.getDefaultInstance("2001::10")); validator.validateRelay(builder.build()); }
### Question: DhcpRelayCustomizer extends FutureJVppCustomizer implements InitializingListReaderCustomizer<Relay, RelayKey, RelayBuilder>, JvppReplyConsumer, ByteDataTranslator, Ipv6Translator, Ipv4Translator { @Nonnull @Override public Initialized<? extends DataObject> init(@Nonnull final InstanceIdentifier<Relay> id, @Nonnull final Relay readValue, @Nonnull final ReadContext ctx) { return Initialized.create(id, readValue); } DhcpRelayCustomizer(final FutureJVppCore vppApi); @Nonnull @Override List<RelayKey> getAllIds(@Nonnull final InstanceIdentifier<Relay> id, @Nonnull final ReadContext context); @Override void merge(@Nonnull final Builder<? extends DataObject> builder, @Nonnull final List<Relay> readData); @Nonnull @Override RelayBuilder getBuilder(@Nonnull final InstanceIdentifier<Relay> id); @Override void readCurrentAttributes(@Nonnull final InstanceIdentifier<Relay> id, @Nonnull final RelayBuilder builder, @Nonnull final ReadContext ctx); @Nonnull @Override Initialized<? extends DataObject> init(@Nonnull final InstanceIdentifier<Relay> id, @Nonnull final Relay readValue, @Nonnull final ReadContext ctx); }### Answer: @Test public void testInit() { final Relay data = new RelayBuilder().build(); invokeInitTest(IP4_IID, data, IP4_IID, data); }
### Question: AclValidator implements Validator<Acl>, AclDataExtractor { @Override public void validateUpdate(final InstanceIdentifier<Acl> id, final Acl dataBefore, final Acl dataAfter, final WriteContext ctx) throws UpdateValidationFailedException { try { validateAcl(dataAfter); } catch (RuntimeException e) { throw new UpdateValidationFailedException(id, dataBefore, dataAfter, e); } } @Override void validateWrite(final InstanceIdentifier<Acl> id, final Acl dataAfter, final WriteContext ctx); @Override void validateUpdate(final InstanceIdentifier<Acl> id, final Acl dataBefore, final Acl dataAfter, final WriteContext ctx); @Override void validateDelete(final InstanceIdentifier<Acl> id, final Acl dataBefore, final WriteContext ctx); }### Answer: @Test public void testValidateUpdate( @InjectTestData(resourcePath = "/acl/standard/standard-acl-icmp.json") Acls acls) throws DataValidationFailedException.UpdateValidationFailedException { final Acl data = acls.getAcl().get(0); validator.validateUpdate(ID, data, data, writeContext); } @Test(expected = DataValidationFailedException.UpdateValidationFailedException.class) public void testValidateUpdateUnsupportedType( @InjectTestData(resourcePath = "/acl/ipv4/ipv4-acl.json") Acls acls) throws DataValidationFailedException.UpdateValidationFailedException { final Acl data = acls.getAcl().get(0); validator.validateUpdate(ID, data, data, writeContext); }
### Question: BgpPrefixSidMplsWriter implements RouteWriter<LabeledUnicastRoute>, MplsRouteRequestProducer, IpRouteRequestProducer, JvppReplyConsumer { @Override public void update(@Nonnull final InstanceIdentifier<LabeledUnicastRoute> id, @Nonnull final LabeledUnicastRoute routeBefore, @Nonnull final LabeledUnicastRoute routeAfter) throws WriteFailedException.UpdateFailedException { throw new WriteFailedException.UpdateFailedException(id, routeBefore, routeAfter, new UnsupportedOperationException("Operation not supported")); } BgpPrefixSidMplsWriter(@Nonnull final FutureJVppCore vppApi); @Override void create(@Nonnull final InstanceIdentifier<LabeledUnicastRoute> id, @Nonnull final LabeledUnicastRoute route); @Override void delete(@Nonnull final InstanceIdentifier<LabeledUnicastRoute> id, @Nonnull final LabeledUnicastRoute route); @Override void update(@Nonnull final InstanceIdentifier<LabeledUnicastRoute> id, @Nonnull final LabeledUnicastRoute routeBefore, @Nonnull final LabeledUnicastRoute routeAfter); @Nonnull @Override InstanceIdentifier<LabeledUnicastRoute> getManagedDataObjectType(); }### Answer: @Test(expected = WriteFailedException.UpdateFailedException.class) public void testUpdate() throws WriteFailedException.UpdateFailedException { final String routeKey = "route-key"; final PathId pathId = new PathId(123L); writer.update(id(pathId, routeKey), mock(LabeledUnicastRoute.class), mock(LabeledUnicastRoute.class)); verifyZeroInteractions(vppApi); }
### Question: Ipv4Writer implements RouteWriter<Ipv4Route>, Ipv4Translator, JvppReplyConsumer, RouteRequestProducer { @Override public void create(@Nonnull final InstanceIdentifier<Ipv4Route> id, @Nonnull final Ipv4Route route) throws WriteFailedException.CreateFailedException { final IpAddDelRoute request = request(route, true); LOG.debug("Translating id={}, route={} to {}", id, route, request); getReplyForCreate(vppApi.ipAddDelRoute(request).toCompletableFuture(), id, route); LOG.debug("VPP FIB updated successfully (added id={}).", id); } Ipv4Writer(@Nonnull final FutureJVppCore vppApi); @Override void create(@Nonnull final InstanceIdentifier<Ipv4Route> id, @Nonnull final Ipv4Route route); @Override void delete(@Nonnull final InstanceIdentifier<Ipv4Route> id, @Nonnull final Ipv4Route route); @Override void update(@Nonnull final InstanceIdentifier<Ipv4Route> id, @Nonnull final Ipv4Route routeBefore, @Nonnull final Ipv4Route routeAfter); @Nonnull @Override InstanceIdentifier<Ipv4Route> getManagedDataObjectType(); }### Answer: @Test public void testCreate() throws WriteFailedException.CreateFailedException { final Ipv4Prefix destination = new Ipv4Prefix("1.2.3.4/24"); final PathId pathId = new PathId(123L); final Ipv4Address nextHopAddress = new Ipv4AddressNoZone("5.6.7.8"); writer.create( id(destination, pathId), route(destination, pathId, nextHopAddress) ); verifyRequest(true); }
### Question: Ipv4Writer implements RouteWriter<Ipv4Route>, Ipv4Translator, JvppReplyConsumer, RouteRequestProducer { @Override public void delete(@Nonnull final InstanceIdentifier<Ipv4Route> id, @Nonnull final Ipv4Route route) throws WriteFailedException.DeleteFailedException { LOG.debug("Removing id={}, route={}", id, route); getReplyForDelete(vppApi.ipAddDelRoute(request(route, false)).toCompletableFuture(), id); LOG.debug("VPP FIB updated successfully (removed id={}).", id); } Ipv4Writer(@Nonnull final FutureJVppCore vppApi); @Override void create(@Nonnull final InstanceIdentifier<Ipv4Route> id, @Nonnull final Ipv4Route route); @Override void delete(@Nonnull final InstanceIdentifier<Ipv4Route> id, @Nonnull final Ipv4Route route); @Override void update(@Nonnull final InstanceIdentifier<Ipv4Route> id, @Nonnull final Ipv4Route routeBefore, @Nonnull final Ipv4Route routeAfter); @Nonnull @Override InstanceIdentifier<Ipv4Route> getManagedDataObjectType(); }### Answer: @Test public void testDelete() throws WriteFailedException.DeleteFailedException { final Ipv4Prefix destination = new Ipv4Prefix("1.2.3.4/24"); final PathId pathId = new PathId(456L); final Ipv4Address nextHopAddress = new Ipv4AddressNoZone("5.6.7.8"); writer.delete( id(destination, pathId), route(destination, pathId, nextHopAddress) ); verifyRequest(false); }
### Question: Ipv4Writer implements RouteWriter<Ipv4Route>, Ipv4Translator, JvppReplyConsumer, RouteRequestProducer { @Override public void update(@Nonnull final InstanceIdentifier<Ipv4Route> id, @Nonnull final Ipv4Route routeBefore, @Nonnull final Ipv4Route routeAfter) throws WriteFailedException.UpdateFailedException { throw new WriteFailedException.UpdateFailedException(id, routeBefore, routeAfter, new UnsupportedOperationException("Operation not supported")); } Ipv4Writer(@Nonnull final FutureJVppCore vppApi); @Override void create(@Nonnull final InstanceIdentifier<Ipv4Route> id, @Nonnull final Ipv4Route route); @Override void delete(@Nonnull final InstanceIdentifier<Ipv4Route> id, @Nonnull final Ipv4Route route); @Override void update(@Nonnull final InstanceIdentifier<Ipv4Route> id, @Nonnull final Ipv4Route routeBefore, @Nonnull final Ipv4Route routeAfter); @Nonnull @Override InstanceIdentifier<Ipv4Route> getManagedDataObjectType(); }### Answer: @Test(expected = WriteFailedException.UpdateFailedException.class) public void testUpdate() throws WriteFailedException.UpdateFailedException { final Ipv4Prefix destination = new Ipv4Prefix("10.1.0.1/28"); final PathId pathId = new PathId(456L); writer.update(id(destination, pathId), mock(Ipv4Route.class), mock(Ipv4Route.class)); }
### Question: Ipv6Writer implements RouteWriter<Ipv6Route>, Ipv6Translator, JvppReplyConsumer, RouteRequestProducer { @Override public void create(@Nonnull final InstanceIdentifier<Ipv6Route> id, @Nonnull final Ipv6Route route) throws WriteFailedException.CreateFailedException { final IpAddDelRoute request = request(route, true); LOG.debug("Translating id={}, route={} to {}", id, route, request); getReplyForCreate(vppApi.ipAddDelRoute(request).toCompletableFuture(), id, route); LOG.debug("VPP FIB updated successfully (added id={}).", id); } Ipv6Writer(@Nonnull final FutureJVppCore vppApi); @Override void create(@Nonnull final InstanceIdentifier<Ipv6Route> id, @Nonnull final Ipv6Route route); @Override void delete(@Nonnull final InstanceIdentifier<Ipv6Route> id, @Nonnull final Ipv6Route route); @Override void update(@Nonnull final InstanceIdentifier<Ipv6Route> id, @Nonnull final Ipv6Route routeBefore, @Nonnull final Ipv6Route routeAfter); @Nonnull @Override InstanceIdentifier<Ipv6Route> getManagedDataObjectType(); }### Answer: @Test public void testCreate() throws WriteFailedException.CreateFailedException { final Ipv6Prefix destination = new Ipv6Prefix("2001:db8:a0b:12f0:0:0:0:1/64"); final PathId pathId = new PathId(123L); final Ipv6Address nextHopAddress = new Ipv6AddressNoZone("2001:db8:a0b:12f0:0:0:0:2"); writer.create( id(destination, pathId), route(destination, pathId, nextHopAddress) ); verifyRequest(true); }
### Question: Ipv6Writer implements RouteWriter<Ipv6Route>, Ipv6Translator, JvppReplyConsumer, RouteRequestProducer { @Override public void delete(@Nonnull final InstanceIdentifier<Ipv6Route> id, @Nonnull final Ipv6Route route) throws WriteFailedException.DeleteFailedException { LOG.debug("Removing id={}, route={}", id, route); getReplyForDelete(vppApi.ipAddDelRoute(request(route, false)).toCompletableFuture(), id); LOG.debug("VPP FIB updated successfully (removed id={}).", id); } Ipv6Writer(@Nonnull final FutureJVppCore vppApi); @Override void create(@Nonnull final InstanceIdentifier<Ipv6Route> id, @Nonnull final Ipv6Route route); @Override void delete(@Nonnull final InstanceIdentifier<Ipv6Route> id, @Nonnull final Ipv6Route route); @Override void update(@Nonnull final InstanceIdentifier<Ipv6Route> id, @Nonnull final Ipv6Route routeBefore, @Nonnull final Ipv6Route routeAfter); @Nonnull @Override InstanceIdentifier<Ipv6Route> getManagedDataObjectType(); }### Answer: @Test public void testDelete() throws WriteFailedException.DeleteFailedException { final Ipv6Prefix destination = new Ipv6Prefix("2001:db8:a0b:12f0:0:0:0:1/64"); final PathId pathId = new PathId(456L); final Ipv6Address nextHopAddress = new Ipv6AddressNoZone("2001:db8:a0b:12f0:0:0:0:2"); writer.delete( id(destination, pathId), route(destination, pathId, nextHopAddress) ); verifyRequest(false); }
### Question: Ipv6Writer implements RouteWriter<Ipv6Route>, Ipv6Translator, JvppReplyConsumer, RouteRequestProducer { @Override public void update(@Nonnull final InstanceIdentifier<Ipv6Route> id, @Nonnull final Ipv6Route routeBefore, @Nonnull final Ipv6Route routeAfter) throws WriteFailedException.UpdateFailedException { throw new WriteFailedException.UpdateFailedException(id, routeBefore, routeAfter, new UnsupportedOperationException("Operation not supported")); } Ipv6Writer(@Nonnull final FutureJVppCore vppApi); @Override void create(@Nonnull final InstanceIdentifier<Ipv6Route> id, @Nonnull final Ipv6Route route); @Override void delete(@Nonnull final InstanceIdentifier<Ipv6Route> id, @Nonnull final Ipv6Route route); @Override void update(@Nonnull final InstanceIdentifier<Ipv6Route> id, @Nonnull final Ipv6Route routeBefore, @Nonnull final Ipv6Route routeAfter); @Nonnull @Override InstanceIdentifier<Ipv6Route> getManagedDataObjectType(); }### Answer: @Test(expected = WriteFailedException.UpdateFailedException.class) public void testUpdate() throws WriteFailedException.UpdateFailedException { final Ipv6Prefix destination = new Ipv6Prefix("2001:db8:a0b:12f0:0:0:0:1/64"); final PathId pathId = new PathId(456L); writer.update(id(destination, pathId), mock(Ipv6Route.class), mock(Ipv6Route.class)); }
### Question: AclValidator implements Validator<Acl>, AclDataExtractor { @Override public void validateDelete(final InstanceIdentifier<Acl> id, final Acl dataBefore, final WriteContext ctx) throws DeleteValidationFailedException { try { validateAcl(dataBefore); final List<String> references = checkAclReferenced(ctx, dataBefore); checkState(references.isEmpty(), "%s cannot be removed, it is referenced in following interfaces %s", dataBefore, references); } catch (RuntimeException e) { throw new DeleteValidationFailedException(id, e); } } @Override void validateWrite(final InstanceIdentifier<Acl> id, final Acl dataAfter, final WriteContext ctx); @Override void validateUpdate(final InstanceIdentifier<Acl> id, final Acl dataBefore, final Acl dataAfter, final WriteContext ctx); @Override void validateDelete(final InstanceIdentifier<Acl> id, final Acl dataBefore, final WriteContext ctx); }### Answer: @Test public void testValidateDelete( @InjectTestData(resourcePath = "/acl/standard/standard-acl-icmp.json") Acls acls) throws DataValidationFailedException.DeleteValidationFailedException { validator.validateDelete(ID, acls.getAcl().get(0), writeContext); } @Test(expected = DataValidationFailedException.DeleteValidationFailedException.class) public void testValidateDeleteReferenced( @InjectTestData(resourcePath = "/acl/standard/standard-acl-udp.json") Acls standardAcls, @InjectTestData(id = "/ietf-access-control-list:acls/ietf-access-control-list:attachment-points", resourcePath = "/acl/standard/interface-ref-acl-udp.json") AttachmentPoints references) throws Exception { when(writeContext.readAfter(AclIIds.ACLS_AP)).thenReturn( Optional.of(new AttachmentPointsBuilder().setInterface(references.getInterface()).build())); validator.validateDelete(ID, standardAcls.getAcl().get(0), writeContext); }
### Question: IoamExportWriterCustomizer extends FutureJVppIoamexportCustomizer implements WriterCustomizer<IoamExport>, JvppReplyConsumer, Ipv4Translator { @Override public void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<IoamExport> instanceIdentifier, @Nonnull final IoamExport ioamExport, @Nonnull final WriteContext writeContext) throws WriteFailedException { deleteExportProfile(ioamExport,instanceIdentifier); LOG.info("Export profile {} deleted, id: {}", ioamExport, instanceIdentifier); } IoamExportWriterCustomizer(FutureJVppIoamexport jVppIoamExport); @Override void writeCurrentAttributes(@Nonnull final InstanceIdentifier<IoamExport> instanceIdentifier, @Nonnull final IoamExport ioamExport, @Nonnull final WriteContext writeContext); @Override void updateCurrentAttributes(@Nonnull final InstanceIdentifier<IoamExport> instanceIdentifier, @Nonnull final IoamExport dataBefore, @Nonnull final IoamExport dataAfter, @Nonnull final WriteContext writeContext); @Override void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<IoamExport> instanceIdentifier, @Nonnull final IoamExport ioamExport, @Nonnull final WriteContext writeContext); }### Answer: @Test public void testDelete() throws Exception { final IoamExport ioamExport = generateExportProfile(); final InstanceIdentifier<IoamExport> id = InstanceIdentifier.create(IoamExport.class); whenExportDelThenSuccess(); customizer.deleteCurrentAttributes(id, ioamExport, writeContext); verify(jVppIoamexport).ioamExportIp6EnableDisable(generateIoamExportIp6EnableDisable(true)); } @Test public void testDeleteFailed() throws Exception { final IoamExport ioamExport = generateExportProfile(); final InstanceIdentifier<IoamExport> id = InstanceIdentifier.create(IoamExport.class); whenExportDelThenFailure(); try { customizer.deleteCurrentAttributes(id, ioamExport, writeContext); } catch (WriteFailedException e) { verify(jVppIoamexport).ioamExportIp6EnableDisable(generateIoamExportIp6EnableDisable(true)); return; } fail("WriteFailedException.CreateFailedException was expected"); }
### Question: Srv6Util { public static String getCandidatePathName(final Ipv6Address bsid, final long weight) { return bsid.getValue() + "-" + weight; } private Srv6Util(); static String getCandidatePathName(final Ipv6Address bsid, final long weight); static Ipv6Address extractBsid( final @Nonnull InstanceIdentifier<T> instanceIdentifier, final @Nonnull WriteContext writeContext, boolean isWrite); static int extractVrfFib(final @Nonnull InstanceIdentifier<T> instanceIdentifier, final @Nonnull WriteContext writeContext, boolean isWrite); }### Answer: @Test public void getCandidatePathNameTest() { Assert.assertEquals(CANDIDATE_PATH_NAME, Srv6Util.getCandidatePathName(BSID, 0L)); }
### Question: Srv6Util { public static <T extends DataObject> Ipv6Address extractBsid( final @Nonnull InstanceIdentifier<T> instanceIdentifier, final @Nonnull WriteContext writeContext, boolean isWrite) { Optional<Policy> policyOptional = isWrite ? writeContext.readAfter(RWUtils.cutId(instanceIdentifier, Policy.class)) : writeContext.readBefore(RWUtils.cutId(instanceIdentifier, Policy.class)); if (policyOptional.isPresent() && policyOptional.get().getBindingSid() != null && policyOptional.get().getBindingSid().getConfig() != null) { org.opendaylight.yang.gen.v1.http.cisco.com.ns.yang.oc.srte.policy.rev170918.binding.sid.properties.binding.sid.Config config = policyOptional.get().getBindingSid().getConfig(); if (config.getType() == DataplaneType.Srv6 && config.getValue() != null && config.getValue().getIpAddress() != null && config.getValue().getIpAddress().getIpv6Address() != null) { return config.getValue().getIpAddress().getIpv6Address(); } } return null; } private Srv6Util(); static String getCandidatePathName(final Ipv6Address bsid, final long weight); static Ipv6Address extractBsid( final @Nonnull InstanceIdentifier<T> instanceIdentifier, final @Nonnull WriteContext writeContext, boolean isWrite); static int extractVrfFib(final @Nonnull InstanceIdentifier<T> instanceIdentifier, final @Nonnull WriteContext writeContext, boolean isWrite); }### Answer: @Test public void extractBsidTest() { Assert.assertEquals(BSID.getValue(), Srv6Util.extractBsid(POLICY_IID, ctx, true).getValue()); }
### Question: Srv6Util { public static <T extends DataObject> int extractVrfFib(final @Nonnull InstanceIdentifier<T> instanceIdentifier, final @Nonnull WriteContext writeContext, boolean isWrite) { Optional<Policy> policyOptional = isWrite ? writeContext.readAfter(RWUtils.cutId(instanceIdentifier, Policy.class)) : writeContext.readBefore(RWUtils.cutId(instanceIdentifier, Policy.class)); if (policyOptional.isPresent() && policyOptional.get().augmentation(VppSrPolicyAugmentation.class) != null && policyOptional.get().augmentation(VppSrPolicyAugmentation.class).getVppSrPolicy() != null) { VppSrPolicy vppSrPolicy = policyOptional.get().augmentation(VppSrPolicyAugmentation.class).getVppSrPolicy(); if (vppSrPolicy.getConfig() != null && vppSrPolicy.getConfig().getTableId() != null) { return vppSrPolicy.getConfig().getTableId().getValue().intValue(); } } return 0; } private Srv6Util(); static String getCandidatePathName(final Ipv6Address bsid, final long weight); static Ipv6Address extractBsid( final @Nonnull InstanceIdentifier<T> instanceIdentifier, final @Nonnull WriteContext writeContext, boolean isWrite); static int extractVrfFib(final @Nonnull InstanceIdentifier<T> instanceIdentifier, final @Nonnull WriteContext writeContext, boolean isWrite); }### Answer: @Test public void extractVrfFibTest() { Assert.assertEquals(0, Srv6Util.extractVrfFib(POLICY_IID, ctx, true)); }
### Question: FilterParser { public Filter parseTableFilter(boolean matchParents) throws ParseException { List<Filter> result = new ArrayList<>(); for (List<IdentifierMatcher> list : parse()) { if (list.size() < 1 || list.size() > 2) { throw new ParseException("Syntax error in table filter list; expected list of comma- or newline-separated names in [schema.]table notation: '" + s + "'"); } if (list.size() == 1) { result.add(new FilterMatchTable(Filter.NULL_MATCHER, list.get(0), matchParents)); } else { result.add(new FilterMatchTable(list.get(0), list.get(1), matchParents)); } } return FilterMatchAny.create(result); } FilterParser(String filterSpec); Filter parseSchemaFilter(); Filter parseTableFilter(boolean matchParents); Filter parseColumnFilter(boolean matchParents); List<List<IdentifierMatcher>> parse(); }### Answer: @Test public void testParseAsTableFilter() throws ParseException { Filter result = new FilterParser("schema.table1,schema.table2,table3").parseTableFilter(false); Assert.assertTrue(result.matchesTable("schema", "table1")); Assert.assertTrue(result.matchesTable("schema", "table2")); Assert.assertTrue(result.matchesTable(null, "table3")); Assert.assertFalse(result.matchesTable("schema", "table3")); Assert.assertFalse(result.matchesTable("schema", "table4")); Assert.assertFalse(result.matchesTable("schema2", "table1")); Assert.assertFalse(result.matchesTable(null, "table1")); Assert.assertFalse(result.matchesTable(null, "table4")); } @Test public void testTableFilterTooMany() { try { new FilterParser("a.b.c").parseTableFilter(true); Assert.fail("Should have failed because not in schema notation"); } catch (ParseException ex) { } }
### Question: FilterParser { public Filter parseColumnFilter(boolean matchParents) throws ParseException { List<Filter> result = new ArrayList<>(); for (List<IdentifierMatcher> list : parse()) { if (list.size() < 2 || list.size() > 3) { throw new ParseException("Syntax error in column filter list; expected list of comma- or newline-separated names in [schema.]table.column notation: '" + s + "'"); } if (list.size() == 2) { result.add(new FilterMatchColumn(Filter.NULL_MATCHER, list.get(0), list.get(1), matchParents)); } else { result.add(new FilterMatchColumn(list.get(0), list.get(1), list.get(2), matchParents)); } } return FilterMatchAny.create(result); } FilterParser(String filterSpec); Filter parseSchemaFilter(); Filter parseTableFilter(boolean matchParents); Filter parseColumnFilter(boolean matchParents); List<List<IdentifierMatcher>> parse(); }### Answer: @Test public void testParseAsColumnFilter() throws ParseException { Filter result = new FilterParser("s.t1.c1,t2.c2,t2.c3").parseColumnFilter(false); Assert.assertTrue(result.matchesColumn("s", "t1", "c1")); Assert.assertTrue(result.matchesColumn(null, "t2", "c2")); Assert.assertTrue(result.matchesColumn(null, "t2", "c3")); Assert.assertFalse(result.matchesColumn(null, "t1", "c1")); Assert.assertFalse(result.matchesColumn("s", "t2", "c2")); Assert.assertFalse(result.matchesColumn(null, "t1", "c3")); }
### Question: GraphPatternTranslator { public List<NodeRelation> translate() { if (triplePatterns.isEmpty()) { return Collections.singletonList(NodeRelation.TRUE); } Iterator<Triple> it = triplePatterns.iterator(); List<CandidateList> candidateLists = new ArrayList<>(triplePatterns.size()); int index = 1; while (it.hasNext()) { Triple triplePattern = it.next(); CandidateList candidates = new CandidateList( triplePattern, triplePatterns.size() > 1, index); if (candidates.isEmpty()) { return Collections.emptyList(); } candidateLists.add(candidates); index++; } Collections.sort(candidateLists); List<TripleRelationJoiner> joiners = new ArrayList<>(); joiners.add(TripleRelationJoiner.create(this.useAllOptimizations)); for (CandidateList candidates : candidateLists) { List<TripleRelationJoiner> nextJoiners = new ArrayList<>(); for (TripleRelationJoiner joiner : joiners) { nextJoiners.addAll(joiner.joinAll(candidates.triplePattern(), candidates.all())); } joiners = nextJoiners; } List<NodeRelation> results = new ArrayList<>(joiners.size()); for (TripleRelationJoiner joiner : joiners) { NodeRelation nodeRelation = joiner.toNodeRelation(); if (!nodeRelation.baseRelation().equals(Relation.EMPTY) || !useAllOptimizations) results.add(nodeRelation); } return results; } GraphPatternTranslator(List<Triple> triplePatterns, Collection<TripleRelation> tripleRelations, boolean useAllOptimizations); List<NodeRelation> translate(); }### Answer: @Test public void testReturnMultipleMatchesForSingleTriplePattern() { NodeRelation[] rels = translate("?s ?p ?o", "engine/simple.n3"); Assert.assertEquals(2, rels.length); }
### Question: URIMakerRule implements Comparator<TripleRelation> { public List<TripleRelation> sortRDFRelations(Collection<TripleRelation> tripleRelations) { ArrayList<TripleRelation> results = new ArrayList<>(tripleRelations); results.sort(this); return results; } List<TripleRelation> sortRDFRelations(Collection<TripleRelation> tripleRelations); URIMakerRuleChecker createRuleChecker(Node node); @Override int compare(TripleRelation o1, TripleRelation o2); }### Answer: @Test public void testSort() { Collection<TripleRelation> unsorted = new ArrayList<>(Arrays.asList(this.withURIColumnSubject, this.withURIPatternSubject, this.withURIPatternSubjectAndObject, this.withURIPatternSubjectAndURIColumnObject)); Collection<TripleRelation> sorted = new ArrayList<>(Arrays.asList(this.withURIPatternSubjectAndObject, this.withURIPatternSubject, this.withURIPatternSubjectAndURIColumnObject, this.withURIColumnSubject)); Assert.assertEquals(sorted, new URIMakerRule().sortRDFRelations(unsorted)); }
### Question: VocabularySummarizer { public Set<Property> getAllProperties() { return properties; } VocabularySummarizer(Class<?> vocabularyJavaClass); static Set<Resource> getStandardResources(); static Set<Property> getStandardProperties(); static Set<X> getResources(Class<X> type, Class<?>... classes); static Stream<? extends Resource> resources(Class<?>... classes); static Stream<X> resources(Class<X> type, Class<?>... classes); @SuppressWarnings("unchecked") Set<X> get(Class<X> type); Set<Property> getAllProperties(); Set<Resource> getAllClasses(); String getNamespace(); Collection<Resource> getUndefinedClasses(Model model); Collection<Property> getUndefinedProperties(Model model); void assertNoUndefinedTerms(Model model, int undefinedPropertyErrorCode, int undefinedClassErrorCode); }### Answer: @Test public void testAllPropertiesEmpty() { VocabularySummarizer vocab = new VocabularySummarizer(Object.class); Assert.assertTrue(vocab.getAllProperties().isEmpty()); } @Test public void testAllPropertiesContainsProperty() { VocabularySummarizer vocab = new VocabularySummarizer(D2RQ.class); Assert.assertTrue(vocab.getAllProperties().contains(D2RQ.column)); Assert.assertTrue(vocab.getAllProperties().contains(D2RQ.belongsToClassMap)); } @Test public void testAllPropertiesDoesNotContainClass() { VocabularySummarizer vocab = new VocabularySummarizer(D2RQ.class); Assert.assertFalse(vocab.getAllProperties().contains(D2RQ.Database)); } @Test public void testAllPropertiesDoesNotContainTermFromOtherNamespace() { VocabularySummarizer vocab = new VocabularySummarizer(D2RQ.class); Assert.assertFalse(vocab.getAllProperties().contains(RDF.type)); }
### Question: VocabularySummarizer { public Set<Resource> getAllClasses() { return classes; } VocabularySummarizer(Class<?> vocabularyJavaClass); static Set<Resource> getStandardResources(); static Set<Property> getStandardProperties(); static Set<X> getResources(Class<X> type, Class<?>... classes); static Stream<? extends Resource> resources(Class<?>... classes); static Stream<X> resources(Class<X> type, Class<?>... classes); @SuppressWarnings("unchecked") Set<X> get(Class<X> type); Set<Property> getAllProperties(); Set<Resource> getAllClasses(); String getNamespace(); Collection<Resource> getUndefinedClasses(Model model); Collection<Property> getUndefinedProperties(Model model); void assertNoUndefinedTerms(Model model, int undefinedPropertyErrorCode, int undefinedClassErrorCode); }### Answer: @Test public void testAllClassesEmpty() { VocabularySummarizer vocab = new VocabularySummarizer(Object.class); Assert.assertTrue(vocab.getAllClasses().isEmpty()); } @Test public void testAllClassesContainsClass() { VocabularySummarizer vocab = new VocabularySummarizer(D2RQ.class); Assert.assertTrue(vocab.getAllClasses().contains(D2RQ.Database)); } @Test public void testAllClassesDoesNotContainProperty() { VocabularySummarizer vocab = new VocabularySummarizer(D2RQ.class); Assert.assertFalse(vocab.getAllClasses().contains(D2RQ.column)); } @Test public void testAllClassesDoesNotContainTermFromOtherNamespace() { VocabularySummarizer vocab = new VocabularySummarizer(D2RQ.class); Assert.assertFalse(vocab.getAllClasses().contains(D2RConfig.Server)); }
### Question: VocabularySummarizer { public String getNamespace() { return namespace; } VocabularySummarizer(Class<?> vocabularyJavaClass); static Set<Resource> getStandardResources(); static Set<Property> getStandardProperties(); static Set<X> getResources(Class<X> type, Class<?>... classes); static Stream<? extends Resource> resources(Class<?>... classes); static Stream<X> resources(Class<X> type, Class<?>... classes); @SuppressWarnings("unchecked") Set<X> get(Class<X> type); Set<Property> getAllProperties(); Set<Resource> getAllClasses(); String getNamespace(); Collection<Resource> getUndefinedClasses(Model model); Collection<Property> getUndefinedProperties(Model model); void assertNoUndefinedTerms(Model model, int undefinedPropertyErrorCode, int undefinedClassErrorCode); }### Answer: @Test public void testGetNamespaceEmpty() { Assert.assertNull(new VocabularySummarizer(Object.class).getNamespace()); } @Test public void testGetNamespaceD2RQ() { Assert.assertEquals(D2RQ.NS, new VocabularySummarizer(D2RQ.class).getNamespace()); } @Test public void testGetNamespaceD2RConfig() { Assert.assertEquals(D2RConfig.NS, new VocabularySummarizer(D2RConfig.class).getNamespace()); }
### Question: MapParser { public static void checkDistinctMapObjects(Model model) throws D2RQException { ensureAllDistinct(model, D2RQ.Database, D2RQ.ClassMap, D2RQ.PropertyBridge, D2RQ.TranslationTable, D2RQ.Translation); } static String absolutizeURI(String uri); static void insertBase(Model model, String baseURI); static void validate(Model model); static void fixLegacy(Model model); static void fixLegacyReferences(Model m); static void fixLegacyAdditionalProperty(Model m); static void fixLegacyPropertyBridges(Model m); static void checkVocabulary(Model model); static void checkDistinctMapObjects(Model model); }### Answer: @Test(expected = D2RQException.class) public void validateDistinctMembers() { Mapping m = MappingFactory.create() .createDatabase("x").getMapping() .createClassMap("x").getMapping(); MapParser.checkDistinctMapObjects(m.asModel()); }
### Question: MapParser { public static void checkVocabulary(Model model) throws D2RQException { new VocabularySummarizer(D2RQ.class).assertNoUndefinedTerms(model, D2RQException.MAPPING_UNKNOWN_D2RQ_PROPERTY, D2RQException.MAPPING_UNKNOWN_D2RQ_CLASS); } static String absolutizeURI(String uri); static void insertBase(Model model, String baseURI); static void validate(Model model); static void fixLegacy(Model model); static void fixLegacyReferences(Model m); static void fixLegacyAdditionalProperty(Model m); static void fixLegacyPropertyBridges(Model m); static void checkVocabulary(Model model); static void checkDistinctMapObjects(Model model); }### Answer: @Test(expected = D2RQException.class) public void validateExternalResources() { Model m = ModelFactory.createDefaultModel(); m.createResource("x", m.createResource(D2RQ.NS + "XClass")); MapParser.checkVocabulary(m); }
### Question: Pattern implements ValueMaker { @Override public String toString() { return "Pattern(" + this.pattern + ")"; } Pattern(String pattern); String firstLiteralPart(); String lastLiteralPart(); boolean literalPartsMatchRegex(String regex); List<Attribute> attributes(); @Override void describeSelf(NodeSetFilter c); boolean matches(String value); @Override Expression valueExpression(String value); @Override Set<ProjectionSpec> projectionSpecs(); @Override String makeValue(ResultRow row); @Override List<OrderSpec> orderSpecs(boolean ascending); @Override String toString(); @Override boolean equals(Object otherObject); @Override int hashCode(); boolean isEquivalentTo(Pattern p); @Override ValueMaker renameAttributes(ColumnRenamer renames); Iterator<Object> partsIterator(); Expression toExpression(); boolean usesColumnFunctions(); final static String DELIMITER; }### Answer: @Test public void testToString() { Assert.assertEquals("Pattern(foo@@table.col1@@)", new Pattern("foo@@table.col1@@").toString()); }
### Question: Pattern implements ValueMaker { @Override public int hashCode() { return this.pattern.hashCode(); } Pattern(String pattern); String firstLiteralPart(); String lastLiteralPart(); boolean literalPartsMatchRegex(String regex); List<Attribute> attributes(); @Override void describeSelf(NodeSetFilter c); boolean matches(String value); @Override Expression valueExpression(String value); @Override Set<ProjectionSpec> projectionSpecs(); @Override String makeValue(ResultRow row); @Override List<OrderSpec> orderSpecs(boolean ascending); @Override String toString(); @Override boolean equals(Object otherObject); @Override int hashCode(); boolean isEquivalentTo(Pattern p); @Override ValueMaker renameAttributes(ColumnRenamer renames); Iterator<Object> partsIterator(); Expression toExpression(); boolean usesColumnFunctions(); final static String DELIMITER; }### Answer: @Test public void testSamePatternsAreEqual() { Pattern p1 = new Pattern("foo@@table.col1@@"); Pattern p2 = new Pattern("foo@@table.col1@@"); Assert.assertEquals(p1, p2); Assert.assertEquals(p2, p1); Assert.assertEquals(p1.hashCode(), p2.hashCode()); } @Test public void testPatternsWithDifferentColumnsAreNotEqual() { Pattern p1 = new Pattern("foo@@table.col1@@"); Pattern p2 = new Pattern("foo@@table.col2@@"); Assert.assertNotEquals(p1, p2); Assert.assertNotEquals(p2, p1); Assert.assertNotEquals(p1.hashCode(), p2.hashCode()); } @Test public void testPatternsWithDifferentLiteralPartsAreNotEqual() { Pattern p1 = new Pattern("foo@@table.col1@@"); Pattern p2 = new Pattern("bar@@table.col1@@"); Assert.assertNotEquals(p1, p2); Assert.assertNotEquals(p2, p1); Assert.assertNotEquals(p1.hashCode(), p2.hashCode()); }
### Question: Pattern implements ValueMaker { public boolean literalPartsMatchRegex(String regex) { if (!this.firstLiteralPart.matches(regex)) { return false; } for (String literalPart : literalParts) { if (!literalPart.matches(regex)) { return false; } } return true; } Pattern(String pattern); String firstLiteralPart(); String lastLiteralPart(); boolean literalPartsMatchRegex(String regex); List<Attribute> attributes(); @Override void describeSelf(NodeSetFilter c); boolean matches(String value); @Override Expression valueExpression(String value); @Override Set<ProjectionSpec> projectionSpecs(); @Override String makeValue(ResultRow row); @Override List<OrderSpec> orderSpecs(boolean ascending); @Override String toString(); @Override boolean equals(Object otherObject); @Override int hashCode(); boolean isEquivalentTo(Pattern p); @Override ValueMaker renameAttributes(ColumnRenamer renames); Iterator<Object> partsIterator(); Expression toExpression(); boolean usesColumnFunctions(); final static String DELIMITER; }### Answer: @Test public void testLiteralPatternsMatchTrivialRegex() { Assert.assertTrue(new Pattern("asdf").literalPartsMatchRegex(".*")); } @Test public void testLiteralPatternsDontMatchTrivialRegex() { Assert.assertFalse(new Pattern("asdf").literalPartsMatchRegex("foo")); } @Test public void testLiteralPatternRegexIsAnchored() { Assert.assertFalse(new Pattern("aaa").literalPartsMatchRegex("b*")); } @Test public void testLiteralPatternRegexMultipleParts() { Assert.assertTrue(new Pattern("aaa@@aaa.aaa@@aaa").literalPartsMatchRegex("aaa")); } @Test public void testLiteralPatternRegexMatchesOnlyLiteralParts() { Assert.assertTrue(new Pattern("aaa@@bbb.ccc@@aaa").literalPartsMatchRegex("a+")); }
### Question: Conjunction extends Expression { @Override public String toString() { List<String> fragments = new ArrayList<>(this.expressions.size()); for (Expression expression : expressions) { fragments.add(expression.toString()); } Collections.sort(fragments); StringBuilder result = new StringBuilder("Conjunction("); Iterator<String> it = fragments.iterator(); while (it.hasNext()) { String fragment = it.next(); result.append(fragment); if (it.hasNext()) { result.append(", "); } } result.append(")"); return result.toString(); } private Conjunction(Set<Expression> expressions); static Expression create(Collection<Expression> expressions); @Override boolean isTrue(); @Override boolean isFalse(); @Override Set<Attribute> attributes(); @Override Expression renameAttributes(ColumnRenamer columnRenamer); @Override String toSQL(ConnectedDB database, AliasMap aliases); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); }### Answer: @Test public void testToString() { Assert.assertEquals("Conjunction(SQL(papers.publish = 1), SQL(papers.rating > 4))", conjunction12.toString()); }
### Question: Pattern implements ValueMaker { public String firstLiteralPart() { return firstLiteralPart; } Pattern(String pattern); String firstLiteralPart(); String lastLiteralPart(); boolean literalPartsMatchRegex(String regex); List<Attribute> attributes(); @Override void describeSelf(NodeSetFilter c); boolean matches(String value); @Override Expression valueExpression(String value); @Override Set<ProjectionSpec> projectionSpecs(); @Override String makeValue(ResultRow row); @Override List<OrderSpec> orderSpecs(boolean ascending); @Override String toString(); @Override boolean equals(Object otherObject); @Override int hashCode(); boolean isEquivalentTo(Pattern p); @Override ValueMaker renameAttributes(ColumnRenamer renames); Iterator<Object> partsIterator(); Expression toExpression(); boolean usesColumnFunctions(); final static String DELIMITER; }### Answer: @Test public void testTrivialPatternFirstPart() { Assert.assertEquals("aaa", new Pattern("aaa").firstLiteralPart()); } @Test public void testEmptyFirstPart() { Assert.assertEquals("", new Pattern("@@table.col1@@aaa").firstLiteralPart()); }
### Question: Pattern implements ValueMaker { public String lastLiteralPart() { if (literalParts.isEmpty()) { return firstLiteralPart; } return literalParts.get(literalParts.size() - 1); } Pattern(String pattern); String firstLiteralPart(); String lastLiteralPart(); boolean literalPartsMatchRegex(String regex); List<Attribute> attributes(); @Override void describeSelf(NodeSetFilter c); boolean matches(String value); @Override Expression valueExpression(String value); @Override Set<ProjectionSpec> projectionSpecs(); @Override String makeValue(ResultRow row); @Override List<OrderSpec> orderSpecs(boolean ascending); @Override String toString(); @Override boolean equals(Object otherObject); @Override int hashCode(); boolean isEquivalentTo(Pattern p); @Override ValueMaker renameAttributes(ColumnRenamer renames); Iterator<Object> partsIterator(); Expression toExpression(); boolean usesColumnFunctions(); final static String DELIMITER; }### Answer: @Test public void testTrivialPatternLastPart() { Assert.assertEquals("aaa", new Pattern("aaa").lastLiteralPart()); } @Test public void testEmptyLastPart() { Assert.assertEquals("", new Pattern("aaa@@table.col1@@").lastLiteralPart()); }
### Question: Conjunction extends Expression { @Override public int hashCode() { return this.expressions.hashCode(); } private Conjunction(Set<Expression> expressions); static Expression create(Collection<Expression> expressions); @Override boolean isTrue(); @Override boolean isFalse(); @Override Set<Attribute> attributes(); @Override Expression renameAttributes(ColumnRenamer columnRenamer); @Override String toSQL(ConnectedDB database, AliasMap aliases); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); }### Answer: @Test public void testOrderDoesNotAffectEquality() { Assert.assertEquals(conjunction12, conjunction21); Assert.assertEquals(conjunction12.hashCode(), conjunction21.hashCode()); }
### Question: Concatenation extends Expression { public static Expression create(List<Expression> expressions) { List<Expression> nonEmpty = new ArrayList<>(expressions.size()); for (Expression expression : expressions) { if (expression instanceof Constant && "".equals(((Constant) expression).value())) { continue; } nonEmpty.add(expression); } if (nonEmpty.isEmpty()) { return new Constant(""); } if (nonEmpty.size() == 1) { return nonEmpty.get(0); } return new Concatenation(nonEmpty); } private Concatenation(List<Expression> parts); static Expression create(List<Expression> expressions); @Override Set<Attribute> attributes(); @Override boolean isFalse(); @Override boolean isTrue(); @Override Expression renameAttributes(ColumnRenamer columnRenamer); @Override String toSQL(ConnectedDB database, AliasMap aliases); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testCreateEmpty() { Assert.assertEquals(new Constant(""), Concatenation.create(Collections.emptyList())); } @Test public void testCreateOnePart() { Expression expr = new AttributeExpr(new Attribute(null, "table", "col")); Assert.assertEquals(expr, Concatenation.create(Collections.singletonList(expr))); } @Test public void testFilterEmptyParts() { Expression empty = new Constant(""); Expression expr1 = new Constant("aaa"); Assert.assertEquals(expr1, Concatenation.create(Arrays.asList( empty, empty, expr1, empty))); }
### Question: SQLExpression extends Expression { public static Expression create(String sql) { sql = sql.trim(); if ("1".equals(sql)) { return Expression.TRUE; } if ("0".equals(sql)) { return Expression.FALSE; } return new SQLExpression(sql); } private SQLExpression(String expression); static Expression create(String sql); @Override boolean isTrue(); @Override boolean isFalse(); @Override Set<Attribute> attributes(); @Override Expression renameAttributes(ColumnRenamer columnRenamer); @Override String toSQL(ConnectedDB database, AliasMap aliases); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); String getExpression(); }### Answer: @Test public void testCreate() { Expression e = SQLExpression.create("papers.publish = 1"); Assert.assertEquals("SQL(papers.publish = 1)", e.toString()); Assert.assertFalse(e.isTrue()); Assert.assertFalse(e.isFalse()); }
### Question: SQLExpression extends Expression { @Override public String toString() { return "SQL(" + this.expression + ")"; } private SQLExpression(String expression); static Expression create(String sql); @Override boolean isTrue(); @Override boolean isFalse(); @Override Set<Attribute> attributes(); @Override Expression renameAttributes(ColumnRenamer columnRenamer); @Override String toSQL(ConnectedDB database, AliasMap aliases); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); String getExpression(); }### Answer: @Test public void testToString() { Expression e = SQLExpression.create("papers.publish = 1"); Assert.assertEquals("SQL(papers.publish = 1)", e.toString()); }
### Question: Expression { public abstract String toSQL(ConnectedDB database, AliasMap aliases); abstract boolean isTrue(); abstract boolean isFalse(); abstract Set<Attribute> attributes(); abstract Expression renameAttributes(ColumnRenamer columnRenamer); abstract String toSQL(ConnectedDB database, AliasMap aliases); Expression and(Expression other); Expression or(Expression other); static final Expression TRUE; static final Expression FALSE; }### Answer: @Test public void testConstantToSQL() { Assert.assertEquals("'foo'", new Constant("foo").toSQL(DummyDB.create(), AliasMap.NO_ALIASES)); } @Test public void testConstantToSQLWithType() { Attribute attribute = SQL.parseAttribute("table.col1"); ConnectedDB db = DummyDB.create(Collections.singletonMap("table.col1", GenericType.NUMERIC)); Assert.assertEquals("42", new Constant("42", attribute).toSQL(db, AliasMap.NO_ALIASES)); } @Test public void testConstantToSQLWithTypeAndAlias() { Attribute aliasedAttribute = SQL.parseAttribute("alias.col1"); ConnectedDB db = DummyDB.create(Collections.singletonMap("table.col1", GenericType.NUMERIC)); Assert.assertEquals("42", new Constant("42", aliasedAttribute).toSQL(db, aliases)); }
### Question: Expression { public abstract Expression renameAttributes(ColumnRenamer columnRenamer); abstract boolean isTrue(); abstract boolean isFalse(); abstract Set<Attribute> attributes(); abstract Expression renameAttributes(ColumnRenamer columnRenamer); abstract String toSQL(ConnectedDB database, AliasMap aliases); Expression and(Expression other); Expression or(Expression other); static final Expression TRUE; static final Expression FALSE; }### Answer: @Test public void testConstantTypeAttributeIsRenamed() { Attribute attribute = SQL.parseAttribute("table.col1"); Assert.assertEquals("Constant([email protected])", new Constant("42", attribute).renameAttributes(aliases).toString()); }
### Question: Relation implements RelationalOperators { public boolean isTrivial() { return projections().isEmpty() && condition().isTrue() && joinConditions().isEmpty(); } static Relation createSimpleRelation( ConnectedDB database, Attribute[] attributes); abstract ConnectedDB database(); abstract AliasMap aliases(); abstract Set<Join> joinConditions(); abstract Expression condition(); abstract Expression softCondition(); abstract Set<ProjectionSpec> projections(); abstract boolean isUnique(); abstract List<OrderSpec> orderSpecs(); abstract int limit(); abstract int limitInverse(); Set<Attribute> allKnownAttributes(); Set<RelationName> tables(); boolean isTrivial(); static int combineLimits(int limit1, int limit2); final static int NO_LIMIT; static Relation EMPTY; static Relation TRUE; }### Answer: @Test public void testTrueRelationIsTrivial() { Assert.assertTrue(Relation.TRUE.isTrivial()); } @Test public void testQueryWithSelectColumnsIsNotTrivial() { Assert.assertFalse(rel1.isTrivial()); }
### Question: Attribute implements ProjectionSpec { @Override public String toString() { return "@@" + this.qualifiedName + "@@"; } Attribute(String schemaName, String tableName, String attributeName); Attribute(RelationName relationName, String attributeName); String qualifiedName(); @Override String toSQL(ConnectedDB database, AliasMap aliases); String attributeName(); String tableName(); RelationName relationName(); String schemaName(); @Override Set<Attribute> requiredAttributes(); Expression selectValue(String value); @Override ProjectionSpec renameAttributes(ColumnRenamer renamer); @Override Expression toExpression(); @Override Expression notNullExpression(ConnectedDB db, AliasMap aliases); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); @Override int compareTo(ProjectionSpec other); }### Answer: @Test public void testAttributeToString() { Assert.assertEquals("@@foo.bar@@", new Attribute(null, "foo", "bar").toString()); Assert.assertEquals("@@schema.foo.bar@@", new Attribute("schema", "foo", "bar").toString()); } @Test public void testRelationNameToString() { Assert.assertEquals("table", new RelationName(null, "table").toString()); Assert.assertEquals("schema.table", new RelationName("schema", "table").toString()); }
### Question: Attribute implements ProjectionSpec { @Override public int hashCode() { return this.qualifiedName.hashCode(); } Attribute(String schemaName, String tableName, String attributeName); Attribute(RelationName relationName, String attributeName); String qualifiedName(); @Override String toSQL(ConnectedDB database, AliasMap aliases); String attributeName(); String tableName(); RelationName relationName(); String schemaName(); @Override Set<Attribute> requiredAttributes(); Expression selectValue(String value); @Override ProjectionSpec renameAttributes(ColumnRenamer renamer); @Override Expression toExpression(); @Override Expression notNullExpression(ConnectedDB db, AliasMap aliases); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); @Override int compareTo(ProjectionSpec other); }### Answer: @Test public void testSameRelationNameIsEqual() { Assert.assertEquals(table1, table1b); Assert.assertEquals(table1b, table1); Assert.assertEquals(table1.hashCode(), table1b.hashCode()); } @Test public void testDifferentRelationNamesAreNotEqual() { Assert.assertNotEquals(table1, table2); Assert.assertNotEquals(table2, table1); Assert.assertNotEquals(table1.hashCode(), table2.hashCode()); } @Test public void testSameRelationAndSchemaNameIsEqual() { Assert.assertEquals(table1, table1b); Assert.assertEquals(table1b, table1); Assert.assertEquals(table1.hashCode(), table1b.hashCode()); } @Test public void testDifferentSchemaNamesAreNotEqual() { Assert.assertNotEquals(xTable1, yTable1); Assert.assertNotEquals(yTable1, xTable1); Assert.assertNotEquals(xTable1.hashCode(), yTable1.hashCode()); } @Test public void testSchemaAndNoSchemaAreNotEqual() { Assert.assertNotEquals(xTable1, table1); Assert.assertNotEquals(table1, xTable1); Assert.assertNotEquals(table1.hashCode(), xTable1.hashCode()); }
### Question: Attribute implements ProjectionSpec { public String qualifiedName() { return this.qualifiedName; } Attribute(String schemaName, String tableName, String attributeName); Attribute(RelationName relationName, String attributeName); String qualifiedName(); @Override String toSQL(ConnectedDB database, AliasMap aliases); String attributeName(); String tableName(); RelationName relationName(); String schemaName(); @Override Set<Attribute> requiredAttributes(); Expression selectValue(String value); @Override ProjectionSpec renameAttributes(ColumnRenamer renamer); @Override Expression toExpression(); @Override Expression notNullExpression(ConnectedDB db, AliasMap aliases); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); @Override int compareTo(ProjectionSpec other); }### Answer: @Test public void testRelationNameWithPrefixNoSchema() { Assert.assertEquals("T42_table1", table1.withPrefix(42).qualifiedName()); } @Test public void testRelationNameWithPrefixWithSchema() { Assert.assertEquals("T42_x_table1", xTable1.withPrefix(42).qualifiedName()); }
### Question: ColumnRenamer { public abstract Attribute applyTo(Attribute original); abstract Attribute applyTo(Attribute original); Join applyTo(Join original); Expression applyTo(Expression original); Set<Join> applyToJoinSet(Set<Join> joins); ProjectionSpec applyTo(ProjectionSpec original); Set<ProjectionSpec> applyToProjectionSet(Set<ProjectionSpec> projections); List<OrderSpec> applyTo(List<OrderSpec> orderSpecs); abstract AliasMap applyTo(AliasMap aliases); final static ColumnRenamer NULL; }### Answer: @Test public void testApplyToUnmappedColumnReturnsSameColumn() { Assert.assertEquals(col3, this.col1ToCol2.applyTo(col3)); } @Test public void testApplyToMappedColumnReturnsNewName() { Assert.assertEquals(col2, this.col1ToCol2.applyTo(col1)); } @Test public void testApplyToNewNameReturnsNewName() { Assert.assertEquals(col2, this.col1ToCol2.applyTo(col2)); } @Test public void testApplyToExpressionReplacesMappedColumns() { Expression e = SQLExpression.create("foo.col1=foo.col3"); Assert.assertEquals(SQLExpression.create("foo.col2=foo.col3"), this.col1ToCol2.applyTo(e)); } @Test public void testApplyToAliasMapReturnsOriginal() { AliasMap aliases = new AliasMap(Collections.singleton(new Alias( new RelationName(null, "foo"), new RelationName(null, "bar")))); Assert.assertEquals(aliases, this.col1ToCol2.applyTo(aliases)); } @Test public void testRenameWithSchema() { Attribute foo_c1 = new Attribute("schema", "foo", "col1"); Attribute bar_c2 = new Attribute("schema", "bar", "col2"); ColumnRenamer renamer = new ColumnRenamerMap(Collections.singletonMap(foo_c1, bar_c2)); Assert.assertEquals(bar_c2, renamer.applyTo(foo_c1)); Assert.assertEquals(col1, renamer.applyTo(col1)); }
### Question: AliasMap extends ColumnRenamer { public RelationName originalOf(RelationName name) { if (!isAlias(name)) { return name; } Alias alias = this.byAlias.get(name); return alias.original(); } AliasMap(Collection<Alias> aliases); static AliasMap create1(RelationName original, RelationName alias); boolean isAlias(RelationName name); boolean hasAlias(RelationName original); RelationName applyTo(RelationName original); RelationName originalOf(RelationName name); Attribute applyTo(Attribute attribute); Attribute originalOf(Attribute attribute); Alias applyTo(Alias alias); Alias originalOf(Alias alias); @Override Join applyTo(Join join); @Override AliasMap applyTo(AliasMap other); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); static final AliasMap NO_ALIASES; }### Answer: @Test public void testOriginalOfColumn() { Assert.assertEquals(baz_col1, this.fooAsBarMap.originalOf(baz_col1)); Assert.assertEquals(foo_col1, this.fooAsBarMap.originalOf(foo_col1)); Assert.assertEquals(foo_col1, this.fooAsBarMap.originalOf(bar_col1)); } @Test public void testOriginalOfAliasEmpty() { Assert.assertEquals(fooAsBar, AliasMap.NO_ALIASES.originalOf(fooAsBar)); } @Test public void testOriginalOfAlias() { Assert.assertEquals(fooAsBaz, fooAsBarMap.originalOf(new Alias(bar, baz))); }
### Question: AliasMap extends ColumnRenamer { @Override public int hashCode() { return this.byAlias.hashCode(); } AliasMap(Collection<Alias> aliases); static AliasMap create1(RelationName original, RelationName alias); boolean isAlias(RelationName name); boolean hasAlias(RelationName original); RelationName applyTo(RelationName original); RelationName originalOf(RelationName name); Attribute applyTo(Attribute attribute); Attribute originalOf(Attribute attribute); Alias applyTo(Alias alias); Alias originalOf(Alias alias); @Override Join applyTo(Join join); @Override AliasMap applyTo(AliasMap other); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); static final AliasMap NO_ALIASES; }### Answer: @Test public void testEqualMapsHaveSameHashCode() { AliasMap m1 = new AliasMap(new ArrayList<>()); AliasMap m2 = new AliasMap(new ArrayList<>()); Assert.assertEquals(m1.hashCode(), m2.hashCode()); } @Test public void testAliasEquals() { Alias fooAsBar2 = new Alias(foo, bar); Assert.assertEquals(fooAsBar, fooAsBar2); Assert.assertEquals(fooAsBar2, fooAsBar); Assert.assertEquals(fooAsBar.hashCode(), fooAsBar2.hashCode()); } @Test public void testAliasNotEquals() { Assert.assertNotEquals(fooAsBar, fooAsBaz); Assert.assertNotEquals(fooAsBaz, fooAsBar); Assert.assertNotEquals(fooAsBar, bazAsBar); Assert.assertNotEquals(bazAsBar, fooAsBar); Assert.assertNotEquals(fooAsBar.hashCode(), fooAsBaz.hashCode()); Assert.assertNotEquals(fooAsBar.hashCode(), bazAsBar.hashCode()); }
### Question: AliasMap extends ColumnRenamer { @Override public String toString() { StringBuilder result = new StringBuilder(); result.append("AliasMap("); List<RelationName> tables = new ArrayList<>(this.byAlias.keySet()); Collections.sort(tables); Iterator<RelationName> it = tables.iterator(); while (it.hasNext()) { result.append(this.byAlias.get(it.next())); if (it.hasNext()) { result.append(", "); } } result.append(")"); return result.toString(); } AliasMap(Collection<Alias> aliases); static AliasMap create1(RelationName original, RelationName alias); boolean isAlias(RelationName name); boolean hasAlias(RelationName original); RelationName applyTo(RelationName original); RelationName originalOf(RelationName name); Attribute applyTo(Attribute attribute); Attribute originalOf(Attribute attribute); Alias applyTo(Alias alias); Alias originalOf(Alias alias); @Override Join applyTo(Join join); @Override AliasMap applyTo(AliasMap other); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); static final AliasMap NO_ALIASES; }### Answer: @Test public void testAliasToString() { Assert.assertEquals("foo AS bar", fooAsBar.toString()); } @Test public void testToStringEmpty() { Assert.assertEquals("AliasMap()", AliasMap.NO_ALIASES.toString()); } @Test public void testToStringOneAlias() { Assert.assertEquals("AliasMap(foo AS bar)", fooAsBarMap.toString()); } @Test public void testToStringTwoAliases() { Collection<Alias> aliases = new ArrayList<>(); aliases.add(fooAsBar); aliases.add(new Alias(new RelationName(null, "abc"), new RelationName(null, "xyz"))); Assert.assertEquals("AliasMap(foo AS bar, abc AS xyz)", new AliasMap(aliases).toString()); }
### Question: Join { public Join renameColumns(ColumnRenamer columnRenamer) { List<Attribute> oneSide = new ArrayList<>(); List<Attribute> otherSide = new ArrayList<>(); for (Attribute column : attributes1) { oneSide.add(columnRenamer.applyTo(column)); otherSide.add(columnRenamer.applyTo(equalAttribute(column))); } return new Join(oneSide, otherSide, joinDirection); } Join(Attribute oneSide, Attribute otherSide, int joinDirection); Join(List<Attribute> oneSideAttributes, List<Attribute> otherSideAttributes, int joinDirection); boolean isSameTable(); boolean containsColumn(Attribute column); RelationName table1(); RelationName table2(); List<Attribute> attributes1(); List<Attribute> attributes2(); int joinDirection(); Attribute equalAttribute(Attribute column); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object otherObject); Join renameColumns(ColumnRenamer columnRenamer); static final int DIRECTION_UNDIRECTED; static final int DIRECTION_LEFT; static final int DIRECTION_RIGHT; static final String[] joinOperators; }### Answer: @Test public void testRenameColumns() { ColumnRenamer renamer = new ColumnRenamerMap(Collections.singletonMap(table1foo, table1bar)); Join join = new Join(table1foo, table2foo, Join.DIRECTION_RIGHT); Assert.assertEquals("Join(table1.bar => table2.foo)", join.renameColumns(renamer).toString()); }
### Question: Join { public RelationName table1() { return this.table1; } Join(Attribute oneSide, Attribute otherSide, int joinDirection); Join(List<Attribute> oneSideAttributes, List<Attribute> otherSideAttributes, int joinDirection); boolean isSameTable(); boolean containsColumn(Attribute column); RelationName table1(); RelationName table2(); List<Attribute> attributes1(); List<Attribute> attributes2(); int joinDirection(); Attribute equalAttribute(Attribute column); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object otherObject); Join renameColumns(ColumnRenamer columnRenamer); static final int DIRECTION_UNDIRECTED; static final int DIRECTION_LEFT; static final int DIRECTION_RIGHT; static final String[] joinOperators; }### Answer: @Test public void testTableOrderIsRetained() { Assert.assertEquals(table1, new Join(table1foo, table2foo, Join.DIRECTION_RIGHT).table1()); Assert.assertEquals(table2, new Join(table2foo, table1foo, Join.DIRECTION_RIGHT).table1()); }
### Question: FilterParser { public Filter parseSchemaFilter() throws ParseException { List<Filter> result = new ArrayList<>(); for (List<IdentifierMatcher> list : parse()) { if (list.size() != 1) { throw new ParseException("Syntax error in schema filter list; expected list of comma- or newline-separated schema names: '" + s + "'"); } result.add(new FilterMatchSchema(list.get(0))); } return FilterMatchAny.create(result); } FilterParser(String filterSpec); Filter parseSchemaFilter(); Filter parseTableFilter(boolean matchParents); Filter parseColumnFilter(boolean matchParents); List<List<IdentifierMatcher>> parse(); }### Answer: @Test public void testParseAsSchemaFilter() throws ParseException { Filter result = new FilterParser("schema1,schema2").parseSchemaFilter(); Assert.assertTrue(result.matchesSchema("schema1")); Assert.assertTrue(result.matchesSchema("schema2")); Assert.assertFalse(result.matchesSchema("schema3")); Assert.assertFalse(result.matchesSchema(null)); } @Test public void testParseAsSchemaFilterWithRegex() throws ParseException { Filter result = new FilterParser("/schema[12]/i").parseSchemaFilter(); Assert.assertTrue(result.matchesSchema("schema1")); Assert.assertTrue(result.matchesSchema("SCHEMA2")); Assert.assertFalse(result.matchesSchema("schema3")); Assert.assertFalse(result.matchesSchema(null)); } @Test public void testParseAsSchemaFilterFail() { try { new FilterParser("schema.table").parseSchemaFilter(); Assert.fail("Should have failed because schema.table is not in schema notation"); } catch (ParseException ex) { } }
### Question: NiFIAtlasHook extends AtlasHook { public void createLineageToKafkaTopic() throws Exception { final List<HookNotification.HookNotificationMessage> messages = new ArrayList<>(); final Referenceable topic = new Referenceable("kafka_topic"); topic.set(ATTR_NAME, "notification"); topic.set("topic", "notification"); topic.set(ATTR_QUALIFIED_NAME, "notification@HDPF"); topic.set(ATTR_DESCRIPTION, "Description"); topic.set("uri", "0.hdpf.aws.mine"); final HookNotification.EntityCreateRequest createTopic = new HookNotification.EntityCreateRequest("nifi", topic); final Referenceable path5 = new Referenceable(TYPE_NIFI_FLOW_PATH); path5.set(ATTR_QUALIFIED_NAME, "path5"); final ArrayList<Object> path5Outputs = new ArrayList<>(); path5Outputs.add(new Referenceable(topic)); path5.set(ATTR_OUTPUTS, path5Outputs); messages.add(createTopic); messages.add(new HookNotification.EntityPartialUpdateRequest("nifi", TYPE_NIFI_FLOW_PATH, ATTR_QUALIFIED_NAME, "path5", path5)); notifyEntities(messages); } void sendMessage(); void createLineageFromKafkaTopic(); void createLineageToKafkaTopic(); void addDataSetRefs(DataSetRefs dataSetRefs, Referenceable flowPathRef); void addDataSetRefs(DataSetRefs dataSetRefs, Referenceable flowPathRef, boolean create); void addCreateReferenceable(Collection<Referenceable> ins, Referenceable ref); void addUpdateReferenceable(Referenceable ref); void commitMessages(); }### Answer: @Test public void test() throws Exception { final NiFIAtlasHook hook = new NiFIAtlasHook(); hook.createLineageToKafkaTopic(); }
### Question: NiFiFlowAnalyzer { public NiFiFlow analyzeProcessGroup(AtlasVariables atlasVariables, ReportingContext context) throws IOException { final ProcessGroupStatus rootProcessGroup = context.getEventAccess().getGroupStatus("root"); final String flowName = rootProcessGroup.getName(); final String nifiUrlForAtlasMetadata = atlasVariables.getNifiUrl(); final String nifiUrl = nifiUrlForAtlasMetadata; final NiFiFlow nifiFlow = new NiFiFlow(flowName, rootProcessGroup.getId(), nifiUrl); analyzeProcessGroup(rootProcessGroup, nifiFlow); analyzeRootGroupPorts(nifiFlow, rootProcessGroup); return nifiFlow; } NiFiFlow analyzeProcessGroup(AtlasVariables atlasVariables, ReportingContext context); void analyzePaths(NiFiFlow nifiFlow); }### Answer: @Test public void testEmptyFlow() throws Exception { ReportingContext reportingContext = Mockito.mock(ReportingContext.class); EventAccess eventAccess = Mockito.mock(EventAccess.class); ProcessGroupStatus rootPG = createEmptyProcessGroupStatus(); when(reportingContext.getEventAccess()).thenReturn(eventAccess); when(eventAccess.getGroupStatus(matches("root"))).thenReturn(rootPG); final NiFiFlowAnalyzer analyzer = new NiFiFlowAnalyzer(); final NiFiFlow nifiFlow = analyzer.analyzeProcessGroup(atlasVariables, reportingContext); assertEquals("Flow name", nifiFlow.getFlowName()); }
### Question: Stats { @GET @Produces(MediaType.APPLICATION_JSON) public String getStats() { StatsManager statsManager = this.statsManager; if (this.statsManager != null) { return JSONSerializer.serializeStatistics(statsManager.getStatistics()).toJSONString(); } return new JSONObject().toJSONString(); } @GET @Produces(MediaType.APPLICATION_JSON) String getStats(); }### Answer: @Test public void testGetStats() throws ParseException { Map<String, Object> fakeStats = new HashMap<>(); fakeStats.put("stat1", "value1"); fakeStats.put("stat2", "value2"); VideobridgeStatistics videobridgeStatistics = mock(VideobridgeStatistics.class); when(videobridgeStatistics.getStats()).thenReturn(fakeStats); when(statsManager.getStatistics()).thenReturn(videobridgeStatistics); Response resp = target(BASE_URL).request().get(); assertEquals(HttpStatus.OK_200, resp.getStatus()); assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType()); JSONObject json = getJsonResult(resp); assertEquals("value1", json.get("stat1")); assertEquals("value2", json.get("stat2")); }
### Question: BasicList1 extends BasicConstList<E> { @Override public ConstList<E> delete(int index) { if (index == 0) { return emptyList(); } throw new IndexOutOfBoundsException(); } @SuppressWarnings("unchecked") BasicList1(Object e0); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override int indexOf(Object o); @Override int lastIndexOf(Object o); @Override E get(int index); @Override Object[] toArray(); @Override ConstList<E> with(E e); @Override ConstList<E> with(int index, E e); @Override ConstList<E> withAll(Collection<? extends E> c); @Override ConstList<E> withAll(int index, Collection<? extends E> c); @Override ConstList<E> replace(int index, E e); @Override ConstList<E> without(Object o); @Override ConstList<E> delete(int index); @Override ConstList<E> withoutAll(Collection<?> c); @Override ConstList<E> subList(int fromIndex, int toIndex); @Override boolean equals(Object that); @Override int hashCode(); }### Answer: @Test public void test_delete() { compare_lists(Collections.emptyList(), new BasicList1<>(1).delete(0)); } @Test(expected = IndexOutOfBoundsException.class) public void test_delete_out_of_bounds() { new BasicList1<>(1).delete(1); }
### Question: BasicList1 extends BasicConstList<E> { @Override public ConstList<E> withoutAll(Collection<?> c) { return !c.contains(e0) ? this : BasicCollections.<E>emptyList(); } @SuppressWarnings("unchecked") BasicList1(Object e0); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override int indexOf(Object o); @Override int lastIndexOf(Object o); @Override E get(int index); @Override Object[] toArray(); @Override ConstList<E> with(E e); @Override ConstList<E> with(int index, E e); @Override ConstList<E> withAll(Collection<? extends E> c); @Override ConstList<E> withAll(int index, Collection<? extends E> c); @Override ConstList<E> replace(int index, E e); @Override ConstList<E> without(Object o); @Override ConstList<E> delete(int index); @Override ConstList<E> withoutAll(Collection<?> c); @Override ConstList<E> subList(int fromIndex, int toIndex); @Override boolean equals(Object that); @Override int hashCode(); }### Answer: @Test public void test_withoutAll() { ConstList<Integer> list = new BasicList1<>(1); assertSame(BasicList0.instance(), list.withoutAll(Arrays.asList(1))); assertSame(BasicList0.instance(), list.withoutAll(Arrays.asList(2, 1))); assertSame(list, list.withoutAll(Arrays.asList(2))); assertSame(list, list.withoutAll(Arrays.asList())); } @Test(expected = NullPointerException.class) public void test_withoutAll_throws() { new BasicList1<>(1).withoutAll(null); }
### Question: BasicList1 extends BasicConstList<E> { @Override public ConstList<E> subList(int fromIndex, int toIndex) { ArrayTools.checkRange(fromIndex, toIndex, 1); return fromIndex != toIndex ? this : BasicCollections.<E>emptyList(); } @SuppressWarnings("unchecked") BasicList1(Object e0); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override int indexOf(Object o); @Override int lastIndexOf(Object o); @Override E get(int index); @Override Object[] toArray(); @Override ConstList<E> with(E e); @Override ConstList<E> with(int index, E e); @Override ConstList<E> withAll(Collection<? extends E> c); @Override ConstList<E> withAll(int index, Collection<? extends E> c); @Override ConstList<E> replace(int index, E e); @Override ConstList<E> without(Object o); @Override ConstList<E> delete(int index); @Override ConstList<E> withoutAll(Collection<?> c); @Override ConstList<E> subList(int fromIndex, int toIndex); @Override boolean equals(Object that); @Override int hashCode(); }### Answer: @Test public void test_subList() { ConstList<Integer> list = new BasicList1<>(1); assertSame(BasicList0.instance(), list.subList(0, 0)); assertSame(list, list.subList(0, 1)); assertSame(BasicList0.instance(), list.subList(1, 1)); }
### Question: BasicList1 extends BasicConstList<E> { private boolean equals(List<?> that) { if (that.size() == 1) { Object o; try { o = that.get(0); } catch (IndexOutOfBoundsException e) { return false; } return Objects.equals(o, e0); } return false; } @SuppressWarnings("unchecked") BasicList1(Object e0); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override int indexOf(Object o); @Override int lastIndexOf(Object o); @Override E get(int index); @Override Object[] toArray(); @Override ConstList<E> with(E e); @Override ConstList<E> with(int index, E e); @Override ConstList<E> withAll(Collection<? extends E> c); @Override ConstList<E> withAll(int index, Collection<? extends E> c); @Override ConstList<E> replace(int index, E e); @Override ConstList<E> without(Object o); @Override ConstList<E> delete(int index); @Override ConstList<E> withoutAll(Collection<?> c); @Override ConstList<E> subList(int fromIndex, int toIndex); @Override boolean equals(Object that); @Override int hashCode(); }### Answer: @Test public void test_non_equality() { assertFalse(new BasicList1<>(1).equals(Arrays.asList(2))); assertFalse(Arrays.asList(2).equals(new BasicList1<>(1))); ConstList<Integer> empty = BasicList0.instance(); assertFalse(new BasicList1<>(1).equals(empty)); }
### Question: BasicMap1 extends BasicConstMap<K, V> { @Override public ConstMap<K, V> with(K key, V value) { if (Objects.equals(key, k0)) { if (Objects.equals(value, v0)) { return this; } return new BasicMap1<>(k0, value); } return new BasicMapN<>(new Object[] {k0, key}, new Object[] {v0, value}); } @SuppressWarnings("unchecked") BasicMap1(Object k0, Object v0); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override V get(Object key); @Override ConstSet<K> keySet(); @Override ConstCollection<V> values(); @Override ConstSet<Entry<K, V>> entrySet(); @Override ConstMap<K, V> with(K key, V value); @Override ConstMap<K, V> withAll(Map<? extends K, ? extends V> map); @Override ConstMap<K, V> without(Object key); @Override ConstMap<K, V> withoutAll(Collection<?> keys); @Override int hashCode(); }### Answer: @Test public void test_with() { ConstMap<Object, Object> map; map = new BasicMap1<>("a", 1); compare_maps(newMap("a", 1, "b", 2), map.with("b", 2)); compare_maps(newMap("a", 2), map.with("a", 2)); compare_maps(newMap("a", 1, null, null), map.with(null, null)); compare_maps(newMap("a", null), map.with("a", null)); assertSame(map, map.with("a", 1)); map = new BasicMap1<>(null, null); assertSame(map, map.with(null, null)); }
### Question: BasicMap1 extends BasicConstMap<K, V> { @Override public ConstMap<K, V> withAll(Map<? extends K, ? extends V> map) { if (map.isEmpty()) { return this; } MapColumns mc = copy(map); return condenseToMap(unionInto(new Object[] {k0}, new Object[] {v0}, mc.keys, mc.values)); } @SuppressWarnings("unchecked") BasicMap1(Object k0, Object v0); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override V get(Object key); @Override ConstSet<K> keySet(); @Override ConstCollection<V> values(); @Override ConstSet<Entry<K, V>> entrySet(); @Override ConstMap<K, V> with(K key, V value); @Override ConstMap<K, V> withAll(Map<? extends K, ? extends V> map); @Override ConstMap<K, V> without(Object key); @Override ConstMap<K, V> withoutAll(Collection<?> keys); @Override int hashCode(); }### Answer: @Test public void test_withAll() { ConstMap<Object, Object> map = new BasicMap1<>("a", 1); compare_maps(newMap("a", 2, "b", 2, "c", 3), map.withAll(newMap("b", 2, "c", 3, "a", 2))); compare_maps(map, map.withAll(newMap("a", 1))); assertSame(map, map.withAll(newMap())); } @Test(expected = NullPointerException.class) public void test_withAll_throws() { new BasicMap1<>("a", 1).withAll(null); }
### Question: BasicMap1 extends BasicConstMap<K, V> { @Override public ConstMap<K, V> without(Object key) { return !containsKey(key) ? this : BasicCollections.<K, V>emptyMap(); } @SuppressWarnings("unchecked") BasicMap1(Object k0, Object v0); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override V get(Object key); @Override ConstSet<K> keySet(); @Override ConstCollection<V> values(); @Override ConstSet<Entry<K, V>> entrySet(); @Override ConstMap<K, V> with(K key, V value); @Override ConstMap<K, V> withAll(Map<? extends K, ? extends V> map); @Override ConstMap<K, V> without(Object key); @Override ConstMap<K, V> withoutAll(Collection<?> keys); @Override int hashCode(); }### Answer: @Test public void test_without() { ConstMap<Object, Object> map = new BasicMap1<>("a", 1); assertSame(BasicMap0.instance(), map.without("a")); assertSame(map, map.without("b")); assertSame(map, map.without(null)); }
### Question: BasicMap1 extends BasicConstMap<K, V> { @Override public ConstMap<K, V> withoutAll(Collection<?> keys) { return !keys.contains(k0) ? this : BasicCollections.<K, V>emptyMap(); } @SuppressWarnings("unchecked") BasicMap1(Object k0, Object v0); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override V get(Object key); @Override ConstSet<K> keySet(); @Override ConstCollection<V> values(); @Override ConstSet<Entry<K, V>> entrySet(); @Override ConstMap<K, V> with(K key, V value); @Override ConstMap<K, V> withAll(Map<? extends K, ? extends V> map); @Override ConstMap<K, V> without(Object key); @Override ConstMap<K, V> withoutAll(Collection<?> keys); @Override int hashCode(); }### Answer: @Test public void test_withoutAll() { ConstMap<Object, Object> map = new BasicMap1<>("a", 1); assertSame(BasicMap0.instance(), map.withoutAll(Arrays.asList("a"))); assertSame(BasicMap0.instance(), map.withoutAll(Arrays.asList("b", "a", "b", "a"))); assertSame(map, map.withoutAll(Arrays.asList("b"))); assertSame(map, map.withoutAll(Arrays.asList())); } @Test(expected = NullPointerException.class) public void test_withoutAll_throws() { new BasicMap1<>("a", 1).withoutAll(null); }
### Question: BasicMap1 extends BasicConstMap<K, V> { @Override K getKey(int index) { if (index == 0) { return k0; } throw new IndexOutOfBoundsException(); } @SuppressWarnings("unchecked") BasicMap1(Object k0, Object v0); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override V get(Object key); @Override ConstSet<K> keySet(); @Override ConstCollection<V> values(); @Override ConstSet<Entry<K, V>> entrySet(); @Override ConstMap<K, V> with(K key, V value); @Override ConstMap<K, V> withAll(Map<? extends K, ? extends V> map); @Override ConstMap<K, V> without(Object key); @Override ConstMap<K, V> withoutAll(Collection<?> keys); @Override int hashCode(); }### Answer: @Test public void test_get_key() { assertEquals("a", new BasicMap1<>("a", 1).getKey(0)); } @Test(expected = IndexOutOfBoundsException.class) public void test_out_of_bounds_get_key() { new BasicMap1<>("a", 1).getKey(1); }
### Question: BasicMap1 extends BasicConstMap<K, V> { @Override V getValue(int index) { if (index == 0) { return v0; } throw new IndexOutOfBoundsException(); } @SuppressWarnings("unchecked") BasicMap1(Object k0, Object v0); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override V get(Object key); @Override ConstSet<K> keySet(); @Override ConstCollection<V> values(); @Override ConstSet<Entry<K, V>> entrySet(); @Override ConstMap<K, V> with(K key, V value); @Override ConstMap<K, V> withAll(Map<? extends K, ? extends V> map); @Override ConstMap<K, V> without(Object key); @Override ConstMap<K, V> withoutAll(Collection<?> keys); @Override int hashCode(); }### Answer: @Test public void test_get_value() { assertEquals(1, new BasicMap1<>("a", 1).getValue(0)); } @Test(expected = IndexOutOfBoundsException.class) public void test_out_of_bounds_get_value() { new BasicMap1<>("a", 1).getValue(1); }
### Question: BasicConstSortedSet extends BasicConstSet<E> implements ConstSortedSet<E> { @Override public Comparator<? super E> comparator() { return comparator; } BasicConstSortedSet(Comparator<? super E> comparator); @Override Comparator<? super E> comparator(); }### Answer: @Test public void test_emptySortedSet() { assertSame(BasicSortedSet0.instance(null), emptySortedSet(null)); Comparator<Object> reverse = reverseOrder(); assertSame(BasicSortedSet0.instance(reverse).comparator(), emptySortedSet(reverse).comparator()); }
### Question: BasicSortedSet1 extends BasicConstSortedSet<E> { @Override public ConstSortedSet<E> with(E e) { int cmp = compare(e, e0); return cmp == 0 ? this : cmp < 0 ? new BasicSortedSetN<>(comparator, new Object[] {e, e0}) : new BasicSortedSetN<>(comparator, new Object[] {e0, e}); } @SuppressWarnings("unchecked") BasicSortedSet1(Comparator<? super E> comparator, Object e0); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override E first(); @Override E last(); @Override Object[] toArray(); @Override ConstSortedSet<E> with(E e); @Override ConstSortedSet<E> withAll(Collection<? extends E> c); @Override ConstSortedSet<E> without(Object o); @Override ConstSortedSet<E> withoutAll(Collection<?> c); @Override ConstSortedSet<E> headSet(E toElement); @Override ConstSortedSet<E> tailSet(E fromElement); @Override ConstSortedSet<E> subSet(E fromElement, E toElement); @Override int hashCode(); }### Answer: @Test public void test_with() { ConstSortedSet<Integer> set; set = new BasicSortedSet1<>(null, 1); compare_sorted_sets(newSortedSet(null, 1, 2), set.with(2)); assertSame(set, set.with(1)); set = new BasicSortedSet1<>(reverseOrder(), 1); compare_sorted_sets(newSortedSet(reverseOrder(), 2, 1), set.with(2)); assertSame(set, set.with(1)); }
### Question: BasicSortedSet1 extends BasicConstSortedSet<E> { @Override public ConstSortedSet<E> without(Object o) { return !contains(o) ? this : emptySortedSet(comparator); } @SuppressWarnings("unchecked") BasicSortedSet1(Comparator<? super E> comparator, Object e0); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override E first(); @Override E last(); @Override Object[] toArray(); @Override ConstSortedSet<E> with(E e); @Override ConstSortedSet<E> withAll(Collection<? extends E> c); @Override ConstSortedSet<E> without(Object o); @Override ConstSortedSet<E> withoutAll(Collection<?> c); @Override ConstSortedSet<E> headSet(E toElement); @Override ConstSortedSet<E> tailSet(E fromElement); @Override ConstSortedSet<E> subSet(E fromElement, E toElement); @Override int hashCode(); }### Answer: @Test public void test_without() { ConstSortedSet<Integer> set; set = new BasicSortedSet1<>(null, 1); compare_sorted_sets(BasicSortedSet0.instance(null), set.without(1)); assertSame(set, set.without(2)); set = new BasicSortedSet1<>(reverseOrder(), 1); compare_sorted_sets(BasicSortedSet0.instance(reverseOrder()), set.without(1)); assertSame(set, set.without(2)); }
### Question: BasicSortedSet1 extends BasicConstSortedSet<E> { @Override E get(int index) { if (index == 0) { return e0; } throw new IndexOutOfBoundsException(); } @SuppressWarnings("unchecked") BasicSortedSet1(Comparator<? super E> comparator, Object e0); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override E first(); @Override E last(); @Override Object[] toArray(); @Override ConstSortedSet<E> with(E e); @Override ConstSortedSet<E> withAll(Collection<? extends E> c); @Override ConstSortedSet<E> without(Object o); @Override ConstSortedSet<E> withoutAll(Collection<?> c); @Override ConstSortedSet<E> headSet(E toElement); @Override ConstSortedSet<E> tailSet(E fromElement); @Override ConstSortedSet<E> subSet(E fromElement, E toElement); @Override int hashCode(); }### Answer: @Test public void test_get() { assertEquals(1, new BasicSortedSet1<>(null, 1).get(0)); } @Test(expected = IndexOutOfBoundsException.class) public void test_out_of_bounds_get() { new BasicSortedSet1<>(null, 1).get(1); }
### Question: BasicMapN extends BasicConstMap<K, V> { @Override public ConstMap<K, V> withAll(Map<? extends K, ? extends V> map) { if (map.isEmpty()) { return this; } MapColumns mc = copy(map); return condenseToMap(unionInto(keys, values, mc.keys, mc.values)); } @SuppressWarnings("unchecked") BasicMapN(Object[] keys, Object[] values); @Override int size(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override V get(Object key); @Override ConstSet<K> keySet(); @Override ConstCollection<V> values(); @Override ConstSet<Entry<K, V>> entrySet(); @Override ConstMap<K, V> with(K key, V value); @Override ConstMap<K, V> withAll(Map<? extends K, ? extends V> map); @Override ConstMap<K, V> without(Object key); @Override ConstMap<K, V> withoutAll(Collection<?> keysToDelete); @Override int hashCode(); }### Answer: @Test public void test_withAll() { ConstMap<Object, Object> map = new BasicMapN<>(new Object[] {"a", "b", "c", "d"}, new Object[] {1, 2, 3, 4}); compare_maps( newMap("a", 1, "b", 9, "c", 3, "d", 4, "e", 5, "f", 6), map.withAll(newMap("e", 5, "f", 6, "b", 9))); compare_maps(map, map.withAll(newMap("a", 1, "b", 2))); assertSame(map, map.withAll(newMap())); } @Test(expected = NullPointerException.class) public void test_withAll_throws() { new BasicMapN<>(new Object[] {"a", "b", "c", "d"}, new Object[] {1, 2, 3, 4}).withAll(null); }