-
Notifications
You must be signed in to change notification settings - Fork 3
/
Given_a_socket_based_test_server.When_connecting_to_the_server_and_consuming_a_message.cs
243 lines (223 loc) · 12.6 KB
/
Given_a_socket_based_test_server.When_connecting_to_the_server_and_consuming_a_message.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Confluent.Kafka;
using FluentAssertions;
using Kafka.Protocol;
using Kafka.Protocol.Records;
using Xunit;
using Xunit.Abstractions;
using static Kafka.Protocol.OffsetFetchResponse;
using Int32 = Kafka.Protocol.Int32;
using Record = Kafka.Protocol.Records.Record;
using Uuid = Kafka.Protocol.Uuid;
namespace Kafka.TestFramework.Tests
{
public partial class Given_a_socket_based_test_server
{
public class When_connecting_to_the_server_and_consuming_a_message : TestSpecificationAsync
{
private SocketBasedKafkaTestFramework _testServer;
private readonly List<string> _result = new List<string>();
private const int NumberOfMessage = 5;
public When_connecting_to_the_server_and_consuming_a_message(
ITestOutputHelper testOutputHelper)
: base(testOutputHelper)
{
}
protected override Task GivenAsync()
{
_testServer = KafkaTestFramework.WithSocket();
_testServer.On<ApiVersionsRequest, ApiVersionsResponse>(
request => request.Respond()
.WithAllApiKeys());
var topicId = Uuid.From(Guid.NewGuid());
_testServer.On<MetadataRequest, MetadataResponse>(
request => request.Respond()
.WithTopicsCollection(
request.TopicsCollection?.Select(topic =>
new Func<MetadataResponse.MetadataResponseTopic,
MetadataResponse.MetadataResponseTopic>(
responseTopic =>
responseTopic
.WithName(topic.Name)
.WithTopicId(topicId)
.WithPartitionsCollection(partition =>
partition
.WithLeaderId(0)
.WithPartitionIndex(0))))
.ToArray() ??
Array.Empty<Func<MetadataResponse.MetadataResponseTopic,
MetadataResponse.MetadataResponseTopic>>())
.WithBrokersCollection(broker => broker
.WithHost("localhost")
.WithPort(_testServer.Port))
);
_testServer.On<FindCoordinatorRequest, FindCoordinatorResponse>(
request => request.Respond()
.WithHost("localhost")
.WithPort(_testServer.Port)
);
_testServer.On<JoinGroupRequest, JoinGroupResponse>(
request => request.Respond()
.WithProtocolName(request.ProtocolsCollection.First().Value.Name));
_testServer.On<SyncGroupRequest, SyncGroupResponse>(
async (request, cancellationToken) => request.Respond()
.WithAssignment(
await new ConsumerProtocolAssignment(ConsumerProtocolAssignment.MaxVersion)
.WithAssignedPartitionsCollection(partition => partition
.WithTopic("topic1")
.WithPartitionsCollection(new Int32[] { 0 }))
.ToBytesAsync(cancellationToken)
.ConfigureAwait(false))
);
_testServer.On<OffsetFetchRequest, OffsetFetchResponse>(request => request.Respond()
.WithGroupsCollection(request.GroupsCollection.Select(group =>
new Func<OffsetFetchResponseGroup, OffsetFetchResponseGroup>(offsetFetchResponseGroup =>
offsetFetchResponseGroup
.WithGroupId(group.GroupId)
.WithTopicsCollection(
group.TopicsCollection?
.Select(topic =>
new Func<OffsetFetchResponseGroup.OffsetFetchResponseTopics,
OffsetFetchResponseGroup.OffsetFetchResponseTopics>(
responseTopic =>
responseTopic
.WithName(topic.Name)
.WithPartitionsCollection(topic
.PartitionIndexesCollection
.Select(partitionIndex =>
new Func<OffsetFetchResponseGroup.
OffsetFetchResponseTopics.
OffsetFetchResponsePartitions,
OffsetFetchResponseGroup.
OffsetFetchResponseTopics.
OffsetFetchResponsePartitions>(
partition => partition
.WithPartitionIndex(partitionIndex)))
.ToArray())))
.ToArray() ??
Array.Empty<Func<OffsetFetchResponseGroup.OffsetFetchResponseTopics,
OffsetFetchResponseGroup.OffsetFetchResponseTopics>>()))).ToArray()));
var records = new Dictionary<long, Record>();
for (var i = 0; i < NumberOfMessage; i++)
{
records.Add(i, new Record
{
OffsetDelta = i,
Value = Encoding.UTF8.GetBytes(
$"data{i} fetched from broker")
});
}
_testServer.On<FetchRequest, FetchResponse>(async (request, cancellationToken) =>
{
var returnsData = false;
var response = request.Respond()
.WithResponsesCollection(
request.TopicsCollection.Select(topic =>
new Func<FetchResponse.FetchableTopicResponse, FetchResponse.FetchableTopicResponse>(
response => response
.WithTopicId(topic.TopicId)
.WithPartitionsCollection(topic.PartitionsCollection.Select(partition =>
new Func<FetchResponse.FetchableTopicResponse.PartitionData,
FetchResponse.FetchableTopicResponse.PartitionData>(data =>
{
data.WithCurrentLeader(epoch => epoch
.WithLeaderEpoch(epoch.LeaderEpoch)
.WithLeaderId(0))
.WithPartitionIndex(partition.Partition)
.WithHighWatermark(NumberOfMessage - 1);
var recordBatch = new NullableRecordBatch
{
LastOffsetDelta = (int)partition.FetchOffset,
Magic = 2,
Records = records.TryGetValue(partition.FetchOffset.Value,
out var record)
? new NullableArray<Record>(record)
: NullableArray<Record>.Default
};
returnsData = recordBatch.Records != NullableArray<Record>.Default;
return returnsData ? data.WithRecords(recordBatch) : data;
})).ToArray()
))).ToArray());
if (!returnsData)
{
await Task.Delay(request.MaxWaitMs, cancellationToken)
.ConfigureAwait(false);
}
return response;
});
_testServer.On<OffsetCommitRequest, OffsetCommitResponse>(request => request.Respond()
.WithTopicsCollection(request.TopicsCollection.Select(topic =>
new Func<OffsetCommitResponse.OffsetCommitResponseTopic,
OffsetCommitResponse.OffsetCommitResponseTopic>(responseTopic => responseTopic
.WithName(topic.Name)
.WithPartitionsCollection(topic.PartitionsCollection.Select(partition =>
new Func<OffsetCommitResponse.OffsetCommitResponseTopic.
OffsetCommitResponsePartition,
OffsetCommitResponse.OffsetCommitResponseTopic.
OffsetCommitResponsePartition>(responsePartition => responsePartition
.WithPartitionIndex(partition.PartitionIndex))).ToArray())
)).ToArray()
));
_testServer.On<LeaveGroupRequest, LeaveGroupResponse>(request => request.Respond());
_testServer.On<HeartbeatRequest, HeartbeatResponse>(request => request.Respond());
_testServer.On<GetTelemetrySubscriptionsRequest, GetTelemetrySubscriptionsResponse>(request => request.Respond()
.WithPushIntervalMs(1000));
return Task.CompletedTask;
}
protected override async Task WhenAsync()
{
await using (_testServer.Start()
.ConfigureAwait(false))
{
ConsumeMessages("localhost", _testServer.Port, _testServer.Stopping);
}
}
[Fact]
public void It_should_have_read_the_messages_sent()
{
_result.Should().HaveCount(NumberOfMessage);
for (var i = 0; i < NumberOfMessage; i++)
{
_result.Should().Contain($"data{i} fetched from broker");
}
}
private void ConsumeMessages(string host,
int port, CancellationToken testServerStopping)
{
var consumerConfig = new ConsumerConfig(new Dictionary<string, string>
{
{ "log_level", "7" }
})
{
BootstrapServers = $"{host}:{port}",
ApiVersionRequestTimeoutMs = 30000,
Debug = "all",
GroupId = "group1",
LogThreadName = false
};
using var consumer = new ConsumerBuilder<Ignore, string>(consumerConfig)
.SetLogHandler(this.Log)
.Build();
consumer.Subscribe("topic1");
var cancellationToken = CancellationTokenSource
.CreateLinkedTokenSource(testServerStopping, TimeoutCancellationToken).Token;
try
{
for (var i = 0; i < NumberOfMessage; i++)
{
_result.Add(consumer.Consume(cancellationToken).Message.Value);
}
}
finally
{
consumer.Close();
}
}
}
}
}