-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathHttpClientEventDispatcher45Test.cs
More file actions
214 lines (184 loc) · 7.25 KB
/
HttpClientEventDispatcher45Test.cs
File metadata and controls
214 lines (184 loc) · 7.25 KB
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
/*
* Copyright 2026, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !NET35 && !NET40
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using OptimizelySDK.Event;
using OptimizelySDK.Event.Dispatcher;
using OptimizelySDK.Logger;
namespace OptimizelySDK.Tests.EventTests
{
[TestFixture]
public class HttpClientEventDispatcher45Test
{
[SetUp]
public void Setup()
{
_mockLogger = new Mock<ILogger>();
_mockLogger.Setup(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()));
_requestTimestamps = new List<DateTime>();
}
private Mock<ILogger> _mockLogger;
private List<DateTime> _requestTimestamps;
[Test]
public void DispatchEvent_Success_SingleAttempt()
{
var handler = new MockHttpMessageHandler(HttpStatusCode.OK);
var httpClient = new HttpClient(handler);
var dispatcher = new HttpClientEventDispatcher45(httpClient)
{
Logger = _mockLogger.Object,
};
var logEvent = CreateLogEvent();
dispatcher.DispatchEvent(logEvent);
Thread.Sleep(500); // Wait for async dispatch
Assert.AreEqual(1, handler.RequestCount);
_mockLogger.Verify(l => l.Log(LogLevel.ERROR, It.IsAny<string>()), Times.Never);
}
[Test]
public void DispatchEvent_ServerError500_RetriesThreeTimes()
{
var handler = new MockHttpMessageHandler(HttpStatusCode.InternalServerError);
var httpClient = new HttpClient(handler);
var dispatcher = new HttpClientEventDispatcher45(httpClient)
{
Logger = _mockLogger.Object,
};
var logEvent = CreateLogEvent();
dispatcher.DispatchEvent(logEvent);
Thread.Sleep(1500);
Assert.AreEqual(3, handler.RequestCount);
_mockLogger.Verify(
l => l.Log(LogLevel.ERROR, It.Is<string>(s => s.Contains("3 attempt(s)"))),
Times.Once);
}
[Test]
public void DispatchEvent_ClientError400_NoRetry()
{
var handler = new MockHttpMessageHandler(HttpStatusCode.BadRequest);
var httpClient = new HttpClient(handler);
var dispatcher = new HttpClientEventDispatcher45(httpClient)
{
Logger = _mockLogger.Object,
};
var logEvent = CreateLogEvent();
dispatcher.DispatchEvent(logEvent);
Thread.Sleep(500);
Assert.AreEqual(1, handler.RequestCount);
_mockLogger.Verify(l => l.Log(LogLevel.ERROR, It.IsAny<string>()), Times.Once);
}
[Test]
public void DispatchEvent_SucceedsOnSecondAttempt_StopsRetrying()
{
var handler = new MockHttpMessageHandler(new[]
{
HttpStatusCode.InternalServerError,
HttpStatusCode.OK,
});
var httpClient = new HttpClient(handler);
var dispatcher = new HttpClientEventDispatcher45(httpClient)
{
Logger = _mockLogger.Object,
};
var logEvent = CreateLogEvent();
dispatcher.DispatchEvent(logEvent);
Thread.Sleep(1000);
Assert.AreEqual(2, handler.RequestCount);
_mockLogger.Verify(l => l.Log(LogLevel.ERROR, It.IsAny<string>()), Times.Never);
}
[Test]
public void DispatchEvent_ExponentialBackoff_VerifyTiming()
{
var handler =
new MockHttpMessageHandler(HttpStatusCode.InternalServerError, _requestTimestamps);
var httpClient = new HttpClient(handler);
var dispatcher = new HttpClientEventDispatcher45(httpClient)
{
Logger = _mockLogger.Object,
};
var logEvent = CreateLogEvent();
dispatcher.DispatchEvent(logEvent);
Thread.Sleep(1500); // Wait for all retries
Assert.AreEqual(3, _requestTimestamps.Count);
// First retry after ~200ms
var firstDelay = (_requestTimestamps[1] - _requestTimestamps[0]).TotalMilliseconds;
Assert.That(firstDelay, Is.GreaterThanOrEqualTo(180).And.LessThan(350),
$"First retry delay was {firstDelay}ms, expected ~200ms");
// Second retry after ~400ms
var secondDelay = (_requestTimestamps[2] - _requestTimestamps[1]).TotalMilliseconds;
Assert.That(secondDelay, Is.GreaterThanOrEqualTo(380).And.LessThan(550),
$"Second retry delay was {secondDelay}ms, expected ~400ms");
}
private static LogEvent CreateLogEvent()
{
return new LogEvent(
"https://logx.optimizely.com/v1/events",
new Dictionary<string, object>
{
{ "accountId", "12345" },
{ "visitors", new object[] { } },
},
"POST",
new Dictionary<string, string>());
}
/// <summary>
/// Mock HTTP message handler for testing.
/// </summary>
private class MockHttpMessageHandler : HttpMessageHandler
{
private readonly HttpStatusCode[] _statusCodes;
private readonly List<DateTime> _timestamps;
private int _currentIndex;
public MockHttpMessageHandler(HttpStatusCode statusCode,
List<DateTime> timestamps = null
)
: this(new[] { statusCode }, timestamps) { }
public MockHttpMessageHandler(HttpStatusCode[] statusCodes,
List<DateTime> timestamps = null
)
{
_statusCodes = statusCodes;
_timestamps = timestamps;
_currentIndex = 0;
}
public int RequestCount { get; private set; }
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken
)
{
RequestCount++;
_timestamps?.Add(DateTime.Now);
var statusCode = _currentIndex < _statusCodes.Length ?
_statusCodes[_currentIndex] :
_statusCodes[_statusCodes.Length - 1];
_currentIndex++;
var response = new HttpResponseMessage(statusCode)
{
Content = new StringContent("{}"),
};
return Task.FromResult(response);
}
}
}
}
#endif