/
RouteTests.cs
622 lines (517 loc) · 22.7 KB
/
RouteTests.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
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
using System;
using System.Net;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Funq;
using NUnit.Framework;
using ServiceStack.Formats;
using ServiceStack.Host;
using ServiceStack.Host.Handlers;
using ServiceStack.Text;
using ServiceStack.WebHost.Endpoints.Tests.Support.Services;
namespace ServiceStack.WebHost.Endpoints.Tests
{
[TestFixture]
public class RouteTests
{
private RouteAppHost appHost;
[OneTimeSetUp]
public void TestFixtureSetUp()
{
appHost = new RouteAppHost();
appHost.Init();
appHost.Start(Config.AbsoluteBaseUri);
}
[OneTimeTearDown]
public void TestFixtureTearDown()
{
appHost.Dispose();
}
[Test]
public void Can_download_original_route()
{
var response = Config.AbsoluteBaseUri.CombineWith("/custom/foo")
.GetStringFromUrl(responseFilter: httpRes =>
{
Assert.That(httpRes.ContentType.MatchesContentType(MimeTypes.Html));
});
Assert.That(response, Does.StartWith("<!doctype html>"));
}
[Test]
public void Can_download_original_route_with_Accept_json()
{
var response = Config.AbsoluteBaseUri.CombineWith("/custom/foo")
.GetStringFromUrl(
requestFilter: req => req.Accept = MimeTypes.Json,
responseFilter: httpRes =>
{
Assert.That(httpRes.ContentType.MatchesContentType(MimeTypes.Json));
});
Assert.That(response.ToLower(), Is.EqualTo("{\"data\":\"foo\"}"));
}
[Test]
public void Can_download_original_route_with_trailing_slash_and_Accept_json()
{
var response = Config.AbsoluteBaseUri.CombineWith("/custom/foo/")
.GetStringFromUrl(
requestFilter: req => req.Accept = MimeTypes.Json,
responseFilter: httpRes =>
{
Assert.That(httpRes.ContentType.MatchesContentType(MimeTypes.Json));
});
Assert.That(response.ToLower(), Is.EqualTo("{\"data\":\"foo\"}"));
}
[Test]
public void Can_download_original_route_with_json_extension()
{
var response = Config.AbsoluteBaseUri.CombineWith("/custom/foo.json")
.GetStringFromUrl(responseFilter: httpRes =>
{
Assert.That(httpRes.ContentType.MatchesContentType(MimeTypes.Json));
});
Assert.That(response.ToLower(), Is.EqualTo("{\"data\":\"foo\"}"));
}
[Test]
public void Can_process_plaintext_as_JSON()
{
var response = Config.AbsoluteBaseUri.CombineWith("/custom")
.PostStringToUrl("{\"data\":\"foo\"}",
contentType:MimeTypes.PlainText,
responseFilter: httpRes =>
{
Assert.That(httpRes.ContentType.MatchesContentType(MimeTypes.Json));
});
Assert.That(response.ToLower(), Is.EqualTo("{\"data\":\"foo\"}"));
}
[Test]
public void Can_download_original_route_with_xml_extension()
{
var response = Config.AbsoluteBaseUri.CombineWith("/custom/foo.xml")
.GetStringFromUrl(responseFilter: httpRes =>
{
Assert.That(httpRes.ContentType.MatchesContentType(MimeTypes.Xml));
});
Assert.That(response, Is.EqualTo("<?xml version=\"1.0\" encoding=\"utf-8\"?><CustomRoute xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.servicestack.net/types\"><Data>foo</Data></CustomRoute>"));
}
[Test]
public void Can_download_original_route_with_html_extension()
{
var response = Config.AbsoluteBaseUri.CombineWith("/custom/foo.html")
.GetStringFromUrl(responseFilter: httpRes =>
{
Assert.That(httpRes.ContentType.MatchesContentType(MimeTypes.Html));
});
Assert.That(response, Does.StartWith("<!doctype html>"));
}
[Test]
public void Can_download_original_route_with_csv_extension()
{
var response = Config.AbsoluteBaseUri.CombineWith("/custom/foo.csv")
.GetStringFromUrl(responseFilter: httpRes =>
{
Assert.That(httpRes.ContentType.MatchesContentType(MimeTypes.Csv));
});
Assert.That(response, Is.EqualTo("Data\r\nfoo\r\n"));
}
[Test]
public void Does_encode_route_with_backslash()
{
var request = new CustomRoute { Data = "D\\SN" };
Assert.That(request.ToUrl(), Is.EqualTo("/custom/D%5CSN"));
Assert.That(request.ToUrl().UrlDecode(), Is.EqualTo("/custom/D\\SN"));
//HttpListener and ASP.NET hosts doesn't support `\` or %5C in urls
//var client = new JsonServiceClient(Config.AbsoluteBaseUri);
//var response = client.Get(request);
//Assert.That(response.Data, Is.EqualTo("D\\SN"));
}
[Test]
public void Can_download_route_with_dot_seperator()
{
var response = Config.AbsoluteBaseUri.CombineWith("/customdot/id.data")
.GetJsonFromUrl()
.FromJson<CustomRouteDot>();
Assert.That(response.Id, Is.EqualTo("id"));
Assert.That(response.Data, Is.EqualTo("data"));
}
[Test]
public void Can_download_route_with_dot_seperator_and_extension()
{
var response = Config.AbsoluteBaseUri.CombineWith("/pics/100x100/1.png")
.GetJsonFromUrl()
.FromJson<GetPngPic>();
Assert.That(response.Size, Is.EqualTo("100x100"));
Assert.That(response.Id, Is.EqualTo("1"));
}
[Test]
public void Can_download_route_with_dot_seperator_and_extension_with_jsonserviceclient()
{
var client = new JsonServiceClient(Config.AbsoluteBaseUri);
var request = new GetPngPic {
Id = "1",
Size = "100x100",
};
Assert.That(request.ToGetUrl(), Is.EqualTo("/pics/100x100/1.png"));
var response = client.Get<GetPngPic>(request);
Assert.That(response.Size, Is.EqualTo("100x100"));
Assert.That(response.Id, Is.EqualTo("1"));
}
[Test]
public void Does_populate_version_when_using_Version_Abbreviation()
{
var response = Config.AbsoluteBaseUri.CombineWith("/versioned-request?v=1")
.GetJsonFromUrl()
.FromJson<RequestWithVersion>();
Assert.That(response.Version, Is.EqualTo(1));
response = Config.AbsoluteBaseUri.CombineWith("/versioned-request/1?v=2")
.GetJsonFromUrl()
.FromJson<RequestWithVersion>();
Assert.That(response.Version, Is.EqualTo(2));
response = Config.AbsoluteBaseUri.CombineWith("/versioned-request/1?v=4&Version=3")
.GetJsonFromUrl()
.FromJson<RequestWithVersion>();
Assert.That(response.Version, Is.EqualTo(3));
}
[Test]
public async Task Does_send_version_using_JsonServiceClient()
{
var client = new JsonServiceClient(Config.AbsoluteBaseUri);
var response = client.Send(new RequestWithVersion { Version = 1 });
Assert.That(response.Version, Is.EqualTo(1));
response = await client.SendAsync(new RequestWithVersion { Version = 1 });
Assert.That(response.Version, Is.EqualTo(1));
client.Version = 1;
response = client.Send(new RequestWithVersion());
Assert.That(response.Version, Is.EqualTo(1));
response = await client.SendAsync(new RequestWithVersion());
Assert.That(response.Version, Is.EqualTo(1));
}
[Test]
public async Task Does_send_version_using_JsonHttpClient()
{
var client = new JsonHttpClient(Config.AbsoluteBaseUri);
var response = client.Send(new RequestWithVersion { Version = 1 });
Assert.That(response.Version, Is.EqualTo(1));
response = await client.SendAsync(new RequestWithVersion { Version = 1 });
Assert.That(response.Version, Is.EqualTo(1));
client.Version = 1;
response = client.Send(new RequestWithVersion());
Assert.That(response.Version, Is.EqualTo(1));
response = await client.SendAsync(new RequestWithVersion());
Assert.That(response.Version, Is.EqualTo(1));
}
[Test]
public async Task Can_POST_to_IdWithAlias_with_JsonServiceClient_async()
{
var client = new JsonServiceClient(Config.AbsoluteBaseUri);
var response = await client.PostAsync(new IdWithAlias { Id = 1 });
Assert.That(response.Id, Is.EqualTo(1));
}
[Test]
public async Task Can_POST_to_IdWithAlias_with_JsonHttpClient_async()
{
var client = new JsonHttpClient(Config.AbsoluteBaseUri);
var response = await client.PostAsync(new IdWithAlias { Id = 1 });
Assert.That(response.Id, Is.EqualTo(1));
}
[Test]
public void Can_create_request_DTO_from_URL()
{
Assert.That(HostContext.Metadata.CreateRequestFromUrl("/hello") is Hello);
var request = (Hello)HostContext.Metadata.CreateRequestFromUrl("/hello/foo");
Assert.That(request.Name, Is.EqualTo("foo"));
request = (Hello)HostContext.Metadata.CreateRequestFromUrl("http://domain.org/hello/foo");
Assert.That(request.Name, Is.EqualTo("foo"));
request = (Hello)HostContext.Metadata.CreateRequestFromUrl("https://www.sub.domain.org/hello/foo");
Assert.That(request.Name, Is.EqualTo("foo"));
request = (Hello)HostContext.Metadata.CreateRequestFromUrl("/hello?name=bar");
Assert.That(request.Name, Is.EqualTo("bar"));
var responseType = HostContext.Metadata.GetResponseTypeByRequest(request.GetType());
Assert.That(responseType, Is.EqualTo(typeof(HelloResponse)));
request = (Hello)HostContext.Metadata.CreateRequestFromUrl("/hello?name=gateway");
var response = (HelloResponse)HostContext.AppHost.GetServiceGateway(new BasicRequest()).Send(responseType, request);
Assert.That(response.Result, Is.EqualTo("Hello, gateway"));
}
}
public class RouteAppHost : AppHostHttpListenerBase
{
public RouteAppHost() : base(typeof(BufferedRequestTests).Name, typeof(CustomRouteService).Assembly) { }
public override void Configure(Container container)
{
SetConfig(new HostConfig
{
AllowRouteContentTypeExtensions = true
});
Plugins.Add(new CsvFormat()); //required to allow .csv
ContentTypes.Register(MimeTypes.PlainText,
(req, o, stream) => JsonSerializer.SerializeToStream(o.GetType(), stream),
JsonSerializer.DeserializeFromStream);
PreRequestFilters.Add((req, res) => {
if (req.ContentType.MatchesContentType(MimeTypes.PlainText))
req.ResponseContentType = MimeTypes.Json;
});
}
}
[Route("/custom")]
[Route("/custom/{Data}")]
public class CustomRoute : IReturn<CustomRoute>
{
public string Data { get; set; }
}
[Route("/customdot/{Id}.{Data}")]
public class CustomRouteDot : IReturn<CustomRouteDot>
{
public string Id { get; set; }
public string Data { get; set; }
}
[Route("/pics/{Size}/{Id}.png", "GET")]
public class GetPngPic
{
public string Id { get; set; }
public string Size { get; set; }
}
[Route("/versioned-request")]
[Route("/versioned-request/{Id}")]
public class RequestWithVersion : IReturn<RequestWithVersion>, IHasVersion
{
public int Id { get; set; }
public int Version { get; set; }
}
[Route("/thing/{Id}/point", "POST")]
[DataContract]
public class IdWithAlias : IReturn<IdWithAlias>
{
[DataMember(Name = "id")]
public int Id { get; set; }
}
public class CustomRouteService : IService
{
public object Any(CustomRoute request) => request;
public object Any(CustomRouteDot request) => request;
public object Any(GetPngPic request) => request;
public object Any(RequestWithVersion request) => request;
public object Any(IdWithAlias request) => request;
}
[TestFixture]
public class ModifiedRouteTests
{
private ModifiedRouteAppHost appHost;
[OneTimeSetUp]
public void TestFixtureSetUp()
{
appHost = new ModifiedRouteAppHost();
appHost.Init();
appHost.Start(Config.AbsoluteBaseUri);
// appHost.Start(Config.AnyHostBaseUrl); //go through fiddler
}
[OneTimeTearDown]
public void TestFixtureTearDown()
{
appHost.Dispose();
}
[Test]
public void Does_URL_Decode_PathInfo()
{
var client = new JsonServiceClient(Config.HostNameBaseUrl);
// var client = new JsonServiceClient("http://test.servicestack.net");
var pathInfo = "ern::Closer2U::Userprofile::1c7e9ead-c7d9-46f8-a0cc-2777c4373ac4";
var response = client.Get(new CustomRoute {
Data = pathInfo
});
Assert.That(response.Data, Is.EqualTo(pathInfo));
}
[Test]
public void Can_download_modified_routes()
{
try
{
var notFound = Config.AbsoluteBaseUri.CombineWith("/modified/foo.csv")
.GetStringFromUrl();
Assert.Fail("Existing route should be modified");
}
catch (WebException ex)
{
Assert.That(ex.GetStatus(), Is.EqualTo(HttpStatusCode.NotFound));
}
var response = Config.AbsoluteBaseUri.CombineWith("/api/modified/foo.csv")
.GetStringFromUrl();
Assert.That(response, Is.EqualTo("Data\r\nfoo\r\n"));
}
}
public class ModifiedRouteAppHost : AppHostHttpListenerBase
{
public ModifiedRouteAppHost() : base(typeof(BufferedRequestTests).Name, typeof(CustomRouteService).Assembly) { }
public override void Configure(Container container)
{
}
public override RouteAttribute[] GetRouteAttributes(System.Type requestType)
{
var routes = base.GetRouteAttributes(requestType);
if (requestType != typeof(ModifiedRoute)) return routes;
routes.Each(x => x.Path = "/api" + x.Path);
return routes;
}
}
[Route("/modified")]
[Route("/modified/{Data}")]
public class ModifiedRoute : IReturn<ModifiedRoute>
{
public string Data { get; set; }
}
public class ModifiedRouteService : IService
{
public object Any(ModifiedRoute request)
{
return request;
}
}
[TestFixture]
public class InvalidRouteTests
{
public class UnknownRoute { }
class InvalidRoutesAppHost : AppSelfHostBase
{
public InvalidRoutesAppHost() : base(typeof(InvalidRoutesAppHost).Name, typeof(InvalidRoutesAppHost).Assembly) { }
public override void Configure(Container container)
{
Routes.Add<UnknownRoute>("/unknownroute");
}
}
[Test]
public void Throws_error_when_registering_route_for_unknown_Service()
{
using (var appHost = new InvalidRoutesAppHost()
.Init()
.Start(Config.AbsoluteBaseUri))
{
try
{
var json = Config.AbsoluteBaseUri.CombineWith("/unknownroute").GetJsonFromUrl();
Assert.Fail("Should throw");
}
catch (WebException ex)
{
Assert.That(ex.GetStatus(), Is.EqualTo(HttpStatusCode.MethodNotAllowed));
}
}
}
}
[Route("/routeinfo/{Path*}")]
public class GetRouteInfo
{
public string Path { get; set; }
}
public class GetRouteInfoResponse
{
public string BaseUrl { get; set; }
public string ResolvedUrl { get; set; }
}
public class RouteInfoService : Service
{
public object Any(GetRouteInfo request)
{
return new GetRouteInfoResponse
{
BaseUrl = base.Request.GetBaseUrl(),
ResolvedUrl = base.Request.ResolveAbsoluteUrl("~/resolved")
};
}
}
class RouteInfoAppHost : AppSelfHostBase
{
public RouteInfoAppHost() : base(typeof(RouteInfoAppHost).Name, typeof(RouteInfoAppHost).Assembly) { }
public override void Configure(Container container)
{
CatchAllHandlers.Add((httpMethod, pathInfo, filePath) =>
{
if (pathInfo.StartsWith("/swagger-ui"))
{
return new CustomResponseHandler((req, res) =>
new GetRouteInfoResponse
{
BaseUrl = req.GetBaseUrl(),
ResolvedUrl = req.ResolveAbsoluteUrl("~/resolved")
});
}
return null;
});
}
}
public class RouteInfoPathTests
{
[Test]
public void RootPath_returns_BaseUrl()
{
var url = Config.ServiceStackBaseUri;
using (var appHost = new RouteInfoAppHost()
.Init()
.Start(url + "/"))
{
var response = url.CombineWith("/routeinfo").GetJsonFromUrl().FromJson<GetRouteInfoResponse>();
Assert.That(response.BaseUrl, Is.EqualTo(url));
Assert.That(response.ResolvedUrl, Is.EqualTo(url.AppendPath("resolved")));
response = url.CombineWith("/routeinfo/dir").GetJsonFromUrl().FromJson<GetRouteInfoResponse>();
Assert.That(response.BaseUrl, Is.EqualTo(url));
Assert.That(response.ResolvedUrl, Is.EqualTo(url.AppendPath("resolved")));
response = url.CombineWith("/routeinfo/dir/sub").GetJsonFromUrl().FromJson<GetRouteInfoResponse>();
Assert.That(response.BaseUrl, Is.EqualTo(url));
Assert.That(response.ResolvedUrl, Is.EqualTo(url.AppendPath("resolved")));
response = url.CombineWith("/swagger-ui").GetJsonFromUrl().FromJson<GetRouteInfoResponse>();
Assert.That(response.BaseUrl, Is.EqualTo(url));
Assert.That(response.ResolvedUrl, Is.EqualTo(url.AppendPath("resolved")));
response = url.CombineWith("/swagger-ui/").GetJsonFromUrl().FromJson<GetRouteInfoResponse>();
Assert.That(response.BaseUrl, Is.EqualTo(url));
Assert.That(response.ResolvedUrl, Is.EqualTo(url.AppendPath("resolved")));
}
}
[Test]
public void ApiPath_returns_BaseUrl()
{
var url = Config.AbsoluteBaseUri.AppendPath("api");
using (var appHost = new RouteInfoAppHost()
.Init()
.Start(url + "/"))
{
var response = url.CombineWith("/routeinfo").GetJsonFromUrl().FromJson<GetRouteInfoResponse>();
Assert.That(response.BaseUrl, Is.EqualTo(url));
Assert.That(response.ResolvedUrl, Is.EqualTo(url.AppendPath("resolved")));
response = url.CombineWith("/routeinfo/dir").GetJsonFromUrl().FromJson<GetRouteInfoResponse>();
Assert.That(response.BaseUrl, Is.EqualTo(url));
Assert.That(response.ResolvedUrl, Is.EqualTo(url.AppendPath("resolved")));
response = url.CombineWith("/routeinfo/dir/sub").GetJsonFromUrl().FromJson<GetRouteInfoResponse>();
Assert.That(response.BaseUrl, Is.EqualTo(url));
Assert.That(response.ResolvedUrl, Is.EqualTo(url.AppendPath("resolved")));
response = url.CombineWith("/swagger-ui").GetJsonFromUrl().FromJson<GetRouteInfoResponse>();
Assert.That(response.BaseUrl, Is.EqualTo(url));
Assert.That(response.ResolvedUrl, Is.EqualTo(url.AppendPath("resolved")));
response = url.CombineWith("/swagger-ui/").GetJsonFromUrl().FromJson<GetRouteInfoResponse>();
Assert.That(response.BaseUrl, Is.EqualTo(url));
Assert.That(response.ResolvedUrl, Is.EqualTo(url.AppendPath("resolved")));
}
}
[Test]
public void ApiV1Path_returns_BaseUrl()
{
var url = Config.AbsoluteBaseUri.AppendPath("api").AppendPath("v1");
using (var appHost = new RouteInfoAppHost()
.Init()
.Start(url + "/"))
{
var response = url.CombineWith("/routeinfo").GetJsonFromUrl().FromJson<GetRouteInfoResponse>();
Assert.That(response.BaseUrl, Is.EqualTo(url));
Assert.That(response.ResolvedUrl, Is.EqualTo(url.AppendPath("resolved")));
response = url.CombineWith("/routeinfo/dir").GetJsonFromUrl().FromJson<GetRouteInfoResponse>();
Assert.That(response.BaseUrl, Is.EqualTo(url));
Assert.That(response.ResolvedUrl, Is.EqualTo(url.AppendPath("resolved")));
response = url.CombineWith("/routeinfo/dir/sub").GetJsonFromUrl().FromJson<GetRouteInfoResponse>();
Assert.That(response.BaseUrl, Is.EqualTo(url));
Assert.That(response.ResolvedUrl, Is.EqualTo(url.AppendPath("resolved")));
response = url.CombineWith("/swagger-ui").GetJsonFromUrl().FromJson<GetRouteInfoResponse>();
Assert.That(response.BaseUrl, Is.EqualTo(url));
Assert.That(response.ResolvedUrl, Is.EqualTo(url.AppendPath("resolved")));
response = url.CombineWith("/swagger-ui/").GetJsonFromUrl().FromJson<GetRouteInfoResponse>();
Assert.That(response.BaseUrl, Is.EqualTo(url));
Assert.That(response.ResolvedUrl, Is.EqualTo(url.AppendPath("resolved")));
}
}
}
}