src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
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(SwitchDescrip... | @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 In... |
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_SOF... | @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"); } |
OfPortStatsMapper { public PortStatsData toPostStatsData(List<OFPortStatsReply> data, SwitchId switchId) { try { List<PortStatsEntry> stats = data.stream() .flatMap(reply -> reply.getEntries().stream()) .map(this::toPortStatsEntry) .filter(Objects::nonNull) .collect(toList()); return new PortStatsData(switchId, stats);... | @Test public void testToPortStatsDataV13() { OFFactoryVer13 ofFactoryVer13 = new OFFactoryVer13(); OFPortStatsEntry ofPortStatsEntry = prebuildPortStatsEntry(ofFactoryVer13.buildPortStatsEntry()) .setRxFrameErr(U64.of(rxFrameErr)) .setRxOverErr(U64.of(rxOverErr)) .setRxCrcErr(U64.of(rxCrcErr)) .setCollisions(U64.of(col... |
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);... | @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), ... |
OfFlowStatsMapper { public FlowEntry toFlowEntry(final OFFlowStatsEntry entry) { return FlowEntry.builder() .version(entry.getVersion().toString()) .durationSeconds(entry.getDurationSec()) .durationNanoSeconds(entry.getDurationNsec()) .hardTimeout(entry.getHardTimeout()) .idleTimeout(entry.getIdleTimeout()) .priority(e... | @Test public void testFlowEntry() { OFFlowStatsEntry ofEntry = buildFlowStatsEntry(); FlowEntry entry = OfFlowStatsMapper.INSTANCE.toFlowEntry(ofEntry); assertEquals(tableId, entry.getTableId()); assertEquals(cookie, entry.getCookie()); assertEquals(packetCount, entry.getPacketCount()); assertEquals(byteCount, entry.ge... |
OfFlowStatsMapper { public GroupEntry toFlowGroupEntry(OFGroupDescStatsEntry ofGroupDescStatsEntry) { if (ofGroupDescStatsEntry == null) { return null; } return GroupEntry.builder() .groupType(ofGroupDescStatsEntry.getGroupType().toString()) .groupId(ofGroupDescStatsEntry.getGroup().getGroupNumber()) .buckets(ofGroupDe... | @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(e... |
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(OFTable... | @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 = OfTa... |
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,
... | @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), OfPortDescConve... |
OfPortDescConverter { public PortInfoData toPortInfoData(DatapathId dpId, OFPortDesc portDesc, net.floodlightcontroller.core.PortChangeType type) { return new PortInfoData( new SwitchId(dpId.getLong()), portDesc.getPortNo().getPortNumber(), mapChangeType(type), isPortEnabled(portDesc)); } PortDescription toPortDescrip... | @Test public void testPortChangeTypeMapping() { OFPortDesc portDesc = OFFactoryVer13.INSTANCE.buildPortDesc() .setPortNo(OFPort.of(1)) .setName("test") .build(); Map<org.openkilda.messaging.info.event.PortChangeType, net.floodlightcontroller.core.PortChangeType> expected = new HashMap<>(); expected.put(org.openkilda.me... |
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, ... | @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)) .setPacketInCo... |
SwitchTrackingService implements IOFSwitchListener, IService { @Override @NewCorrelationContextRequired public void switchAdded(final DatapathId switchId) { dashboardLogger.onSwitchEvent(switchId, SwitchChangeType.ADDED); switchDiscovery(switchId, SwitchChangeType.ADDED); } void dumpAllSwitches(); void completeSwitchA... | @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, expectedSwitchVi... |
SwitchTrackingService implements IOFSwitchListener, IService { @Override @NewCorrelationContextRequired public void switchRemoved(final DatapathId switchId) { dashboardLogger.onSwitchEvent(switchId, SwitchChangeType.REMOVED); switchManager.deactivate(switchId); switchDiscovery(switchId, SwitchChangeType.REMOVED); } vo... | @Test public void switchRemoved() { Capture<Message> producedMessage = prepareSwitchEventCommon(dpId); switchManager.deactivate(eq(dpId)); replayAll(); service.switchRemoved(dpId); verifySwitchEvent(SwitchChangeType.REMOVED, null, producedMessage); } |
SwitchTrackingService implements IOFSwitchListener, IService { @Override @NewCorrelationContextRequired public void switchDeactivated(final DatapathId switchId) { dashboardLogger.onSwitchEvent(switchId, SwitchChangeType.DEACTIVATED); switchManager.deactivate(switchId); switchDiscovery(switchId, SwitchChangeType.DEACTIV... | @Test public void switchDeactivated() { Capture<Message> producedMessage = prepareSwitchEventCommon(dpId); switchManager.deactivate(eq(dpId)); replayAll(); service.switchDeactivated(dpId); verifySwitchEvent(SwitchChangeType.DEACTIVATED, null, producedMessage); } |
SwitchOperationsService implements ILinkOperationsServiceCarrier { public Switch patchSwitch(SwitchId switchId, SwitchPatch data) throws SwitchNotFoundException { return transactionManager.doInTransaction(() -> { Switch foundSwitch = switchRepository.findById(switchId) .orElseThrow(() -> new SwitchNotFoundException(swi... | @Test public void shouldPatchSwitch() throws SwitchNotFoundException { Switch sw = Switch.builder().switchId(TEST_SWITCH_ID).status(SwitchStatus.ACTIVE).build(); switchRepository.add(sw); SwitchPatch switchPatch = new SwitchPatch("pop", new SwitchLocation(48.860611, 2.337633, "street", "city", "country")); switchOperat... |
SwitchTrackingService implements IOFSwitchListener, IService { @Override @NewCorrelationContextRequired public void switchChanged(final DatapathId switchId) { dashboardLogger.onSwitchEvent(switchId, SwitchChangeType.CHANGED); switchDiscovery(switchId, SwitchChangeType.CHANGED); } void dumpAllSwitches(); void completeS... | @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, expect... |
SwitchTrackingService implements IOFSwitchListener, IService { public void dumpAllSwitches() { discoveryLock.writeLock().lock(); try { dumpAllSwitchesAction(); } finally { discoveryLock.writeLock().unlock(); } } void dumpAllSwitches(); void completeSwitchActivation(DatapathId dpId); @Override @NewCorrelationContextReq... | @Test public void networkDumpTest() throws Exception { OFSwitch iofSwitch1 = mock(OFSwitch.class); OFSwitch iofSwitch2 = mock(OFSwitch.class); final DatapathId swAid = DatapathId.of(1); final DatapathId swBid = DatapathId.of(2); Map<DatapathId, IOFSwitch> switches = ImmutableMap.of( swAid, iofSwitch1, swBid, iofSwitch2... |
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public Long installDropFlow(final DatapathId dpid) throws SwitchOperationException { return installDropFlowForTable(dpid, INPUT_TABLE_ID, DROP_RULE_COOKIE); } @Override Collection<Class<? extends IFloodlightS... | @Test public void installDropRule() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); switchManager.installDropFlow(defaultDpid); assertEquals(scheme.installDropFlowRule(), capture.getValue()); } |
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public Long installVerificationRule(final DatapathId dpid, final boolean isBroadcast) throws SwitchOperationException { String ruleName = (isBroadcast) ? "Broadcast" : "Unicast"; String flowName = ruleName + "... | @Test public void installVerificationUnicastRule() throws Exception { mockGetMetersRequest(Lists.newArrayList(broadcastMeterId), true, 10L); mockBarrierRequest(); expect(iofSwitch.write(anyObject(OFMeterMod.class))).andReturn(true).times(1); Capture<OFFlowMod> capture = prepareForInstallTest(); switchManager.installVer... |
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public Long installDropLoopRule(DatapathId dpid) throws SwitchOperationException { return installDefaultFlow(dpid, switchFlowFactory.getDropLoopFlowGenerator(), "--DropLoopRule--"); } @Override Collection<Cla... | @Test public void installDropLoopRule() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); switchManager.installDropLoopRule(dpid); OFFlowMod result = capture.getValue(); assertEquals(scheme.installDropLoopRule(dpid), result); } |
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public Long installDropFlowForTable(final DatapathId dpid, final int tableId, final long cookie) throws SwitchOperationException { return installDefaultFlow(dpid, switchFlowFactory.getDropFlowGenerator(cookie,... | @Test public void installDropFlowForTable() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); switchManager.installDropFlowForTable(dpid, 1, DROP_RULE_COOKIE); OFFlowMod result = capture.getValue(); assertEquals(scheme.installDropFlowForTable(dpid, 1, DROP_RULE_COOKIE), result); } |
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public long installEgressIslVxlanRule(DatapathId dpid, int port) throws SwitchOperationException { IOFSwitch sw = lookupSwitch(dpid); OFFactory ofFactory = sw.getOFFactory(); OFFlowMod flowMod = buildEgressIsl... | @Test public void installEgressIslVxlanRule() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); switchManager.installEgressIslVxlanRule(dpid, 1); OFFlowMod result = capture.getValue(); assertEquals(scheme.installEgressIslVxlanRule(dpid, 1), result); } |
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public long installTransitIslVxlanRule(DatapathId dpid, int port) throws SwitchOperationException { IOFSwitch sw = lookupSwitch(dpid); OFFactory ofFactory = sw.getOFFactory(); OFFlowMod flowMod = buildTransitI... | @Test public void installTransitIslVxlanRule() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); switchManager.installTransitIslVxlanRule(dpid, 1); OFFlowMod result = capture.getValue(); assertEquals(scheme.installTransitIslVxlanRule(dpid, 1), result); } |
SwitchManager implements IFloodlightModule, IFloodlightService, ISwitchManager, IOFMessageListener { @Override public long installEgressIslVlanRule(DatapathId dpid, int port) throws SwitchOperationException { IOFSwitch sw = lookupSwitch(dpid); OFFactory ofFactory = sw.getOFFactory(); OFFlowMod flowMod = buildEgressIslV... | @Test public void installEgressIslVlanRule() throws Exception { Capture<OFFlowMod> capture = prepareForInstallTest(); switchManager.installEgressIslVlanRule(dpid, 1); OFFlowMod result = capture.getValue(); assertEquals(scheme.installEgressIslVlanRule(dpid, 1), result); } |
JsonConverter implements Converter { @Override public SchemaAndValue toConnectData(String topic, byte[] value) { JsonNode jsonValue; try { jsonValue = deserializer.deserialize(topic, value); } catch (SerializationException e) { throw new DataException("Converting byte[] to Kafka Connect data failed due to serialization... | @Test public void testConnectSchemaMetadataTranslation() { assertEquals(new SchemaAndValue(Schema.BOOLEAN_SCHEMA, true), converter.toConnectData(TOPIC, "{ \"schema\": { \"type\": \"boolean\" }, \"payload\": true }".getBytes())); assertEquals(new SchemaAndValue(Schema.OPTIONAL_BOOLEAN_SCHEMA, null), converter.toConnectD... |
StickyTaskAssignor implements TaskAssignor<ID, TaskId> { @Override public void assign(final int numStandbyReplicas) { assignActive(); assignStandby(numStandbyReplicas); } StickyTaskAssignor(final Map<ID, ClientState> clients, final Set<TaskId> taskIds); @Override void assign(final int numStandbyReplicas); } | @Test public void shouldRebalanceTasksToClientsBasedOnCapacity() throws Exception { createClientWithPreviousActiveTasks(p2, 1, task00, task03, task02); createClient(p3, 2); final StickyTaskAssignor<Integer> taskAssignor = createTaskAssignor(task00, task02, task03); taskAssignor.assign(0); assertThat(clients.get(p2).ass... |
SubscriptionInfo { public static SubscriptionInfo decode(ByteBuffer data) { data.rewind(); int version = data.getInt(); if (version == CURRENT_VERSION || version == 1) { UUID processId = new UUID(data.getLong(), data.getLong()); Set<TaskId> prevTasks = new HashSet<>(); int numPrevs = data.getInt(); for (int i = 0; i < ... | @Test public void shouldBeBackwardCompatible() throws Exception { UUID processId = UUID.randomUUID(); Set<TaskId> activeTasks = new HashSet<>(Arrays.asList(new TaskId(0, 0), new TaskId(0, 1), new TaskId(1, 0))); Set<TaskId> standbyTasks = new HashSet<>(Arrays.asList(new TaskId(1, 1), new TaskId(2, 0))); final ByteBuffe... |
ConnectorsResource { @GET @Path("/{connector}/config") public Map<String, String> getConnectorConfig(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward) throws Throwable { FutureCallback<Map<String, String>> cb = new FutureCallback<>(); herder.connectorConfig(connector, cb); re... | @Test(expected = NotFoundException.class) public void testGetConnectorConfigConnectorNotFound() throws Throwable { final Capture<Callback<Map<String, String>>> cb = Capture.newInstance(); herder.connectorConfig(EasyMock.eq(CONNECTOR_NAME), EasyMock.capture(cb)); expectAndCallbackException(cb, new NotFoundException("not... |
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... | @Test public void shouldHaveNotReachedCapacityWhenAssignedTasksLessThanCapacity() throws Exception { assertFalse(client.reachedCapacity()); } |
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 d... | @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 vo... |
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); } | @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.u... |
StoreChangelogReader implements ChangelogReader { @Override public void validatePartitionExists(final TopicPartition topicPartition, final String storeName) { final long start = time.milliseconds(); if (partitionInfo.isEmpty()) { try { partitionInfo.putAll(consumer.listTopics()); } catch (final TimeoutException e) { lo... | @SuppressWarnings("unchecked") @Test public void shouldThrowStreamsExceptionWhenTimeoutExceptionThrown() throws Exception { final MockConsumer<byte[], byte[]> consumer = new MockConsumer(OffsetResetStrategy.EARLIEST) { @Override public Map<String, List<PartitionInfo>> listTopics() { throw new TimeoutException("KABOOM!"... |
ConnectorsResource { @PUT @Path("/{connector}/config") public Response putConnectorConfig(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward, final Map<String, String> connectorConfig) throws Throwable { FutureCallback<Herder.Created<ConnectorInfo>> cb = new FutureCallback<>();... | @Test public void testPutConnectorConfig() throws Throwable { final Capture<Callback<Herder.Created<ConnectorInfo>>> cb = Capture.newInstance(); herder.putConnectorConfig(EasyMock.eq(CONNECTOR_NAME), EasyMock.eq(CONNECTOR_CONFIG), EasyMock.eq(true), EasyMock.capture(cb)); expectAndCallbackResult(cb, new Herder.Created<... |
StoreChangelogReader implements ChangelogReader { public void restore() { final long start = time.milliseconds(); try { if (!consumer.subscription().isEmpty()) { throw new IllegalStateException(String.format("Restore consumer should have not subscribed to any partitions (%s) beforehand", consumer.subscription())); } fi... | @Test public void shouldThrowExceptionIfConsumerHasCurrentSubscription() throws Exception { consumer.subscribe(Collections.singleton("sometopic")); try { changelogReader.restore(); fail("Should have thrown IllegalStateException"); } catch (final IllegalStateException e) { } } |
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); e... | @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(Colle... |
InternalTopicManager { public void makeReady(final Map<InternalTopicConfig, Integer> topics) { for (int i = 0; i < MAX_TOPIC_READY_TRY; i++) { try { final MetadataResponse metadata = streamsKafkaClient.fetchMetadata(); final Map<String, Integer> existingTopicPartitions = fetchExistingPartitionCountByTopic(metadata); fi... | @Test public void shouldCreateRequiredTopics() throws Exception { InternalTopicManager internalTopicManager = new InternalTopicManager(streamsKafkaClient, 1, WINDOW_CHANGE_LOG_ADDITIONAL_RETENTION_DEFAULT, time); internalTopicManager.makeReady(Collections.singletonMap(new InternalTopicConfig(topic, Collections.singleto... |
AbstractTask { protected void updateOffsetLimits() { log.debug("{} Updating store offset limits {}", logPrefix); for (final TopicPartition partition : partitions) { try { final OffsetAndMetadata metadata = consumer.committed(partition); stateMgr.putOffsetLimit(partition, metadata != null ? metadata.offset() : 0L); } ca... | @Test(expected = ProcessorStateException.class) public void shouldThrowProcessorStateExceptionOnInitializeOffsetsWhenAuthorizationException() throws Exception { final Consumer consumer = mockConsumer(new AuthorizationException("blah")); final AbstractTask task = createTask(consumer); task.updateOffsetLimits(); }
@Test(... |
TopologyBuilder { public synchronized final TopologyBuilder addSource(final String name, final String... topics) { return addSource(null, name, null, null, null, topics); } TopologyBuilder(); synchronized final TopologyBuilder setApplicationId(final String applicationId); synchronized final TopologyBuilder addSource(fi... | @Test public void shouldNotAllowOffsetResetSourceWithoutTopics() { final TopologyBuilder builder = new TopologyBuilder(); final Serde<String> stringSerde = Serdes.String(); try { builder.addSource(TopologyBuilder.AutoOffsetReset.EARLIEST, "source", null, stringSerde.deserializer(), stringSerde.deserializer(), new Strin... |
TopologyBuilder { public synchronized final TopologyBuilder addProcessor(final String name, final ProcessorSupplier supplier, final String... parentNames) { Objects.requireNonNull(name, "name must not be null"); Objects.requireNonNull(supplier, "supplier must not be null"); if (nodeFactories.containsKey(name)) throw ne... | @Test(expected = TopologyBuilderException.class) public void testAddProcessorWithWrongParent() { final TopologyBuilder builder = new TopologyBuilder(); builder.addProcessor("processor", new MockProcessorSupplier(), "source"); }
@Test(expected = TopologyBuilderException.class) public void testAddProcessorWithSelfParent(... |
TopologyBuilder { public synchronized final TopologyBuilder addSink(final String name, final String topic, final String... parentNames) { return addSink(name, topic, null, null, parentNames); } TopologyBuilder(); synchronized final TopologyBuilder setApplicationId(final String applicationId); synchronized final Topolog... | @Test(expected = TopologyBuilderException.class) public void testAddSinkWithWrongParent() { final TopologyBuilder builder = new TopologyBuilder(); builder.addSink("sink", "topic-2", "source"); }
@Test(expected = TopologyBuilderException.class) public void testAddSinkWithSelfParent() { final TopologyBuilder builder = ne... |
TopologyBuilder { public synchronized final TopologyBuilder addStateStore(final StateStoreSupplier supplier, final String... processorNames) { Objects.requireNonNull(supplier, "supplier can't be null"); if (stateFactories.containsKey(supplier.name())) { throw new TopologyBuilderException("StateStore " + supplier.name()... | @Test(expected = TopologyBuilderException.class) public void testAddStateStoreWithNonExistingProcessor() { final TopologyBuilder builder = new TopologyBuilder(); builder.addStateStore(new MockStateStoreSupplier("store", false), "no-such-processsor"); }
@Test(expected = TopologyBuilderException.class) public void testAd... |
ConnectorsResource { @GET @Path("/{connector}/tasks") public List<TaskInfo> getTaskConfigs(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward) throws Throwable { FutureCallback<List<TaskInfo>> cb = new FutureCallback<>(); herder.taskConfigs(connector, cb); return completeOrForw... | @Test public void testGetConnectorTaskConfigs() throws Throwable { final Capture<Callback<List<TaskInfo>>> cb = Capture.newInstance(); herder.taskConfigs(EasyMock.eq(CONNECTOR_NAME), EasyMock.capture(cb)); expectAndCallbackResult(cb, TASK_INFOS); PowerMock.replayAll(); List<TaskInfo> taskInfos = connectorsResource.getT... |
TopologyBuilder { public synchronized Map<Integer, TopicsInfo> topicGroups() { final Map<Integer, TopicsInfo> topicGroups = new LinkedHashMap<>(); if (nodeGroups == null) nodeGroups = makeNodeGroups(); for (Map.Entry<Integer, Set<String>> entry : nodeGroups.entrySet()) { final Set<String> sinkTopics = new HashSet<>(); ... | @Test public void testTopicGroups() { final TopologyBuilder builder = new TopologyBuilder(); builder.setApplicationId("X"); builder.addInternalTopic("topic-1x"); builder.addSource("source-1", "topic-1", "topic-1x"); builder.addSource("source-2", "topic-2"); builder.addSource("source-3", "topic-3"); builder.addSource("s... |
TopologyBuilder { public synchronized ProcessorTopology build(final Integer topicGroupId) { Set<String> nodeGroup; if (topicGroupId != null) { nodeGroup = nodeGroups().get(topicGroupId); } else { final Set<String> globalNodeGroups = globalNodeGroups(); final Collection<Set<String>> values = nodeGroups().values(); nodeG... | @Test public void testBuild() { final TopologyBuilder builder = new TopologyBuilder(); builder.addSource("source-1", "topic-1", "topic-1x"); builder.addSource("source-2", "topic-2"); builder.addSource("source-3", "topic-3"); builder.addSource("source-4", "topic-4"); builder.addSource("source-5", "topic-5"); builder.add... |
TopologyBuilder { public synchronized final TopologyBuilder connectProcessorAndStateStores(final String processorName, final String... stateStoreNames) { Objects.requireNonNull(processorName, "processorName can't be null"); if (stateStoreNames != null) { for (String stateStoreName : stateStoreNames) { connectProcessorA... | @Test(expected = NullPointerException.class) public void shouldNotAllowNullProcessorNameWhenConnectingProcessorAndStateStores() throws Exception { final TopologyBuilder builder = new TopologyBuilder(); builder.connectProcessorAndStateStores(null, "store"); } |
TopologyBuilder { public synchronized final TopologyBuilder addInternalTopic(final String topicName) { Objects.requireNonNull(topicName, "topicName can't be null"); this.internalTopicNames.add(topicName); return this; } TopologyBuilder(); synchronized final TopologyBuilder setApplicationId(final String applicationId); ... | @Test(expected = NullPointerException.class) public void shouldNotAddNullInternalTopic() throws Exception { final TopologyBuilder builder = new TopologyBuilder(); builder.addInternalTopic(null); } |
TopologyBuilder { public synchronized final TopologyBuilder setApplicationId(final String applicationId) { Objects.requireNonNull(applicationId, "applicationId can't be null"); this.applicationId = applicationId; return this; } TopologyBuilder(); synchronized final TopologyBuilder setApplicationId(final String applicat... | @Test(expected = NullPointerException.class) public void shouldNotSetApplicationIdToNull() throws Exception { final TopologyBuilder builder = new TopologyBuilder(); builder.setApplicationId(null); } |
TopologyBuilder { public synchronized TopologyBuilder addGlobalStore(final StateStoreSupplier<KeyValueStore> storeSupplier, final String sourceName, final Deserializer keyDeserializer, final Deserializer valueDeserializer, final String topic, final String processorName, final ProcessorSupplier stateUpdateSupplier) { re... | @Test(expected = TopologyBuilderException.class) public void shouldNotAllowToAddGlobalStoreWithSourceNameEqualsProcessorName() { final String sameNameForSourceAndProcessor = "sameName"; final TopologyBuilder topologyBuilder = new TopologyBuilder() .addGlobalStore(new MockStateStoreSupplier("anyName", false, false), sam... |
ConnectorsResource { @POST @Path("/{connector}/tasks") public void putTaskConfigs(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward, final List<Map<String, String>> taskConfigs) throws Throwable { FutureCallback<Void> cb = new FutureCallback<>(); herder.putTaskConfigs(connecto... | @Test public void testPutConnectorTaskConfigs() throws Throwable { final Capture<Callback<Void>> cb = Capture.newInstance(); herder.putTaskConfigs(EasyMock.eq(CONNECTOR_NAME), EasyMock.eq(TASK_CONFIGS), EasyMock.capture(cb)); expectAndCallbackResult(cb, null); PowerMock.replayAll(); connectorsResource.putTaskConfigs(CO... |
ConnectorsResource { @POST @Path("/{connector}/restart") public void restartConnector(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward) throws Throwable { FutureCallback<Void> cb = new FutureCallback<>(); herder.restartConnector(connector, cb); completeOrForwardRequest(cb, "/... | @Test(expected = NotFoundException.class) public void testRestartConnectorNotFound() throws Throwable { final Capture<Callback<Void>> cb = Capture.newInstance(); herder.restartConnector(EasyMock.eq(CONNECTOR_NAME), EasyMock.capture(cb)); expectAndCallbackException(cb, new NotFoundException("not found")); PowerMock.repl... |
ConnectorsResource { @POST @Path("/{connector}/tasks/{task}/restart") public void restartTask(final @PathParam("connector") String connector, final @PathParam("task") Integer task, final @QueryParam("forward") Boolean forward) throws Throwable { FutureCallback<Void> cb = new FutureCallback<>(); ConnectorTaskId taskId =... | @Test(expected = NotFoundException.class) public void testRestartTaskNotFound() throws Throwable { ConnectorTaskId taskId = new ConnectorTaskId(CONNECTOR_NAME, 0); final Capture<Callback<Void>> cb = Capture.newInstance(); herder.restartTask(EasyMock.eq(taskId), EasyMock.capture(cb)); expectAndCallbackException(cb, new ... |
ConnectorPluginsResource { @PUT @Path("/{connectorType}/config/validate") public ConfigInfos validateConfigs( final @PathParam("connectorType") String connType, final Map<String, String> connectorConfig ) throws Throwable { String includedConnType = connectorConfig.get(ConnectorConfig.CONNECTOR_CLASS_CONFIG); if (inclu... | @Test public void testValidateConfigWithSingleErrorDueToMissingConnectorClassname() throws Throwable { herder.validateConnectorConfig(EasyMock.eq(partialProps)); PowerMock.expectLastCall().andAnswer(new IAnswer<ConfigInfos>() { @Override public ConfigInfos answer() { ConfigDef connectorConfigDef = ConnectorConfig.confi... |
AbstractHerder implements Herder, TaskStatus.Listener, ConnectorStatus.Listener { @Override public ConnectorStateInfo connectorStatus(String connName) { ConnectorStatus connector = statusBackingStore.get(connName); if (connector == null) throw new NotFoundException("No status found for connector " + connName); Collecti... | @Test public void connectorStatus() { ConnectorTaskId taskId = new ConnectorTaskId(connector, 0); ConfigBackingStore configStore = strictMock(ConfigBackingStore.class); StatusBackingStore statusStore = strictMock(StatusBackingStore.class); AbstractHerder herder = partialMockBuilder(AbstractHerder.class) .withConstructo... |
AbstractHerder implements Herder, TaskStatus.Listener, ConnectorStatus.Listener { @Override public ConnectorStateInfo.TaskState taskStatus(ConnectorTaskId id) { TaskStatus status = statusBackingStore.get(id); if (status == null) throw new NotFoundException("No status found for task " + id); return new ConnectorStateInf... | @Test public void taskStatus() { ConnectorTaskId taskId = new ConnectorTaskId("connector", 0); String workerId = "workerId"; ConfigBackingStore configStore = strictMock(ConfigBackingStore.class); StatusBackingStore statusStore = strictMock(StatusBackingStore.class); AbstractHerder herder = partialMockBuilder(AbstractHe... |
AbstractHerder implements Herder, TaskStatus.Listener, ConnectorStatus.Listener { @Override public ConfigInfos validateConnectorConfig(Map<String, String> connectorProps) { String connType = connectorProps.get(ConnectorConfig.CONNECTOR_CLASS_CONFIG); if (connType == null) throw new BadRequestException("Connector config... | @Test(expected = BadRequestException.class) public void testConfigValidationEmptyConfig() { AbstractHerder herder = createConfigValidationHerder(TestSourceConnector.class); replayAll(); herder.validateConnectorConfig(new HashMap<String, String>()); verifyAll(); }
@Test() public void testConfigValidationMissingName() { ... |
StandaloneHerder extends AbstractHerder { @Override public synchronized void restartConnector(String connName, Callback<Void> cb) { if (!configState.contains(connName)) cb.onCompletion(new NotFoundException("Connector " + connName + " not found", null), null); Map<String, String> config = configState.connectorConfig(co... | @Test public void testRestartConnector() throws Exception { expectAdd(SourceSink.SOURCE); Map<String, String> config = connectorConfig(SourceSink.SOURCE); expectConfigValidation(config); worker.stopConnector(CONNECTOR_NAME); EasyMock.expectLastCall().andReturn(true); worker.startConnector(EasyMock.eq(CONNECTOR_NAME), E... |
StandaloneHerder extends AbstractHerder { @Override public synchronized void restartTask(ConnectorTaskId taskId, Callback<Void> cb) { if (!configState.contains(taskId.connector())) cb.onCompletion(new NotFoundException("Connector " + taskId.connector() + " not found", null), null); Map<String, String> taskConfigProps =... | @Test public void testRestartTask() throws Exception { ConnectorTaskId taskId = new ConnectorTaskId(CONNECTOR_NAME, 0); expectAdd(SourceSink.SOURCE); Map<String, String> connectorConfig = connectorConfig(SourceSink.SOURCE); expectConfigValidation(connectorConfig); worker.stopAndAwaitTask(taskId); EasyMock.expectLastCal... |
StandaloneHerder extends AbstractHerder { @Override public synchronized void putConnectorConfig(String connName, final Map<String, String> config, boolean allowReplace, final Callback<Created<ConnectorInfo>> callback) { try { if (maybeAddConfigErrors(validateConnectorConfig(config), callback)) { return; } boolean creat... | @Test public void testPutConnectorConfig() throws Exception { Map<String, String> connConfig = connectorConfig(SourceSink.SOURCE); Map<String, String> newConnConfig = new HashMap<>(connConfig); newConnConfig.put("foo", "bar"); Callback<Map<String, String>> connectorConfigCb = PowerMock.createMock(Callback.class); Callb... |
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 wo... | @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(); } |
PluginUtils { public static boolean shouldLoadInIsolation(String name) { return !(name.matches(BLACKLIST) && !name.matches(WHITELIST)); } static boolean shouldLoadInIsolation(String name); static boolean isConcrete(Class<?> klass); static boolean isArchive(Path path); static boolean isClassFile(Path path); static List... | @Test public void testJavaLibraryClasses() throws Exception { assertFalse(PluginUtils.shouldLoadInIsolation("java.")); assertFalse(PluginUtils.shouldLoadInIsolation("java.lang.Object")); assertFalse(PluginUtils.shouldLoadInIsolation("java.lang.String")); assertFalse(PluginUtils.shouldLoadInIsolation("java.util.HashMap$... |
PluginDesc implements Comparable<PluginDesc<T>> { @JsonProperty("location") public String location() { return location; } PluginDesc(Class<? extends T> klass, String version, ClassLoader loader); @Override String toString(); Class<? extends T> pluginClass(); @JsonProperty("class") String className(); @JsonProperty("ver... | @Test public void testRegularPluginDesc() throws Exception { PluginDesc<Connector> connectorDesc = new PluginDesc<>( Connector.class, regularVersion, pluginLoader ); assertPluginDesc(connectorDesc, Connector.class, regularVersion, pluginLoader.location()); PluginDesc<Converter> converterDesc = new PluginDesc<>( Convert... |
PluginDesc implements Comparable<PluginDesc<T>> { @Override public int hashCode() { return Objects.hash(klass, version, type); } PluginDesc(Class<? extends T> klass, String version, ClassLoader loader); @Override String toString(); Class<? extends T> pluginClass(); @JsonProperty("class") String className(); @JsonProper... | @Test public void testPluginDescEquality() throws Exception { PluginDesc<Connector> connectorDescPluginPath = new PluginDesc<>( Connector.class, snaphotVersion, pluginLoader ); PluginDesc<Connector> connectorDescClasspath = new PluginDesc<>( Connector.class, snaphotVersion, systemLoader ); assertEquals(connectorDescPlu... |
DistributedHerder extends AbstractHerder implements Runnable { @Override public void restartConnector(final String connName, final Callback<Void> callback) { addRequest(new Callable<Void>() { @Override public Void call() throws Exception { if (checkRebalanceNeeded(callback)) return null; if (!configState.connectors().c... | @Test public void testRestartConnector() throws Exception { EasyMock.expect(worker.connectorTaskConfigs(CONN1, MAX_TASKS, null)).andStubReturn(TASK_CONFIGS); EasyMock.expect(member.memberId()).andStubReturn("leader"); EasyMock.expect(worker.getPlugins()).andReturn(plugins); expectRebalance(1, singletonList(CONN1), Coll... |
DistributedHerder extends AbstractHerder implements Runnable { @Override public void restartTask(final ConnectorTaskId id, final Callback<Void> callback) { addRequest(new Callable<Void>() { @Override public Void call() throws Exception { if (checkRebalanceNeeded(callback)) return null; if (!configState.connectors().con... | @Test public void testRestartTask() throws Exception { EasyMock.expect(worker.connectorTaskConfigs(CONN1, MAX_TASKS, null)).andStubReturn(TASK_CONFIGS); EasyMock.expect(member.memberId()).andStubReturn("leader"); expectRebalance(1, Collections.<String>emptyList(), singletonList(TASK0)); expectPostRebalanceCatchup(SNAPS... |
DistributedHerder extends AbstractHerder implements Runnable { HerderRequest addRequest(Callable<Void> action, Callback<Void> callback) { return addRequest(0, action, callback); } DistributedHerder(DistributedConfig config,
Time time,
Worker worker,
... | @Test public void testRequestProcessingOrder() throws Exception { final DistributedHerder.HerderRequest req1 = herder.addRequest(100, null, null); final DistributedHerder.HerderRequest req2 = herder.addRequest(10, null, null); final DistributedHerder.HerderRequest req3 = herder.addRequest(200, null, null); final Distri... |
DistributedHerder extends AbstractHerder implements Runnable { @Override public void putConnectorConfig(final String connName, final Map<String, String> config, final boolean allowReplace, final Callback<Created<ConnectorInfo>> callback) { log.trace("Submitting connector config write request {}", connName); addRequest(... | @Test public void testPutConnectorConfig() throws Exception { EasyMock.expect(member.memberId()).andStubReturn("leader"); expectRebalance(1, Arrays.asList(CONN1), Collections.<ConnectorTaskId>emptyList()); expectPostRebalanceCatchup(SNAPSHOT); worker.startConnector(EasyMock.eq(CONN1), EasyMock.<Map<String, String>>anyO... |
WorkerCoordinator extends AbstractCoordinator implements Closeable { @Override public List<ProtocolMetadata> metadata() { configSnapshot = configStorage.snapshot(); ConnectProtocol.WorkerState workerState = new ConnectProtocol.WorkerState(restUrl, configSnapshot.offset()); ByteBuffer metadata = ConnectProtocol.serializ... | @Test public void testMetadata() { EasyMock.expect(configStorage.snapshot()).andReturn(configState1); PowerMock.replayAll(); List<ProtocolMetadata> serialized = coordinator.metadata(); assertEquals(1, serialized.size()); ProtocolMetadata defaultMetadata = serialized.get(0); assertEquals(WorkerCoordinator.DEFAULT_SUBPRO... |
WorkerCoordinator extends AbstractCoordinator implements Closeable { public String memberId() { Generation generation = generation(); if (generation != null) return generation.memberId; return JoinGroupRequest.UNKNOWN_MEMBER_ID; } WorkerCoordinator(ConsumerNetworkClient client,
String group... | @Test public void testJoinLeaderCannotAssign() { EasyMock.expect(configStorage.snapshot()).andReturn(configState1); EasyMock.expect(configStorage.snapshot()).andReturn(configState2); PowerMock.replayAll(); final String memberId = "member"; client.prepareResponse(groupCoordinatorResponse(node, Errors.NONE)); coordinator... |
WorkerCoordinator extends AbstractCoordinator implements Closeable { public void requestRejoin() { rejoinRequested = true; } WorkerCoordinator(ConsumerNetworkClient client,
String groupId,
int rebalanceTimeoutMs,
int sessionTimeoutMs... | @Test public void testRejoinGroup() { EasyMock.expect(configStorage.snapshot()).andReturn(configState1); EasyMock.expect(configStorage.snapshot()).andReturn(configState1); PowerMock.replayAll(); client.prepareResponse(groupCoordinatorResponse(node, Errors.NONE)); coordinator.ensureCoordinatorReady(); client.prepareResp... |
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... | @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_... |
SourceTaskOffsetCommitter { public void remove(ConnectorTaskId id) { final ScheduledFuture<?> task = committers.remove(id); if (task == null) return; try { task.cancel(false); if (!task.isDone()) task.get(); } catch (CancellationException e) { log.trace("Offset commit thread was cancelled by another thread while removi... | @Test public void testRemove() throws Exception { ConnectorTaskId taskId = PowerMock.createMock(ConnectorTaskId.class); ScheduledFuture task = PowerMock.createMock(ScheduledFuture.class); EasyMock.expect(committers.remove(taskId)).andReturn(null); PowerMock.replayAll(); committer.remove(taskId); PowerMock.verifyAll(); ... |
KafkaConfigBackingStore implements ConfigBackingStore { @Override public void putConnectorConfig(String connector, Map<String, String> properties) { log.debug("Writing connector configuration {} for connector {} configuration", properties, connector); Struct connectConfig = new Struct(CONNECTOR_CONFIGURATION_V0); conne... | @Test public void testPutConnectorConfig() throws Exception { expectConfigure(); expectStart(Collections.EMPTY_LIST, Collections.EMPTY_MAP); expectConvertWriteAndRead( CONNECTOR_CONFIG_KEYS.get(0), KafkaConfigBackingStore.CONNECTOR_CONFIGURATION_V0, CONFIGS_SERIALIZED.get(0), "properties", SAMPLE_CONFIGS.get(0)); confi... |
KafkaConfigBackingStore implements ConfigBackingStore { @Override public void putTaskConfigs(String connector, List<Map<String, String>> configs) { try { configLog.readToEnd().get(READ_TO_END_TIMEOUT_MS, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { log.error("Failed... | @Test public void testPutTaskConfigs() throws Exception { expectConfigure(); expectStart(Collections.EMPTY_LIST, Collections.EMPTY_MAP); expectReadToEnd(new LinkedHashMap<String, byte[]>()); expectConvertWriteRead( TASK_CONFIG_KEYS.get(0), KafkaConfigBackingStore.TASK_CONFIGURATION_V0, CONFIGS_SERIALIZED.get(0), "prope... |
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 ... | @Test public void testNoOffsetsToFlush() { PowerMock.replayAll(); assertFalse(writer.beginFlush()); PowerMock.verifyAll(); } |
Time { public static int fromLogical(Schema schema, java.util.Date value) { if (schema.name() == null || !(schema.name().equals(LOGICAL_NAME))) throw new DataException("Requested conversion of Time object but the schema does not match."); Calendar calendar = Calendar.getInstance(UTC); calendar.setTime(value); long unix... | @Test public void testFromLogical() { assertEquals(0, Time.fromLogical(Time.SCHEMA, EPOCH.getTime())); assertEquals(10000, Time.fromLogical(Time.SCHEMA, EPOCH_PLUS_TEN_THOUSAND_MILLIS.getTime())); }
@Test(expected = DataException.class) public void testFromLogicalInvalidHasDateComponents() { Time.fromLogical(Time.SCHEM... |
Time { public static java.util.Date toLogical(Schema schema, int value) { if (schema.name() == null || !(schema.name().equals(LOGICAL_NAME))) throw new DataException("Requested conversion of Date object but the schema does not match."); if (value < 0 || value > MILLIS_PER_DAY) throw new DataException("Time values must ... | @Test public void testToLogical() { assertEquals(EPOCH.getTime(), Time.toLogical(Time.SCHEMA, 0)); assertEquals(EPOCH_PLUS_TEN_THOUSAND_MILLIS.getTime(), Time.toLogical(Time.SCHEMA, 10000)); } |
Struct { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Struct struct = (Struct) o; return Objects.equals(schema, struct.schema) && Arrays.equals(values, struct.values); } Struct(Schema schema); Schema schema(); Object get(String fieldN... | @Test public void testEquals() { Struct struct1 = new Struct(FLAT_STRUCT_SCHEMA) .put("int8", (byte) 12) .put("int16", (short) 12) .put("int32", 12) .put("int64", (long) 12) .put("float32", 12.f) .put("float64", 12.) .put("boolean", true) .put("string", "foobar") .put("bytes", ByteBuffer.wrap("foobar".getBytes())); Str... |
ConnectSchema implements Schema { @Override public List<Field> fields() { if (type != Type.STRUCT) throw new DataException("Cannot list fields on non-struct type"); return fields; } ConnectSchema(Type type, boolean optional, Object defaultValue, String name, Integer version, String doc, Map<String, String> parameters, ... | @Test(expected = DataException.class) public void testFieldsOnlyValidForStructs() { Schema.INT8_SCHEMA.fields(); }
@Test public void testEmptyStruct() { final ConnectSchema emptyStruct = new ConnectSchema(Schema.Type.STRUCT, false, null, null, null, null); assertEquals(0, emptyStruct.fields().size()); new Struct(emptyS... |
ConnectSchema implements Schema { public static void validateValue(Schema schema, Object value) { validateValue(null, schema, value); } ConnectSchema(Type type, boolean optional, Object defaultValue, String name, Integer version, String doc, Map<String, String> parameters, List<Field> fields, Schema keySchema, Schema v... | @Test public void testValidateValueMatchingType() { ConnectSchema.validateValue(Schema.INT8_SCHEMA, (byte) 1); ConnectSchema.validateValue(Schema.INT16_SCHEMA, (short) 1); ConnectSchema.validateValue(Schema.INT32_SCHEMA, 1); ConnectSchema.validateValue(Schema.INT64_SCHEMA, (long) 1); ConnectSchema.validateValue(Schema.... |
SchemaBuilder implements Schema { @Override public Map<String, String> parameters() { return parameters == null ? null : Collections.unmodifiableMap(parameters); } SchemaBuilder(Type type); @Override boolean isOptional(); SchemaBuilder optional(); SchemaBuilder required(); @Override Object defaultValue(); SchemaBuilder... | @Test public void testParameters() { Map<String, String> expectedParameters = new HashMap<>(); expectedParameters.put("foo", "val"); expectedParameters.put("bar", "baz"); Schema schema = SchemaBuilder.string().parameter("foo", "val").parameter("bar", "baz").build(); assertTypeAndDefault(schema, Schema.Type.STRING, fals... |
Date { public static int fromLogical(Schema schema, java.util.Date value) { if (schema.name() == null || !(schema.name().equals(LOGICAL_NAME))) throw new DataException("Requested conversion of Date object but the schema does not match."); Calendar calendar = Calendar.getInstance(UTC); calendar.setTime(value); if (calen... | @Test public void testFromLogical() { assertEquals(0, Date.fromLogical(Date.SCHEMA, EPOCH.getTime())); assertEquals(10000, Date.fromLogical(Date.SCHEMA, EPOCH_PLUS_TEN_THOUSAND_DAYS.getTime())); }
@Test(expected = DataException.class) public void testFromLogicalInvalidHasTimeComponents() { Date.fromLogical(Date.SCHEMA,... |
Date { public static java.util.Date toLogical(Schema schema, int value) { if (schema.name() == null || !(schema.name().equals(LOGICAL_NAME))) throw new DataException("Requested conversion of Date object but the schema does not match."); return new java.util.Date(value * MILLIS_PER_DAY); } static SchemaBuilder builder(... | @Test public void testToLogical() { assertEquals(EPOCH.getTime(), Date.toLogical(Date.SCHEMA, 0)); assertEquals(EPOCH_PLUS_TEN_THOUSAND_DAYS.getTime(), Date.toLogical(Date.SCHEMA, 10000)); } |
Timestamp { public static long fromLogical(Schema schema, java.util.Date value) { if (schema.name() == null || !(schema.name().equals(LOGICAL_NAME))) throw new DataException("Requested conversion of Timestamp object but the schema does not match."); return value.getTime(); } static SchemaBuilder builder(); static long... | @Test public void testFromLogical() { assertEquals(0L, Timestamp.fromLogical(Timestamp.SCHEMA, EPOCH.getTime())); assertEquals(TOTAL_MILLIS, Timestamp.fromLogical(Timestamp.SCHEMA, EPOCH_PLUS_MILLIS.getTime())); } |
Timestamp { public static java.util.Date toLogical(Schema schema, long value) { if (schema.name() == null || !(schema.name().equals(LOGICAL_NAME))) throw new DataException("Requested conversion of Timestamp object but the schema does not match."); return new java.util.Date(value); } static SchemaBuilder builder(); sta... | @Test public void testToLogical() { assertEquals(EPOCH.getTime(), Timestamp.toLogical(Timestamp.SCHEMA, 0L)); assertEquals(EPOCH_PLUS_MILLIS.getTime(), Timestamp.toLogical(Timestamp.SCHEMA, TOTAL_MILLIS)); } |
SchemaProjector { public static Object project(Schema source, Object record, Schema target) throws SchemaProjectorException { checkMaybeCompatible(source, target); if (source.isOptional() && !target.isOptional()) { if (target.defaultValue() != null) { if (record != null) { return projectRequiredSchema(source, record, t... | @Test public void testPrimitiveTypeProjection() throws Exception { Object projected; projected = SchemaProjector.project(Schema.BOOLEAN_SCHEMA, false, Schema.BOOLEAN_SCHEMA); assertEquals(false, projected); byte[] bytes = {(byte) 1, (byte) 2}; projected = SchemaProjector.project(Schema.BYTES_SCHEMA, bytes, Schema.BYTES... |
ConnectorUtils { public static <T> List<List<T>> groupPartitions(List<T> elements, int numGroups) { if (numGroups <= 0) throw new IllegalArgumentException("Number of groups must be positive."); List<List<T>> result = new ArrayList<>(numGroups); int perGroup = elements.size() / numGroups; int leftover = elements.size() ... | @Test public void testGroupPartitions() { List<List<Integer>> grouped = ConnectorUtils.groupPartitions(FIVE_ELEMENTS, 1); assertEquals(Arrays.asList(FIVE_ELEMENTS), grouped); grouped = ConnectorUtils.groupPartitions(FIVE_ELEMENTS, 2); assertEquals(Arrays.asList(Arrays.asList(1, 2, 3), Arrays.asList(4, 5)), grouped); gr... |
StringConverter implements Converter { @Override public byte[] fromConnectData(String topic, Schema schema, Object value) { try { return serializer.serialize(topic, value == null ? null : value.toString()); } catch (SerializationException e) { throw new DataException("Failed to serialize to a string: ", e); } } StringC... | @Test public void testStringToBytes() throws UnsupportedEncodingException { assertArrayEquals(SAMPLE_STRING.getBytes("UTF8"), converter.fromConnectData(TOPIC, Schema.STRING_SCHEMA, SAMPLE_STRING)); }
@Test public void testNonStringToBytes() throws UnsupportedEncodingException { assertArrayEquals("true".getBytes("UTF8")... |
StringConverter implements Converter { @Override public SchemaAndValue toConnectData(String topic, byte[] value) { try { return new SchemaAndValue(Schema.OPTIONAL_STRING_SCHEMA, deserializer.deserialize(topic, value)); } catch (SerializationException e) { throw new DataException("Failed to deserialize string: ", e); } ... | @Test public void testBytesToString() { SchemaAndValue data = converter.toConnectData(TOPIC, SAMPLE_STRING.getBytes()); assertEquals(Schema.OPTIONAL_STRING_SCHEMA, data.schema()); assertEquals(SAMPLE_STRING, data.value()); }
@Test public void testBytesNullToString() { SchemaAndValue data = converter.toConnectData(TOPIC... |
FileStreamSourceConnector extends SourceConnector { @Override public void start(Map<String, String> props) { filename = props.get(FILE_CONFIG); topic = props.get(TOPIC_CONFIG); if (topic == null || topic.isEmpty()) throw new ConnectException("FileStreamSourceConnector configuration must include 'topic' setting"); if (t... | @Test(expected = ConnectException.class) public void testMultipleSourcesInvalid() { sourceProperties.put(FileStreamSourceConnector.TOPIC_CONFIG, MULTIPLE_TOPICS); connector.start(sourceProperties); } |
FileStreamSourceConnector extends SourceConnector { @Override public Class<? extends Task> taskClass() { return FileStreamSourceTask.class; } @Override String version(); @Override void start(Map<String, String> props); @Override Class<? extends Task> taskClass(); @Override List<Map<String, String>> taskConfigs(int max... | @Test public void testTaskClass() { PowerMock.replayAll(); connector.start(sourceProperties); assertEquals(FileStreamSourceTask.class, connector.taskClass()); PowerMock.verifyAll(); } |
FileStreamSinkConnector extends SinkConnector { @Override public Class<? extends Task> taskClass() { return FileStreamSinkTask.class; } @Override String version(); @Override void start(Map<String, String> props); @Override Class<? extends Task> taskClass(); @Override List<Map<String, String>> taskConfigs(int maxTasks)... | @Test public void testTaskClass() { PowerMock.replayAll(); connector.start(sinkProperties); assertEquals(FileStreamSinkTask.class, connector.taskClass()); PowerMock.verifyAll(); }
@Test public void testTaskClass() { replayAll(); connector.start(sinkProperties); assertEquals(FileStreamSinkTask.class, connector.taskClass... |
FileStreamSourceTask extends SourceTask { @Override public void start(Map<String, String> props) { filename = props.get(FileStreamSourceConnector.FILE_CONFIG); if (filename == null || filename.isEmpty()) { stream = System.in; streamOffset = null; reader = new BufferedReader(new InputStreamReader(stream, StandardCharset... | @Test(expected = ConnectException.class) public void testMissingTopic() throws InterruptedException { replay(); config.remove(FileStreamSourceConnector.TOPIC_CONFIG); task.start(config); } |
ApiVersions { public synchronized byte maxUsableProduceMagic() { return maxUsableProduceMagic; } synchronized void update(String nodeId, NodeApiVersions nodeApiVersions); synchronized void remove(String nodeId); synchronized NodeApiVersions get(String nodeId); synchronized byte maxUsableProduceMagic(); } | @Test public void testMaxUsableProduceMagic() { ApiVersions apiVersions = new ApiVersions(); assertEquals(RecordBatch.CURRENT_MAGIC_VALUE, apiVersions.maxUsableProduceMagic()); apiVersions.update("0", NodeApiVersions.create()); assertEquals(RecordBatch.CURRENT_MAGIC_VALUE, apiVersions.maxUsableProduceMagic()); apiVersi... |
ClientUtils { public static List<InetSocketAddress> parseAndValidateAddresses(List<String> urls) { List<InetSocketAddress> addresses = new ArrayList<>(); for (String url : urls) { if (url != null && !url.isEmpty()) { try { String host = getHost(url); Integer port = getPort(url); if (host == null || port == null) throw ... | @Test public void testParseAndValidateAddresses() { check("127.0.0.1:8000"); check("mydomain.com:8080"); check("[::1]:8000"); check("[2001:db8:85a3:8d3:1319:8a2e:370:7348]:1234", "mydomain.com:10000"); List<InetSocketAddress> validatedAddresses = check("some.invalid.hostname.foo.bar.local:9999", "mydomain.com:10000"); ... |
NetworkClient implements KafkaClient { @Override public void close(String nodeId) { selector.close(nodeId); for (InFlightRequest request : inFlightRequests.clearAll(nodeId)) if (request.isInternalRequest && request.header.apiKey() == ApiKeys.METADATA.id) metadataUpdater.handleDisconnection(request.destination); connect... | @Test public void testClose() { client.ready(node, time.milliseconds()); awaitReady(client, node); client.poll(1, time.milliseconds()); assertTrue("The client should be ready", client.isReady(node, time.milliseconds())); ProduceRequest.Builder builder = new ProduceRequest.Builder(RecordBatch.CURRENT_MAGIC_VALUE, (short... |
NetworkClient implements KafkaClient { @Override public Node leastLoadedNode(long now) { List<Node> nodes = this.metadataUpdater.fetchNodes(); int inflight = Integer.MAX_VALUE; Node found = null; int offset = this.randOffset.nextInt(nodes.size()); for (int i = 0; i < nodes.size(); i++) { int idx = (offset + i) % nodes.... | @Test public void testLeastLoadedNode() { client.ready(node, time.milliseconds()); awaitReady(client, node); client.poll(1, time.milliseconds()); assertTrue("The client should be ready", client.isReady(node, time.milliseconds())); Node leastNode = client.leastLoadedNode(time.milliseconds()); assertEquals("There should ... |
NetworkClient implements KafkaClient { @Override public long connectionDelay(Node node, long now) { return connectionStates.connectionDelay(node.idString(), now); } NetworkClient(Selectable selector,
Metadata metadata,
String clientId,
int maxIn... | @Test public void testConnectionDelay() { long now = time.milliseconds(); long delay = client.connectionDelay(node, now); assertEquals(0, delay); }
@Test public void testConnectionDelayConnected() { awaitReady(client, node); long now = time.milliseconds(); long delay = client.connectionDelay(node, now); assertEquals(Lo... |
NodeApiVersions { @Override public String toString() { return toString(false); } NodeApiVersions(Collection<ApiVersion> nodeApiVersions); static NodeApiVersions create(); static NodeApiVersions create(Collection<ApiVersion> overrides); short usableVersion(ApiKeys apiKey); short usableVersion(ApiKeys apiKey, Short desir... | @Test public void testUnsupportedVersionsToString() { NodeApiVersions versions = new NodeApiVersions(Collections.<ApiVersion>emptyList()); StringBuilder bld = new StringBuilder(); String prefix = "("; for (ApiKeys apiKey : ApiKeys.values()) { bld.append(prefix).append(apiKey.name). append("(").append(apiKey.id).append(... |
NodeApiVersions { public short usableVersion(ApiKeys apiKey) { return usableVersion(apiKey, null); } NodeApiVersions(Collection<ApiVersion> nodeApiVersions); static NodeApiVersions create(); static NodeApiVersions create(Collection<ApiVersion> overrides); short usableVersion(ApiKeys apiKey); short usableVersion(ApiKeys... | @Test public void testUsableVersionCalculation() { List<ApiVersion> versionList = new ArrayList<>(); versionList.add(new ApiVersion(ApiKeys.CONTROLLED_SHUTDOWN_KEY.id, (short) 0, (short) 0)); versionList.add(new ApiVersion(ApiKeys.FETCH.id, (short) 1, (short) 2)); NodeApiVersions versions = new NodeApiVersions(versionL... |
ConsumerConfig extends AbstractConfig { public static Map<String, Object> addDeserializerToConfig(Map<String, Object> configs, Deserializer<?> keyDeserializer, Deserializer<?> valueDeserializer) { Map<String, Object> newConfigs = new HashMap<String, Object>(); newConfigs.putAll(configs); if (keyDeserializer != null) ne... | @Test public void testDeserializerToPropertyConfig() { Properties properties = new Properties(); properties.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, keyDeserializerClassName); properties.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, valueDeserializerClassName); Properties newProperties = ... |
StickyAssignor extends AbstractPartitionAssignor { public Map<String, List<TopicPartition>> assign(Map<String, Integer> partitionsPerTopic, Map<String, Subscription> subscriptions) { Map<String, List<TopicPartition>> currentAssignment = new HashMap<>(); partitionMovements = new PartitionMovements(); prepopulateCurrentA... | @Test public void testOneConsumerNoTopic() { String consumerId = "consumer"; Map<String, Integer> partitionsPerTopic = new HashMap<>(); Map<String, Subscription> subscriptions = Collections.singletonMap(consumerId, new Subscription(Collections.<String>emptyList())); Map<String, List<TopicPartition>> assignment = assign... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.