Esempio n. 1
0
        internal protected override Task <HttpResponse> HandleRequest(
            TestContext ctx, HttpOperation operation, HttpConnection connection, HttpRequest request,
            RequestFlags effectiveFlags, CancellationToken cancellationToken)
        {
            var keepAlive = (effectiveFlags & (RequestFlags.KeepAlive | RequestFlags.CloseConnection)) == RequestFlags.KeepAlive;

            var redirect = operation.RegisterRedirect(ctx, Target);
            var response = HttpResponse.CreateRedirect(Code, redirect.Uri);

            if (keepAlive)
            {
                response.KeepAlive = true;
            }

            if (operation.HasAnyFlags(HttpOperationFlags.ClientDoesNotSendRedirect))
            {
                redirect.Listener.UnregisterOperation(redirect);
            }
            else
            {
                response.Redirect = redirect;
            }

            return(Task.FromResult(response));
        }
Esempio n. 2
0
        public override async Task Initialize(TestContext ctx, HttpOperation operation, CancellationToken cancellationToken)
        {
            remoteEndPoint = (IPEndPoint)Socket.RemoteEndPoint;
            ctx.LogDebug(5, $"{ME} INITIALIZE: {ListenSocket?.LocalEndPoint} {remoteEndPoint} {operation?.ME}");
            if (operation != null)
            {
                networkStream = operation.CreateNetworkStream(ctx, Socket, true);
            }
            if (networkStream == null)
            {
                networkStream = new NetworkStream(Socket, true);
            }

            if (Server.SslStreamProvider != null)
            {
                sslStream = await CreateSslStream(ctx, networkStream, cancellationToken).ConfigureAwait(false);

                Stream = sslStream;
            }
            else
            {
                Stream = networkStream;
            }

            reader = new HttpStreamReader(Stream);
            ctx.LogDebug(5, $"{ME} INITIALIZE DONE: {ListenSocket?.LocalEndPoint} {remoteEndPoint}");
        }
Esempio n. 3
0
 public override void CheckFaults(HttpOperation operation, HttpResponse response)
 {
     if (!response.Is2XX && !response.Is100)
     {
         operation.Fault("Response status code is not 100, 200-299.");
     }
 }
        private static IEnumerable <JProperty> GetRequestProperties(HttpOperation operation)
        {
            if (string.IsNullOrWhiteSpace(operation.Description) == false)
            {
                yield return(new JProperty("description", operation.Description));
            }

            var request = operation.Request;

            yield return(new JProperty("method", request.GetRequestFullMethod()));

            var headers = request.GetAllHeaders(operation.TestServer.HttpClient.DefaultRequestHeaders);

            if (headers.Count > 0)
            {
                yield return(new JProperty("headers", new JObject(headers.Select(GetHeader))));
            }

            var requestJson = request.Content.ReadJson();

            if (requestJson != null)
            {
                yield return(new JProperty("body", requestJson));
            }
        }
        public override Result Assert(HttpOperation operation)
        {
            var current = GeneratePattern(operation);

            if (_savedPattern == null)
            {
                SaveNewPattern(current);
                return(Ok);
            }

            var patterns = new JsonComparer(_savedPattern, current, _ignore);

            if (operation.TestServer.Repair && patterns.AreEquivalent == false)
            {
                SaveNewPattern(current);
                return(Ok);
            }

            if (patterns.AreEquivalent)
            {
                return(Ok);
            }

            return(Failure($"Operation is different than expected. \nVerify the differences: \n\n{patterns.GetDifferences()}"));
        }
 public virtual object OnResponseApplyConverters(object value, HttpOperation operation, FieldInfo fi)
 {
     if (Converters != null)
     {
         Type[] converters = Converters;
         foreach (Type type in converters)
         {
             IValueConverter valueConverter = Activator.CreateInstance(type) as IValueConverter;
             if (valueConverter == null)
             {
                 operation.Log("(HttpMappedValueAttribute)(OnResponseApplyConverters) Converter '" + type.FullName + "' must implement IValueConverter!", LogSeverity.ERROR);
                 continue;
             }
             bool successful = false;
             value = valueConverter.Convert(value, fi, out successful, null);
             if (successful)
             {
                 operation.Log("(HttpMappedValueAttribute)(OnResponseApplyConverters) Converter '" + type.FullName + "' applied.  Output type is " + ((value != null) ? ("'" + value.GetType().FullName + "'") : "(unknown) because @value is null") + ".", LogSeverity.VERBOSE);
             }
             else
             {
                 operation.Log("(HttpMappedValueAttribute)(OnResponseApplyConverters) Converter '" + type.FullName + "' failed!", LogSeverity.WARNING);
             }
         }
     }
     return(value);
 }
Esempio n. 7
0
        async Task <bool> ReuseConnection(TestContext ctx, HttpOperation operation, CancellationToken cancellationToken)
        {
            var me = $"{ME}({connection.ME}) REUSE";

            ctx.LogDebug(2, $"{me}");

            cancellationToken.ThrowIfCancellationRequested();
            var reusable = await connection.ReuseConnection(ctx, cancellationToken).ConfigureAwait(false);

            ctx.LogDebug(2, $"{me} #1: {reusable}");

            if (reusable && (operation?.HasAnyFlags(HttpOperationFlags.ClientUsesNewConnection) ?? false))
            {
                try {
                    await connection.ReadRequest(ctx, cancellationToken).ConfigureAwait(false);

                    throw ctx.AssertFail("Expected client to use a new connection.");
                } catch (OperationCanceledException) {
                    throw;
                } catch (Exception ex) {
                    ctx.LogDebug(2, $"{ME} EXPECTED EXCEPTION: {ex.GetType ()} {ex.Message}");
                }
                connection.Dispose();
                return(false);
            }

            return(reusable);
        }
        public override void CheckFaults(HttpOperation operation, HttpResponse response)
        {
            if (!response.Request.RequestModelResult.Headers.ContainsKey("Accept") || !response.Headers.ContainsKey("Content-Type"))
            {
                return;
            }
            string text = response.Request.RequestModelResult.Headers["Accept"].ToLower();

            string[] array = text.Split(new char[1] {
                ','
            }, StringSplitOptions.RemoveEmptyEntries);
            string text2 = response.Headers["Content-Type"].ToLower();

            for (int i = 0; i < array.Length; i++)
            {
                array[i] = array[i].Trim();
                if (array[i].Contains("/*"))
                {
                    array[i] = array[i].Remove(array[i].IndexOf("/*"), array[i].Length - array[i].IndexOf("/*"));
                }
                if (array[i] == "*" || text2.StartsWith(array[i]))
                {
                    return;
                }
            }
            operation.Fault("Unexpected media type.  Expected '" + text + "' but received '" + text2 + "'.");
        }
Esempio n. 9
0
 public override void CheckFaults(HttpOperation operation, HttpResponse response)
 {
     if (response.StatusCode != HttpStatusCode.OK)
     {
         operation.Fault("Response status code is not 200.");
     }
 }
Esempio n. 10
0
 internal protected override Task <HttpResponse> HandleRequest(
     TestContext ctx, HttpOperation operation, HttpConnection connection, HttpRequest request,
     RequestFlags effectiveFlags, CancellationToken cancellationToken)
 {
     ctx.Assert(request.Method, Is.EqualTo("GET"), "method");
     return(Task.FromResult(new HttpResponse(Status, Content)));
 }
Esempio n. 11
0
 internal protected override Task <HttpResponse> HandleRequest(
     TestContext ctx, HttpOperation operation, HttpConnection connection, HttpRequest request,
     RequestFlags effectiveFlags, CancellationToken cancellationToken)
 {
     clientRequest.Request.Abort();
     return(Task.FromResult(HttpResponse.CreateSuccess()));
 }
        private static IEnumerable <JProperty> GetPatternProperties(HttpOperation operation)
        {
            yield return(new JProperty("expectations", GetExpectations(operation)));

            yield return(new JProperty("request", new JObject(GetRequestProperties(operation))));

            yield return(new JProperty("response", new JObject(GetResponseProperties(operation))));
        }
Esempio n. 13
0
        private static void InsertResponse(StringBuilder report, HttpOperation operation)
        {
            var response = GetHttpResponseFrom(operation);

            report.AppendLine("- Response");
            report.AppendLine("```");
            report.AppendLine(response.ToHttpLook());
            report.AppendLine("```");
        }
Esempio n. 14
0
        private static void InsertRequest(StringBuilder report, HttpOperation operation)
        {
            var request = GetHttpRequestFrom(operation);

            report.AppendLine("- Request");
            report.AppendLine("```");
            report.AppendLine(request.ToHttpLook(operation.TestServer.HttpClient.DefaultRequestHeaders));
            report.AppendLine("```");
        }
Esempio n. 15
0
 private static void InsertOperationResponseStatusTable(StringBuilder report, HttpOperation operation)
 {
     report.AppendLine($"| Expected Results  | Status |");
     report.AppendLine($"|-------------------|--------|");
     foreach (var assertion in operation.Assertions.Cast <IExpectation>())
     {
         report.AppendLine($"| {assertion.ExpectedResult} | OK |");
     }
 }
Esempio n. 16
0
        internal protected override async Task <HttpResponse> HandleRequest(
            TestContext ctx, HttpOperation operation, HttpConnection connection, HttpRequest request,
            RequestFlags effectiveFlags, CancellationToken cancellationToken)
        {
            ctx.Assert(request.Method, Is.EqualTo("GET"), "method");
            await Task.Delay(Delay).ConfigureAwait(false);

            return(HttpResponse.CreateSuccess());
        }
 public override object OnResponseApplyConverters(object value, HttpOperation operation, FieldInfo fi)
 {
     if (operation.IsFaulted)
     {
         operation.Log("(HttpResponseBinaryValueAttribute)(OnResponseApplyConverters) Operation has faulted and converters will not be applied!  Nullifying value to prevent further exceptions.", LogSeverity.WARNING);
         return(null);
     }
     return(base.OnResponseApplyConverters(value, operation, fi));
 }
Esempio n. 18
0
        public override Task Initialize(TestContext ctx, HttpOperation operation, CancellationToken cancellationToken)
        {
            if (Server.SslStreamProvider?.SupportsHttpListenerContext ?? false)
            {
                sslStream = Server.SslStreamProvider.GetSslStream(Context);
            }

            return(Handler.CompletedTask);
        }
Esempio n. 19
0
        protected internal override async Task <HttpResponse> HandleRequest(
            TestContext ctx, HttpOperation operation, HttpConnection connection, HttpRequest request,
            RequestFlags effectiveFlags, CancellationToken cancellationToken)
        {
            var listenerContext = ((HttpListenerConnection)connection).Context;

            await HandleRequest(ctx, listenerContext, cancellationToken).ConfigureAwait(false);

            return(HttpResponse.CreateFrom(listenerContext.Response));
        }
Esempio n. 20
0
        protected internal override async Task <HttpResponse> HandleRequest(
            TestContext ctx, HttpOperation operation, HttpConnection connection, HttpRequest request,
            RequestFlags effectiveFlags, CancellationToken cancellationToken)
        {
            AuthenticationState state;
            var response = Manager.HandleAuthentication(ctx, connection, request, out state);

            if (request.Method == "GET" || request.Method == "HEAD" || request.Body == null)
            {
                if (request.Headers.TryGetValue("Transfer-Encoding", out string transferEncoding))
                {
                    ctx.AssertFail($"Must not send 'Transfer-Encoding' header with '${request.Method}' request.");
                }
                if (request.Headers.TryGetValue("Content-Length", out string contentLength))
                {
                    ctx.AssertFail($"Must not send 'Content-Length' header with '${request.Method}' request.");
                }
            }
            else if (state == AuthenticationState.Challenge)
            {
                if (request.Headers.TryGetValue("Content-Length", out string contentLength))
                {
                    ctx.Assert(int.Parse(contentLength), Is.EqualTo(0), "Must send zero-length content with NTLM challenge.");
                }
                else
                {
                    ctx.AssertFail("Must send 'Content-Length: 0' with NTLM challenge.");
                }
            }
            else
            {
                if (request.Headers.TryGetValue("Transfer-Encoding", out string transferEncoding))
                {
                    ctx.Assert(transferEncoding, Is.EqualTo("chunked"), "Transfer-Encoding");
                }
                else if (!request.Headers.TryGetValue("Content-Length", out string contentLength))
                {
                    ctx.AssertFail("Need either 'Transfer-Encoding' or 'Content-Length'");
                }
            }

            var keepAlive = (effectiveFlags & (RequestFlags.KeepAlive | RequestFlags.CloseConnection)) == RequestFlags.KeepAlive;

            if (response != null)
            {
                response.Redirect = operation.RegisterRedirect(ctx, this, request.Path);
                return(response);
            }

            effectiveFlags |= RequestFlags.Redirected;

            cancellationToken.ThrowIfCancellationRequested();
            return(await Target.HandleRequest(ctx, operation, connection, request, effectiveFlags, cancellationToken));
        }
Esempio n. 21
0
        private static string GetOperationRequestTitle(HttpOperation operation)
        {
            var description = operation.Description;

            if (String.IsNullOrWhiteSpace(description))
            {
                return("Request");
            }

            return($"Request to [{description}]");
        }
 public virtual object OnResponseResolveValue(string name, HttpOperation operation, FieldInfo fi, HttpResponse response)
 {
     if (VariableValue != null && Configuration.HasSetting(VariableValue))
     {
         return(Configuration.GetSetting(VariableValue));
     }
     if (!string.IsNullOrEmpty(Value))
     {
         return(Value);
     }
     return(fi.GetValue(operation));
 }
 public virtual string OnResponseResolveName(HttpOperation operation, FieldInfo fi, HttpResponse response)
 {
     if (VariableName != null && Configuration.HasSetting(VariableName))
     {
         return(Configuration.GetSetting <string>(VariableName));
     }
     if (!string.IsNullOrEmpty(Name))
     {
         return(Name);
     }
     return(fi.Name);
 }
 private void resolve(string name, object value, ref HttpRequestModel model, HttpOperation operation, FieldInfo fi)
 {
     value = Convert.ChangeType(value, typeof(string));
     if (!string.IsNullOrEmpty(name) && (!string.IsNullOrEmpty((string)value) || (string.IsNullOrEmpty((string)value) && !IgnoreWhenValueIsEmpty)))
     {
         model.AddQueryString(name, (value != null) ? value.ToString() : "");
     }
     else
     {
         operation.Log("(HttpQueryStringAttribute)(OnRequestResolveModel) Query string part failed to add because the name is empty!", LogSeverity.WARNING);
     }
 }
        public static async Task <T> DeleteAsync <T>(ApiRequest request, string url)
            where T : ApiResponse
        {
            var bytes = await HttpOperation
                        .WithUrl(url)
                        .WithAppacitiveKeyOrSession(request.ApiKey, request.SessionToken, request.UseApiSession)
                        .WithEnvironment(request.Environment)
                        .WithUserToken(request.UserToken)
                        .DeleteAsync();

            return(Parse <T>(bytes));
        }
Esempio n. 26
0
        public QueuedOperation(HttpOperation operation, string[] parameters, RequestQueueAttribute[] operationQueues)
        {
            Operation  = operation;
            Parameters = parameters;
            int num = operationQueues.Length;

            Queues = new string[num];
            for (int i = 0; i < num; i++)
            {
                Queues[i] = operationQueues[i].QueueId;
            }
        }
        public override Result Assert(HttpOperation operation)
        {
            var actualContentType = operation.Response.Content.Headers.ContentType.MediaType;

            if (_expectedContentType == actualContentType)
            {
                return(Ok);
            }

            return(Failure($"Expected HTTP Content-Type is \"{_expectedContentType}\" but was \"{actualContentType}\" " +
                           $"in response: \n\n{operation.Response.ToHttpLook()}"));
        }
Esempio n. 28
0
        public ListenerOperation(Listener listener, HttpOperation operation, Handler handler, Uri uri)
        {
            Listener  = listener;
            Operation = operation;
            Handler   = handler;
            Uri       = uri;

            ME                 = $"[{ID}:{GetType ().Name}:{operation.ME}]";
            serverInitTask     = Listener.TaskSupport.CreateAsyncCompletionSource <object> ();
            serverFinishedTask = Listener.TaskSupport.CreateAsyncCompletionSource <object> ();
            contextTask        = Listener.TaskSupport.CreateAsyncCompletionSource <ListenerContext> ();
            finishedTask       = Listener.TaskSupport.CreateAsyncCompletionSource <object> ();
        }
Esempio n. 29
0
    protected override void sendOperation(HttpOperation operation, params string[] parameters)
    {
        RequestQueueAttribute[] array = (RequestQueueAttribute[])operation.GetType().GetCustomAttributes(typeof(RequestQueueAttribute), inherit: true);
        if (array.Length == 0)
        {
            base.sendOperation(operation, parameters);
            return;
        }
        QueuedOperation pending = new QueuedOperation(operation, parameters, array);

        addToQueue(pending);
        processQueue(pending);
    }
Esempio n. 30
0
        public override Result Assert(HttpOperation operation)
        {
            var actualStatus = operation.Response.StatusCode;

            if (_expectedStatus == actualStatus)
            {
                return(Ok);
            }

            return(Failure(
                       $"Expected HTTP status is {_expectedStatus} but was {actualStatus} " +
                       $"in response: \n\n{operation.Response.ToHttpLook()}"));
        }