summaryrefslogtreecommitdiffstats
path: root/src/DotNetOpenAuth.Test/MockingHostFactories.cs
blob: d9f6b02cb7a09928bf402b78d343d991ee88a6bc (plain)
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
//-----------------------------------------------------------------------
// <copyright file="MockingHostFactories.cs" company="Andrew Arnott">
//     Copyright (c) Andrew Arnott. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace DotNetOpenAuth.Test {
	using System.Collections.Generic;
	using System.Net;
	using System.Net.Http;
	using System.Threading;
	using System.Threading.Tasks;
	using System.Linq;
	using Validation;

	internal class MockingHostFactories : IHostFactories {
		private readonly List<TestBase.Handler> handlers;

		public MockingHostFactories(List<TestBase.Handler> handlers = null) {
			this.handlers = handlers ?? new List<TestBase.Handler>();
			this.CookieContainer = new CookieContainer();
			this.AllowAutoRedirects = true;
		}

		public List<TestBase.Handler> Handlers {
			get { return this.handlers; }
		}

		public CookieContainer CookieContainer { get; set; }

		public bool AllowAutoRedirects { get; set; }

		public HttpMessageHandler CreateHttpMessageHandler() {
			var forwardingMessageHandler = new ForwardingMessageHandler(this.handlers, this);
			var cookieDelegatingHandler = new CookieDelegatingHandler(forwardingMessageHandler, this.CookieContainer);
			if (this.AllowAutoRedirects) {
				return new AutoRedirectHandler(cookieDelegatingHandler);
			} else {
				return cookieDelegatingHandler;
			}
		}

		public HttpClient CreateHttpClient(HttpMessageHandler handler = null) {
			return new HttpClient(handler ?? this.CreateHttpMessageHandler());
		}

		private class ForwardingMessageHandler : HttpMessageHandler {
			private readonly IEnumerable<TestBase.Handler> handlers;

			private readonly IHostFactories hostFactories;

			public ForwardingMessageHandler(IEnumerable<TestBase.Handler> handlers, IHostFactories hostFactories) {
				Requires.NotNull(handlers, "handlers");

				this.handlers = handlers;
				this.hostFactories = hostFactories;
			}

			protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
				foreach (var handler in this.handlers) {
					if (handler.Uri.IsBaseOf(request.RequestUri) && handler.Uri.AbsolutePath == request.RequestUri.AbsolutePath) {
						var response = await handler.MessageHandler(request);
						if (response != null) {
							if (response.RequestMessage == null) {
								response.RequestMessage = request;
							}

							return response;
						}
					}
				}

				return new HttpResponseMessage(HttpStatusCode.NotFound);
			}
		}
	}
}