using System; using System.Net.WebSockets; using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace k8s.Tests.Mock.Server { /// /// Adapter used to capture WebSockets accepted by the test server and provide them to calling test. /// /// /// Each AcceptedXXXConnection property returns an awaitable object that yields a the server-side WebSocket once a connection has been accepted. /// /// All server-side WebSockets will be closed when is called. /// public class WebSocketTestAdapter { /// /// Completion source for the task. /// private readonly TaskCompletionSource _testCompletion = new TaskCompletionSource(); /// /// A that completes when the test is complete (providing is called). /// public Task TestCompleted => _testCompletion.Task; /// /// await server-side acceptance of a WebSocket connection for the exec-in-pod (v1) API. /// public ServerSocketAcceptance AcceptedPodExecV1Connection { get; } = new ServerSocketAcceptance(); /// /// await server-side acceptance of a WebSocket connection for the pod-port-forward (v1) API. /// public ServerSocketAcceptance AcceptedPodPortForwardV1Connection { get; } = new ServerSocketAcceptance(); /// /// Mark the current test as complete, closing all server-side sockets. /// public void CompleteTest() => _testCompletion.SetResult(true); /// /// An object that enables awaiting server-side acceptance of a WebSocket connection. /// /// /// Simply await this object to wait for the server socket to be accepted. /// public class ServerSocketAcceptance { /// /// Completion source for the task. /// private readonly TaskCompletionSource _completion = new TaskCompletionSource(); /// /// A that completes when the server accepts a WebSocket connection (i.e. when or is called). /// public Task Task => _completion.Task; /// /// Notify the calling test that the server has accepted a WebSocket connection. /// /// /// The server-side . /// public void AcceptServerSocket(WebSocket serverSocket) { if (serverSocket == null) { throw new ArgumentNullException(nameof(serverSocket)); } _completion.SetResult(serverSocket); } /// /// Notify the calling test that the server has rejected a WebSocket connection. /// /// /// An representing the reason that the connection was rejected. /// public void RejectServerSocket(Exception reason) { if (reason == null) { throw new ArgumentNullException(nameof(reason)); } _completion.SetException(reason); } /// /// Get an awaiter for the socket-acceptance task. /// /// /// The . /// public TaskAwaiter GetAwaiter() => Task.GetAwaiter(); } } }