method2testcases
stringlengths 118
3.08k
|
---|
### Question:
FlowSegmentCookieConverter implements AttributeConverter<FlowSegmentCookie, Long> { @Override public Long toGraphProperty(FlowSegmentCookie value) { if (value == null) { return null; } return value.getValue(); } @Override Long toGraphProperty(FlowSegmentCookie value); @Override FlowSegmentCookie toEntityAttribute(Long value); static final FlowSegmentCookieConverter INSTANCE; }### Answer:
@Test public void shouldConvertIdToLong() { FlowSegmentCookie cookie = new FlowSegmentCookie((long) 0x123); Long graphObject = FlowSegmentCookieConverter.INSTANCE.toGraphProperty(cookie); assertEquals(cookie.getValue(), (long) graphObject); } |
### Question:
FlowSegmentCookieConverter implements AttributeConverter<FlowSegmentCookie, Long> { @Override public FlowSegmentCookie toEntityAttribute(Long value) { if (value == null) { return null; } return new FlowSegmentCookie(value); } @Override Long toGraphProperty(FlowSegmentCookie value); @Override FlowSegmentCookie toEntityAttribute(Long value); static final FlowSegmentCookieConverter INSTANCE; }### Answer:
@Test public void shouldConvertLongToId() { FlowSegmentCookie cookie = new FlowSegmentCookie((long) 0x123); FlowSegmentCookie actualEntity = FlowSegmentCookieConverter.INSTANCE.toEntityAttribute(cookie.getValue()); assertEquals(cookie, actualEntity); } |
### Question:
SwitchStatusConverter implements AttributeConverter<SwitchStatus, String> { @Override public String toGraphProperty(SwitchStatus value) { if (value == null) { return null; } return value.name().toLowerCase(); } @Override String toGraphProperty(SwitchStatus value); @Override SwitchStatus toEntityAttribute(String value); static final SwitchStatusConverter INSTANCE; }### Answer:
@Test public void shouldConvertToGraphProperty() { SwitchStatusConverter converter = SwitchStatusConverter.INSTANCE; assertEquals("active", converter.toGraphProperty(SwitchStatus.ACTIVE)); assertEquals("inactive", converter.toGraphProperty(SwitchStatus.INACTIVE)); } |
### Question:
SwitchStatusConverter implements AttributeConverter<SwitchStatus, String> { @Override public SwitchStatus toEntityAttribute(String value) { if (value == null || value.trim().isEmpty()) { return null; } return SwitchStatus.valueOf(value.toUpperCase()); } @Override String toGraphProperty(SwitchStatus value); @Override SwitchStatus toEntityAttribute(String value); static final SwitchStatusConverter INSTANCE; }### Answer:
@Test public void shouldConvertToEntity() { SwitchStatusConverter converter = SwitchStatusConverter.INSTANCE; assertEquals(SwitchStatus.ACTIVE, converter.toEntityAttribute("ACTIVE")); assertEquals(SwitchStatus.ACTIVE, converter.toEntityAttribute("active")); assertEquals(SwitchStatus.INACTIVE, converter.toEntityAttribute("InActive")); } |
### Question:
FlowEncapsulationTypeConverter implements AttributeConverter<FlowEncapsulationType, String> { @Override public String toGraphProperty(FlowEncapsulationType value) { if (value == null) { return null; } return value.name(); } @Override String toGraphProperty(FlowEncapsulationType value); @Override FlowEncapsulationType toEntityAttribute(String value); static final FlowEncapsulationTypeConverter INSTANCE; }### Answer:
@Test public void shouldConvertToGraphProperty() { assertEquals("TRANSIT_VLAN", FlowEncapsulationTypeConverter.INSTANCE.toGraphProperty(FlowEncapsulationType.TRANSIT_VLAN)); } |
### Question:
FlowEncapsulationTypeConverter implements AttributeConverter<FlowEncapsulationType, String> { @Override public FlowEncapsulationType toEntityAttribute(String value) { if (value == null || value.trim().isEmpty()) { return null; } return FlowEncapsulationType.valueOf(value); } @Override String toGraphProperty(FlowEncapsulationType value); @Override FlowEncapsulationType toEntityAttribute(String value); static final FlowEncapsulationTypeConverter INSTANCE; }### Answer:
@Test public void shouldConvertToEntity() { assertEquals(FlowEncapsulationType.TRANSIT_VLAN, FlowEncapsulationTypeConverter.INSTANCE.toEntityAttribute("TRANSIT_VLAN")); } |
### Question:
MeterIdConverter implements AttributeConverter<MeterId, Long> { @Override public Long toGraphProperty(MeterId value) { if (value == null) { return null; } return value.getValue(); } @Override Long toGraphProperty(MeterId value); @Override MeterId toEntityAttribute(Long value); static final MeterIdConverter INSTANCE; }### Answer:
@Test public void shouldConvertIdToString() { MeterId meterId = new MeterId(0x123); Long graphObject = MeterIdConverter.INSTANCE.toGraphProperty(meterId); assertEquals(meterId.getValue(), (long) graphObject); } |
### Question:
MeterIdConverter implements AttributeConverter<MeterId, Long> { @Override public MeterId toEntityAttribute(Long value) { if (value == null) { return null; } return new MeterId(value); } @Override Long toGraphProperty(MeterId value); @Override MeterId toEntityAttribute(Long value); static final MeterIdConverter INSTANCE; }### Answer:
@Test public void shouldConvertStringToId() { MeterId meterId = new MeterId(0x123); MeterId actualEntity = MeterIdConverter.INSTANCE.toEntityAttribute(meterId.getValue()); assertEquals(meterId, actualEntity); } |
### Question:
IslStatusConverter implements AttributeConverter<IslStatus, String> { @Override public String toGraphProperty(IslStatus value) { if (value == null) { return null; } return value.name().toLowerCase(); } @Override String toGraphProperty(IslStatus value); @Override IslStatus toEntityAttribute(String value); static final IslStatusConverter INSTANCE; }### Answer:
@Test public void shouldConvertToGraphProperty() { IslStatusConverter converter = IslStatusConverter.INSTANCE; assertEquals("active", converter.toGraphProperty(IslStatus.ACTIVE)); assertEquals("inactive", converter.toGraphProperty(IslStatus.INACTIVE)); } |
### Question:
IslStatusConverter implements AttributeConverter<IslStatus, String> { @Override public IslStatus toEntityAttribute(String value) { if (value == null || value.trim().isEmpty()) { return null; } return IslStatus.valueOf(value.toUpperCase()); } @Override String toGraphProperty(IslStatus value); @Override IslStatus toEntityAttribute(String value); static final IslStatusConverter INSTANCE; }### Answer:
@Test public void shouldConvertToEntity() { IslStatusConverter converter = IslStatusConverter.INSTANCE; assertEquals(IslStatus.ACTIVE, converter.toEntityAttribute("ACTIVE")); assertEquals(IslStatus.ACTIVE, converter.toEntityAttribute("active")); assertEquals(IslStatus.INACTIVE, converter.toEntityAttribute("InActive")); } |
### Question:
FermaPortPropertiesRepository extends FermaGenericRepository<PortProperties, PortPropertiesData, PortPropertiesFrame> implements PortPropertiesRepository { @Override public Collection<PortProperties> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(PortPropertiesFrame.FRAME_LABEL)) .toListExplicit(PortPropertiesFrame.class).stream() .map(PortProperties::new) .collect(Collectors.toList()); } FermaPortPropertiesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<PortProperties> findAll(); @Override Optional<PortProperties> getBySwitchIdAndPort(SwitchId switchId, int port); @Override Collection<PortProperties> getAllBySwitchId(SwitchId switchId); }### Answer:
@Test public void shouldCreatePortPropertiesWithRelation() { Switch origSwitch = createTestSwitch(TEST_SWITCH_ID.getId()); PortProperties portProperties = PortProperties.builder() .switchObj(origSwitch) .discoveryEnabled(false) .build(); portPropertiesRepository.add(portProperties); Collection<PortProperties> portPropertiesResult = portPropertiesRepository.findAll(); assertEquals(1, portPropertiesResult.size()); assertNotNull(portPropertiesResult.iterator().next().getSwitchObj()); } |
### Question:
FermaPortPropertiesRepository extends FermaGenericRepository<PortProperties, PortPropertiesData, PortPropertiesFrame> implements PortPropertiesRepository { @Override public Optional<PortProperties> getBySwitchIdAndPort(SwitchId switchId, int port) { List<? extends PortPropertiesFrame> portPropertiesFrames = framedGraph().traverse(g -> g.V() .hasLabel(PortPropertiesFrame.FRAME_LABEL) .has(PortPropertiesFrame.SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(PortPropertiesFrame.PORT_NO_PROPERTY, port)) .toListExplicit(PortPropertiesFrame.class); return portPropertiesFrames.isEmpty() ? Optional.empty() : Optional.of(portPropertiesFrames.get(0)) .map(PortProperties::new); } FermaPortPropertiesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<PortProperties> findAll(); @Override Optional<PortProperties> getBySwitchIdAndPort(SwitchId switchId, int port); @Override Collection<PortProperties> getAllBySwitchId(SwitchId switchId); }### Answer:
@Test public void shouldGetPortPropertiesBySwitchIdAndPort() { Switch origSwitch = createTestSwitch(TEST_SWITCH_ID.getId()); int port = 7; PortProperties portProperties = PortProperties.builder() .switchObj(origSwitch) .port(port) .discoveryEnabled(false) .build(); portPropertiesRepository.add(portProperties); Optional<PortProperties> portPropertiesResult = portPropertiesRepository.getBySwitchIdAndPort(origSwitch.getSwitchId(), port); assertTrue(portPropertiesResult.isPresent()); assertEquals(origSwitch.getSwitchId(), portPropertiesResult.get().getSwitchObj().getSwitchId()); assertEquals(port, portPropertiesResult.get().getPort()); assertFalse(portPropertiesResult.get().isDiscoveryEnabled()); } |
### Question:
FermaFlowCookieRepository extends FermaGenericRepository<FlowCookie, FlowCookieData, FlowCookieFrame> implements FlowCookieRepository { @Override public Collection<FlowCookie> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(FlowCookieFrame.FRAME_LABEL)) .toListExplicit(FlowCookieFrame.class).stream() .map(FlowCookie::new) .collect(Collectors.toList()); } FermaFlowCookieRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowCookie> findAll(); @Override boolean exists(long unmaskedCookie); @Override Optional<FlowCookie> findByCookie(long unmaskedCookie); @Override Optional<Long> findFirstUnassignedCookie(long lowestCookieValue, long highestCookieValue); }### Answer:
@Test public void shouldCreateFlowCookie() { createFlowCookie(); Collection<FlowCookie> allCookies = flowCookieRepository.findAll(); FlowCookie foundCookie = allCookies.iterator().next(); assertEquals(TEST_COOKIE, foundCookie.getUnmaskedCookie()); assertEquals(TEST_FLOW_ID, foundCookie.getFlowId()); }
@Test public void shouldDeleteFlowCookie() { FlowCookie cookie = createFlowCookie(); transactionManager.doInTransaction(() -> flowCookieRepository.remove(cookie)); assertEquals(0, flowCookieRepository.findAll().size()); }
@Test public void shouldDeleteFoundFlowCookie() { createFlowCookie(); transactionManager.doInTransaction(() -> { Collection<FlowCookie> allCookies = flowCookieRepository.findAll(); FlowCookie foundCookie = allCookies.iterator().next(); flowCookieRepository.remove(foundCookie); }); assertEquals(0, flowCookieRepository.findAll().size()); } |
### Question:
FermaFlowCookieRepository extends FermaGenericRepository<FlowCookie, FlowCookieData, FlowCookieFrame> implements FlowCookieRepository { @Override public Optional<FlowCookie> findByCookie(long unmaskedCookie) { List<? extends FlowCookieFrame> flowCookieFrames = framedGraph().traverse(g -> g.V() .hasLabel(FlowCookieFrame.FRAME_LABEL) .has(FlowCookieFrame.UNMASKED_COOKIE_PROPERTY, unmaskedCookie)) .toListExplicit(FlowCookieFrame.class); return flowCookieFrames.isEmpty() ? Optional.empty() : Optional.of(flowCookieFrames.get(0)) .map(FlowCookie::new); } FermaFlowCookieRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowCookie> findAll(); @Override boolean exists(long unmaskedCookie); @Override Optional<FlowCookie> findByCookie(long unmaskedCookie); @Override Optional<Long> findFirstUnassignedCookie(long lowestCookieValue, long highestCookieValue); }### Answer:
@Test public void shouldSelectNextInOrderResourceWhenFindUnassignedCookie() { long first = findUnassignedCookieAndCreate("flow_1"); assertEquals(5, first); long second = findUnassignedCookieAndCreate("flow_2"); assertEquals(6, second); long third = findUnassignedCookieAndCreate("flow_3"); assertEquals(7, third); transactionManager.doInTransaction(() -> flowCookieRepository.findByCookie(second).ifPresent(flowCookieRepository::remove)); long fourth = findUnassignedCookieAndCreate("flow_4"); assertEquals(6, fourth); long fifth = findUnassignedCookieAndCreate("flow_5"); assertEquals(8, fifth); } |
### Question:
FermaApplicationRepository extends FermaGenericRepository<ApplicationRule, ApplicationRuleData,
ApplicationRuleFrame> implements ApplicationRepository { @Override public Collection<ApplicationRule> findBySwitchId(SwitchId switchId) { return framedGraph().traverse(g -> g.V() .hasLabel(ApplicationRuleFrame.FRAME_LABEL) .has(ApplicationRuleFrame.SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId))) .toListExplicit(ApplicationRuleFrame.class).stream() .map(ApplicationRule::new) .collect(Collectors.toList()); } FermaApplicationRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Optional<ApplicationRule> lookupRuleByMatchAndFlow(SwitchId switchId, String flowId, String srcIp,
Integer srcPort, String dstIp, Integer dstPort,
String proto, String ethType, Long metadata); @Override Optional<ApplicationRule> lookupRuleByMatchAndCookie(SwitchId switchId, ExclusionCookie cookie, String srcIp,
Integer srcPort, String dstIp, Integer dstPort,
String proto, String ethType, Long metadata); @Override Collection<ApplicationRule> findBySwitchId(SwitchId switchId); @Override Collection<ApplicationRule> findByFlowId(String flowId); }### Answer:
@Test public void shouldFindBySwitchId() { Collection<ApplicationRule> foundRules = applicationRepository.findBySwitchId(TEST_SWITCH_ID); assertEquals(2, foundRules.size()); assertTrue(foundRules.contains(buildRuleA())); assertTrue(foundRules.contains(buildRuleC())); } |
### Question:
FermaApplicationRepository extends FermaGenericRepository<ApplicationRule, ApplicationRuleData,
ApplicationRuleFrame> implements ApplicationRepository { @Override public Collection<ApplicationRule> findByFlowId(String flowId) { return framedGraph().traverse(g -> g.V() .hasLabel(ApplicationRuleFrame.FRAME_LABEL) .has(ApplicationRuleFrame.FLOW_ID_PROPERTY, flowId)) .toListExplicit(ApplicationRuleFrame.class).stream() .map(ApplicationRule::new) .collect(Collectors.toList()); } FermaApplicationRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Optional<ApplicationRule> lookupRuleByMatchAndFlow(SwitchId switchId, String flowId, String srcIp,
Integer srcPort, String dstIp, Integer dstPort,
String proto, String ethType, Long metadata); @Override Optional<ApplicationRule> lookupRuleByMatchAndCookie(SwitchId switchId, ExclusionCookie cookie, String srcIp,
Integer srcPort, String dstIp, Integer dstPort,
String proto, String ethType, Long metadata); @Override Collection<ApplicationRule> findBySwitchId(SwitchId switchId); @Override Collection<ApplicationRule> findByFlowId(String flowId); }### Answer:
@Test public void shouldFindByFlowId() { Collection<ApplicationRule> foundRules = applicationRepository.findByFlowId(TEST_FLOW_ID); assertEquals(2, foundRules.size()); assertTrue(foundRules.contains(buildRuleA())); assertTrue(foundRules.contains(buildRuleB())); } |
### Question:
FermaSwitchRepository extends FermaGenericRepository<Switch, SwitchData, SwitchFrame> implements SwitchRepository { @Override public Collection<Switch> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(SwitchFrame.FRAME_LABEL)) .toListExplicit(SwitchFrame.class).stream() .map(Switch::new) .collect(Collectors.toList()); } FermaSwitchRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<Switch> findAll(); @Override boolean exists(SwitchId switchId); @Override Collection<Switch> findActive(); @Override Optional<Switch> findById(SwitchId switchId); @Override Collection<Switch> findSwitchesInFlowPathByFlowId(String flowId); @Override @TransactionRequired boolean removeIfNoDependant(Switch entity); }### Answer:
@Test public void shouldCreateSwitch() { switchRepository.add(Switch.builder() .switchId(TEST_SWITCH_ID_A) .description("Some description") .build()); assertEquals(1, switchRepository.findAll().size()); }
@Test public void shouldDeleteSwitch() { Switch origSwitch = Switch.builder() .switchId(TEST_SWITCH_ID_A) .description("Some description") .build(); switchRepository.add(origSwitch); transactionManager.doInTransaction(() -> switchRepository.remove(origSwitch)); assertEquals(0, switchRepository.findAll().size()); } |
### Question:
FermaSwitchRepository extends FermaGenericRepository<Switch, SwitchData, SwitchFrame> implements SwitchRepository { @Override public Collection<Switch> findActive() { return framedGraph().traverse(g -> g.V() .hasLabel(SwitchFrame.FRAME_LABEL) .has(SwitchFrame.STATUS_PROPERTY, SwitchStatusConverter.INSTANCE.toGraphProperty(SwitchStatus.ACTIVE))) .toListExplicit(SwitchFrame.class).stream() .map(Switch::new) .collect(Collectors.toList()); } FermaSwitchRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<Switch> findAll(); @Override boolean exists(SwitchId switchId); @Override Collection<Switch> findActive(); @Override Optional<Switch> findById(SwitchId switchId); @Override Collection<Switch> findSwitchesInFlowPathByFlowId(String flowId); @Override @TransactionRequired boolean removeIfNoDependant(Switch entity); }### Answer:
@Test public void shouldFindActive() { Switch activeSwitch = Switch.builder().switchId(TEST_SWITCH_ID_A) .status(SwitchStatus.ACTIVE).build(); Switch inactiveSwitch = Switch.builder().switchId(TEST_SWITCH_ID_B) .status(SwitchStatus.INACTIVE).build(); switchRepository.add(activeSwitch); switchRepository.add(inactiveSwitch); Collection<Switch> switches = switchRepository.findActive(); assertEquals(1, switches.size()); assertEquals(TEST_SWITCH_ID_A, switches.iterator().next().getSwitchId()); } |
### Question:
FermaSwitchRepository extends FermaGenericRepository<Switch, SwitchData, SwitchFrame> implements SwitchRepository { @Override public Optional<Switch> findById(SwitchId switchId) { return SwitchFrame.load(framedGraph(), SwitchIdConverter.INSTANCE.toGraphProperty(switchId)).map(Switch::new); } FermaSwitchRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<Switch> findAll(); @Override boolean exists(SwitchId switchId); @Override Collection<Switch> findActive(); @Override Optional<Switch> findById(SwitchId switchId); @Override Collection<Switch> findSwitchesInFlowPathByFlowId(String flowId); @Override @TransactionRequired boolean removeIfNoDependant(Switch entity); }### Answer:
@Test public void shouldFindSwitchById() { Switch origSwitch = Switch.builder() .switchId(TEST_SWITCH_ID_A) .description("Some description") .build(); switchRepository.add(origSwitch); Switch foundSwitch = switchRepository.findById(TEST_SWITCH_ID_A).get(); assertEquals(origSwitch.getDescription(), foundSwitch.getDescription()); } |
### Question:
FermaTransitVlanRepository extends FermaGenericRepository<TransitVlan, TransitVlanData, TransitVlanFrame> implements TransitVlanRepository { @Override public Collection<TransitVlan> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(TransitVlanFrame.FRAME_LABEL)) .toListExplicit(TransitVlanFrame.class).stream() .map(TransitVlan::new) .collect(Collectors.toList()); } FermaTransitVlanRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<TransitVlan> findAll(); @Override Collection<TransitVlan> findByPathId(PathId pathId, PathId oppositePathId); @Override Optional<TransitVlan> findByPathId(PathId pathId); @Override boolean exists(int vlan); @Override Optional<TransitVlan> findByVlan(int vlan); @Override Optional<Integer> findFirstUnassignedVlan(int lowestTransitVlan, int highestTransitVlan); }### Answer:
@Test public void shouldCreateTransitVlan() { TransitVlan vlan = createTransitVlan(); Collection<TransitVlan> allVlans = transitVlanRepository.findAll(); TransitVlan foundVlan = allVlans.iterator().next(); assertEquals(vlan.getVlan(), foundVlan.getVlan()); assertEquals(TEST_FLOW_ID, foundVlan.getFlowId()); }
@Test public void shouldDeleteTransitVlan() { TransitVlan vlan = createTransitVlan(); transactionManager.doInTransaction(() -> transitVlanRepository.remove(vlan)); assertEquals(0, transitVlanRepository.findAll().size()); }
@Test public void shouldDeleteFoundTransitVlan() { createTransitVlan(); Collection<TransitVlan> allVlans = transitVlanRepository.findAll(); TransitVlan foundVlan = allVlans.iterator().next(); transactionManager.doInTransaction(() -> transitVlanRepository.remove(foundVlan)); assertEquals(0, transitVlanRepository.findAll().size()); } |
### Question:
FermaFlowMeterRepository extends FermaGenericRepository<FlowMeter, FlowMeterData, FlowMeterFrame> implements FlowMeterRepository { @Override public Optional<FlowMeter> findByPathId(PathId pathId) { List<? extends FlowMeterFrame> flowMeterFrames = framedGraph().traverse(g -> g.V() .hasLabel(FlowMeterFrame.FRAME_LABEL) .has(FlowMeterFrame.PATH_ID_PROPERTY, PathIdConverter.INSTANCE.toGraphProperty(pathId))) .toListExplicit(FlowMeterFrame.class); return flowMeterFrames.isEmpty() ? Optional.empty() : Optional.of(flowMeterFrames.get(0)) .map(FlowMeter::new); } FermaFlowMeterRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowMeter> findAll(); @Override Optional<FlowMeter> findByPathId(PathId pathId); @Override boolean exists(SwitchId switchId, MeterId meterId); @Override Optional<MeterId> findFirstUnassignedMeter(SwitchId switchId, MeterId lowestMeterId,
MeterId highestMeterId); }### Answer:
@Ignore("InMemoryGraph doesn't enforce constraint") @Test(expected = PersistenceException.class) public void shouldNotGetMoreThanOneMetersForPath() { createFlowMeter(1, new PathId(TEST_PATH_ID)); createFlowMeter(2, new PathId(TEST_PATH_ID)); flowMeterRepository.findByPathId(new PathId(TEST_PATH_ID)); }
@Test public void shouldGetZeroMetersForPath() { Optional<FlowMeter> meters = flowMeterRepository.findByPathId(new PathId(TEST_PATH_ID)); assertFalse(meters.isPresent()); } |
### Question:
FermaSwitchConnectedDevicesRepository extends FermaGenericRepository<SwitchConnectedDevice, SwitchConnectedDeviceData, SwitchConnectedDeviceFrame> implements SwitchConnectedDeviceRepository { @Override public Collection<SwitchConnectedDevice> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(SwitchConnectedDeviceFrame.FRAME_LABEL)) .toListExplicit(SwitchConnectedDeviceFrame.class).stream() .map(SwitchConnectedDevice::new) .collect(Collectors.toList()); } FermaSwitchConnectedDevicesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<SwitchConnectedDevice> findAll(); @Override Collection<SwitchConnectedDevice> findBySwitchId(SwitchId switchId); @Override Collection<SwitchConnectedDevice> findByFlowId(String flowId); @Override Optional<SwitchConnectedDevice> findLldpByUniqueFieldCombination(
SwitchId switchId, int portNumber, int vlan, String macAddress, String chassisId, String portId); @Override Optional<SwitchConnectedDevice> findArpByUniqueFieldCombination(
SwitchId switchId, int portNumber, int vlan, String macAddress, String ipAddress); }### Answer:
@Test public void createConnectedDeviceTest() { connectedDeviceRepository.add(lldpConnectedDeviceA); Collection<SwitchConnectedDevice> devices = connectedDeviceRepository.findAll(); assertEquals(lldpConnectedDeviceA, devices.iterator().next()); assertNotNull(devices.iterator().next().getSwitchObj()); }
@Test public void deleteConnectedDeviceTest() { transactionManager.doInTransaction(() -> { connectedDeviceRepository.add(lldpConnectedDeviceA); connectedDeviceRepository.add(lldpConnectedDeviceB); assertEquals(2, connectedDeviceRepository.findAll().size()); connectedDeviceRepository.remove(lldpConnectedDeviceA); assertEquals(1, connectedDeviceRepository.findAll().size()); assertEquals(lldpConnectedDeviceB, connectedDeviceRepository.findAll().iterator().next()); connectedDeviceRepository.remove(lldpConnectedDeviceB); assertEquals(0, connectedDeviceRepository.findAll().size()); }); } |
### Question:
FermaSwitchConnectedDevicesRepository extends FermaGenericRepository<SwitchConnectedDevice, SwitchConnectedDeviceData, SwitchConnectedDeviceFrame> implements SwitchConnectedDeviceRepository { @Override public Collection<SwitchConnectedDevice> findByFlowId(String flowId) { return framedGraph().traverse(g -> g.V() .hasLabel(SwitchConnectedDeviceFrame.FRAME_LABEL) .has(SwitchConnectedDeviceFrame.FLOW_ID_PROPERTY, flowId)) .toListExplicit(SwitchConnectedDeviceFrame.class).stream() .map(SwitchConnectedDevice::new) .collect(Collectors.toList()); } FermaSwitchConnectedDevicesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<SwitchConnectedDevice> findAll(); @Override Collection<SwitchConnectedDevice> findBySwitchId(SwitchId switchId); @Override Collection<SwitchConnectedDevice> findByFlowId(String flowId); @Override Optional<SwitchConnectedDevice> findLldpByUniqueFieldCombination(
SwitchId switchId, int portNumber, int vlan, String macAddress, String chassisId, String portId); @Override Optional<SwitchConnectedDevice> findArpByUniqueFieldCombination(
SwitchId switchId, int portNumber, int vlan, String macAddress, String ipAddress); }### Answer:
@Test public void findByFlowIdTest() { connectedDeviceRepository.add(lldpConnectedDeviceA); connectedDeviceRepository.add(lldpConnectedDeviceB); connectedDeviceRepository.add(arpConnectedDeviceC); connectedDeviceRepository.add(arpConnectedDeviceD); Collection<SwitchConnectedDevice> firstDevice = connectedDeviceRepository.findByFlowId(FIRST_FLOW_ID); assertEquals(1, firstDevice.size()); assertEquals(lldpConnectedDeviceA, firstDevice.iterator().next()); Collection<SwitchConnectedDevice> secondDevices = connectedDeviceRepository.findByFlowId(SECOND_FLOW_ID); assertEquals(2, secondDevices.size()); assertEquals(newHashSet(lldpConnectedDeviceB, arpConnectedDeviceD), newHashSet(secondDevices)); } |
### Question:
FermaFeatureTogglesRepository extends FermaGenericRepository<FeatureToggles, FeatureTogglesData, FeatureTogglesFrame> implements FeatureTogglesRepository { @Override public Optional<FeatureToggles> find() { List<? extends FeatureTogglesFrame> featureTogglesFrames = framedGraph().traverse(g -> g.V() .hasLabel(FeatureTogglesFrame.FRAME_LABEL)) .toListExplicit(FeatureTogglesFrame.class); return featureTogglesFrames.isEmpty() ? Optional.empty() : Optional.of(featureTogglesFrames.get(0)) .map(FeatureToggles::new); } FermaFeatureTogglesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Optional<FeatureToggles> find(); @Override FeatureToggles getOrDefault(); }### Answer:
@Test public void shouldCreateAndUpdateFeatureToggles() { FeatureToggles featureTogglesA = FeatureToggles.builder() .flowsRerouteOnIslDiscoveryEnabled(false) .createFlowEnabled(false) .updateFlowEnabled(false) .deleteFlowEnabled(false) .useBfdForIslIntegrityCheck(false) .floodlightRoutePeriodicSync(false) .flowsRerouteUsingDefaultEncapType(false) .build(); featureTogglesRepository.add(featureTogglesA); FeatureToggles foundFeatureToggles = featureTogglesRepository.find().get(); assertEquals(featureTogglesA, foundFeatureToggles); foundFeatureToggles.setUpdateFlowEnabled(true); FeatureToggles updatedFeatureToggles = featureTogglesRepository.find().get(); assertTrue(updatedFeatureToggles.getUpdateFlowEnabled()); } |
### Question:
FermaBfdSessionRepository extends FermaGenericRepository<BfdSession, BfdSessionData, BfdSessionFrame> implements BfdSessionRepository { @Override public Collection<BfdSession> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(BfdSessionFrame.FRAME_LABEL)) .toListExplicit(BfdSessionFrame.class).stream() .map(BfdSession::new) .collect(Collectors.toList()); } FermaBfdSessionRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<BfdSession> findAll(); @Override boolean exists(SwitchId switchId, Integer port); @Override Optional<BfdSession> findBySwitchIdAndPort(SwitchId switchId, Integer port); }### Answer:
@Test public void shouldCreateBfdPort() { createBfdSession(); assertEquals(1, repository.findAll().size()); }
@Test public void shouldDeleteBfdPort() { BfdSession bfdSession = createBfdSession(); assertEquals(1, repository.findAll().size()); transactionManager.doInTransaction(() -> repository.remove(bfdSession)); assertEquals(0, repository.findAll().size()); }
@Ignore("Need to fix: in-memory persistence doesn't impose constraints") @Test(expected = ConstraintViolationException.class) public void createUseCaseTest() { assertEquals(TEST_DISCRIMINATOR, getDiscriminator(TEST_SWITCH_ID, TEST_PORT, TEST_DISCRIMINATOR)); assertEquals(TEST_DISCRIMINATOR, getDiscriminator(TEST_SWITCH_ID, TEST_PORT, TEST_DISCRIMINATOR)); assertEquals(1, repository.findAll().size()); assertEquals(TEST_DISCRIMINATOR, getDiscriminator(TEST_SWITCH_ID, TEST_PORT + 1, TEST_DISCRIMINATOR)); }
@Test public void deleteUseCaseTest() { getDiscriminator(TEST_SWITCH_ID, TEST_PORT, TEST_DISCRIMINATOR); assertEquals(1, repository.findAll().size()); freeDiscriminator(TEST_SWITCH_ID, TEST_PORT); assertEquals(0, repository.findAll().size()); } |
### Question:
FermaBfdSessionRepository extends FermaGenericRepository<BfdSession, BfdSessionData, BfdSessionFrame> implements BfdSessionRepository { @Override public Optional<BfdSession> findBySwitchIdAndPort(SwitchId switchId, Integer port) { List<? extends BfdSessionFrame> bfdSessionFrames = framedGraph().traverse(g -> g.V() .hasLabel(BfdSessionFrame.FRAME_LABEL) .has(BfdSessionFrame.SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(BfdSessionFrame.PORT_PROPERTY, port)) .toListExplicit(BfdSessionFrame.class); return bfdSessionFrames.isEmpty() ? Optional.empty() : Optional.of(bfdSessionFrames.get(0)) .map(BfdSession::new); } FermaBfdSessionRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<BfdSession> findAll(); @Override boolean exists(SwitchId switchId, Integer port); @Override Optional<BfdSession> findBySwitchIdAndPort(SwitchId switchId, Integer port); }### Answer:
@Test public void shouldFindBySwitchIdAndPort() { BfdSession bfdSession = createBfdSession(); BfdSession foundPort = repository.findBySwitchIdAndPort(TEST_SWITCH_ID, TEST_PORT).get(); assertEquals(bfdSession.getDiscriminator(), foundPort.getDiscriminator()); } |
### Question:
FermaSwitchPropertiesRepository extends FermaGenericRepository<SwitchProperties, SwitchPropertiesData, SwitchPropertiesFrame> implements SwitchPropertiesRepository { @Override public Collection<SwitchProperties> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(SwitchPropertiesFrame.FRAME_LABEL)) .toListExplicit(SwitchPropertiesFrame.class).stream() .map(SwitchProperties::new) .collect(Collectors.toList()); } FermaSwitchPropertiesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<SwitchProperties> findAll(); @Override Optional<SwitchProperties> findBySwitchId(SwitchId switchId); }### Answer:
@Test public void shouldCreateSwitchPropertiesWithRelation() { Switch origSwitch = Switch.builder() .switchId(TEST_SWITCH_ID) .description("Some description") .build(); switchRepository.add(origSwitch); SwitchProperties switchProperties = SwitchProperties.builder() .switchObj(origSwitch) .supportedTransitEncapsulation(SwitchProperties.DEFAULT_FLOW_ENCAPSULATION_TYPES) .build(); switchPropertiesRepository.add(switchProperties); List<SwitchProperties> switchPropertiesResult = new ArrayList<>(switchPropertiesRepository.findAll()); assertEquals(1, switchPropertiesResult.size()); assertNotNull(switchPropertiesResult.get(0).getSwitchObj()); } |
### Question:
FermaLinkPropsRepository extends FermaGenericRepository<LinkProps, LinkPropsData, LinkPropsFrame> implements LinkPropsRepository { @Override public Collection<LinkProps> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(LinkPropsFrame.FRAME_LABEL)) .toListExplicit(LinkPropsFrame.class).stream() .map(LinkProps::new) .collect(Collectors.toList()); } FermaLinkPropsRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<LinkProps> findAll(); @Override Collection<LinkProps> findByEndpoints(SwitchId srcSwitch, Integer srcPort,
SwitchId dstSwitch, Integer dstPort); }### Answer:
@Test public void shouldCreateLinkProps() { createLinkProps(1); assertEquals(1, linkPropsRepository.findAll().size()); }
@Test public void shouldDeleteLinkProps() { LinkProps linkProps = createLinkProps(1); transactionManager.doInTransaction(() -> { linkPropsRepository.remove(linkProps); }); assertEquals(0, linkPropsRepository.findAll().size()); } |
### Question:
FlowValidationService { public List<SwitchId> getSwitchIdListByFlowId(String flowId) { return switchRepository.findSwitchesInFlowPathByFlowId(flowId).stream() .map(Switch::getSwitchId) .collect(Collectors.toList()); } FlowValidationService(PersistenceManager persistenceManager, FlowResourcesConfig flowResourcesConfig,
long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient); void checkFlowStatus(String flowId); List<SwitchId> getSwitchIdListByFlowId(String flowId); List<FlowValidationResponse> validateFlow(String flowId, List<SwitchFlowEntries> switchFlowEntries,
List<SwitchMeterEntries> switchMeterEntries); }### Answer:
@Test public void shouldGetSwitchIdListByFlowId() { buildTransitVlanFlow(""); List<SwitchId> switchIds = service.getSwitchIdListByFlowId(TEST_FLOW_ID_A); assertEquals(4, switchIds.size()); buildOneSwitchPortFlow(); switchIds = service.getSwitchIdListByFlowId(TEST_FLOW_ID_B); assertEquals(1, switchIds.size()); } |
### Question:
OneToOneMapping implements MappingApproach { public void remove(SwitchId switchId, String region) { remove(switchId); } OneToOneMapping(Clock clock, Duration staleWipeDelay); Optional<String> lookup(SwitchId switchId); @Override void set(SwitchId switchId, String region); void add(SwitchId switchId, String region); void remove(SwitchId switchId, String region); void remove(SwitchId switchId); Map<String, Set<SwitchId>> makeReversedMapping(); }### Answer:
@Test public void testRemove() { OneToOneMapping subject = makeSubject(); subject.add(SWITCH_ALPHA, REGION_A); subject.add(SWITCH_BETA, REGION_A); subject.remove(SWITCH_ALPHA); Optional<String> result = subject.lookup(SWITCH_ALPHA); Assert.assertTrue(result.isPresent()); Assert.assertEquals(REGION_A, result.get()); Assert.assertTrue(subject.lookup(SWITCH_ALPHA).isPresent()); clock.adjust(staleDelay.plus(Duration.ofSeconds(1))); Assert.assertFalse(subject.lookup(SWITCH_ALPHA).isPresent()); Assert.assertTrue(subject.lookup(SWITCH_BETA).isPresent()); } |
### Question:
SwitchMonitorService { public void handleStatusUpdateNotification(SwitchInfoData notification, String region) { SwitchMonitorEntry entry = lookupOrCreateSwitchMonitor(notification.getSwitchId()); entry.handleStatusUpdateNotification(notification, region); } SwitchMonitorService(Clock clock, SwitchMonitorCarrier carrier); void handleTimerTick(); void handleRegionOfflineNotification(String region); void handleStatusUpdateNotification(SwitchInfoData notification, String region); void handleNetworkDumpResponse(NetworkDumpSwitchData response, String region); }### Answer:
@Test public void regularSwitchConnectSequence() { SwitchMonitorService subject = makeSubject(); SwitchInfoData swAdd = new SwitchInfoData(SWITCH_ALPHA, SwitchChangeType.ADDED); subject.handleStatusUpdateNotification(swAdd, REGION_ALPHA); verify(carrier).regionUpdateNotification( eq(new RegionMappingAdd(swAdd.getSwitchId(), REGION_ALPHA, false))); verifyNoMoreInteractions(carrier); SwitchInfoData swActivate = makeSwitchActivateNotification(swAdd.getSwitchId()); subject.handleStatusUpdateNotification(swActivate, REGION_ALPHA); verify(carrier).switchStatusUpdateNotification(eq(swActivate.getSwitchId()), eq(swActivate)); verify(carrier).regionUpdateNotification( eq(new RegionMappingSet(swActivate.getSwitchId(), REGION_ALPHA, true))); verifyNoMoreInteractions(carrier); } |
### Question:
PacketService { public void handleArpData(ArpInfoData data) { transactionManager.doInTransaction(() -> { FlowRelatedData flowRelatedData = findFlowRelatedData(data); if (flowRelatedData == null) { return; } SwitchConnectedDevice device = getOrCreateArpDevice(data, flowRelatedData.originalVlan); if (device == null) { return; } device.setTimeLastSeen(Instant.ofEpochMilli(data.getTimestamp())); device.setFlowId(flowRelatedData.flowId); device.setSource(flowRelatedData.source); }); } PacketService(PersistenceManager persistenceManager); void handleLldpData(LldpInfoData data); void handleArpData(ArpInfoData data); static final int FULL_PORT_VLAN; }### Answer:
@Test public void testHandleArpDataSameTimeOnCreate() { packetService.handleArpData(createArpInfoData()); Collection<SwitchConnectedDevice> devices = switchConnectedDeviceRepository.findAll(); assertEquals(1, devices.size()); assertEquals(devices.iterator().next().getTimeFirstSeen(), devices.iterator().next().getTimeLastSeen()); }
@Test public void testHandleArpDataDifferentTimeOnUpdate() throws InterruptedException { packetService.handleArpData(createArpInfoData()); Thread.sleep(10); packetService.handleArpData(createArpInfoData()); Collection<SwitchConnectedDevice> devices = switchConnectedDeviceRepository.findAll(); assertEquals(1, devices.size()); assertNotEquals(devices.iterator().next().getTimeFirstSeen(), devices.iterator().next().getTimeLastSeen()); }
@Test public void testHandleArpDataNonExistentSwitch() { ArpInfoData data = createArpInfoData(); data.setSwitchId(new SwitchId("12345")); packetService.handleArpData(data); assertTrue(switchConnectedDeviceRepository.findAll().isEmpty()); } |
### Question:
PacketService { @VisibleForTesting FlowRelatedData findFlowRelatedDataForVxlanFlow(ConnectedDevicePacketBase data) { int inputVlan = data.getVlans().isEmpty() ? 0 : data.getVlans().get(0); Flow flow = getFlowBySwitchIdPortAndVlan( data.getSwitchId(), data.getPortNumber(), inputVlan, getPacketName(data)); if (flow == null) { return null; } if (data.getSwitchId().equals(flow.getSrcSwitchId())) { return new FlowRelatedData(inputVlan, flow.getFlowId(), true); } else if (data.getSwitchId().equals(flow.getDestSwitchId())) { return new FlowRelatedData(inputVlan, flow.getFlowId(), false); } else { log.warn("Got {} packet from Flow {} on non-src/non-dst switch {}. Port number {}, input vlan {}", getPacketName(data), flow.getFlowId(), data.getSwitchId(), data.getPortNumber(), inputVlan); return null; } } PacketService(PersistenceManager persistenceManager); void handleLldpData(LldpInfoData data); void handleArpData(ArpInfoData data); static final int FULL_PORT_VLAN; }### Answer:
@Test @Parameters(method = "getInOutVlanCombinationForVxlanParameters") public void findFlowRelatedDataForVxlanFlowTest( int inVlan, int srcVlan, int dstVlan, List<Integer> vlansInPacket, boolean source) { createFlow(FLOW_ID, srcVlan, dstVlan, null, false, false); LldpInfoData data = createLldpInfoDataData( source ? SWITCH_ID_1 : SWITCH_ID_2, vlansInPacket, source ? PORT_NUMBER_1 : PORT_NUMBER_2); FlowRelatedData flowRelatedData = packetService.findFlowRelatedDataForVxlanFlow(data); assertEquals(FLOW_ID, flowRelatedData.getFlowId()); assertEquals(inVlan, flowRelatedData.getOriginalVlan()); assertEquals(source, flowRelatedData.getSource()); } |
### Question:
ExtendableTimeWindow { public boolean flushIfReady() { if (firstEventTime == null) { return false; } LocalDateTime now = LocalDateTime.now(clock); boolean isTimeToFlush = lastEventTime.plus(minDelay, ChronoUnit.SECONDS).isBefore(now) || firstEventTime.plus(maxDelay, ChronoUnit.SECONDS).isBefore(now); if (isTimeToFlush) { firstEventTime = null; lastEventTime = null; } return isTimeToFlush; } ExtendableTimeWindow(long minDelay, long maxDelay); ExtendableTimeWindow(long minDelay, long maxDelay, Clock clock); void registerEvent(); boolean flushIfReady(); }### Answer:
@Test public void noFlushEmptyWindow() { assertFalse(extendableTimeWindow.flushIfReady()); }
@Test public void noFlushEmptyWindow2() { when(clock.instant()).thenReturn(Instant.now()); assertFalse(extendableTimeWindow.flushIfReady()); } |
### Question:
NetworkBfdPortService { public void updateLinkStatus(Endpoint logicalEndpoint, LinkStatus linkStatus) { log.debug("BFD-port service receive logical port status update for {} (logical) status:{}", logicalEndpoint, linkStatus); BfdPortFsm controller = lookupControllerByLogicalEndpoint(logicalEndpoint); controller.updateLinkStatus(carrier, linkStatus); } NetworkBfdPortService(IBfdPortCarrier carrier, PersistenceManager persistenceManager); void setup(Endpoint endpoint, int physicalPortNumber); Endpoint remove(Endpoint logicalEndpoint); void updateLinkStatus(Endpoint logicalEndpoint, LinkStatus linkStatus); void updateOnlineMode(Endpoint endpoint, boolean mode); void enable(Endpoint physicalEndpoint, IslReference reference); void disable(Endpoint physicalEndpoint); void speakerResponse(String key, Endpoint logicalEndpoint, BfdSessionResponse response); void speakerTimeout(String key, Endpoint logicalEndpoint); }### Answer:
@Test public void upDownUp() { setupAndEnable(); service.updateLinkStatus(alphaLogicalEndpoint, LinkStatus.DOWN); verify(carrier).bfdDownNotification(alphaEndpoint); verifyNoMoreInteractions(carrier); reset(carrier); service.updateLinkStatus(alphaLogicalEndpoint, LinkStatus.UP); verify(carrier).bfdUpNotification(alphaEndpoint); verifyNoMoreInteractions(carrier); } |
### Question:
NetworkBfdPortService { public Endpoint remove(Endpoint logicalEndpoint) { log.info("BFD-port service receive REMOVE request for {} (logical)", logicalEndpoint); BfdPortFsm controller = controllerByLogicalPort.remove(logicalEndpoint); if (controller == null) { throw BfdPortControllerNotFoundException.ofLogical(logicalEndpoint); } controllerByPhysicalPort.remove(controller.getPhysicalEndpoint()); remove(controller); return controller.getPhysicalEndpoint(); } NetworkBfdPortService(IBfdPortCarrier carrier, PersistenceManager persistenceManager); void setup(Endpoint endpoint, int physicalPortNumber); Endpoint remove(Endpoint logicalEndpoint); void updateLinkStatus(Endpoint logicalEndpoint, LinkStatus linkStatus); void updateOnlineMode(Endpoint endpoint, boolean mode); void enable(Endpoint physicalEndpoint, IslReference reference); void disable(Endpoint physicalEndpoint); void speakerResponse(String key, Endpoint logicalEndpoint, BfdSessionResponse response); void speakerTimeout(String key, Endpoint logicalEndpoint); }### Answer:
@Test public void killDuringInstalling() { setupController(); doAnswer(invocation -> invocation.getArgument(0)) .when(bfdSessionRepository).add(any()); NoviBfdSession session = doEnable(); when(carrier.removeBfdSession(any(NoviBfdSession.class))).thenReturn(removeRequestKey); service.remove(alphaLogicalEndpoint); verifyTerminateSequence(session); }
@Test public void killDuringActiveUp() { NoviBfdSession session = setupAndEnable(); when(carrier.removeBfdSession(any(NoviBfdSession.class))).thenReturn(removeRequestKey); service.remove(alphaLogicalEndpoint); verify(carrier).bfdKillNotification(alphaEndpoint); verifyTerminateSequence(session); } |
### Question:
NetworkWatcherService { public void addWatch(Endpoint endpoint) { addWatch(endpoint, now()); } NetworkWatcherService(
IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); @VisibleForTesting NetworkWatcherService(
Clock clock, IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime,
Integer taskId); void addWatch(Endpoint endpoint); void removeWatch(Endpoint endpoint); void tick(); void confirmation(Endpoint endpoint, long packetNo); void discovery(IslInfoData discoveryEvent); void roundTripDiscovery(Endpoint endpoint, long packetId); }### Answer:
@Test public void addWatch() { NetworkWatcherService w = makeService(); w.addWatch(Endpoint.of(new SwitchId(1), 1), 1); w.addWatch(Endpoint.of(new SwitchId(1), 2), 1); w.addWatch(Endpoint.of(new SwitchId(2), 1), 2); w.addWatch(Endpoint.of(new SwitchId(2), 1), 2); w.addWatch(Endpoint.of(new SwitchId(2), 2), 3); assertThat(w.getConfirmedPackets().size(), is(0)); assertThat(w.getTimeouts().size(), is(3)); verify(carrier, times(5)).sendDiscovery(any(DiscoverIslCommandData.class)); } |
### Question:
NetworkWatcherService { public void tick() { tick(now()); } NetworkWatcherService(
IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); @VisibleForTesting NetworkWatcherService(
Clock clock, IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime,
Integer taskId); void addWatch(Endpoint endpoint); void removeWatch(Endpoint endpoint); void tick(); void confirmation(Endpoint endpoint, long packetNo); void discovery(IslInfoData discoveryEvent); void roundTripDiscovery(Endpoint endpoint, long packetId); }### Answer:
@Test public void tick() { NetworkWatcherService w = makeService(); w.addWatch(Endpoint.of(new SwitchId(1), 1), 1); w.addWatch(Endpoint.of(new SwitchId(1), 2), 1); w.addWatch(Endpoint.of(new SwitchId(2), 1), 2); w.addWatch(Endpoint.of(new SwitchId(2), 1), 2); w.addWatch(Endpoint.of(new SwitchId(2), 2), 3); assertThat(w.getConfirmedPackets().size(), is(0)); assertThat(w.getTimeouts().size(), is(3)); verify(carrier, times(5)).sendDiscovery(any(DiscoverIslCommandData.class)); w.confirmation(Endpoint.of(new SwitchId(1), 1), 0); w.confirmation(Endpoint.of(new SwitchId(2), 1), 2); assertThat(w.getConfirmedPackets().size(), is(2)); w.tick(100); assertThat(w.getConfirmedPackets().size(), is(0)); verify(carrier).discoveryFailed(eq(Endpoint.of(new SwitchId(1), 1)), eq(0L), anyLong()); verify(carrier).discoveryFailed(eq(Endpoint.of(new SwitchId(2), 1)), eq(2L), anyLong()); verify(carrier, times(2)).discoveryFailed(any(Endpoint.class), anyLong(), anyLong()); assertThat(w.getTimeouts().size(), is(0)); } |
### Question:
NetworkDecisionMakerService { public void discovered(Endpoint endpoint, long packetId, IslInfoData discoveryEvent) { discovered(endpoint, packetId, discoveryEvent, now()); } NetworkDecisionMakerService(IDecisionMakerCarrier carrier, long failTimeout, long awaitTime); void discovered(Endpoint endpoint, long packetId, IslInfoData discoveryEvent); void failed(Endpoint endpoint, long packetId); void tick(); void clear(Endpoint endpoint); }### Answer:
@Test public void discovered() { NetworkDecisionMakerService w = new NetworkDecisionMakerService(carrier, 10, 5); w.discovered(endpointBeta, 1L, islAlphaBeta, 1L); w.discovered(endpointAlpha, 2L, islBetaAlpha, 2L); verify(carrier).linkDiscovered(eq(islAlphaBeta)); verify(carrier).linkDiscovered(eq(islBetaAlpha)); } |
### Question:
NetworkDecisionMakerService { public void failed(Endpoint endpoint, long packetId) { failed(endpoint, packetId, now()); } NetworkDecisionMakerService(IDecisionMakerCarrier carrier, long failTimeout, long awaitTime); void discovered(Endpoint endpoint, long packetId, IslInfoData discoveryEvent); void failed(Endpoint endpoint, long packetId); void tick(); void clear(Endpoint endpoint); }### Answer:
@Test public void failed() { NetworkDecisionMakerService w = new NetworkDecisionMakerService(carrier, 10, 5); w.failed(endpointAlpha, 0L, 0); w.failed(endpointAlpha, 1L, 1); w.failed(endpointAlpha, 2L, 4); verify(carrier, never()).linkDestroyed(any(Endpoint.class)); w.failed(endpointAlpha, 3L, 5); verify(carrier).linkDestroyed(eq(endpointAlpha)); w.discovered(endpointAlpha, 4L, islBetaAlpha, 20); verify(carrier).linkDiscovered(islBetaAlpha); reset(carrier); w.failed(endpointAlpha, 5L, 21); w.failed(endpointAlpha, 6L, 23); w.failed(endpointAlpha, 7L, 24); verify(carrier, never()).linkDestroyed(any(Endpoint.class)); w.failed(endpointAlpha, 8L, 31); verify(carrier).linkDestroyed(eq(endpointAlpha)); } |
### Question:
Isl implements CompositeDataEntity<Isl.IslData> { public boolean isUnstable() { if (islConfig == null) { throw new IllegalStateException("IslConfig has not initialized."); } return getTimeUnstable() != null && getTimeUnstable().plus(islConfig.getUnstableIslTimeout()).isAfter(Instant.now()); } private Isl(); Isl(@NonNull Isl entityToClone); @Builder Isl(@NonNull Switch srcSwitch, @NonNull Switch destSwitch, int srcPort, int destPort,
long latency, long speed, int cost, long maxBandwidth, long defaultMaxBandwidth,
long availableBandwidth, IslStatus status, IslStatus actualStatus, IslStatus roundTripStatus,
IslDownReason downReason,
boolean underMaintenance, boolean enableBfd, BfdSessionStatus bfdSessionStatus, Instant timeUnstable); Isl(@NonNull IslData data); boolean isUnstable(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void shouldComputeIsUnstable() { Isl isl = Isl.builder() .srcSwitch(Switch.builder().switchId(new SwitchId(1)).build()) .destSwitch(Switch.builder().switchId(new SwitchId(2)).build()) .build(); isl.setIslConfig(islConfig); isl.setTimeUnstable(Instant.now().minus(islConfig.getUnstableIslTimeout())); assertFalse(isl.isUnstable()); isl.setTimeUnstable(Instant.now()); assertTrue(isl.isUnstable()); } |
### Question:
Meter implements Serializable { public static long convertRateToKiloBits(long rateInPackets, long packetSizeInBytes) { return Math.max(MIN_RATE_IN_KBPS, (rateInPackets * packetSizeInBytes * 8) / 1024L); } static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits,
double flowMeterBurstCoefficient, String switchDescription); static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits,
double flowMeterBurstCoefficient, String switchManufacturerDescription,
String switchSoftwareDescription); static long calculateBurstSizeConsideringHardwareLimitations(
long bandwidth, long requestedBurstSize, Set<SwitchFeature> features); static long convertRateToKiloBits(long rateInPackets, long packetSizeInBytes); static long convertBurstSizeToKiloBits(long burstSizeInPackets, long packetSizeInBytes); static String[] getMeterKbpsFlags(); static String[] getMeterPktpsFlags(); static boolean equalsRate(long actual, long expected, boolean isESwitch); static boolean equalsBurstSize(long actual, long expected, boolean isESwitch); static final int MIN_RATE_IN_KBPS; }### Answer:
@Test public void convertRateToKiloBitsTest() { assertEquals(800, Meter.convertRateToKiloBits(100, 1024)); assertEquals(64, Meter.convertRateToKiloBits(1, 1)); assertEquals(64, Meter.convertRateToKiloBits(8, 16)); } |
### Question:
Meter implements Serializable { public static long convertBurstSizeToKiloBits(long burstSizeInPackets, long packetSizeInBytes) { return (burstSizeInPackets * packetSizeInBytes * 8) / 1024L; } static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits,
double flowMeterBurstCoefficient, String switchDescription); static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits,
double flowMeterBurstCoefficient, String switchManufacturerDescription,
String switchSoftwareDescription); static long calculateBurstSizeConsideringHardwareLimitations(
long bandwidth, long requestedBurstSize, Set<SwitchFeature> features); static long convertRateToKiloBits(long rateInPackets, long packetSizeInBytes); static long convertBurstSizeToKiloBits(long burstSizeInPackets, long packetSizeInBytes); static String[] getMeterKbpsFlags(); static String[] getMeterPktpsFlags(); static boolean equalsRate(long actual, long expected, boolean isESwitch); static boolean equalsBurstSize(long actual, long expected, boolean isESwitch); static final int MIN_RATE_IN_KBPS; }### Answer:
@Test public void convertBurstSizeToKiloBitsTest() { assertEquals(800, Meter.convertBurstSizeToKiloBits(100, 1024)); assertEquals(1, Meter.convertBurstSizeToKiloBits(8, 16)); } |
### Question:
FlowSegmentCookie extends Cookie { @Override public FlowSegmentCookieBuilder toBuilder() { return new FlowSegmentCookieBuilder() .type(getType()) .direction(getDirection()) .flowEffectiveId(getFlowEffectiveId()); } @JsonCreator FlowSegmentCookie(long value); FlowSegmentCookie(FlowPathDirection direction, long flowEffectiveId); FlowSegmentCookie(CookieType type, long value); @Builder private FlowSegmentCookie(CookieType type, FlowPathDirection direction, long flowEffectiveId); @Override void validate(); @Override FlowSegmentCookieBuilder toBuilder(); FlowPathDirection getValidatedDirection(); FlowPathDirection getDirection(); long getFlowEffectiveId(); static FlowSegmentCookieBuilder builder(); }### Answer:
@Test public void changingOfFlowSegmentCookieTypeTest() { FlowSegmentCookie flowCookie = new FlowSegmentCookie(FlowPathDirection.FORWARD, 10); Assert.assertEquals(CookieType.SERVICE_OR_FLOW_SEGMENT, flowCookie.getType()); FlowSegmentCookie server42Cookie = flowCookie.toBuilder() .type(CookieType.SERVER_42_INGRESS) .build(); Assert.assertEquals(CookieType.SERVER_42_INGRESS, server42Cookie.getType()); } |
### Question:
PathSegment implements CompositeDataEntity<PathSegment.PathSegmentData> { public boolean containsNode(SwitchId switchId, int port) { if (switchId == null) { throw new IllegalArgumentException("Switch id must be not null"); } return (switchId.equals(getSrcSwitchId()) && port == getSrcPort()) || (switchId.equals(getDestSwitchId()) && port == getDestPort()); } private PathSegment(); PathSegment(@NonNull PathSegment entityToClone, FlowPath path); @Builder PathSegment(@NonNull Switch srcSwitch, @NonNull Switch destSwitch, int srcPort, int destPort,
boolean srcWithMultiTable, boolean destWithMultiTable, int seqId, Long latency, long bandwidth,
boolean ignoreBandwidth, boolean failed); PathSegment(@NonNull PathSegmentData data); boolean containsNode(SwitchId switchId, int port); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testContainsNodeInvalidInput() { flow.getForwardPath().getSegments().get(0).containsNode(null, 1); }
@Test public void testContainsNodeSourceMatch() { assertTrue(flow.getForwardPath().getSegments().get(0).containsNode(SWITCH_ID_A, 1)); }
@Test public void testContainsNodeDestinationMatch() { assertTrue(flow.getForwardPath().getSegments().get(0).containsNode(SWITCH_ID_B, 1)); }
@Test public void testContainsNodeNoSwitchMatch() { assertFalse(flow.getForwardPath().getSegments().get(0).containsNode(SWITCH_ID_C, 1)); }
@Test public void testContainsNodeNoPortMatch() { assertFalse(flow.getForwardPath().getSegments().get(0).containsNode(SWITCH_ID_B, 2)); }
@Test public void testContainsNodeNoSwitchPortMatch() { assertFalse(flow.getForwardPath().getSegments().get(0).containsNode(SWITCH_ID_C, 2)); } |
### Question:
MeterId implements Comparable<MeterId>, Serializable { public static MeterId createMeterIdForDefaultRule(long cookie) { if (!Cookie.isDefaultRule(cookie)) { throw new IllegalArgumentException(String.format("Cookie '%s' is not a cookie of default rule", cookie)); } return new MeterId((int) (cookie & METER_ID_DEFAULT_RULE_MASK)); } @JsonCreator MeterId(long value); static boolean isMeterIdOfDefaultRule(long meterId); static MeterId createMeterIdForDefaultRule(long cookie); @JsonValue long getValue(); @Override int compareTo(MeterId compareWith); static final long METER_ID_DEFAULT_RULE_MASK; static final int MIN_FLOW_METER_ID; static final int MAX_FLOW_METER_ID; static final int MIN_SYSTEM_RULE_METER_ID; static final int MAX_SYSTEM_RULE_METER_ID; }### Answer:
@Test(expected = IllegalArgumentException.class) public void createMeterIdForInvalidDefaultRuleTest() { MeterId.createMeterIdForDefaultRule(0x0000000000000123L); } |
### Question:
SwitchProperties implements CompositeDataEntity<SwitchProperties.SwitchPropertiesData> { @VisibleForTesting public boolean validateProp(SwitchFeature feature) { if (getSwitchObj() != null && !getSwitchObj().getFeatures().contains(feature)) { String message = String.format("Switch %s doesn't support requested feature %s", getSwitchId(), feature); throw new IllegalArgumentException(message); } return true; } private SwitchProperties(); SwitchProperties(@NonNull SwitchProperties entityToClone); @Builder SwitchProperties(Switch switchObj, Set<FlowEncapsulationType> supportedTransitEncapsulation,
boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt,
Integer server42Port, MacAddress server42MacAddress, Integer server42Vlan,
Integer inboundTelescopePort, Integer outboundTelescopePort,
Integer telescopeIngressVlan, Integer telescopeEgressVlan); SwitchProperties(@NonNull SwitchPropertiesData data); void setMultiTable(boolean multiTable); void setSupportedTransitEncapsulation(Set<FlowEncapsulationType> supportedTransitEncapsulation); @VisibleForTesting boolean validateProp(SwitchFeature feature); @Override boolean equals(Object o); @Override int hashCode(); static Set<FlowEncapsulationType> DEFAULT_FLOW_ENCAPSULATION_TYPES; }### Answer:
@Test(expected = IllegalArgumentException.class) public void validatePropRaiseTest() { Switch sw = Switch.builder() .switchId(new SwitchId(1)) .build(); SwitchProperties sp = SwitchProperties.builder() .switchObj(sw) .build(); sp.validateProp(SwitchFeature.BFD); }
@Test public void validatePropPassesTest() { Set<SwitchFeature> features = new HashSet<>(); features.add(SwitchFeature.MULTI_TABLE); Switch sw = Switch.builder() .switchId(new SwitchId(1)) .features(features) .build(); SwitchProperties sp = SwitchProperties.builder() .switchObj(sw) .build(); assertTrue(sp.validateProp(SwitchFeature.MULTI_TABLE)); } |
### Question:
SwitchProperties implements CompositeDataEntity<SwitchProperties.SwitchPropertiesData> { public void setMultiTable(boolean multiTable) { if (multiTable) { validateProp(SwitchFeature.MULTI_TABLE); } data.setMultiTable(multiTable); } private SwitchProperties(); SwitchProperties(@NonNull SwitchProperties entityToClone); @Builder SwitchProperties(Switch switchObj, Set<FlowEncapsulationType> supportedTransitEncapsulation,
boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt,
Integer server42Port, MacAddress server42MacAddress, Integer server42Vlan,
Integer inboundTelescopePort, Integer outboundTelescopePort,
Integer telescopeIngressVlan, Integer telescopeEgressVlan); SwitchProperties(@NonNull SwitchPropertiesData data); void setMultiTable(boolean multiTable); void setSupportedTransitEncapsulation(Set<FlowEncapsulationType> supportedTransitEncapsulation); @VisibleForTesting boolean validateProp(SwitchFeature feature); @Override boolean equals(Object o); @Override int hashCode(); static Set<FlowEncapsulationType> DEFAULT_FLOW_ENCAPSULATION_TYPES; }### Answer:
@Test(expected = IllegalArgumentException.class) public void setUnsupportedMultiTableFlagTest() { Switch sw = Switch.builder() .switchId(new SwitchId(1)) .build(); SwitchProperties sp = SwitchProperties.builder() .switchObj(sw) .build(); sp.setMultiTable(true); } |
### Question:
SwitchProperties implements CompositeDataEntity<SwitchProperties.SwitchPropertiesData> { public void setSupportedTransitEncapsulation(Set<FlowEncapsulationType> supportedTransitEncapsulation) { if (supportedTransitEncapsulation != null && supportedTransitEncapsulation.contains(FlowEncapsulationType.VXLAN)) { validateProp(SwitchFeature.NOVIFLOW_COPY_FIELD); } data.setSupportedTransitEncapsulation(supportedTransitEncapsulation); } private SwitchProperties(); SwitchProperties(@NonNull SwitchProperties entityToClone); @Builder SwitchProperties(Switch switchObj, Set<FlowEncapsulationType> supportedTransitEncapsulation,
boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt,
Integer server42Port, MacAddress server42MacAddress, Integer server42Vlan,
Integer inboundTelescopePort, Integer outboundTelescopePort,
Integer telescopeIngressVlan, Integer telescopeEgressVlan); SwitchProperties(@NonNull SwitchPropertiesData data); void setMultiTable(boolean multiTable); void setSupportedTransitEncapsulation(Set<FlowEncapsulationType> supportedTransitEncapsulation); @VisibleForTesting boolean validateProp(SwitchFeature feature); @Override boolean equals(Object o); @Override int hashCode(); static Set<FlowEncapsulationType> DEFAULT_FLOW_ENCAPSULATION_TYPES; }### Answer:
@Test(expected = IllegalArgumentException.class) public void setUnsupportedTransitEncapsulationTest() { Switch sw = Switch.builder() .switchId(new SwitchId(1)) .build(); SwitchProperties sp = SwitchProperties.builder() .switchObj(sw) .build(); Set<FlowEncapsulationType> flowEncapsulationTypes = new HashSet<>(); flowEncapsulationTypes.add(FlowEncapsulationType.VXLAN); sp.setSupportedTransitEncapsulation(flowEncapsulationTypes); } |
### Question:
PathWeight implements Comparable<PathWeight> { public PathWeight add(PathWeight toAdd) { List<Long> result = new ArrayList<>(); Iterator<Long> firstIterator = params.iterator(); Iterator<Long> secondIterator = toAdd.params.iterator(); while (firstIterator.hasNext() || secondIterator.hasNext()) { long first = firstIterator.hasNext() ? firstIterator.next() : 0L; long second = secondIterator.hasNext() ? secondIterator.next() : 0L; result.add(first + second); } return new PathWeight(result); } PathWeight(long... params); PathWeight(List<Long> params); PathWeight add(PathWeight toAdd); long toLong(); @Override int compareTo(PathWeight o); }### Answer:
@Test public void add() { PathWeight first = new PathWeight(2, 7); PathWeight second = new PathWeight(1, 2); PathWeight actual = first.add(second); assertEquals(0, actual.compareTo(new PathWeight(3, 9))); } |
### Question:
PathWeight implements Comparable<PathWeight> { @Override public int compareTo(PathWeight o) { int firstSize = params.size(); int secondSize = o.params.size(); int limit = Math.min(firstSize, secondSize); int i = 0; while (i < limit) { long first = params.get(i).longValue(); long second = o.params.get(i).longValue(); if (first != second) { return first > second ? 1 : -1; } i++; } if (firstSize == secondSize) { return 0; } else { return Integer.compare(firstSize, secondSize); } } PathWeight(long... params); PathWeight(List<Long> params); PathWeight add(PathWeight toAdd); long toLong(); @Override int compareTo(PathWeight o); }### Answer:
@Test public void compareTo() { final PathWeight first = new PathWeight(2, 7); final PathWeight second = new PathWeight(5, 7); final PathWeight equalToSecond = new PathWeight(5, 7); final PathWeight third = new PathWeight(7); final PathWeight fourth = new PathWeight(7, 2); assertTrue(first.compareTo(second) < 0); assertTrue(second.compareTo(first) > 0); assertTrue(second.compareTo(equalToSecond) == 0); assertTrue(second.compareTo(third) < 0); assertTrue(third.compareTo(fourth) < 0); assertTrue(fourth.compareTo(third) > 0); } |
### Question:
PathComputerFactory { public PathComputer getPathComputer() { return new InMemoryPathComputer(availableNetworkFactory, new BestWeightAndShortestPathFinder(config.getMaxAllowedDepth()), config); } PathComputerFactory(PathComputerConfig config, AvailableNetworkFactory availableNetworkFactory); PathComputer getPathComputer(); }### Answer:
@Test public void shouldCreateAnInstance() { PathComputerFactory factory = new PathComputerFactory( mock(PathComputerConfig.class), mock(AvailableNetworkFactory.class)); PathComputer pathComputer = factory.getPathComputer(); assertTrue(pathComputer instanceof InMemoryPathComputer); } |
### Question:
FlowStatusResponse extends InfoData { public FlowIdStatusPayload getPayload() { return payload; } @JsonCreator FlowStatusResponse(@JsonProperty(PAYLOAD) final FlowIdStatusPayload payload); FlowIdStatusPayload getPayload(); void setPayload(final FlowIdStatusPayload payload); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object object); }### Answer:
@Test public void testJsonSerialization() throws IOException { InfoMessage msg = new InfoMessage(new FlowStatusResponse( new FlowIdStatusPayload("FLOW", FlowState.UP)), 10L, "CORRELATION", Destination.NORTHBOUND, null); InfoMessage fromJson = MAPPER.readValue(json, InfoMessage.class); FlowStatusResponse fsrJson = (FlowStatusResponse) fromJson.getData(); FlowStatusResponse fsrObj = (FlowStatusResponse) msg.getData(); Assert.assertEquals(fsrJson.getPayload().getId(), fsrObj.getPayload().getId()); Assert.assertEquals(fsrJson.getPayload().getStatus(), fsrObj.getPayload().getStatus()); Assert.assertEquals(fsrJson.getPayload().getStatus(), FlowState.UP); Assert.assertEquals(fromJson.getCorrelationId(), msg.getCorrelationId()); System.out.println("JSON: " + MAPPER.writeValueAsString(msg)); } |
### Question:
NoviflowResponseMapper { public Boolean toBoolean(YesNo yesNo) { if (yesNo == null) { return null; } switch (yesNo) { case YES: return true; case NO: return false; default: return null; } } @Mapping(source = "logicalportno", target = "logicalPortNumber") @Mapping(source = "portnoList", target = "portNumbers") @Mapping(source = "logicalporttype", target = "type") abstract LogicalPort map(io.grpc.noviflow.LogicalPort port); @Mapping(source = "ethLinksList", target = "ethLinks") @Mapping(source = "buildsList", target = "builds") abstract SwitchInfoStatus map(StatusSwitch statusSwitch); @Mapping(source = "ipaddr", target = "ipAddress") abstract RemoteLogServer map(io.grpc.noviflow.RemoteLogServer remoteLogServer); abstract PacketInOutStatsDto map(PacketInOutStatsResponse stats); abstract PacketInOutStatsResponse map(PacketInOutStats stats); LogicalPortType map(io.grpc.noviflow.LogicalPortType type); io.grpc.noviflow.LogicalPortType map(LogicalPortType type); Boolean toBoolean(YesNo yesNo); }### Answer:
@Test public void yesNoTest() { Assert.assertTrue(mapper.toBoolean(YesNo.YES)); Assert.assertFalse(mapper.toBoolean(YesNo.NO)); assertNull(mapper.toBoolean(null)); assertNull(mapper.toBoolean(YesNo.UNRECOGNIZED)); assertNull(mapper.toBoolean(YesNo.YESNO_RESERVED)); } |
### Question:
IntersectionComputer { public static boolean isProtectedPathOverlaps( List<PathSegment> primaryFlowSegments, List<PathSegment> protectedFlowSegments) { Set<Edge> primaryEdges = primaryFlowSegments.stream().map(Edge::fromPathSegment).collect(Collectors.toSet()); Set<Edge> protectedEdges = protectedFlowSegments.stream().map(Edge::fromPathSegment) .collect(Collectors.toSet()); return !Sets.intersection(primaryEdges, protectedEdges).isEmpty(); } IntersectionComputer(String targetFlowId, PathId targetForwardPathId, PathId targetReversePathId,
Collection<FlowPath> paths); OverlappingSegmentsStats getOverlappingStats(); OverlappingSegmentsStats getOverlappingStats(PathId forwardPathId, PathId reversePathId); static boolean isProtectedPathOverlaps(
List<PathSegment> primaryFlowSegments, List<PathSegment> protectedFlowSegments); }### Answer:
@Test public void isProtectedPathOverlapsPositive() { List<FlowPath> paths = getFlowPaths(PATH_ID, PATH_ID_REVERSE, flow); List<PathSegment> primarySegments = getFlowPathSegments(paths); List<PathSegment> protectedSegmets = Collections.singletonList( buildPathSegment(SWITCH_ID_A, SWITCH_ID_B, 1, 1)); assertTrue(IntersectionComputer.isProtectedPathOverlaps(primarySegments, protectedSegmets)); }
@Test public void isProtectedPathOverlapsNegative() { List<FlowPath> paths = getFlowPaths(PATH_ID, PATH_ID_REVERSE, flow); List<PathSegment> primarySegments = getFlowPathSegments(paths); List<PathSegment> protectedSegmets = Collections.singletonList( buildPathSegment(SWITCH_ID_A, SWITCH_ID_C, 3, 3)); assertFalse(IntersectionComputer.isProtectedPathOverlaps(primarySegments, protectedSegmets)); } |
### Question:
PortMapper { @Mapping(source = "state", target = "status") public abstract Port map(PortInfoData portInfoData); @Mapping(source = "state", target = "status") abstract Port map(PortInfoData portInfoData); @Mapping(target = "timestamp", ignore = true) @Mapping(target = "maxCapacity", ignore = true) @Mapping(target = "state", ignore = true) @Mapping(target = "enabled", ignore = true) abstract PortInfoData map(Port port); PortStatus map(PortChangeType portChangeType); @Mapping(source = "switchObj.switchId", target = "switchId") @Mapping(source = "port", target = "portNumber") @Mapping(target = "timestamp", ignore = true) abstract PortPropertiesPayload map(PortProperties portProperties); static final PortMapper INSTANCE; }### Answer:
@Test public void portMapperTest() { PortMapper portMapper = Mappers.getMapper(PortMapper.class); PortInfoData portInfoData = new PortInfoData(TEST_SWITCH_ID, 1, PortChangeType.UP); Port port = portMapper.map(portInfoData); Assert.assertEquals(PortStatus.UP, port.getStatus()); PortInfoData portInfoDataMapping = portMapper.map(port); Assert.assertEquals(TEST_SWITCH_ID, portInfoDataMapping.getSwitchId()); Assert.assertEquals(1, portInfoDataMapping.getPortNo()); } |
### Question:
CookiePool { public CookiePool(PersistenceManager persistenceManager, long minCookie, long maxCookie, int poolSize) { transactionManager = persistenceManager.getTransactionManager(); RepositoryFactory repositoryFactory = persistenceManager.getRepositoryFactory(); flowCookieRepository = repositoryFactory.createFlowCookieRepository(); this.minCookie = minCookie; this.maxCookie = maxCookie; this.poolSize = poolSize; } CookiePool(PersistenceManager persistenceManager, long minCookie, long maxCookie, int poolSize); @TransactionRequired long allocate(String flowId); void deallocate(long unmaskedCookie); }### Answer:
@Test public void cookiePool() { transactionManager.doInTransaction(() -> { Set<Long> cookies = new HashSet<>(); for (long i = MIN_COOKIE; i <= MAX_COOKIE; i++) { cookies.add(cookiePool.allocate(format("flow_%d", i))); } assertEquals(MAX_COOKIE - MIN_COOKIE + 1, cookies.size()); cookies.forEach(cookie -> assertTrue(cookie >= MIN_COOKIE && cookie <= MAX_COOKIE)); }); } |
### Question:
CookiePool { @TransactionRequired public long allocate(String flowId) { if (nextCookie > 0) { if (nextCookie <= maxCookie && !flowCookieRepository.exists(nextCookie)) { addCookie(flowId, nextCookie); return nextCookie++; } else { nextCookie = 0; } } if (nextCookie == 0) { long numOfPools = (maxCookie - minCookie) / poolSize; if (numOfPools > 1) { long poolToTake = Math.abs(new Random().nextInt()) % numOfPools; Optional<Long> availableCookie = flowCookieRepository.findFirstUnassignedCookie( minCookie + poolToTake * poolSize, minCookie + (poolToTake + 1) * poolSize - 1); if (availableCookie.isPresent()) { nextCookie = availableCookie.get(); addCookie(flowId, nextCookie); return nextCookie++; } } nextCookie = -1; } if (nextCookie == -1) { Optional<Long> availableCookie = flowCookieRepository.findFirstUnassignedCookie(minCookie, maxCookie); if (availableCookie.isPresent()) { nextCookie = availableCookie.get(); addCookie(flowId, nextCookie); return nextCookie++; } } throw new ResourceNotAvailableException("No cookie available"); } CookiePool(PersistenceManager persistenceManager, long minCookie, long maxCookie, int poolSize); @TransactionRequired long allocate(String flowId); void deallocate(long unmaskedCookie); }### Answer:
@Test(expected = ResourceNotAvailableException.class) public void cookiePoolFullTest() { transactionManager.doInTransaction(() -> { for (long i = MIN_COOKIE; i <= MAX_COOKIE + 1; i++) { assertTrue(cookiePool.allocate(format("flow_%d", i)) > 0); } }); }
@Test public void cookieLldp() { transactionManager.doInTransaction(() -> { String flowId = "flow_1"; long flowCookie = cookiePool.allocate(flowId); long lldpCookie = cookiePool.allocate(flowId); assertNotEquals(flowCookie, lldpCookie); }); } |
### Question:
FlowResourcesManager { public void deallocatePathResources(PathId pathId, long unmaskedCookie, FlowEncapsulationType encapsulationType) { log.debug("Deallocate flow resources for path {}, cookie: {}.", pathId, unmaskedCookie); transactionManager.doInTransaction(() -> { cookiePool.deallocate(unmaskedCookie); meterPool.deallocate(pathId); EncapsulationResourcesProvider encapsulationResourcesProvider = getEncapsulationResourcesProvider(encapsulationType); encapsulationResourcesProvider.deallocate(pathId); }); } FlowResourcesManager(PersistenceManager persistenceManager, FlowResourcesConfig config); FlowResources allocateFlowResources(Flow flow); void deallocatePathResources(PathId pathId, long unmaskedCookie, FlowEncapsulationType encapsulationType); void deallocatePathResources(FlowResources resources); Optional<EncapsulationResources> getEncapsulationResources(PathId pathId,
PathId oppositePathId,
FlowEncapsulationType encapsulationType); }### Answer:
@Test public void deallocatePathResourcesTest() throws Exception { transactionManager.doInTransaction(() -> { Flow flow = convertFlow(firstFlow); FlowResources resources = resourcesManager.allocateFlowResources(flow); resourcesManager.deallocatePathResources(resources.getForward().getPathId(), resources.getUnmaskedCookie(), flow.getEncapsulationType()); resourcesManager.deallocatePathResources(resources.getReverse().getPathId(), resources.getUnmaskedCookie(), flow.getEncapsulationType()); verifyResourcesDeallocation(); }); } |
### Question:
MeterPool { public MeterPool(PersistenceManager persistenceManager, MeterId minMeterId, MeterId maxMeterId, int poolSize) { transactionManager = persistenceManager.getTransactionManager(); RepositoryFactory repositoryFactory = persistenceManager.getRepositoryFactory(); flowMeterRepository = repositoryFactory.createFlowMeterRepository(); this.minMeterId = minMeterId; this.maxMeterId = maxMeterId; this.poolSize = poolSize; } MeterPool(PersistenceManager persistenceManager, MeterId minMeterId, MeterId maxMeterId, int poolSize); @TransactionRequired MeterId allocate(SwitchId switchId, String flowId, PathId pathId); void deallocate(PathId... pathIds); }### Answer:
@Test public void meterPoolTest() { transactionManager.doInTransaction(() -> { long minMeterId = MIN_METER_ID.getValue(); long maxMeterId = MAX_METER_ID.getValue(); Set<MeterId> meterIds = new HashSet<>(); for (long i = minMeterId; i <= maxMeterId; i++) { meterIds.add(meterPool.allocate(SWITCH_ID, format("flow_%d", i), new PathId(format("path_%d", i)))); } assertEquals(maxMeterId - minMeterId + 1, meterIds.size()); meterIds.forEach(meterId -> assertTrue(meterId.getValue() >= minMeterId && meterId.getValue() <= maxMeterId)); }); } |
### Question:
FlowRttMetricGenBolt extends MetricGenBolt { @VisibleForTesting static long noviflowTimestamp(Long v) { long seconds = (v >> 32); long nanoseconds = (v & 0xFFFFFFFFL); return seconds * TEN_TO_NINE + nanoseconds; } FlowRttMetricGenBolt(String metricPrefix); static final long TEN_TO_NINE; }### Answer:
@Test public void testNoviflowTimstampToLong() { long seconds = 123456789; long nanoseconds = 987654321; long timestampNovi = (seconds << 32) + nanoseconds; assertEquals(123456789_987654321L, noviflowTimestamp(timestampNovi)); } |
### Question:
FlowDirectionHelper { public static Direction findDirection(long rawCookie) throws FlowCookieException { return findDirectionSafe(rawCookie) .orElseThrow(() -> new FlowCookieException(String.format( "unknown direction for %s", new Cookie(rawCookie)))); } private FlowDirectionHelper(); static Direction findDirection(long rawCookie); static Optional<Direction> findDirectionSafe(long rawCookie); }### Answer:
@Test public void findDirectionTest() throws Exception { assertEquals(Direction.FORWARD, FlowDirectionHelper.findDirection(FORWARD_COOKIE)); assertEquals(Direction.REVERSE, FlowDirectionHelper.findDirection(REVERSE_COOKIE)); thrown.expect(FlowCookieException.class); FlowDirectionHelper.findDirection(BAD_COOKIE); } |
### Question:
OfInput { public boolean packetInCookieMismatchAll(Logger log, U64... expected) { boolean isMismatched = packetInCookieMismatchCheck(expected); if (isMismatched) { log.debug("{} - cookie mismatch (expected one of:{}, actual:{})", this, expected, packetInCookie()); } return isMismatched; } OfInput(IOFSwitch sw, OFMessage message, FloodlightContext context); U64 packetInCookie(); boolean packetInCookieMismatchAll(Logger log, U64... expected); OFType getType(); long getReceiveTime(); DatapathId getDpId(); OFMessage getMessage(); Long getLatency(); Ethernet getPacketInPayload(); OFPort getPort(); @Override String toString(); }### Answer:
@Test public void isCookieMismatch0() { OfInput input = makeInput(U64.of(cookieAlpha.getValue())); Assert.assertFalse(input.packetInCookieMismatchAll(callerLogger, cookieAlpha)); }
@Test public void isCookieMismatch1() { OfInput input = makeInput(U64.of(-1)); Assert.assertFalse(input.packetInCookieMismatchAll(callerLogger, cookieAlpha)); input = makeInput(U64.ZERO); Assert.assertFalse(input.packetInCookieMismatchAll(callerLogger, cookieAlpha)); }
@Test public void isCookieMismatch3() { OfInput input = makeInput(cookieAlpha); Assert.assertTrue(input.packetInCookieMismatchAll(callerLogger, cookieBeta)); } |
### Question:
ValidatingConfigurationProvider implements ConfigurationProvider { @Override public <T> T getConfiguration(Class<T> configurationType) { requireNonNull(configurationType, "configurationType cannot be null"); T instance = factory.createConfiguration(configurationType, source); Set<ConstraintViolation<T>> errors = validator.validate(instance); if (!errors.isEmpty()) { Set<String> errorDetails = errors.stream() .map(v -> v.getPropertyPath() + " " + v.getMessage()) .collect(toSet()); throw new ConfigurationException( format("The configuration value(s) for %s violate constraint(s): %s", configurationType.getSimpleName(), String.join(";", errorDetails)), errorDetails); } return instance; } ValidatingConfigurationProvider(ConfigurationSource source, ConfigurationFactory factory); @Override T getConfiguration(Class<T> configurationType); }### Answer:
@Test public void shouldPassValidationForValidConfig() { Properties source = new Properties(); source.setProperty(TEST_KEY, String.valueOf(VALID_TEST_VALUE)); ValidatingConfigurationProvider provider = new ValidatingConfigurationProvider( new PropertiesConfigurationSource(source), new JdkProxyStaticConfigurationFactory()); TestConfig config = provider.getConfiguration(TestConfig.class); assertEquals(VALID_TEST_VALUE, config.getTestProperty()); }
@Test public void shouldFailValidationForInvalidConfig() { Properties source = new Properties(); source.setProperty(TEST_KEY, String.valueOf(INVALID_TEST_VALUE)); ValidatingConfigurationProvider provider = new ValidatingConfigurationProvider( new PropertiesConfigurationSource(source), new JdkProxyStaticConfigurationFactory()); expectedException.expect(ConfigurationException.class); provider.getConfiguration(TestConfig.class); } |
### Question:
IslStatsBolt extends AbstractBolt implements IslStatsCarrier { @VisibleForTesting List<Object> buildTsdbTuple(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort, long latency, long timestamp) throws JsonProcessingException { Map<String, String> tags = new HashMap<>(); tags.put("src_switch", srcSwitchId.toOtsdFormat()); tags.put("src_port", String.valueOf(srcPort)); tags.put("dst_switch", dstSwitchId.toOtsdFormat()); tags.put("dst_port", String.valueOf(dstPort)); return tsdbTuple(metricFormatter.format(LATENCY_METRIC_NAME), timestamp, latency, tags); } IslStatsBolt(String metricPrefix, long latencyTimeout); @Override void emitLatency(SwitchId srcSwitch, int srcPort, SwitchId dstSwitch, int dstPort,
long latency, long timestamp); @Override void declareOutputFields(OutputFieldsDeclarer declarer); static final String LATENCY_METRIC_NAME; }### Answer:
@Test public void buildTsdbTupleFromIslOneWayLatency() throws JsonEncodeException, IOException { List<Object> tsdbTuple = statsBolt.buildTsdbTuple( SWITCH1_ID, NODE1.getPortNo(), SWITCH2_ID, NODE2.getPortNo(), LATENCY, TIMESTAMP); assertTsdbTuple(tsdbTuple); } |
### Question:
IslStatsService { @VisibleForTesting boolean isRecordStillValid(LatencyRecord record) { Instant expirationTime = Instant.ofEpochMilli(record.getTimestamp()) .plusSeconds(latencyTimeout); return Instant.now().isBefore(expirationTime); } IslStatsService(IslStatsCarrier carrier, long latencyTimeout); void handleRoundTripLatencyMetric(long timestamp, IslRoundTripLatency data, Endpoint destination); void handleOneWayLatencyMetric(long timestamp, IslOneWayLatency data); void handleIstStatusUpdateNotification(IslStatusUpdateNotification notification); }### Answer:
@Test public void isRecordStillValidTest() { assertFalse(islStatsService.isRecordStillValid(new LatencyRecord(1, 0))); long expiredTimestamp = Instant.now().minusSeconds(LATENCY_TIMEOUT * 2).toEpochMilli(); assertFalse(islStatsService.isRecordStillValid(new LatencyRecord(1, expiredTimestamp))); assertTrue(islStatsService.isRecordStillValid(new LatencyRecord(1, System.currentTimeMillis()))); long freshTimestamp = Instant.now().plusSeconds(LATENCY_TIMEOUT * 2).toEpochMilli(); assertTrue(islStatsService.isRecordStillValid(new LatencyRecord(1, freshTimestamp))); } |
### Question:
CacheService { public void handleGetDataFromCache(IslRoundTripLatency roundTripLatency) { Endpoint source = Endpoint.of(roundTripLatency.getSrcSwitchId(), roundTripLatency.getSrcPortNo()); Endpoint destination = cache.get(source); try { if (destination == null) { destination = updateCache(source); } carrier.emitCachedData(roundTripLatency, destination); } catch (IslNotFoundException e) { log.debug(String.format("Could not update ISL cache: %s", e.getMessage()), e); } catch (IllegalIslStateException e) { log.error(String.format("Could not update ISL cache: %s", e.getMessage()), e); } } CacheService(CacheCarrier carrier, RepositoryFactory repositoryFactory); void handleUpdateCache(IslStatusUpdateNotification notification); void handleGetDataFromCache(IslRoundTripLatency roundTripLatency); }### Answer:
@Test() public void handleGetDataFromCacheTest() { IslRoundTripLatency forward = new IslRoundTripLatency(SWITCH_ID_1, PORT_1, 1, 0L); IslRoundTripLatency reverse = new IslRoundTripLatency(SWITCH_ID_2, PORT_2, 1, 0L); checkHandleGetDataFromCache(forward, SWITCH_ID_2, PORT_2); checkHandleGetDataFromCache(reverse, SWITCH_ID_1, PORT_1); } |
### Question:
CacheService { public void handleUpdateCache(IslStatusUpdateNotification notification) { if (notification.getStatus() == IslStatus.MOVED || notification.getStatus() == IslStatus.INACTIVE) { Endpoint source = Endpoint.of(notification.getSrcSwitchId(), notification.getSrcPortNo()); Endpoint destination = Endpoint.of(notification.getDstSwitchId(), notification.getDstPortNo()); cache.remove(source); cache.remove(destination); log.info("Remove ISL {}_{} ===> {}_{} from isl latency cache", notification.getSrcSwitchId(), notification.getSrcPortNo(), notification.getDstSwitchId(), notification.getDstPortNo()); } } CacheService(CacheCarrier carrier, RepositoryFactory repositoryFactory); void handleUpdateCache(IslStatusUpdateNotification notification); void handleGetDataFromCache(IslRoundTripLatency roundTripLatency); }### Answer:
@Test() public void handleUpdateCacheInactiveTest() { IslStatusUpdateNotification notification = new IslStatusUpdateNotification(SWITCH_ID_1, PORT_1, SWITCH_ID_2, PORT_2, INACTIVE); updateIslStatus(SWITCH_ID_1, PORT_1, SWITCH_ID_2, PORT_2, INACTIVE); updateIslStatus(SWITCH_ID_2, PORT_2, SWITCH_ID_1, PORT_1, INACTIVE); cacheService.handleUpdateCache(notification); IslRoundTripLatency forward = new IslRoundTripLatency(SWITCH_ID_1, PORT_1, 1, 0L); checkHandleGetDataFromCache(forward, SWITCH_ID_2, PORT_2); IslRoundTripLatency reverse = new IslRoundTripLatency(SWITCH_ID_2, PORT_2, 1, 0L); checkHandleGetDataFromCache(reverse, SWITCH_ID_1, PORT_1); } |
### Question:
IslLatencyService { public void handleOneWayIslLatency(IslOneWayLatency data, long timestamp) { log.debug("Received one way latency {} for ISL {}_{} ===> {}_{}, Packet Id: {}", data.getLatency(), data.getSrcSwitchId(), data.getSrcPortNo(), data.getDstSwitchId(), data.getDstPortNo(), data.getPacketId()); IslKey islKey = new IslKey(data); oneWayLatencyStorage.putIfAbsent(islKey, new LinkedList<>()); oneWayLatencyStorage.get(islKey).add(new LatencyRecord(data.getLatency(), timestamp)); if (isUpdateRequired(islKey)) { updateOneWayLatencyIfNeeded(data, islKey); } } IslLatencyService(TransactionManager transactionManager,
RepositoryFactory repositoryFactory, long latencyUpdateInterval,
long latencyUpdateTimeRange); void handleRoundTripIslLatency(IslRoundTripLatency data, Endpoint destination, long timestamp); void handleOneWayIslLatency(IslOneWayLatency data, long timestamp); static final String ONE_WAY_LATENCY; static final String ROUND_TRIP_LATENCY; }### Answer:
@Test public void handleOneWayIslLatencyTest() { assertTrue(islLatencyService.isUpdateRequired(FORWARD_ISL_KEY)); islLatencyService.handleOneWayIslLatency(createForwardOneWayLatency(1), System.currentTimeMillis()); assertForwardLatency(1); assertFalse(islLatencyService.isUpdateRequired(FORWARD_ISL_KEY)); islLatencyService.handleOneWayIslLatency(createForwardOneWayLatency(10000), System.currentTimeMillis()); assertForwardLatency(1); assertFalse(islLatencyService.isUpdateRequired(FORWARD_ISL_KEY)); } |
### Question:
IslLatencyService { @VisibleForTesting boolean isUpdateRequired(IslKey islKey) { return Instant.now().isAfter(nextUpdateTimeMap.getOrDefault(islKey, Instant.MIN)); } IslLatencyService(TransactionManager transactionManager,
RepositoryFactory repositoryFactory, long latencyUpdateInterval,
long latencyUpdateTimeRange); void handleRoundTripIslLatency(IslRoundTripLatency data, Endpoint destination, long timestamp); void handleOneWayIslLatency(IslOneWayLatency data, long timestamp); static final String ONE_WAY_LATENCY; static final String ROUND_TRIP_LATENCY; }### Answer:
@Test public void isUpdateRequiredTest() { assertTrue(islLatencyService.isUpdateRequired(FORWARD_ISL_KEY)); IslRoundTripLatency data = new IslRoundTripLatency(SWITCH_ID_1, PORT_1, 1L, 0L); Endpoint destination = Endpoint.of(SWITCH_ID_2, PORT_2); islLatencyService.handleRoundTripIslLatency(data, destination, System.currentTimeMillis()); assertFalse(islLatencyService.isUpdateRequired(FORWARD_ISL_KEY)); } |
### Question:
IslLatencyService { @VisibleForTesting Instant getNextUpdateTime() { return Instant.now().plusSeconds(latencyUpdateInterval); } IslLatencyService(TransactionManager transactionManager,
RepositoryFactory repositoryFactory, long latencyUpdateInterval,
long latencyUpdateTimeRange); void handleRoundTripIslLatency(IslRoundTripLatency data, Endpoint destination, long timestamp); void handleOneWayIslLatency(IslOneWayLatency data, long timestamp); static final String ONE_WAY_LATENCY; static final String ROUND_TRIP_LATENCY; }### Answer:
@Test public void getNextUpdateTimeTest() { Instant actualTime = islLatencyService.getNextUpdateTime(); long expectedTime = System.currentTimeMillis() + LATENCY_UPDATE_INTERVAL * 1000; assertEquals(expectedTime, actualTime.toEpochMilli(), 50); } |
### Question:
IslLatencyService { @VisibleForTesting long calculateAverageLatency(Queue<LatencyRecord> recordsQueue) { if (recordsQueue.isEmpty()) { log.error("Couldn't calculate average latency. Records queue is empty"); return -1; } long sum = 0; for (LatencyRecord record : recordsQueue) { sum += record.getLatency(); } return sum / recordsQueue.size(); } IslLatencyService(TransactionManager transactionManager,
RepositoryFactory repositoryFactory, long latencyUpdateInterval,
long latencyUpdateTimeRange); void handleRoundTripIslLatency(IslRoundTripLatency data, Endpoint destination, long timestamp); void handleOneWayIslLatency(IslOneWayLatency data, long timestamp); static final String ONE_WAY_LATENCY; static final String ROUND_TRIP_LATENCY; }### Answer:
@Test public void calculateAverageLatencyTest() { Queue<LatencyRecord> latencyRecords = new LinkedList<>(); for (int i = 1; i <= 5; i++) { latencyRecords.add(new LatencyRecord(i, 1)); } assertEquals(3, islLatencyService.calculateAverageLatency(latencyRecords)); }
@Test public void calculateAverageLatencyEmptyTest() { assertEquals(-1, islLatencyService.calculateAverageLatency(new LinkedList<>())); } |
### Question:
IslLatencyService { @VisibleForTesting void pollExpiredRecords(Queue<LatencyRecord> recordsQueue) { if (recordsQueue == null) { return; } Instant oldestTimeInRange = Instant.now().minusSeconds(latencyUpdateTimeRange); while (!recordsQueue.isEmpty() && Instant.ofEpochMilli(recordsQueue.peek().getTimestamp()).isBefore(oldestTimeInRange)) { recordsQueue.poll(); } } IslLatencyService(TransactionManager transactionManager,
RepositoryFactory repositoryFactory, long latencyUpdateInterval,
long latencyUpdateTimeRange); void handleRoundTripIslLatency(IslRoundTripLatency data, Endpoint destination, long timestamp); void handleOneWayIslLatency(IslOneWayLatency data, long timestamp); static final String ONE_WAY_LATENCY; static final String ROUND_TRIP_LATENCY; }### Answer:
@Test public void pollExpiredRecordsTest() { Instant time = Instant.now().minusSeconds(LATENCY_UPDATE_TIME_RANGE * 2); Queue<LatencyRecord> latencyRecords = new LinkedList<>(); for (int i = 0; i < 5; i++) { latencyRecords.add(new LatencyRecord(i, time.toEpochMilli())); time = time.plusSeconds(1); } time = Instant.now().minusSeconds(LATENCY_UPDATE_TIME_RANGE - 7); for (int i = 5; i < 10; i++) { latencyRecords.add(new LatencyRecord(i, time.toEpochMilli())); time = time.plusSeconds(1); } assertEquals(10, latencyRecords.size()); islLatencyService.pollExpiredRecords(latencyRecords); assertEquals(5, latencyRecords.size()); for (int i = 5; i < 10; i++) { assertEquals(i, latencyRecords.poll().getLatency()); } } |
### Question:
KafkaProducerService implements IKafkaProducerService { public void sendMessageAndTrack(String topic, Message message) { produce(encode(topic, message), new SendStatusCallback(this, topic, message)); } @Override void setup(FloodlightModuleContext moduleContext); void sendMessageAndTrack(String topic, Message message); void sendMessageAndTrack(String topic, String key, Message message); @Override void sendMessageAndTrack(String topic, String key, AbstractMessage message); SendStatus sendMessage(String topic, Message message); int getFailedSendMessageCounter(); }### Answer:
@Test public void errorReporting() throws Exception { final ExecutionException error = new ExecutionException("Emulate kafka send error", new IOException()); Future promise = mock(Future.class); expect(promise.get()).andThrow(error).anyTimes(); replay(promise); expect(kafkaProducer.send(anyObject(), anyObject(Callback.class))) .andAnswer(new IAnswer<Future<RecordMetadata>>() { @Override public Future<RecordMetadata> answer() { Callback callback = (Callback) getCurrentArguments()[1]; callback.onCompletion(null, error); return promise; } }); replay(kafkaProducer); subject.sendMessageAndTrack(TOPIC, makePayload()); verify(kafkaProducer); } |
### Question:
KafkaProducerService implements IKafkaProducerService { public SendStatus sendMessage(String topic, Message message) { SendStatus sendStatus = produce(encode(topic, message), null); return sendStatus; } @Override void setup(FloodlightModuleContext moduleContext); void sendMessageAndTrack(String topic, Message message); void sendMessageAndTrack(String topic, String key, Message message); @Override void sendMessageAndTrack(String topic, String key, AbstractMessage message); SendStatus sendMessage(String topic, Message message); int getFailedSendMessageCounter(); }### Answer:
@Test public void errorDetection() throws Exception { Future promise = mock(Future.class); final ExecutionException error = new ExecutionException("Emulate kafka send error", new IOException()); expect(promise.get()).andThrow(error).anyTimes(); replay(promise); expect(kafkaProducer.send(anyObject(), anyObject(Callback.class))).andReturn(promise); replay(kafkaProducer); SendStatus status = subject.sendMessage(TOPIC, makePayload()); verify(kafkaProducer); Boolean isThrown; try { status.waitTillComplete(); isThrown = false; } catch (ExecutionException e) { isThrown = true; } Assert.assertTrue(String.format( "Exception was not thrown by %s object", status.getClass().getCanonicalName()), isThrown); } |
### Question:
WatcherService { public void addWatch(SwitchId switchId, int portNo, long currentTime) { Packet packet = Packet.of(switchId, portNo, packetNo); timeouts.computeIfAbsent(currentTime + awaitTime, mappingFunction -> new HashSet<>()) .add(packet); carrier.sendDiscovery(switchId, portNo, packetNo, currentTime); packetNo += 1; } WatcherService(IWatcherServiceCarrier carrier, long awaitTime); void addWatch(SwitchId switchId, int portNo, long currentTime); void removeWatch(SwitchId switchId, int portNo); void tick(long tickTime); void confirmation(SwitchId switchId, int portNo, long packetNo); void discovery(SwitchId switchId, int portNo, SwitchId endSwitchId, int endPortNo, long packetNo, long currentTime); Set<Packet> getConfirmations(); SortedMap<Long, Set<Packet>> getTimeouts(); }### Answer:
@Test public void addWatch() { WatcherService w = new WatcherService(carrier, 10); w.addWatch(new SwitchId(1), 1, 1); w.addWatch(new SwitchId(1), 2, 1); w.addWatch(new SwitchId(2), 1, 2); w.addWatch(new SwitchId(2), 1, 2); w.addWatch(new SwitchId(2), 2, 3); assertThat(w.getConfirmations().size(), is(0)); assertThat(w.getTimeouts().size(), is(3)); verify(carrier, times(5)).sendDiscovery(any(SwitchId.class), anyInt(), anyLong(), anyLong()); } |
### Question:
WatcherService { public void removeWatch(SwitchId switchId, int portNo) { } WatcherService(IWatcherServiceCarrier carrier, long awaitTime); void addWatch(SwitchId switchId, int portNo, long currentTime); void removeWatch(SwitchId switchId, int portNo); void tick(long tickTime); void confirmation(SwitchId switchId, int portNo, long packetNo); void discovery(SwitchId switchId, int portNo, SwitchId endSwitchId, int endPortNo, long packetNo, long currentTime); Set<Packet> getConfirmations(); SortedMap<Long, Set<Packet>> getTimeouts(); }### Answer:
@Test public void removeWatch() { } |
### Question:
DecisionMakerService { void discovered(SwitchId switchId, int portNo, SwitchId endSwitchId, int endPortNo, long currentTime) { carrier.discovered(switchId, portNo, endSwitchId, endPortNo, currentTime); lastDiscovery.put(Endpoint.of(switchId, portNo), currentTime); } DecisionMakerService(IDecisionMakerCarrier carrier, int failTimeout, int awaitTime); HashMap<Endpoint, Long> getLastDiscovery(); }### Answer:
@Test public void discovered() { DecisionMakerService w = new DecisionMakerService(carrier, 10, 5); w.discovered(new SwitchId(1), 10, new SwitchId(2), 20, 1L); w.discovered(new SwitchId(2), 20, new SwitchId(3), 30, 2L); verify(carrier).discovered(eq(new SwitchId(1)), eq(10), eq(new SwitchId(2)), eq(20), anyLong()); verify(carrier).discovered(eq(new SwitchId(2)), eq(20), eq(new SwitchId(3)), eq(30), anyLong()); } |
### Question:
DecisionMakerService { void failed(SwitchId switchId, int portNo, long currentTime) { Endpoint endpoint = Endpoint.of(switchId, portNo); if (!lastDiscovery.containsKey(endpoint)) { lastDiscovery.put(endpoint, currentTime - awaitTime); } long timeWindow = lastDiscovery.get(endpoint) + failTimeout; if (currentTime >= timeWindow) { carrier.failed(switchId, portNo, currentTime); } } DecisionMakerService(IDecisionMakerCarrier carrier, int failTimeout, int awaitTime); HashMap<Endpoint, Long> getLastDiscovery(); }### Answer:
@Test public void failed() { DecisionMakerService w = new DecisionMakerService(carrier, 10, 5); w.failed(new SwitchId(1), 10, 0); w.failed(new SwitchId(1), 10, 1); w.failed(new SwitchId(1), 10, 11); w.failed(new SwitchId(1), 10, 12); verify(carrier, times(2)).failed(eq(new SwitchId(1)), eq(10), anyLong()); w.discovered(new SwitchId(1), 10, new SwitchId(2), 20, 20); verify(carrier).discovered(new SwitchId(1), 10, new SwitchId(2), 20, 20); reset(carrier); w.failed(new SwitchId(1), 10, 21); w.failed(new SwitchId(1), 10, 23); w.failed(new SwitchId(1), 10, 24); verify(carrier, never()).failed(any(SwitchId.class), anyInt(), anyInt()); w.failed(new SwitchId(1), 10, 31); verify(carrier).failed(new SwitchId(1), 10, 31); } |
### Question:
OfFlowPresenceVerifier { public List<OFFlowMod> getMissing() { return expectedOfFlows.values().stream() .flatMap(Collection::stream) .collect(Collectors.toList()); } OfFlowPresenceVerifier(
IOfFlowDumpProducer dumpProducer, List<OFFlowMod> expectedFlows, Set<SwitchFeature> switchFeatures); List<OFFlowMod> getMissing(); }### Answer:
@Test public void inaccurateSetFieldVlanVidActionNegative() { OfFlowPresenceVerifier presenceVerifier = testInaccurateSetFieldVlanVidAction(Collections.emptySet()); Assert.assertFalse(presenceVerifier.getMissing().isEmpty()); }
@Test public void inaccurateSetFieldVlanVidActionPositive() { OfFlowPresenceVerifier presenceVerifier = testInaccurateSetFieldVlanVidAction(Collections.singleton( SwitchFeature.INACCURATE_SET_VLAN_VID_ACTION)); Assert.assertTrue(presenceVerifier.getMissing().isEmpty()); } |
### Question:
CorrelationContext { public static String getId() { return Optional.ofNullable(ID.get()).orElse(DEFAULT_CORRELATION_ID); } private CorrelationContext(); static String getId(); static CorrelationContextClosable create(String correlationId); }### Answer:
@Ignore("Fix applying aspects to test classes") @Test @NewCorrelationContextRequired public void shouldInitializeCorrelationId() { String correlationId = CorrelationContext.getId(); assertNotEquals(DEFAULT_CORRELATION_ID, correlationId); } |
### Question:
NoviflowSpecificFeature extends AbstractFeature { static boolean isWbSeries(IOFSwitch sw) { if (! isNoviSwitch(sw)) { return false; } if (E_SWITCH_MANUFACTURER_DESCRIPTION.equalsIgnoreCase(getManufacturer(sw))) { return true; } Optional<SwitchDescription> description = Optional.ofNullable(sw.getSwitchDescription()); return E_SWITCH_HARDWARE_DESCRIPTION_REGEX.matcher( description .map(SwitchDescription::getHardwareDescription) .orElse("")).matches(); } static final String NOVIFLOW_MANUFACTURER_SUFFIX; }### Answer:
@Test public void testIsWbSeries() { assertTrue(isWbSeries(makeSwitchMock("NoviFlow Inc", "NW500.0.1", "WB5164-E"))); assertTrue(isWbSeries(makeSwitchMock("E", "NW400.4.0", "WB5164"))); assertFalse(isWbSeries(makeSwitchMock("NoviFlow Inc", "NW400.4.0", "NS21100"))); assertFalse(isWbSeries(makeSwitchMock("NoviFlow Inc", "NW500.2.0_dev", "NS21100"))); assertFalse(isWbSeries(makeSwitchMock("NoviFlow Inc", "NW500.0.1", "SM5000-SM"))); assertFalse(isWbSeries(makeSwitchMock("Common Inc", "Soft123", "Hard123"))); assertFalse(isWbSeries(makeSwitchMock("Nicira, Inc.", "Soft123", "Hard123"))); assertFalse(isWbSeries(makeSwitchMock("2004-2016 Centec Networks Inc", "2.8.16.21", "48T"))); assertFalse(isWbSeries(makeSwitchMock("Sonus Networks Inc, 4 Technology Park Dr, Westford, MA 01886, USA", "8.1.0.14", "VX3048"))); } |
### Question:
NoviflowSpecificFeature extends AbstractFeature { static boolean isSmSeries(IOFSwitch sw) { if (! isNoviSwitch(sw)) { return false; } Optional<SwitchDescription> description = Optional.ofNullable(sw.getSwitchDescription()); return NOVIFLOW_VIRTUAL_SWITCH_HARDWARE_DESCRIPTION_REGEX.matcher( description.map(SwitchDescription::getHardwareDescription) .orElse("")).matches(); } static final String NOVIFLOW_MANUFACTURER_SUFFIX; }### Answer:
@Test public void testIsSmSeries() { assertTrue(isSmSeries(makeSwitchMock("NoviFlow Inc", "NW500.0.1", "SM5000-SM"))); assertFalse(isSmSeries(makeSwitchMock("NoviFlow Inc", "NW500.0.1", "WB5164-E"))); assertFalse(isSmSeries(makeSwitchMock("E", "NW400.4.0", "WB5164"))); assertFalse(isSmSeries(makeSwitchMock("NoviFlow Inc", "NW400.4.0", "NS21100"))); assertFalse(isSmSeries(makeSwitchMock("NoviFlow Inc", "NW500.2.0_dev", "NS21100"))); assertFalse(isSmSeries(makeSwitchMock("Common Inc", "Soft123", "Hard123"))); assertFalse(isSmSeries(makeSwitchMock("Nicira, Inc.", "Soft123", "Hard123"))); assertFalse(isSmSeries(makeSwitchMock("2004-2016 Centec Networks Inc", "2.8.16.21", "48T"))); assertFalse(isSmSeries(makeSwitchMock("Sonus Networks Inc, 4 Technology Park Dr, Westford, MA 01886, USA", "8.1.0.14", "VX3048"))); } |
### Question:
BfdFeature extends AbstractFeature { @Override public Optional<SwitchFeature> discover(IOFSwitch sw) { Optional<SwitchFeature> empty = Optional.empty(); SwitchDescription description = sw.getSwitchDescription(); if (description == null || description.getSoftwareDescription() == null) { return empty; } if (!NOVIFLOW_SOFTWARE_DESCRIPTION_REGEX.matcher(description.getSoftwareDescription()).matches()) { return empty; } return Optional.of(SwitchFeature.BFD); } @Override Optional<SwitchFeature> discover(IOFSwitch sw); }### Answer:
@Test public void testDiscoverOfSwitchWithoutBfdSupport() { Assert.assertFalse(bfdFeature.discover(createSwitchWithDescription(null)).isPresent()); assertWithoutBfdSupport("2.8.16.21"); assertWithoutBfdSupport("2.8.16.15"); assertWithoutBfdSupport("8.1.0.14"); } |
### Question:
OfFlowStatsMapper { public FlowStatsData toFlowStatsData(List<OFFlowStatsReply> data, SwitchId switchId) { try { List<FlowStatsEntry> stats = data.stream() .flatMap(reply -> reply.getEntries().stream()) .map(this::toFlowStatsEntry) .filter(Objects::nonNull) .collect(toList()); return new FlowStatsData(switchId, stats); } catch (NullPointerException | UnsupportedOperationException | IllegalArgumentException e) { log.error(String.format("Could not convert flow stats data %s on switch %s", data, switchId), e); return null; } } FlowEntry toFlowEntry(final OFFlowStatsEntry entry); FlowEntry toFlowEntry(final OFFlowMod entry); FlowMatchField toFlowMatchField(final Match match); FlowInstructions toFlowInstructions(final List<OFInstruction> instructions); GroupEntry toFlowGroupEntry(OFGroupDescStatsEntry ofGroupDescStatsEntry); GroupBucket toGroupBucket(OFBucket ofBucket); FlowApplyActions toFlowApplyActions(List<OFAction> ofApplyActions); FlowStatsData toFlowStatsData(List<OFFlowStatsReply> data, SwitchId switchId); FlowStatsEntry toFlowStatsEntry(OFFlowStatsEntry entry); static final OfFlowStatsMapper INSTANCE; }### Answer:
@Test public void testToFlowStatsData() { OFFlowStatsEntry ofEntry = buildFlowStatsEntry(); OFFlowStatsReply ofReply = factory.buildFlowStatsReply() .setXid(xId) .setEntries(Collections.singletonList(ofEntry)) .build(); FlowStatsData data = OfFlowStatsMapper.INSTANCE.toFlowStatsData(Collections.singletonList(ofReply), switchId); assertEquals(switchId, data.getSwitchId()); assertEquals(1, data.getStats().size()); FlowStatsEntry entry = data.getStats().get(0); assertEquals(tableId, entry.getTableId()); assertEquals(cookie, entry.getCookie()); assertEquals(packetCount, entry.getPacketCount()); assertEquals(byteCount, entry.getByteCount()); } |
### Question:
OfFlowStatsMapper { public GroupEntry toFlowGroupEntry(OFGroupDescStatsEntry ofGroupDescStatsEntry) { if (ofGroupDescStatsEntry == null) { return null; } return GroupEntry.builder() .groupType(ofGroupDescStatsEntry.getGroupType().toString()) .groupId(ofGroupDescStatsEntry.getGroup().getGroupNumber()) .buckets(ofGroupDescStatsEntry.getBuckets().stream() .map(this::toGroupBucket) .collect(toList())) .build(); } FlowEntry toFlowEntry(final OFFlowStatsEntry entry); FlowEntry toFlowEntry(final OFFlowMod entry); FlowMatchField toFlowMatchField(final Match match); FlowInstructions toFlowInstructions(final List<OFInstruction> instructions); GroupEntry toFlowGroupEntry(OFGroupDescStatsEntry ofGroupDescStatsEntry); GroupBucket toGroupBucket(OFBucket ofBucket); FlowApplyActions toFlowApplyActions(List<OFAction> ofApplyActions); FlowStatsData toFlowStatsData(List<OFFlowStatsReply> data, SwitchId switchId); FlowStatsEntry toFlowStatsEntry(OFFlowStatsEntry entry); static final OfFlowStatsMapper INSTANCE; }### Answer:
@Test public void testFlowGroupEntry() { OFGroupDescStatsEntry entry = buildFlowGroupEntry(); GroupEntry result = OfFlowStatsMapper.INSTANCE.toFlowGroupEntry(entry); assertEquals(entry.getGroup().getGroupNumber(), result.getGroupId()); assertEquals(entry.getGroupType().toString(), result.getGroupType()); assertEquals(entry.getBuckets().size(), result.getBuckets().size()); GroupBucket firstBucket = result.getBuckets().get(0); assertEquals("12", firstBucket.getApplyActions().getFlowOutput()); GroupBucket secondBucket = result.getBuckets().get(1); assertEquals(EthType.VLAN_FRAME.toString(), secondBucket.getApplyActions().getPushVlan()); assertEquals("vlan_vid", secondBucket.getApplyActions().getSetFieldActions().get(0).getFieldName()); assertEquals("12", secondBucket.getApplyActions().getSetFieldActions().get(0).getFieldValue()); assertEquals("1", secondBucket.getApplyActions().getFlowOutput()); } |
### Question:
OfTableStatsMapper { @Mapping(source = "tableId.value", target = "tableId") @Mapping(source = "activeCount", target = "activeEntries") @Mapping(source = "lookupCount.value", target = "lookupCount") @Mapping(source = "matchedCount.value", target = "matchedCount") public abstract TableStatsEntry toTableStatsEntry(OFTableStatsEntry source); @Mapping(source = "tableId.value", target = "tableId") @Mapping(source = "activeCount", target = "activeEntries") @Mapping(source = "lookupCount.value", target = "lookupCount") @Mapping(source = "matchedCount.value", target = "matchedCount") abstract TableStatsEntry toTableStatsEntry(OFTableStatsEntry source); static final OfTableStatsMapper INSTANCE; }### Answer:
@Test public void shouldConvertSuccessfully() { OFFactoryVer13 ofFactoryVer13 = new OFFactoryVer13(); OFTableStatsEntry entry = ofFactoryVer13.buildTableStatsEntry() .setTableId(TableId.of(11)) .setActiveCount(10) .setMatchedCount(U64.of(100001L)) .setLookupCount(U64.of(100002L)) .build(); TableStatsEntry result = OfTableStatsMapper.INSTANCE.toTableStatsEntry(entry); assertEquals(result.getTableId(), entry.getTableId().getValue()); assertEquals(result.getActiveEntries(), entry.getActiveCount()); assertEquals(result.getLookupCount(), entry.getLookupCount().getValue()); assertEquals(result.getMatchedCount(), entry.getMatchedCount().getValue()); } |
### Question:
OfPortDescConverter { public boolean isReservedPort(OFPort port) { return OFPort.MAX.getPortNumber() <= port.getPortNumber() && port.getPortNumber() <= -1; } PortDescription toPortDescription(OFPortDesc ofPortDesc); PortInfoData toPortInfoData(DatapathId dpId, OFPortDesc portDesc,
net.floodlightcontroller.core.PortChangeType type); boolean isReservedPort(OFPort port); boolean isPortEnabled(OFPortDesc portDesc); static final OfPortDescConverter INSTANCE; }### Answer:
@Test public void testReservedPortCheck() { for (OFPort port : new OFPort[]{ OFPort.LOCAL, OFPort.ALL, OFPort.CONTROLLER, OFPort.ANY, OFPort.FLOOD, OFPort.NO_MASK, OFPort.IN_PORT, OFPort.NORMAL, OFPort.TABLE}) { Assert.assertTrue(String.format("Port %s must be detected as RESERVED, but it's not", port), OfPortDescConverter.INSTANCE.isReservedPort(port)); } for (OFPort port : new OFPort[]{ OFPort.of(1), OFPort.of(OFPort.MAX.getPortNumber() - 1)}) { Assert.assertFalse(String.format("Port %s must be detected as NOT RESERVED, but it's not", port), OfPortDescConverter.INSTANCE.isReservedPort(port)); } } |
### Question:
OfMeterStatsMapper { public MeterStatsData toMeterStatsData(List<OFMeterStatsReply> data, SwitchId switchId) { try { List<MeterStatsEntry> stats = data.stream() .flatMap(reply -> reply.getEntries().stream()) .map(this::toMeterStatsEntry) .filter(Objects::nonNull) .collect(toList()); return new MeterStatsData(switchId, stats); } catch (NullPointerException | UnsupportedOperationException | IllegalArgumentException e) { log.error(String.format("Could not convert meter stats data %s on switch %s", data, switchId), e); return null; } } MeterStatsData toMeterStatsData(List<OFMeterStatsReply> data, SwitchId switchId); MeterStatsEntry toMeterStatsEntry(OFMeterStats entry); static final OfMeterStatsMapper INSTANCE; }### Answer:
@Test public void testToPortStatsDataV13() { OFFactoryVer13 factory = new OFFactoryVer13(); OFMeterBandStats bandStats = factory.meterBandStats(U64.of(bandPacketCount), U64.of(bandByteCount)); OFMeterStats meterStats = factory.buildMeterStats() .setMeterId(meterId) .setByteInCount(U64.of(meterByteCount)) .setPacketInCount(U64.of(meterPacketCount)) .setBandStats(Collections.singletonList(bandStats)) .build(); OFMeterStatsReply reply = factory.buildMeterStatsReply() .setEntries(Collections.singletonList(meterStats)) .build(); MeterStatsData data = OfMeterStatsMapper.INSTANCE.toMeterStatsData(Collections.singletonList(reply), switchId); assertEquals(switchId, data.getSwitchId()); assertEquals(1, data.getStats().size()); MeterStatsEntry statsEntry = data.getStats().get(0); assertEquals(bandByteCount, statsEntry.getByteInCount()); assertEquals(bandPacketCount, statsEntry.getPacketsInCount()); } |
### Question:
SwitchTrackingService implements IOFSwitchListener, IService { @Override @NewCorrelationContextRequired public void switchAdded(final DatapathId switchId) { dashboardLogger.onSwitchEvent(switchId, SwitchChangeType.ADDED); switchDiscovery(switchId, SwitchChangeType.ADDED); } void dumpAllSwitches(); void completeSwitchActivation(DatapathId dpId); @Override @NewCorrelationContextRequired void switchAdded(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchRemoved(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchActivated(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchDeactivated(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchChanged(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchPortChanged(final DatapathId switchId, final OFPortDesc portDesc, final PortChangeType type); @Override void setup(FloodlightModuleContext context); }### Answer:
@Test public void switchAdded() throws Exception { SpeakerSwitchView expectedSwitchView = makeSwitchRecord(dpId, switchFeatures, true, true); Capture<Message> producedMessage = prepareAliveSwitchEvent(expectedSwitchView); replayAll(); service.switchAdded(dpId); verifySwitchEvent(SwitchChangeType.ADDED, expectedSwitchView, producedMessage); }
@Test public void switchAddedMissing() throws Exception { Capture<Message> producedMessage = prepareRemovedSwitchEvent(); replayAll(); service.switchAdded(dpId); verifySwitchEvent(SwitchChangeType.ADDED, null, producedMessage); } |
### Question:
SwitchTrackingService implements IOFSwitchListener, IService { @Override @NewCorrelationContextRequired public void switchRemoved(final DatapathId switchId) { dashboardLogger.onSwitchEvent(switchId, SwitchChangeType.REMOVED); switchManager.deactivate(switchId); switchDiscovery(switchId, SwitchChangeType.REMOVED); } void dumpAllSwitches(); void completeSwitchActivation(DatapathId dpId); @Override @NewCorrelationContextRequired void switchAdded(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchRemoved(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchActivated(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchDeactivated(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchChanged(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchPortChanged(final DatapathId switchId, final OFPortDesc portDesc, final PortChangeType type); @Override void setup(FloodlightModuleContext context); }### Answer:
@Test public void switchRemoved() { Capture<Message> producedMessage = prepareSwitchEventCommon(dpId); switchManager.deactivate(eq(dpId)); replayAll(); service.switchRemoved(dpId); verifySwitchEvent(SwitchChangeType.REMOVED, null, producedMessage); } |
### Question:
SwitchTrackingService implements IOFSwitchListener, IService { @Override @NewCorrelationContextRequired public void switchDeactivated(final DatapathId switchId) { dashboardLogger.onSwitchEvent(switchId, SwitchChangeType.DEACTIVATED); switchManager.deactivate(switchId); switchDiscovery(switchId, SwitchChangeType.DEACTIVATED); } void dumpAllSwitches(); void completeSwitchActivation(DatapathId dpId); @Override @NewCorrelationContextRequired void switchAdded(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchRemoved(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchActivated(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchDeactivated(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchChanged(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchPortChanged(final DatapathId switchId, final OFPortDesc portDesc, final PortChangeType type); @Override void setup(FloodlightModuleContext context); }### Answer:
@Test public void switchDeactivated() { Capture<Message> producedMessage = prepareSwitchEventCommon(dpId); switchManager.deactivate(eq(dpId)); replayAll(); service.switchDeactivated(dpId); verifySwitchEvent(SwitchChangeType.DEACTIVATED, null, producedMessage); } |
### Question:
SwitchTrackingService implements IOFSwitchListener, IService { @Override @NewCorrelationContextRequired public void switchChanged(final DatapathId switchId) { dashboardLogger.onSwitchEvent(switchId, SwitchChangeType.CHANGED); switchDiscovery(switchId, SwitchChangeType.CHANGED); } void dumpAllSwitches(); void completeSwitchActivation(DatapathId dpId); @Override @NewCorrelationContextRequired void switchAdded(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchRemoved(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchActivated(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchDeactivated(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchChanged(final DatapathId switchId); @Override @NewCorrelationContextRequired void switchPortChanged(final DatapathId switchId, final OFPortDesc portDesc, final PortChangeType type); @Override void setup(FloodlightModuleContext context); }### Answer:
@Test public void switchChanged() throws Exception { SpeakerSwitchView expectedSwitchRecord = makeSwitchRecord(dpId, switchFeatures, true, true); Capture<Message> producedMessage = prepareAliveSwitchEvent(expectedSwitchRecord); replayAll(); service.switchChanged(dpId); verifySwitchEvent(SwitchChangeType.CHANGED, expectedSwitchRecord, producedMessage); }
@Test public void switchChangedMissing() throws Exception { Capture<Message> producedMessage = prepareRemovedSwitchEvent(); replayAll(); service.switchChanged(dpId); verifySwitchEvent(SwitchChangeType.CHANGED, null, producedMessage); } |
### Question:
ClientState { boolean reachedCapacity() { return assignedTasks.size() >= capacity; } ClientState(); ClientState(final int capacity); private ClientState(Set<TaskId> activeTasks, Set<TaskId> standbyTasks, Set<TaskId> assignedTasks, Set<TaskId> prevActiveTasks, Set<TaskId> prevAssignedTasks, int capacity); ClientState copy(); void assign(final TaskId taskId, final boolean active); Set<TaskId> activeTasks(); Set<TaskId> standbyTasks(); int assignedTaskCount(); void incrementCapacity(); int activeTaskCount(); void addPreviousActiveTasks(final Set<TaskId> prevTasks); void addPreviousStandbyTasks(final Set<TaskId> standbyTasks); @Override String toString(); }### Answer:
@Test public void shouldHaveNotReachedCapacityWhenAssignedTasksLessThanCapacity() throws Exception { assertFalse(client.reachedCapacity()); } |
### Question:
ClientState { boolean hasMoreAvailableCapacityThan(final ClientState other) { if (this.capacity <= 0) { throw new IllegalStateException("Capacity of this ClientState must be greater than 0."); } if (other.capacity <= 0) { throw new IllegalStateException("Capacity of other ClientState must be greater than 0"); } final double otherLoad = (double) other.assignedTaskCount() / other.capacity; final double thisLoad = (double) assignedTaskCount() / capacity; if (thisLoad < otherLoad) return true; else if (thisLoad > otherLoad) return false; else return capacity > other.capacity; } ClientState(); ClientState(final int capacity); private ClientState(Set<TaskId> activeTasks, Set<TaskId> standbyTasks, Set<TaskId> assignedTasks, Set<TaskId> prevActiveTasks, Set<TaskId> prevAssignedTasks, int capacity); ClientState copy(); void assign(final TaskId taskId, final boolean active); Set<TaskId> activeTasks(); Set<TaskId> standbyTasks(); int assignedTaskCount(); void incrementCapacity(); int activeTaskCount(); void addPreviousActiveTasks(final Set<TaskId> prevTasks); void addPreviousStandbyTasks(final Set<TaskId> standbyTasks); @Override String toString(); }### Answer:
@Test public void shouldHaveMoreAvailableCapacityWhenCapacityHigherAndSameAssignedTaskCount() throws Exception { final ClientState c2 = new ClientState(2); assertTrue(c2.hasMoreAvailableCapacityThan(client)); assertFalse(client.hasMoreAvailableCapacityThan(c2)); }
@Test(expected = IllegalStateException.class) public void shouldThrowIllegalStateExceptionIfCapacityOfThisClientStateIsZero() throws Exception { final ClientState c1 = new ClientState(0); c1.hasMoreAvailableCapacityThan(new ClientState(1)); }
@Test(expected = IllegalStateException.class) public void shouldThrowIllegalStateExceptionIfCapacityOfOtherClientStateIsZero() throws Exception { final ClientState c1 = new ClientState(1); c1.hasMoreAvailableCapacityThan(new ClientState(0)); } |
### Question:
QuickUnion { public void unite(T id1, T... idList) { for (T id2 : idList) { unitePair(id1, id2); } } void add(T id); boolean exists(T id); T root(T id); void unite(T id1, T... idList); }### Answer:
@SuppressWarnings("unchecked") @Test public void testUnite() { QuickUnion<Long> qu = new QuickUnion<>(); long[] ids = { 1L, 2L, 3L, 4L, 5L }; for (long id : ids) { qu.add(id); } assertEquals(5, roots(qu, ids).size()); qu.unite(1L, 2L); assertEquals(4, roots(qu, ids).size()); assertEquals(qu.root(1L), qu.root(2L)); qu.unite(3L, 4L); assertEquals(3, roots(qu, ids).size()); assertEquals(qu.root(1L), qu.root(2L)); assertEquals(qu.root(3L), qu.root(4L)); qu.unite(1L, 5L); assertEquals(2, roots(qu, ids).size()); assertEquals(qu.root(1L), qu.root(2L)); assertEquals(qu.root(2L), qu.root(5L)); assertEquals(qu.root(3L), qu.root(4L)); qu.unite(3L, 5L); assertEquals(1, roots(qu, ids).size()); assertEquals(qu.root(1L), qu.root(2L)); assertEquals(qu.root(2L), qu.root(3L)); assertEquals(qu.root(3L), qu.root(4L)); assertEquals(qu.root(4L), qu.root(5L)); } |
### Question:
InternalTopicManager { public Map<String, Integer> getNumPartitions(final Set<String> topics) { for (int i = 0; i < MAX_TOPIC_READY_TRY; i++) { try { final MetadataResponse metadata = streamsKafkaClient.fetchMetadata(); final Map<String, Integer> existingTopicPartitions = fetchExistingPartitionCountByTopic(metadata); existingTopicPartitions.keySet().retainAll(topics); return existingTopicPartitions; } catch (StreamsException ex) { log.warn("Could not get number of partitions: " + ex.getMessage() + " Retry #" + i); } time.sleep(100L); } throw new StreamsException("Could not get number of partitions."); } InternalTopicManager(final StreamsKafkaClient streamsKafkaClient, final int replicationFactor,
final long windowChangeLogAdditionalRetention, final Time time); void makeReady(final Map<InternalTopicConfig, Integer> topics); Map<String, Integer> getNumPartitions(final Set<String> topics); void close(); static final String CLEANUP_POLICY_PROP; static final String RETENTION_MS; static final Long WINDOW_CHANGE_LOG_ADDITIONAL_RETENTION_DEFAULT; }### Answer:
@Test public void shouldReturnCorrectPartitionCounts() throws Exception { InternalTopicManager internalTopicManager = new InternalTopicManager(streamsKafkaClient, 1, WINDOW_CHANGE_LOG_ADDITIONAL_RETENTION_DEFAULT, time); Assert.assertEquals(Collections.singletonMap(topic, 1), internalTopicManager.getNumPartitions(Collections.singleton(topic))); } |
### Question:
StandaloneHerder extends AbstractHerder { @Override public void putTaskConfigs(String connName, List<Map<String, String>> configs, Callback<Void> callback) { throw new UnsupportedOperationException("Kafka Connect in standalone mode does not support externally setting task configurations."); } StandaloneHerder(Worker worker); StandaloneHerder(Worker worker,
String workerId,
StatusBackingStore statusBackingStore,
MemoryConfigBackingStore configBackingStore); synchronized void start(); synchronized void stop(); @Override int generation(); @Override synchronized void connectors(Callback<Collection<String>> callback); @Override synchronized void connectorInfo(String connName, Callback<ConnectorInfo> callback); @Override void connectorConfig(String connName, final Callback<Map<String, String>> callback); @Override synchronized void deleteConnectorConfig(String connName, Callback<Created<ConnectorInfo>> callback); @Override synchronized void putConnectorConfig(String connName,
final Map<String, String> config,
boolean allowReplace,
final Callback<Created<ConnectorInfo>> callback); @Override synchronized void requestTaskReconfiguration(String connName); @Override synchronized void taskConfigs(String connName, Callback<List<TaskInfo>> callback); @Override void putTaskConfigs(String connName, List<Map<String, String>> configs, Callback<Void> callback); @Override synchronized void restartTask(ConnectorTaskId taskId, Callback<Void> cb); @Override synchronized void restartConnector(String connName, Callback<Void> cb); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void testPutTaskConfigs() { Callback<Void> cb = PowerMock.createMock(Callback.class); PowerMock.replayAll(); herder.putTaskConfigs(CONNECTOR_NAME, Arrays.asList(singletonMap("config", "value")), cb); PowerMock.verifyAll(); } |
### Question:
SourceTaskOffsetCommitter { public void schedule(final ConnectorTaskId id, final WorkerSourceTask workerTask) { long commitIntervalMs = config.getLong(WorkerConfig.OFFSET_COMMIT_INTERVAL_MS_CONFIG); ScheduledFuture<?> commitFuture = commitExecutorService.scheduleWithFixedDelay(new Runnable() { @Override public void run() { commit(workerTask); } }, commitIntervalMs, commitIntervalMs, TimeUnit.MILLISECONDS); committers.put(id, commitFuture); } SourceTaskOffsetCommitter(WorkerConfig config,
ScheduledExecutorService commitExecutorService,
ConcurrentMap<ConnectorTaskId, ScheduledFuture<?>> committers); SourceTaskOffsetCommitter(WorkerConfig config); void close(long timeoutMs); void schedule(final ConnectorTaskId id, final WorkerSourceTask workerTask); void remove(ConnectorTaskId id); }### Answer:
@Test public void testSchedule() throws Exception { Capture<Runnable> taskWrapper = EasyMock.newCapture(); ScheduledFuture commitFuture = PowerMock.createMock(ScheduledFuture.class); EasyMock.expect(executor.scheduleWithFixedDelay( EasyMock.capture(taskWrapper), eq(DEFAULT_OFFSET_COMMIT_INTERVAL_MS), eq(DEFAULT_OFFSET_COMMIT_INTERVAL_MS), eq(TimeUnit.MILLISECONDS)) ).andReturn(commitFuture); ConnectorTaskId taskId = PowerMock.createMock(ConnectorTaskId.class); WorkerSourceTask task = PowerMock.createMock(WorkerSourceTask.class); EasyMock.expect(committers.put(taskId, commitFuture)).andReturn(null); PowerMock.replayAll(); committer.schedule(taskId, task); assertTrue(taskWrapper.hasCaptured()); assertNotNull(taskWrapper.getValue()); PowerMock.verifyAll(); } |
### Question:
OffsetStorageWriter { public synchronized boolean beginFlush() { if (flushing()) { log.error("Invalid call to OffsetStorageWriter flush() while already flushing, the " + "framework should not allow this"); throw new ConnectException("OffsetStorageWriter is already flushing"); } if (data.isEmpty()) return false; assert !flushing(); toFlush = data; data = new HashMap<>(); return true; } OffsetStorageWriter(OffsetBackingStore backingStore,
String namespace, Converter keyConverter, Converter valueConverter); synchronized void offset(Map<String, ?> partition, Map<String, ?> offset); synchronized boolean beginFlush(); Future<Void> doFlush(final Callback<Void> callback); synchronized void cancelFlush(); }### Answer:
@Test public void testNoOffsetsToFlush() { PowerMock.replayAll(); assertFalse(writer.beginFlush()); PowerMock.verifyAll(); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.