forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCacheServerFeatureTests.cs
More file actions
446 lines (376 loc) · 14.5 KB
/
CacheServerFeatureTests.cs
File metadata and controls
446 lines (376 loc) · 14.5 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
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
using System;
using Funq;
using NUnit.Framework;
using ServiceStack.Caching;
namespace ServiceStack.WebHost.Endpoints.Tests
{
[TestFixture]
public class CacheServerFeatureTests
{
class AppHost : AppSelfHostBase
{
public AppHost()
: base(typeof(CacheServerFeatureTests).Name, typeof(CacheEtagServices).GetAssembly())
{ }
public override void Configure(Container container) { }
}
private readonly ServiceStackHost appHost;
public CacheServerFeatureTests()
{
appHost = new AppHost()
.Init()
.Start(Config.ListeningOn);
}
[OneTimeTearDown]
public void TestFixtureTearDown()
{
appHost.Dispose();
}
[TearDown]
public void TearDown()
{
//clear cache after each test
var cache = appHost.TryResolve<ICacheClient>();
cache.FlushAll();
}
protected JsonServiceClient GetClient()
{
var client = new JsonServiceClient(Config.ListeningOn);
#if NETCORE
client.AddHeader(HttpHeaders.AcceptEncoding, "gzip,deflate");
#endif
return client;
}
[Test]
public void Does_set_Etag_and_Default_MaxAge()
{
var client = GetClient();
client.ResponseFilter = res =>
{
Assert.That(res.Headers[HttpHeaders.ETag], Is.EqualTo("etag".Quoted()));
Assert.That(res.Headers[HttpHeaders.CacheControl], Is.EqualTo("max-age=600"));
};
var request = new SetCache { ETag = "etag" };
var response = client.Get(request);
Assert.That(response, Is.EqualTo(request));
}
[Test]
public void Does_not_set_Etag_and_Default_MaxAge_on_POST()
{
var client = GetClient();
client.ResponseFilter = res =>
{
Assert.That(res.Headers[HttpHeaders.ETag], Is.Null);
Assert.That(res.Headers[HttpHeaders.CacheControl], Is.Null);
};
var request = new SetCache { ETag = "etag" };
var response = client.Post(request);
Assert.That(response, Is.EqualTo(request));
}
[Test]
public void Does_set_LastModified_and_Default_MaxAge()
{
var client = GetClient();
var request = new SetCache { LastModified = new DateTime(2016, 1, 1, 0, 0, 0) };
client.ResponseFilter = res =>
{
Assert.That(res.Headers[HttpHeaders.LastModified], Is.EqualTo(request.LastModified.Value.ToUniversalTime().ToString("r")));
Assert.That(res.Headers[HttpHeaders.CacheControl], Is.EqualTo("max-age=600"));
};
var response = client.Get(request);
Assert.That(response, Is.EqualTo(request));
}
[Test]
public void Does_set_Etag_MaxAge_and_CacheControl()
{
var client = GetClient();
client.ResponseFilter = res =>
{
Assert.That(res.Headers[HttpHeaders.Age], Is.EqualTo("864000"));
Assert.That(res.Headers[HttpHeaders.ETag], Is.EqualTo("etag".Quoted()));
Assert.That(res.Headers[HttpHeaders.CacheControl], Is.EqualTo("max-age=86400, public, must-revalidate, no-store")
.Or.EqualTo("no-store, public, must-revalidate, max-age=86400"));
};
var request = new SetCache
{
ETag = "etag",
Age = TimeSpan.FromDays(10),
MaxAge = TimeSpan.FromDays(1),
CacheControl = CacheControl.Public | CacheControl.NoStore | CacheControl.MustRevalidate,
};
var response = client.Get(request);
Assert.That(response, Is.EqualTo(request));
}
[Test]
public void Does_throw_304_when_etag_matches()
{
var client = GetClient();
client.RequestFilter = req =>
req.Headers[HttpHeaders.IfNoneMatch] = "etag".Quoted();
client.ResponseFilter = res =>
Assert.That(res.ContentLength, Is.EqualTo(0));
try
{
var response = client.Get(new SetCache { ETag = "etag" });
Assert.Fail("Should throw 304 NotModified");
}
catch (Exception ex)
{
if (!ex.IsNotModified())
throw;
}
}
[Test]
public void Returns_response_when_etag_does_not_match()
{
var client = GetClient();
client.RequestFilter = req =>
req.Headers[HttpHeaders.IfNoneMatch] = "etag".Quoted();
client.ResponseFilter = res =>
{
Assert.That(res.Headers[HttpHeaders.ETag], Is.EqualTo("etag-alt".Quoted()));
Assert.That(res.Headers[HttpHeaders.CacheControl], Is.EqualTo("max-age=600"));
};
var request = new SetCache { ETag = "etag-alt" };
var response = client.Get(request);
Assert.That(response, Is.EqualTo(request));
}
[Test]
public void Does_throw_304_when_not_ModifiedSince()
{
var client = GetClient();
var request = new SetCache { LastModified = new DateTime(2016, 1, 1, 0, 0, 0) };
client.RequestFilter = req =>
PclExportClient.Instance.SetIfModifiedSince(req, request.LastModified.Value);
client.ResponseFilter = res =>
{
Assert.That(res.ContentLength, Is.EqualTo(0));
Assert.That(res.Headers[HttpHeaders.CacheControl], Is.EqualTo("max-age=3600"));
};
try
{
var response = client.Get(request);
Assert.Fail("Should throw 304 NotModified");
}
catch (Exception ex)
{
if (!ex.IsNotModified())
throw;
}
}
[Test]
public void Returns_response_when_ModifiedSince_LastModified()
{
var client = GetClient();
var request = new SetCache { LastModified = new DateTime(2016, 1, 1, 0, 0, 0) };
client.RequestFilter = req =>
PclExportClient.Instance.SetIfModifiedSince(req, request.LastModified.Value + TimeSpan.FromSeconds(-1));
client.ResponseFilter = res =>
Assert.That(res.Headers[HttpHeaders.CacheControl], Is.EqualTo("max-age=600"));
var response = client.Get(request);
Assert.That(response, Is.EqualTo(request));
}
[Test]
public void Can_short_circuit_Service_implementation_when_ETag_matches()
{
var client = GetClient();
client.RequestFilter = req =>
req.Headers[HttpHeaders.IfNoneMatch] = "etag".Quoted();
client.ResponseFilter = res =>
{
Assert.That(res.ContentLength, Is.EqualTo(0));
Assert.That(res.Headers[HttpHeaders.Age], Is.Null); //short-circuit
};
try
{
var response = client.Get(new ShortCircuitImpl { ETag = "etag", Age = TimeSpan.FromDays(1) });
Assert.Fail("Should throw 304 NotModified");
}
catch (Exception ex)
{
if (!ex.IsNotModified())
throw;
}
}
[Test]
public void Does_bypass_short_circuit_Service_implementation_when_ETag_not_matches()
{
var client = GetClient();
client.RequestFilter = req =>
req.Headers[HttpHeaders.IfNoneMatch] = "etag".Quoted();
client.ResponseFilter = res =>
Assert.That(res.Headers[HttpHeaders.Age], Is.EqualTo("86400"));
var request = new ShortCircuitImpl
{
ETag = "etag-alt",
Age = TimeSpan.FromDays(1)
};
var response = client.Get(request);
Assert.That(response, Is.EqualTo(request));
}
[Test]
public void ToOptimizedResult_does_populate_LastModified()
{
var client = GetClient();
client.ResponseFilter = res =>
Assert.That(DateTime.Parse(res.Headers[HttpHeaders.LastModified]).ToUniversalTime(),
Is.EqualTo(DateTime.UtcNow).Within(TimeSpan.FromMinutes(1)));
var request = new CachedRequest { ETag = "etag" };
var response = client.Get(request);
Assert.That(response, Is.EqualTo(request));
response = client.Get(request);
Assert.That(response, Is.EqualTo(request));
}
[Test]
public void ToOptimizedResult_throws_304_when_not_ModifiedSince()
{
var client = GetClient();
DateTime? lastModified = null;
client.ResponseFilter = res =>
lastModified = DateTime.Parse(res.Headers[HttpHeaders.LastModified]);
var request = new CachedRequest { Age = TimeSpan.FromHours(1) };
var response = client.Get(request);
Assert.That(response, Is.EqualTo(request));
try
{
client.RequestFilter = req =>
PclExportClient.Instance.SetIfModifiedSince(req, lastModified.Value);
response = client.Get(request);
Assert.Fail("Should throw 304 NotModified");
}
catch (Exception ex)
{
if (!ex.IsNotModified())
throw;
}
}
[Test]
public void CachedServiceClient_does_return_cached_ETag_Requests()
{
var client = new CachedServiceClient(GetClient());
var request = new SetCache { ETag = "etag" };
var response = client.Get(request);
Assert.That(client.CacheHits, Is.EqualTo(0));
Assert.That(response, Is.EqualTo(request));
response = client.Get(request);
Assert.That(client.CacheHits, Is.EqualTo(1));
Assert.That(response, Is.EqualTo(request));
}
}
public abstract class CacheRequestBase
{
public string ETag { get; set; }
public TimeSpan? Age { get; set; }
public TimeSpan? MaxAge { get; set; }
public DateTime? Expires { get; set; }
public DateTime? LastModified { get; set; }
public CacheControl? CacheControl { get; set; }
public bool Equals(CacheRequestBase other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return string.Equals(ETag, other.ETag)
&& MaxAge.Equals(other.MaxAge)
&& Expires.Equals(other.Expires)
&& LastModified.Equals(other.LastModified)
&& CacheControl == other.CacheControl;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((SetCache)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = (ETag != null ? ETag.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ MaxAge.GetHashCode();
hashCode = (hashCode * 397) ^ Expires.GetHashCode();
hashCode = (hashCode * 397) ^ LastModified.GetHashCode();
hashCode = (hashCode * 397) ^ CacheControl.GetHashCode();
return hashCode;
}
}
}
[Route("/set-cache")]
public class SetCache : CacheRequestBase, IReturn<SetCache>, IEquatable<SetCache>
{
public bool Equals(SetCache other)
{
return base.Equals(other);
}
}
public class ShortCircuitImpl : CacheRequestBase, IReturn<ShortCircuitImpl>, IEquatable<ShortCircuitImpl>
{
public bool Equals(ShortCircuitImpl other)
{
return base.Equals(other);
}
}
public class CachedRequest : CacheRequestBase, IReturn<CachedRequest>, IEquatable<CachedRequest>
{
public bool Equals(CachedRequest other)
{
return base.Equals(other);
}
}
public class FailsAfterOnce : CacheRequestBase, IReturn<FailsAfterOnce>, IEquatable<FailsAfterOnce>
{
internal static int Count = 0;
public bool Equals(FailsAfterOnce other)
{
return base.Equals(other);
}
}
public class CacheEtagServices : Service
{
public object Any(SetCache request)
{
return new HttpResult(request)
{
Age = request.Age,
ETag = request.ETag,
MaxAge = request.MaxAge,
Expires = request.Expires,
LastModified = request.LastModified,
CacheControl = request.CacheControl.GetValueOrDefault(CacheControl.None),
};
}
public object Any(ShortCircuitImpl request)
{
if (Request.HasValidCache(request.ETag, request.LastModified))
return HttpResult.NotModified();
return new HttpResult(request)
{
Age = request.Age,
ETag = request.ETag,
MaxAge = request.MaxAge,
Expires = request.Expires,
LastModified = request.LastModified,
CacheControl = request.CacheControl.GetValueOrDefault(CacheControl.None),
};
}
public object Any(CachedRequest request)
{
var cacheKey = Request.QueryString.ToString();
return Request.ToOptimizedResultUsingCache(Cache, cacheKey, () => request);
}
public object Any(FailsAfterOnce request)
{
if (FailsAfterOnce.Count++ > 0)
throw new Exception("Can only be called once");
return new HttpResult(request)
{
Age = request.Age,
ETag = request.ETag,
MaxAge = request.MaxAge,
Expires = request.Expires,
LastModified = request.LastModified,
CacheControl = request.CacheControl.GetValueOrDefault(CacheControl.None),
};
}
}
}