src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
LinkOperationsService { public List<Isl> updateLinkUnderMaintenanceFlag(SwitchId srcSwitchId, Integer srcPort, SwitchId dstSwitchId, Integer dstPort, boolean underMaintenance) throws IslNotFoundException { return transactionManager.doInTransaction(() -> { Optional<Isl> foundIsl = islRepository.findByEndpoints(srcSwitch... | @Test public void shouldUpdateLinkUnderMaintenanceFlag() throws IslNotFoundException { createIsl(IslStatus.ACTIVE); for (int i = 0; i < 2; i++) { List<Isl> link = linkOperationsService .updateLinkUnderMaintenanceFlag(TEST_SWITCH_A_ID, TEST_SWITCH_A_PORT, TEST_SWITCH_B_ID, TEST_SWITCH_B_PORT, true); assertEquals(2, link... |
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(getDestS... | @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 tes... |
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_RUL... | @Test(expected = IllegalArgumentException.class) public void createMeterIdForInvalidDefaultRuleTest() { MeterId.createMeterIdForDefaultRule(0x0000000000000123L); } |
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... | @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<Switch... |
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);... | @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); } |
LinkOperationsService { public Collection<Isl> deleteIsl(SwitchId sourceSwitch, int sourcePort, SwitchId destinationSwitch, int destinationPort, boolean force) throws IllegalIslStateException, IslNotFoundException { log.info("Delete ISL with following parameters: " + "source switch '{}', source port '{}', destination s... | @Test public void shouldDeleteInactiveIsl() throws IslNotFoundException, IllegalIslStateException { createIsl(IslStatus.INACTIVE); linkOperationsService .deleteIsl(TEST_SWITCH_A_ID, TEST_SWITCH_A_PORT, TEST_SWITCH_B_ID, TEST_SWITCH_B_PORT, false); assertTrue(islRepository.findAll().isEmpty()); }
@Test(expected = Illega... |
SwitchProperties implements CompositeDataEntity<SwitchProperties.SwitchPropertiesData> { public void setSupportedTransitEncapsulation(Set<FlowEncapsulationType> supportedTransitEncapsulation) { if (supportedTransitEncapsulation != null && supportedTransitEncapsulation.contains(FlowEncapsulationType.VXLAN)) { validatePr... | @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<>(); flowEnc... |
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 = firstItera... | @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))); } |
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... | @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); asser... |
PathComputerFactory { public PathComputer getPathComputer() { return new InMemoryPathComputer(availableNetworkFactory, new BestWeightAndShortestPathFinder(config.getMaxAllowedDepth()), config); } PathComputerFactory(PathComputerConfig config, AvailableNetworkFactory availableNetworkFactory); PathComputer getPathCompute... | @Test public void shouldCreateAnInstance() { PathComputerFactory factory = new PathComputerFactory( mock(PathComputerConfig.class), mock(AvailableNetworkFactory.class)); PathComputer pathComputer = factory.getPathComputer(); assertTrue(pathComputer instanceof InMemoryPathComputer); } |
AvailableNetworkFactory { public AvailableNetwork getAvailableNetwork(Flow flow, Collection<PathId> reusePathsResources) throws RecoverableException { BuildStrategy buildStrategy = BuildStrategy.from(config.getNetworkStrategy()); AvailableNetwork network = new AvailableNetwork(); try { Collection<Isl> links = getAvaila... | @Test public void shouldBuildAvailableNetworkUsingCostStrategy() throws RecoverableException { Flow flow = getFlow(false); Isl isl = getIsl(flow); when(config.getNetworkStrategy()).thenReturn("COST"); when(islRepository.findActiveWithAvailableBandwidth(flow.getBandwidth(), flow.getEncapsulationType())) .thenReturn(Coll... |
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 h... | @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 = (Flow... |
FlowValidator { @VisibleForTesting void checkForEqualsEndpoints(RequestedFlow firstFlow, RequestedFlow secondFlow) throws InvalidFlowException { String message = "New requested endpoint for '%s' conflicts with existing endpoint for '%s'"; Set<FlowEndpoint> firstFlowEndpoints = validateFlowEqualsEndpoints(firstFlow, mes... | @Test(expected = InvalidFlowException.class) public void shouldFailOnSwapWhenEqualsEndpointsOnFirstFlow() throws InvalidFlowException { RequestedFlow firstFlow = RequestedFlow.builder() .flowId("firstFlow") .srcSwitch(SWITCH_ID_1) .srcPort(10) .srcVlan(11) .destSwitch(SWITCH_ID_2) .destPort(10) .destVlan(11) .build(); ... |
BaseResourceAllocationAction extends
NbTrackableAction<T, S, E, C> { @VisibleForTesting void updateAvailableBandwidth(SwitchId srcSwitch, int srcPort, SwitchId dstSwitch, int dstPort, long allowedOverprovisionedBandwidth, boolean forceToIgnoreBandwidth) throws ResourceAllocationException { long usedBandwidth = ... | @Test(expected = ResourceAllocationException.class) public void updateAvailableBandwidthFailsOnOverProvisionTest() throws ResourceAllocationException { when(persistenceManager.getRepositoryFactory()).thenReturn(repositoryFactory); when(repositoryFactory.createFlowPathRepository()).thenReturn(flowPathRepository); when(r... |
FlowRerouteService { public void handleRequest(String key, FlowRerouteRequest reroute, final CommandContext commandContext) { log.debug("Handling flow reroute request with key {} and flow ID: {}", key, reroute.getFlowId()); try { checkRequestsCollision(key, reroute.getFlowId(), commandContext); } catch (Exception e) { ... | @Test public void shouldSkipRerouteIfNoNewPathFound() throws RecoverableException, UnroutableFlowException { Flow origin = makeFlow(); preparePathComputation(origin.getFlowId(), make2SwitchesPathPair()); FlowRerouteRequest request = new FlowRerouteRequest(origin.getFlowId(), false, false, false, Collections.emptySet(),... |
FlowDeleteService { public void handleRequest(String key, CommandContext commandContext, String flowId) { log.debug("Handling flow delete request with key {} and flow ID: {}", key, flowId); if (fsms.containsKey(key)) { log.error("Attempt to create a FSM with key {}, while there's another active FSM with the same key.",... | @Test public void shouldFailDeleteFlowIfNoFlowFound() { String flowId = "dummy-flow"; FlowRepository repository = persistenceManager.getRepositoryFactory().createFlowRepository(); Assert.assertFalse(repository.findById(flowId).isPresent()); makeService().handleRequest(dummyRequestKey, commandContext, flowId); verifyNoS... |
RequestedFlowMapper { public RequestedFlow toRequestedFlow(FlowRequest request) { RequestedFlow flow = generatedMap(request); RequestedFlowIncrementalMapper.INSTANCE.mapSource(flow, request.getSource()); RequestedFlowIncrementalMapper.INSTANCE.mapDestination(flow, request.getDestination()); return flow; } RequestedFlo... | @Test public void mapFlowRequestToRequestedFlowTest() { RequestedFlow requestedFlow = RequestedFlowMapper.INSTANCE.toRequestedFlow(flowRequest); assertEquals(FLOW_ID, requestedFlow.getFlowId()); assertEquals(SRC_SWITCH_ID, requestedFlow.getSrcSwitch()); assertEquals(SRC_PORT, requestedFlow.getSrcPort()); assertEquals(S... |
RequestedFlowMapper { @Mapping(target = "flowId", source = "flowId") @Mapping(target = "source", expression = "java(new FlowEndpoint(flow.getSrcSwitchId(), " + "flow.getSrcPort(), flow.getSrcVlan()))") @Mapping(target = "destination", expression = "java(new FlowEndpoint(flow.getDestSwitchId(), " + "flow.getDestPort(), ... | @Test public void mapFlowToFlowRequestTest() { FlowRequest flowRequest = RequestedFlowMapper.INSTANCE.toFlowRequest(flow); assertEquals(FLOW_ID, flowRequest.getFlowId()); assertEquals(SRC_SWITCH_ID, flowRequest.getSource().getSwitchId()); assertEquals(SRC_PORT, (int) flowRequest.getSource().getPortNumber()); assertEqua... |
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... | @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)); } |
NoviflowResponseMapper { @Mapping(source = "logicalportno", target = "logicalPortNumber") @Mapping(source = "portnoList", target = "portNumbers") @Mapping(source = "logicalporttype", target = "type") public abstract LogicalPort map(io.grpc.noviflow.LogicalPort port); @Mapping(source = "logicalportno", target = "logica... | @Test public void packetInOutTest() { PacketInOutStats stats = PacketInOutStats.newBuilder() .setPacketInTotalPackets(PACKET_IN_TOTAL_PACKETS) .setPacketInTotalPacketsDataplane(PACKET_IN_TOTAL_PACKETS_DATAPLANE) .setPacketInNoMatchPackets(PACKET_IN_NO_MATCH_PACKETS) .setPacketInApplyActionPackets(PACKET_IN_APPLY_ACTION... |
FlowPathBuilder { public boolean isSamePath(Path path, FlowPath flowPath) { if (!path.getSrcSwitchId().equals(flowPath.getSrcSwitchId()) || !path.getDestSwitchId().equals(flowPath.getDestSwitchId()) || path.getSegments().size() != flowPath.getSegments().size()) { return false; } Iterator<Segment> pathIt = path.getSegme... | @Test public void shouldDetectSameSwitchPaths() { SwitchId switchId = new SwitchId(1); Switch switchEntity = Switch.builder().switchId(switchId).build(); Path path = Path.builder() .srcSwitchId(switchId) .destSwitchId(switchId) .segments(Collections.emptyList()) .build(); FlowPath flowPath = FlowPath.builder() .srcSwit... |
FlowPathBuilder { public FlowPath buildFlowPath(Flow flow, PathResources pathResources, Path path, FlowSegmentCookie cookie, boolean forceToIgnoreBandwidth) { Map<SwitchId, Switch> switches = new HashMap<>(); Map<SwitchId, SwitchProperties> switchProperties = new HashMap<>(); switches.put(flow.getSrcSwitchId(), flow.ge... | @Test public void shouldBuildFlowPathFor1SwitchPath() { SwitchId switchId = new SwitchId(1); Path path = Path.builder() .srcSwitchId(switchId) .destSwitchId(switchId) .segments(Collections.emptyList()) .build(); Flow flow = Flow.builder() .flowId("test_flow") .srcSwitch(Switch.builder().switchId(switchId).build()) .des... |
SpeakerFlowSegmentRequestBuilder implements FlowCommandBuilder { @Override public List<FlowSegmentRequestFactory> buildAllExceptIngress(CommandContext context, @NonNull Flow flow) { return buildAllExceptIngress(context, flow, flow.getForwardPath(), flow.getReversePath()); } SpeakerFlowSegmentRequestBuilder(FlowResource... | @Test public void shouldCreateNonIngressRequestsWithoutVlans() { Switch srcSwitch = Switch.builder().switchId(SWITCH_1).build(); Switch destSwitch = Switch.builder().switchId(SWITCH_2).build(); Flow flow = buildFlow(srcSwitch, 1, 0, destSwitch, 2, 0, 0); setSegmentsWithoutTransitSwitches( Objects.requireNonNull(flow.ge... |
SpeakerFlowSegmentRequestBuilder implements FlowCommandBuilder { @Override public List<FlowSegmentRequestFactory> buildAll(CommandContext context, Flow flow, FlowPath path, SpeakerRequestBuildContext speakerRequestBuildContext) { return makeRequests(context, flow, path, null, true, true, true, speakerRequestBuildContex... | @Test public void shouldCreateOneSwitchFlow() { Switch sw = Switch.builder().switchId(SWITCH_1).build(); Flow flow = buildFlow(sw, 1, 10, sw, 2, 12, 1000); List<FlowSegmentRequestFactory> commands = target.buildAll( COMMAND_CONTEXT, flow, flow.getForwardPath(), flow.getReversePath(), SpeakerRequestBuildContext.EMPTY); ... |
SpeakerFlowSegmentRequestBuilder implements FlowCommandBuilder { @Override public List<FlowSegmentRequestFactory> buildIngressOnly( CommandContext context, @NonNull Flow flow, SpeakerRequestBuildContext speakerRequestBuildContext) { return buildIngressOnly(context, flow, flow.getForwardPath(), flow.getReversePath(), sp... | @Test public void useActualFlowEndpoint() { Switch srcSwitch = Switch.builder().switchId(SWITCH_1).build(); Switch destSwitch = Switch.builder().switchId(SWITCH_2).build(); Flow origin = buildFlow(srcSwitch, 1, 5, destSwitch, 2, 0, 0); setSegmentsWithoutTransitSwitches( Objects.requireNonNull(origin.getForwardPath()), ... |
IntersectionComputer { public OverlappingSegmentsStats getOverlappingStats() { return computeIntersectionCounters( otherEdges.values().stream().flatMap(Collection::stream).collect(Collectors.toSet())); } IntersectionComputer(String targetFlowId, PathId targetForwardPathId, PathId targetReversePathId,
... | @Test public void noGroupIntersections() { List<FlowPath> paths = getFlowPaths(); IntersectionComputer computer = new IntersectionComputer(FLOW_ID, PATH_ID, PATH_ID_REVERSE, paths); OverlappingSegmentsStats stats = computer.getOverlappingStats(); assertEquals(ZERO_STATS, stats); }
@Test public void noGroupIntersections... |
LinkOperationsService { public Collection<Isl> updateEnableBfdFlag(Endpoint source, Endpoint destination, boolean flagValue) throws IslNotFoundException { return transactionManager.doInTransaction(() -> { List<Isl> processed = new ArrayList<>(2); boolean madeChange; madeChange = updateUniIslEnableBfdFlag(source, destin... | @Test public void shouldPropagateBfdEnableFlagUpdateOnFullUpdate() throws IslNotFoundException { createIsl(IslStatus.ACTIVE); Collection<Isl> result = linkOperationsService.updateEnableBfdFlag( Endpoint.of(TEST_SWITCH_A_ID, TEST_SWITCH_A_PORT), Endpoint.of(TEST_SWITCH_B_ID, TEST_SWITCH_B_PORT), true); Assert.assertEqua... |
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().... | @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(Interse... |
IslMapper { public IslInfoData map(Isl isl) { if (isl == null) { return null; } PathNode src = new PathNode(); src.setSwitchId(isl.getSrcSwitchId()); src.setPortNo(isl.getSrcPort()); src.setSegLatency(isl.getLatency()); src.setSeqId(0); PathNode dst = new PathNode(); dst.setSwitchId(isl.getDestSwitchId()); dst.setPortN... | @Test public void islMapperTest() { IslInfoData islInfoData = IslInfoData.builder() .latency(1L) .source(new PathNode(TEST_SWITCH_A_ID, 1, 0)) .destination(new PathNode(TEST_SWITCH_B_ID, 1, 1)) .speed(2L) .state(IslChangeType.DISCOVERED) .cost(700) .availableBandwidth(4L) .underMaintenance(false) .build(); Isl isl = Is... |
FlowMapper { @Mapping(source = "srcPort", target = "sourcePort") @Mapping(source = "srcVlan", target = "sourceVlan") @Mapping(source = "srcInnerVlan", target = "sourceInnerVlan") @Mapping(source = "destPort", target = "destinationPort") @Mapping(source = "destVlan", target = "destinationVlan") @Mapping(source = "destIn... | @Test public void testFlowPairToDto() { PathInfoData pathInfoData = new PathInfoData(); pathInfoData.setLatency(1L); pathInfoData.setPath(asList( new PathNode(SRC_SWITCH_ID, 1, 1, 1L, 1L), new PathNode(DST_SWITCH_ID, 2, 2, 2L, 2L) )); FlowDto forwardFlow = new FlowDto(); forwardFlow.setSourceSwitch(SRC_SWITCH_ID); forw... |
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 = "st... | @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 = portMap... |
SimpleSwitchRuleConverter { public List<SimpleSwitchRule> convertFlowPathToSimpleSwitchRules(Flow flow, FlowPath flowPath, EncapsulationId encapsulationId, long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient) { List<SimpleSwitchRule> rules = new ArrayList<>(); if (!flowPath.isProtected()) { rules.add(bu... | @Test public void shouldConvertFlowPathWithTransitVlanEncapToSimpleSwitchRules() { Flow flow = buildFlow(FlowEncapsulationType.TRANSIT_VLAN); List<SimpleSwitchRule> expectedSwitchRules = getSimpleSwitchRuleForTransitVlan(); List<SimpleSwitchRule> switchRules = simpleSwitchRuleConverter.convertFlowPathToSimpleSwitchRule... |
SimpleSwitchRuleConverter { public List<SimpleSwitchRule> convertSwitchFlowEntriesToSimpleSwitchRules(SwitchFlowEntries rules, SwitchMeterEntries meters) { if (rules == null || rules.getFlowEntries() == null) { return Collections.emptyList(); } List<SimpleSwitchRule> simpleRules = new ArrayList<>(); for (FlowEntry flow... | @Test public void shouldConvertFlowEntriesTransitVlanFlowToSimpleSwitchRules() { List<SimpleSwitchRule> expectedSwitchRules = getSimpleSwitchRuleForTransitVlan(); List<SwitchFlowEntries> switchFlowEntries = getSwitchFlowEntriesWithTransitVlan(); List<SwitchMeterEntries> switchMeterEntries = getSwitchMeterEntries(); for... |
CookiePool { public CookiePool(PersistenceManager persistenceManager, long minCookie, long maxCookie, int poolSize) { transactionManager = persistenceManager.getTransactionManager(); RepositoryFactory repositoryFactory = persistenceManager.getRepositoryFactory(); flowCookieRepository = repositoryFactory.createFlowCooki... | @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(coo... |
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) / poo... | @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... |
FlowResourcesManager { public FlowResources allocateFlowResources(Flow flow) throws ResourceAllocationException { log.debug("Allocate flow resources for {}.", flow); PathId forwardPathId = generatePathId(flow.getFlowId()); PathId reversePathId = generatePathId(flow.getFlowId()); try { return allocateResources(flow, for... | @Test public void shouldAllocateForFlow() throws ResourceAllocationException { transactionManager.doInTransaction(() -> { Flow flow = convertFlow(firstFlow); verifyAllocation(resourcesManager.allocateFlowResources(flow)); }); }
@Test public void shouldAllocateForNoBandwidthFlow() throws ResourceAllocationException { tr... |
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.d... | @Test public void deallocatePathResourcesTest() throws Exception { transactionManager.doInTransaction(() -> { Flow flow = convertFlow(firstFlow); FlowResources resources = resourcesManager.allocateFlowResources(flow); resourcesManager.deallocatePathResources(resources.getForward().getPathId(), resources.getUnmaskedCook... |
TransitVlanPool implements EncapsulationResourcesProvider<TransitVlanEncapsulation> { @Override public TransitVlanEncapsulation allocate(Flow flow, PathId pathId, PathId oppositePathId) { return get(oppositePathId, null) .orElseGet(() -> allocate(flow, pathId)); } TransitVlanPool(PersistenceManager persistenceManager, ... | @Test public void vlanPoolTest() { transactionManager.doInTransaction(() -> { Set<Integer> transitVlans = new HashSet<>(); for (int i = MIN_TRANSIT_VLAN; i <= MAX_TRANSIT_VLAN; i++) { Flow flow = Flow.builder() .flowId(format("flow_%d", i)).srcSwitch(SWITCH_A).destSwitch(SWITCH_B).build(); transitVlans.add(transitVlanP... |
VxlanPool implements EncapsulationResourcesProvider<VxlanEncapsulation> { @Override public VxlanEncapsulation allocate(Flow flow, PathId pathId, PathId oppositePathId) { return get(oppositePathId, null) .orElseGet(() -> allocate(flow, pathId)); } VxlanPool(PersistenceManager persistenceManager, int minVxlan, int maxVxl... | @Test public void vxlanIdPool() { transactionManager.doInTransaction(() -> { Set<Integer> vxlans = new HashSet<>(); for (int i = MIN_VXLAN; i <= MAX_VXLAN; i++) { Flow flow = Flow.builder() .flowId(format("flow_%d", i)).srcSwitch(SWITCH_A).destSwitch(SWITCH_B).build(); vxlans.add(vxlanPool.allocate( flow, new PathId(fo... |
MeterPool { public MeterPool(PersistenceManager persistenceManager, MeterId minMeterId, MeterId maxMeterId, int poolSize) { transactionManager = persistenceManager.getTransactionManager(); RepositoryFactory repositoryFactory = persistenceManager.getRepositoryFactory(); flowMeterRepository = repositoryFactory.createFlow... | @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),... |
MeterPool { @TransactionRequired public MeterId allocate(SwitchId switchId, String flowId, PathId pathId) { MeterId nextMeter = nextMeters.get(switchId); if (nextMeter != null && nextMeter.getValue() > 0) { if (nextMeter.compareTo(maxMeterId) <= 0 && !flowMeterRepository.exists(switchId, nextMeter)) { addMeter(flowId, ... | @Test(expected = ResourceNotAvailableException.class) public void meterPoolFullTest() { transactionManager.doInTransaction(() -> { for (long i = MIN_METER_ID.getValue(); i <= MAX_METER_ID.getValue() + 1; i++) { meterPool.allocate(SWITCH_ID, format("flow_%d", i), new PathId(format("path_%d", i))); } }); }
@Ignore("InMem... |
IslInfoData extends CacheTimeTag { @JsonIgnore public boolean isSelfLooped() { return Objects.equals(source.getSwitchId(), destination.getSwitchId()); } IslInfoData(IslInfoData that); IslInfoData(PathNode source, PathNode destination, IslChangeType state, boolean underMaintenance); @Builder(toBuilder = true) @JsonCrea... | @Test public void shouldReturnTrueWhenSelfLooped() { final SwitchId switchId = new SwitchId("00:00:00:00:00:00:00:01"); PathNode source = new PathNode(switchId, 1, 0); PathNode destination = new PathNode(switchId, 2, 1); IslInfoData isl = new IslInfoData(source, destination, IslChangeType.DISCOVERED, false); assertTrue... |
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; } | @Test public void testNoviflowTimstampToLong() { long seconds = 123456789; long nanoseconds = 987654321; long timestampNovi = (seconds << 32) + nanoseconds; assertEquals(123456789_987654321L, noviflowTimestamp(timestampNovi)); } |
RequestedFlowMapper { @Mapping(target = "flowId", source = "flowId") @Mapping(target = "source", expression = "java(new FlowEndpoint(flow.getSrcSwitchId(), " + "flow.getSrcPort(), flow.getSrcVlan()))") @Mapping(target = "destination", expression = "java(new FlowEndpoint(flow.getDestSwitchId(), " + "flow.getDestPort(), ... | @Test public void mapFlowToFlowRequestTest() { FlowRequest flowRequest = RequestedFlowMapper.INSTANCE.toFlowRequest(flow); assertEquals(FLOW_ID, flowRequest.getFlowId()); assertEquals(SRC_SWITCH_ID, flowRequest.getSource().getSwitchId()); assertEquals(SRC_PORT, flowRequest.getSource().getPortNumber()); assertEquals(SRC... |
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(lo... | @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); } |
FlowController extends BaseController { @ApiOperation(value = "Creates new flow", response = FlowResponsePayload.class) @PutMapping @ResponseStatus(HttpStatus.OK) public CompletableFuture<FlowResponsePayload> createFlow(@RequestBody FlowCreatePayload flow) { return flowService.createFlow(flow); } @ApiOperation(value =... | @Test @WithMockUser(username = USERNAME, password = PASSWORD, roles = ROLE) public void createFlow() throws Exception { MvcResult mvcResult = mockMvc.perform(put("/v1/flows") .header(CORRELATION_ID, testCorrelationId()) .contentType(APPLICATION_JSON_VALUE) .content(MAPPER.writeValueAsString(TestMessageMock.flow))) .and... |
FlowController extends BaseController { @ApiOperation(value = "Gets flow", response = FlowResponsePayload.class) @GetMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) public CompletableFuture<FlowResponsePayload> getFlow(@PathVariable(name = "flow-id") String flowId) { return flowService.getFlow(flowId); ... | @Test @WithMockUser(username = USERNAME, password = PASSWORD, roles = ROLE) public void getFlow() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/v1/flows/{flow-id}", TestMessageMock.FLOW_ID) .header(CORRELATION_ID, testCorrelationId()) .contentType(APPLICATION_JSON_VALUE)) .andReturn(); MvcResult result... |
FlowController extends BaseController { @ApiOperation(value = "Deletes flow", response = FlowResponsePayload.class) @DeleteMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) public CompletableFuture<FlowResponsePayload> deleteFlow(@PathVariable(name = "flow-id") String flowId) { return flowService.deleteFl... | @Test @WithMockUser(username = USERNAME, password = PASSWORD, roles = ROLE) public void deleteFlow() throws Exception { MvcResult mvcResult = mockMvc.perform(delete("/v1/flows/{flow-id}", TestMessageMock.FLOW_ID) .header(CORRELATION_ID, testCorrelationId()) .contentType(APPLICATION_JSON_VALUE)) .andReturn(); MvcResult ... |
FlowController extends BaseController { @ApiOperation(value = "Delete all flows. Requires special authorization", response = FlowResponsePayload.class, responseContainer = "List") @DeleteMapping @ResponseStatus(HttpStatus.OK) @ExtraAuthRequired public CompletableFuture<List<FlowResponsePayload>> deleteFlows() { return ... | @Test @WithMockUser(username = USERNAME, password = PASSWORD, roles = ROLE) public void deleteFlows() throws Exception { MvcResult mvcResult = mockMvc.perform(delete("/v1/flows") .header(CORRELATION_ID, testCorrelationId()) .header(EXTRA_AUTH, System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(119)) .contentType(AP... |
FlowController extends BaseController { @ApiOperation(value = "Updates flow", response = FlowResponsePayload.class) @PutMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) public CompletableFuture<FlowResponsePayload> updateFlow(@PathVariable(name = "flow-id") String flowId, @RequestBody FlowUpdatePayload f... | @Test @WithMockUser(username = USERNAME, password = PASSWORD, roles = ROLE) public void updateFlow() throws Exception { MvcResult mvcResult = mockMvc.perform(put("/v1/flows/{flow-id}", TestMessageMock.FLOW_ID) .header(CORRELATION_ID, testCorrelationId()) .contentType(APPLICATION_JSON_VALUE) .content(MAPPER.writeValueAs... |
FlowController extends BaseController { @ApiOperation(value = "Dumps all flows", response = FlowResponsePayload.class, responseContainer = "List") @GetMapping @ResponseStatus(HttpStatus.OK) public CompletableFuture<List<FlowResponsePayload>> getFlows() { return flowService.getAllFlows(); } @ApiOperation(value = "Creat... | @Test @WithMockUser(username = USERNAME, password = PASSWORD, roles = ROLE) public void getFlows() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/v1/flows", TestMessageMock.FLOW_ID) .header(CORRELATION_ID, testCorrelationId()) .contentType(APPLICATION_JSON_VALUE)) .andReturn(); MvcResult result = mockMv... |
FlowController extends BaseController { @ApiOperation(value = "Gets flow status", response = FlowIdStatusPayload.class) @GetMapping(value = "/status/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) public CompletableFuture<FlowIdStatusPayload> statusFlow(@PathVariable(name = "flow-id") String flowId) { return flowService.... | @Test @WithMockUser(username = USERNAME, password = PASSWORD, roles = ROLE) public void statusFlow() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/v1/flows/status/{flow-id}", TestMessageMock.FLOW_ID) .header(CORRELATION_ID, testCorrelationId()) .contentType(APPLICATION_JSON_VALUE)) .andReturn(); MvcRes... |
FlowController extends BaseController { @ApiOperation(value = "Gets flow path", response = FlowPathPayload.class) @GetMapping(value = "/{flow-id}/path") @ResponseStatus(HttpStatus.OK) public CompletableFuture<FlowPathPayload> pathFlow(@PathVariable(name = "flow-id") String flowId) { return flowService.pathFlow(flowId);... | @Test @WithMockUser(username = USERNAME, password = PASSWORD, roles = ROLE) public void pathFlow() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/v1/flows/{flow-id}/path", TestMessageMock.FLOW_ID) .header(CORRELATION_ID, testCorrelationId()) .contentType(APPLICATION_JSON_VALUE)) .andReturn(); MvcResult ... |
FlowMapper { @Mapping(target = "bandwidth", source = "maximumBandwidth") @Mapping(target = "detectConnectedDevices", expression = "java(new DetectConnectedDevicesDto(" + "request.getSource().getDetectConnectedDevices().isLldp(), " + "request.getSource().getDetectConnectedDevices().isArp(), " + "request.getDestination()... | @Test public void testFlowRequestV2Mapping() { FlowRequestV2 flowRequestV2 = FlowRequestV2.builder() .flowId(FLOW_ID) .encapsulationType(ENCAPSULATION_TYPE) .source(new FlowEndpointV2(SRC_SWITCH_ID, SRC_PORT, SRC_VLAN, SRC_DETECT_CONNECTED_DEVICES)) .destination(new FlowEndpointV2(DST_SWITCH_ID, DST_PORT, DST_VLAN, DST... |
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, OFMessag... | @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(callerLog... |
FlowMapper { public FlowRequest toFlowCreateRequest(FlowRequestV2 source) { return toFlowRequest(source).toBuilder().type(Type.CREATE).build(); } FlowPayload toFlowOutput(FlowDto f); FlowResponsePayload toFlowResponseOutput(FlowDto f); FlowResponseV2 toFlowResponseV2(FlowDto flowDto); @Mapping(target = "flowId", ignor... | @Test public void testFlowCreatePayloadToFlowRequest() { FlowRequest flowRequest = flowMapper.toFlowCreateRequest(FLOW_CREATE_PAYLOAD); assertEquals(FLOW_CREATE_PAYLOAD.getDiverseFlowId(), flowRequest.getDiverseFlowId()); assertEquals(Type.CREATE, flowRequest.getType()); assertFlowDtos(FLOW_CREATE_PAYLOAD, flowRequest)... |
FlowMapper { public FlowRequest toFlowUpdateRequest(FlowUpdatePayload source) { FlowRequest target = toFlowRequest(source).toBuilder() .diverseFlowId(source.getDiverseFlowId()) .type(Type.UPDATE) .build(); if (source.getSource().getDetectConnectedDevices() != null) { DetectConnectedDevicesPayload srcDevs = source.getSo... | @Test public void testFlowUpdatePayloadToFlowRequest() { FlowRequest flowRequest = flowMapper.toFlowUpdateRequest(FLOW_UPDATE_PAYLOAD); assertEquals(FLOW_UPDATE_PAYLOAD.getDiverseFlowId(), flowRequest.getDiverseFlowId()); assertEquals(Type.UPDATE, flowRequest.getType()); assertFlowDtos(FLOW_UPDATE_PAYLOAD, flowRequest)... |
FlowMapper { @Mapping(target = "flowId", ignore = true) @Mapping(target = "maxLatency", expression = "java(flowPatchDto.getMaxLatency() != null ? flowPatchDto.getMaxLatency() * 1000000L : null)") @Mapping(target = "priority", source = "priority") @Mapping(target = "periodicPings", source = "periodicPings") @Mapping(tar... | @Test public void testFlowPatchDtoToFlowDto() { FlowPatchDto flowPatchDto = new FlowPatchDto(LATENCY, PRIORITY, PERIODIC_PINGS, TARGET_PATH_COMPUTATION_STRATEGY); FlowPatch flowPatch = flowMapper.toFlowPatch(flowPatchDto); assertEquals(flowPatchDto.getMaxLatency() * 1000000L, (long) flowPatch.getMaxLatency()); assertEq... |
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 = valida... | @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... |
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", srcSwitchI... | @Test public void buildTsdbTupleFromIslOneWayLatency() throws JsonEncodeException, IOException { List<Object> tsdbTuple = statsBolt.buildTsdbTuple( SWITCH1_ID, NODE1.getPortNo(), SWITCH2_ID, NODE2.getPortNo(), LATENCY, TIMESTAMP); assertTsdbTuple(tsdbTuple); } |
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 handleRoundTripL... | @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(islStatsServi... |
IslStatsService { public void handleIstStatusUpdateNotification(IslStatusUpdateNotification notification) { IslKey key = new IslKey(notification.getSrcSwitchId(), notification.getSrcPortNo(), notification.getDstSwitchId(), notification.getDstPortNo()); if (notification.getStatus() == IslStatus.MOVED) { handleIslMoved(k... | @Test public void handleOneWayLatencyEmitOnIslDownTest() { List<LatencyRecord> buffer = new ArrayList<>(); Instant time = Instant.now().minusSeconds(LATENCY_TIMEOUT).minusMillis(500); for (int i = 0; i < 4; i++) { sendForwardOneWayLatency(i, time); verifyNoMoreInteractions(carrier); buffer.add(new LatencyRecord(i, time... |
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.emitCachedD... | @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_... |
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(noti... | @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); ... |
IslLatencyService { @VisibleForTesting void updateIslLatency( SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort, long latency) throws SwitchNotFoundException, IslNotFoundException { transactionManager.doInTransaction(() -> { Isl isl = islRepository.findByEndpoints(srcSwitchId, srcPort, dstSwitchId, d... | @Test(expected = IslNotFoundException.class) public void updateIslLatencyNonExistentSrcEndpointTest() throws IslNotFoundException, SwitchNotFoundException { islLatencyService.updateIslLatency(NON_EXISTENT_SWITCH_ID, PORT_1, SWITCH_ID_2, PORT_2, 0); }
@Test(expected = IslNotFoundException.class) public void updateIslLat... |
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 =... | @Test public void handleOneWayIslLatencyTest() { assertTrue(islLatencyService.isUpdateRequired(FORWARD_ISL_KEY)); islLatencyService.handleOneWayIslLatency(createForwardOneWayLatency(1), System.currentTimeMillis()); assertForwardLatency(1); assertFalse(islLatencyService.isUpdateRequired(FORWARD_ISL_KEY)); islLatencyServ... |
IslLatencyService { public void handleRoundTripIslLatency(IslRoundTripLatency data, Endpoint destination, long timestamp) { if (data.getLatency() < 0) { log.warn("Received invalid round trip latency {} for ISL {}_{} ===> {}_{}. Packet Id: {}", data.getLatency(), data.getSrcSwitchId(), data.getSrcPortNo(), destination.g... | @Test public void handleRoundTripIslLatencyTest() { assertTrue(islLatencyService.isUpdateRequired(FORWARD_ISL_KEY)); islLatencyService.handleRoundTripIslLatency( createForwardRoundTripLatency(5), FORWARD_DESTINATION, System.currentTimeMillis()); assertForwardLatency(5); assertFalse(islLatencyService.isUpdateRequired(FO... |
IslLatencyService { @VisibleForTesting boolean isUpdateRequired(IslKey islKey) { return Instant.now().isAfter(nextUpdateTimeMap.getOrDefault(islKey, Instant.MIN)); } IslLatencyService(TransactionManager transactionManager,
RepositoryFactory repositoryFactory, long latencyUpdateInterval,
... | @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.curr... |
IslLatencyService { @VisibleForTesting Instant getNextUpdateTime() { return Instant.now().plusSeconds(latencyUpdateInterval); } IslLatencyService(TransactionManager transactionManager,
RepositoryFactory repositoryFactory, long latencyUpdateInterval,
long latency... | @Test public void getNextUpdateTimeTest() { Instant actualTime = islLatencyService.getNextUpdateTime(); long expectedTime = System.currentTimeMillis() + LATENCY_UPDATE_INTERVAL * 1000; assertEquals(expectedTime, actualTime.toEpochMilli(), 50); } |
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 ... | @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() { a... |
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(ol... | @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()... |
FlowController extends BaseController { @RequestMapping(value = "/all/history/{flowId}", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.FW_FLOW_HISTORY }) public @ResponseBody List<FlowHistory> getFlowHistory(@PathVariable final String flowId, @RequestParam(name... | @Test public void testGetFlowHistory() throws Exception { try { mockMvc.perform(get("/api/flows/all/history/{flowId}", TestFlowMock.FLOW_ID) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); assertTrue(true); } catch (Exception exception) { assertTrue(false); } }
@Test public void testGetFlowHistor... |
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);... | @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.... |
FlowController extends BaseController { @RequestMapping(value = "/{flowId}", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_FLOWS }) public @ResponseBody FlowInfo getFlowById(@PathVariable final String flowId, @RequestParam(name = "controller", required = f... | @Test public void testGetFlowById() throws Exception { FlowInfo flowInfo = new FlowInfo(); try { when(flowService.getFlowById(TestFlowMock.FLOW_ID, TestFlowMock.CONTROLLER_FLAG)).thenReturn(flowInfo); mockMvc.perform(get("/api/flows/{flowId}", TestFlowMock.FLOW_ID).contentType(MediaType.APPLICATION_JSON)) .andExpect(st... |
FlowController extends BaseController { @RequestMapping(value = "/path/{flowId}", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) public @ResponseBody FlowPayload getFlowPath(@PathVariable final String flowId) { LOGGER.info("Get flow path. Flow id: '" + flowId + "'"); return flowService.getFlowPath(flowId); ... | @Test public void testGetFlowPath() throws Exception { FlowPayload flowPayload = new FlowPayload(); try { when(flowService.getFlowPath(Mockito.anyString())).thenReturn(flowPayload); mockMvc.perform(get("/api/flows/path/{flowId}", TestFlowMock.FLOW_ID) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()... |
SwitchController { @RequestMapping(path = "/{switchId}/flows", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) public @ResponseBody ResponseEntity<List<?>> getPortFlows(@PathVariable final String switchId, @RequestParam(value = "port", required = false) final String port, @RequestParam(value = "inventory", r... | @Test public void testGetAllSwitchFlows() { ResponseEntity<List<?>> responseList = new ResponseEntity<List<?>>(HttpStatus.OK); try { when(serviceSwitch.getPortFlows(TestSwitchMock.SWITCH_ID, TestSwitchMock.PORT, TestFlowMock.CONTROLLER_FLAG)).thenReturn(responseList); mockMvc.perform(get("/api/switch/{switchId}/flows",... |
SwitchController { @RequestMapping(value = "/{switchId}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.SW_SWITCH_DELETE }) public @ResponseBody SwitchInfo deleteSwitch(@PathVariable final String switchId, @RequestParam(name = "force", required = false) bool... | @Test public void testDeleteSwitch() { SwitchInfo switcheInfo = new SwitchInfo(); try { when(serviceSwitch.deleteSwitch(TestSwitchMock.SWITCH_ID, false)).thenReturn(switcheInfo); mockMvc.perform(delete("/api/switch/{switchId}", TestSwitchMock.SWITCH_ID, true) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status(... |
SwitchController { @RequestMapping(value = "/links", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.ISL_DELETE_LINK }) public @ResponseBody List<IslLinkInfo> deleteIsl(@RequestBody final LinkParametersDto linkParametersDto) { Long userId = null; if (serverCon... | @Test public void testDeleteIsl() throws Exception { LinkParametersDto linkParametersDto = new LinkParametersDto(); linkParametersDto.setSrcPort(Integer.valueOf(TestIslMock.SRC_PORT)); linkParametersDto.setSrcSwitch(TestIslMock.SRC_SWITCH); linkParametersDto.setDstPort(Integer.valueOf(TestIslMock.DST_PORT)); linkParame... |
SwitchController { @RequestMapping(value = "/{switchId}/ports/{port}/properties", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.SW_UPDATE_PORT_PROPERTIES }) public @ResponseBody SwitchProperty updateSwitchPortProperty(@PathVariable final String switchId, @PathV... | @Test public void testUpdateSwitchPortProperty() throws Exception { try { SwitchProperty switchProperty = new SwitchProperty(); switchProperty.setDiscoveryEnabled(true); String inputJson = mapToJson(switchProperty); MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders .put("/api/switch/{switchId}/ports/{port}/p... |
SwitchController { @RequestMapping(value = "/{switchId}/ports/{port}/properties", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) public @ResponseBody SwitchProperty getSwitchPortProperty(@PathVariable final String switchId, @PathVariable final String port) { return serviceSwitch.getSwitchPortProperty(switch... | @Test public void testGetSwitchPortProperties() { SwitchProperty switchProperty = new SwitchProperty(); try { when(serviceSwitch.getSwitchPortProperty(TestSwitchMock.SWITCH_ID, TestSwitchMock.PORT)) .thenReturn(switchProperty); mockMvc.perform(get("/api/switch/{switchId}/ports/{port}/properties", TestSwitchMock.SWITCH_... |
StatsController { @RequestMapping(value = "flowid/{flowid}/{startDate}/{endDate}/{downsample}/{metric}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_FLOWS }) @ResponseBody public String getFlowStats(@PathVaria... | @Test public void testGetFlowStats() throws Exception { try { mockMvc.perform( get("/api/stats/flowid/{flowId}/{startDate}/{endDate}/{downsample}/{metric}", TestMockStats.FLOW_ID, TestMockStats.START_DATE, TestMockStats.END_DATE, TestMockStats.DOWNSAMPLE, TestMockStats.METRIC_BITS, TestMockStats.DIRECTION_FORWARD) .con... |
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)... | @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.... |
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 += ... | @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.g... |
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 ... | @Test public void removeWatch() { } |
WatcherService { public void tick(long tickTime) { SortedMap<Long, Set<Packet>> range = timeouts.subMap(0L, tickTime + 1); if (!range.isEmpty()) { for (Set<Packet> e : range.values()) { for (Packet ee : e) { if (confirmations.remove(ee)) { carrier.failed(ee.switchId, ee.port, tickTime); } } } range.clear(); } } Watcher... | @Test public void tick() { 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.getTi... |
WatcherService { public void discovery(SwitchId switchId, int portNo, SwitchId endSwitchId, int endPortNo, long packetNo, long currentTime) { Packet packet = Packet.of(switchId, portNo, packetNo); confirmations.remove(packet); carrier.discovered(switchId, portNo, endSwitchId, endPortNo, currentTime); } WatcherService(I... | @Test public void discovery() { 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.... |
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, i... | @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()); ver... |
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 >= tim... | @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... |
SessionService implements IService, IInputTranslator { public Session open(IOFSwitch sw) { return open(new MessageContext(), sw); } Session open(IOFSwitch sw); Session open(MessageContext context, IOFSwitch sw); @Override void setup(FloodlightModuleContext moduleContext); @Override Command makeCommand(CommandContext c... | @Test public void positive() throws Exception { IOFSwitch sw = createMock(IOFSwitch.class); setupSwitchMock(sw, dpId); swWriteAlwaysSuccess(sw); doneWithSetUp(sw); CompletableFuture<Optional<OFMessage>> future; OFPacketOut pktOut = makePacketOut(sw.getOFFactory(), 1); try (Session session = subject.open(context, sw)) {... |
ConnectedDevicesService implements IService, IInputTranslator { @VisibleForTesting LldpPacketData deserializeLldp(Ethernet eth, SwitchId switchId, long cookie) { try { List<Integer> vlans = new ArrayList<>(); IPacket payload = EthernetPacketToolbox.extractPayload(eth, vlans); if (payload instanceof LLDP) { LldpPacket l... | @Test public void deserializeLldpTest() { Ethernet ethernet = buildEthernet(srcAndDstMacAddresses, ethTypeToByteArray(EthType.LLDP), LldpPacketTest.packet); LldpPacketData data = service.deserializeLldp(ethernet, null, 0); assertNotNull(data); assertTrue(data.getVlans().isEmpty()); assertEquals(LldpPacketTest.buildLldp... |
ConnectedDevicesService implements IService, IInputTranslator { @VisibleForTesting ArpPacketData deserializeArp(Ethernet eth, SwitchId switchId, long cookie) { try { List<Integer> vlans = new ArrayList<>(); IPacket payload = EthernetPacketToolbox.extractPayload(eth, vlans); if (payload instanceof ARP) { return new ArpP... | @Test public void deserializeArpTest() throws PacketParsingException { Ethernet ethernet = buildEthernet(srcAndDstMacAddresses, ethTypeToByteArray(EthType.ARP), arpPacket); ArpPacketData data = service.deserializeArp(ethernet, null, 0); assertNotNull(data); assertTrue(data.getVlans().isEmpty()); assertEquals(buildArpPa... |
FloodlightModuleConfigurationProvider extends ValidatingConfigurationProvider { public static FloodlightModuleConfigurationProvider of(FloodlightModuleContext moduleContext, IFloodlightModule module) { Map<String, String> configData = moduleContext.getConfigParams(module); FloodlightModuleConfigurationProvider provider... | @Test public void shouldCreateConfigFromContextParameters() { FloodlightModuleContext context = new FloodlightModuleContext(); IFloodlightModule module = niceMock(IFloodlightModule.class); context.addConfigParam(module, "bootstrap-servers", TEST_BOOTSTRAP_SERVERS); FloodlightModuleConfigurationProvider provider = Flood... |
PingResponseCommand extends PingCommand { @Override public Command call() { log.debug("{} - {}", getClass().getCanonicalName(), input); byte[] payload = unwrap(); if (payload == null) { return null; } log.info("Receive flow ping packet from switch {} OF-xid:{}", input.getDpId(), input.getMessage().getXid()); try { Ping... | @Test public void success() throws Exception { final PingService realPingService = new PingService(); moduleContext.addService(PingService.class, realPingService); final ISwitchManager realSwitchManager = new SwitchManager(); moduleContext.addService(ISwitchManager.class, realSwitchManager); InputService inputService =... |
IngressFlowModFactory { public OFFlowMod makeOuterVlanMatchSharedMessage() { FlowEndpoint endpoint = command.getEndpoint(); FlowSharedSegmentCookie cookie = FlowSharedSegmentCookie.builder(SharedSegmentType.QINQ_OUTER_VLAN) .portNumber(endpoint.getPortNumber()) .vlanId(endpoint.getOuterVlanId()) .build(); return flowMo... | @Test public void makeOuterVlanMatchSharedMessage() { final IngressFlowModFactory factory = makeFactory(); final IngressFlowSegmentBase command = factory.getCommand(); final FlowEndpoint endpoint = command.getEndpoint(); RoutingMetadata metadata = RoutingMetadata.builder() .outerVlanId(endpoint.getOuterVlanId()) .build... |
IngressFlowModFactory { public OFFlowMod makeCustomerPortSharedCatchMessage() { FlowEndpoint endpoint = command.getEndpoint(); return flowModBuilderFactory.makeBuilder(of, TableId.of(SwitchManager.INPUT_TABLE_ID)) .setPriority(SwitchManager.INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE) .setCookie(U64.of(Cookie.encode... | @Test public void makeCustomerPortSharedCatchInstallMessage() { IngressFlowModFactory factory = makeFactory(); FlowEndpoint endpoint = factory.getCommand().getEndpoint(); OFFlowMod expected = of.buildFlowAdd() .setTableId(TableId.of(SwitchManager.INPUT_TABLE_ID)) .setPriority(SwitchManager.INGRESS_CUSTOMER_PORT_RULE_PR... |
EthernetPacketToolbox { public static IPacket extractPayload(Ethernet packet, List<Integer> vlanStack) { short rootVlan = packet.getVlanID(); if (0 < rootVlan) { vlanStack.add((int) rootVlan); } IPacket payload = packet.getPayload(); while (payload instanceof VlanTag) { short vlanId = ((VlanTag) payload).getVlanId(); v... | @Test public void extractEthernetPayloadTest() { short vlan1 = 1234; short vlan2 = 2345; short vlan3 = 4000; byte[] originPayload = new byte[]{0x55, (byte) 0xAA}; Ethernet ethernet = buildEthernet( new byte[]{ 0x01, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x01, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B }, ethTypeToByteArray(EthType.Q_IN_Q), ... |
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> g... | @Test public void inaccurateSetFieldVlanVidActionNegative() { OfFlowPresenceVerifier presenceVerifier = testInaccurateSetFieldVlanVidAction(Collections.emptySet()); Assert.assertFalse(presenceVerifier.getMissing().isEmpty()); }
@Test public void inaccurateSetFieldVlanVidActionPositive() { OfFlowPresenceVerifier presenc... |
CorrelationContext { public static String getId() { return Optional.ofNullable(ID.get()).orElse(DEFAULT_CORRELATION_ID); } private CorrelationContext(); static String getId(); static CorrelationContextClosable create(String correlationId); } | @Ignore("Fix applying aspects to test classes") @Test @NewCorrelationContextRequired public void shouldInitializeCorrelationId() { String correlationId = CorrelationContext.getId(); assertNotEquals(DEFAULT_CORRELATION_ID, correlationId); } |
NoviflowSpecificFeature extends AbstractFeature { static boolean isNoviSwitch(IOFSwitch sw) { if (sw == null || sw.getSwitchDescription() == null) { return false; } String manufacturer = getManufacturer(sw); if (E_SWITCH_MANUFACTURER_DESCRIPTION.equalsIgnoreCase(manufacturer)) { return true; } SwitchDescription descrip... | @Test public void testIsNoviSwitch() { assertTrue(isNoviSwitch(makeSwitchMock("NoviFlow Inc", "NW400.4.0", "NS21100"))); assertTrue(isNoviSwitch(makeSwitchMock("NoviFlow Inc", "NW500.2.0_dev", "NS21100"))); assertTrue(isNoviSwitch(makeSwitchMock("NoviFlow Inc", "NW500.0.1", "WB5164-E"))); assertTrue(isNoviSwitch(makeSw... |
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()); re... | @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",... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.