public async Task ProblemDetails_JsonValidationWorks()
        {
            var problemStatus = HttpStatusCode.TooManyRequests;

            var details = new ValidationProblemDetails
            {
                Title            = "Too Many Requests",
                HttpStatus       = (int)problemStatus,
                ValidationErrors = new Dictionary <string, string[]>
                {
                    { "item1", new[] { "error1", "error2" } },
                    { "item2", new[] { "error1", "error2", "error3", "error4" } }
                }
            };

            var ex = new ProblemDetailsException(details);

            using (var server = CreateServer(handler: ResponseThrows(ex)))
                using (var client = server.CreateClient())
                {
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var response = await client.GetAsync("/");

                    var content = await response.Content.ReadAsStringAsync();

                    Assert.Equal(problemStatus, response.StatusCode);
                    await AssertIsProblemDetailsResponse(response);

                    Assert.DoesNotContain("KeyValueOf", content);
                    Assert.DoesNotContain("KeyValuePairOf", content);
                    //Assert.Contains("errosdasdasar1", content);
                }
        }
        public async Task ProblemDetailsException_WithInnerException_InnerExceptionToBeIncludedInProblemDetailsExceptionDetails()
        {
            const int expected = StatusCodes.Status429TooManyRequests;

            var details = new MvcProblemDetails
            {
                Title  = ReasonPhrases.GetReasonPhrase(expected),
                Type   = $"https://httpstatuses.com/{expected}",
                Status = expected,
            };

            const string innerExceptionMessage = "inner exception message";

            var innerException = new ArgumentException(innerExceptionMessage);

            var ex = new ProblemDetailsException(details, innerException);

            using var client = CreateClient(handler: ResponseThrows(ex), SetOnBeforeWriteDetails);

            var response = await client.GetAsync(string.Empty);

            var responseProblemDetails = await response.Content.ReadFromJsonAsync <MvcProblemDetails>();

            var responseExceptionDetails = (JsonElement)responseProblemDetails.Extensions[ProblemDetailsOptions.DefaultExceptionDetailsPropertyName];

            var responseExceptionMessage = responseExceptionDetails.EnumerateArray().ToList()[0].GetProperty("message").GetString();

            Assert.Equal(innerExceptionMessage, responseExceptionMessage);
        }
Beispiel #3
0
        public async Task ProblemDetailsExceptionHandler_RethrowsException()
        {
            var ex = new ProblemDetailsException(new EvilProblemDetails());

            using var client = CreateClient(handler: ResponseThrows(ex));

            await Assert.ThrowsAnyAsync <Exception>(() => client.GetAsync(string.Empty));
        }
Beispiel #4
0
        public void Constructor_InitializesMessage()
        {
            var problemDetails = CreateProblemDetails();

            var exception = new ProblemDetailsException(problemDetails);

            Assert.Equal("https://httpstatuses.com/303 : See other", exception.Message);
        }
Beispiel #5
0
        public void Constructor_FromHttpStatusCodeAndTitle()
        {
            var exception = new ProblemDetailsException(400, "foobar");

            Assert.IsType <StatusCodeProblemDetails>(exception.Details);
            Assert.Equal(400, exception.Details.Status);
            Assert.Equal("foobar", exception.Details.Title);
        }
Beispiel #6
0
        public void Constructor_FromHttpStatusCode()
        {
            var exception = new ProblemDetailsException(400);

            Assert.IsType <StatusCodeProblemDetails>(exception.Details);
            Assert.Equal(400, exception.Details.Status);
            Assert.Equal(ReasonPhrases.GetReasonPhrase(400), exception.Details.Title);
        }
Beispiel #7
0
        public void Constructor_FromHttpStatusCodeTitleAndInnerException()
        {
            var exception = new ProblemDetailsException(400, "foobar", new DivideByZeroException());

            Assert.IsType <Microsoft.AspNetCore.Mvc.ProblemDetails>(exception.Details);
            Assert.IsType <DivideByZeroException>(exception.InnerException);
            Assert.Equal(400, exception.Details.Status);
            Assert.Equal("foobar", exception.Details.Title);
        }
        public void Constructor_Empty()
        {
            // Arrange
            var defaultStatusCode = HttpStatusCode.InternalServerError;

            // Act
            var problemDetails = new ProblemDetailsException();

            // Assert
            Assert.Equal(defaultStatusCode, problemDetails.Status);
        }
        public void Constructor_Status()
        {
            // Arrange
            var statusCode = HttpStatusCode.BadRequest;

            // Act
            var problemDetails = new ProblemDetailsException(statusCode);

            // Assert
            Assert.Equal(statusCode, problemDetails.Status);
        }
Beispiel #10
0
        public static ProblemDetailsException ThrowValidationException(this object here, string property, string error)
        {
            var validationProblemDetails = new ValidationProblemDetails(new Dictionary <string, string[]> {
                { property, new[] { error } }
            })
            {
                Status = 400
            };
            var problemDetails = new ProblemDetailsException(validationProblemDetails);

            throw problemDetails;
        }
        public void Constructor_StatusAndMessage()
        {
            // Arrange
            var statusCode = HttpStatusCode.BadRequest;
            var message    = "Unit testing error thrown";

            // Act
            var problemDetails = new ProblemDetailsException(statusCode, message);

            // Assert
            Assert.Equal(statusCode, problemDetails.Status);
            Assert.Equal(message, problemDetails.Message);
        }
        public async Task ProblemDetailsExceptionHandler_RethrowsException()
        {
            var ex = new ProblemDetailsException(new EvilProblemDetails());

            using (var server = CreateServer(handler: ResponseThrows(ex)))
                using (var client = server.CreateClient())
                {
                    await Assert.ThrowsAnyAsync <Exception>(async() =>
                    {
                        var response = await client.GetAsync(string.Empty);

                        Assert.Equal(1, response.Content.Headers.ContentLength);
                        Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
                    });
                }
        }
Beispiel #13
0
        public void ToString_ReturnsAllDetails()
        {
            var problemDetails = CreateProblemDetails();

            var exception = new ProblemDetailsException(problemDetails);
            var actual    = exception.ToString();

            var expected = @"Type    : https://httpstatuses.com/303
Title   : See other
Status  : 303
Detail  : Look somewhere else.
Instance: https://example.com/problem/123
";

            Assert.Equal(expected, actual, ignoreLineEndingDifferences: true);
        }
Beispiel #14
0
        public async Task Explicit_Client_Exception_Is_Not_Logged_As_Unhandled_Error()
        {
            var details = new MvcProblemDetails
            {
                Title  = "Too Many Requests",
                Status = StatusCodes.Status429TooManyRequests,
            };

            var ex = new ProblemDetailsException(details);

            using var client = CreateClient(handler: ResponseThrows(ex));

            var response = await client.GetAsync(string.Empty);

            Assert.Equal((HttpStatusCode)StatusCodes.Status429TooManyRequests, response.StatusCode);
            AssertUnhandledExceptionNotLogged(Logger);
        }
Beispiel #15
0
        public async Task ProblemDetailsException_IsHandled()
        {
            var expected = HttpStatusCode.TooManyRequests;

            var details = new MvcProblemDetails
            {
                Title  = "Too Many Requests",
                Status = (int)expected,
            };

            var ex = new ProblemDetailsException(details);

            using var client = CreateClient(handler: ResponseThrows(ex));

            var response = await client.GetAsync("/");

            Assert.Equal(expected, response.StatusCode);
            await AssertIsProblemDetailsResponse(response);
        }
        public async Task ProblemDetailsException_IsHandled()
        {
            const int expected = StatusCodes.Status429TooManyRequests;

            var details = new MvcProblemDetails
            {
                Title  = ReasonPhrases.GetReasonPhrase(expected),
                Type   = $"https://httpstatuses.com/{expected}",
                Status = expected,
            };

            var ex = new ProblemDetailsException(details);

            using var client = CreateClient(handler: ResponseThrows(ex));

            var response = await client.GetAsync("/");

            Assert.Equal(expected, (int)response.StatusCode);

            await AssertIsProblemDetailsResponse(response, expectExceptionDetails : false);
        }
        public async Task ProblemDetailsException_IsHandled()
        {
            var problemStatus = HttpStatusCode.TooManyRequests;

            var details = new MvcProblemDetails
            {
                Title  = "Too Many Requests",
                Status = (int)problemStatus,
            };

            var ex = new ProblemDetailsException(details);

            using (var server = CreateServer(handler: ResponseThrows(ex)))
                using (var client = server.CreateClient())
                {
                    var response = await client.GetAsync("/");

                    Assert.Equal(problemStatus, response.StatusCode);
                    await AssertIsProblemDetailsResponse(response);
                }
        }
Beispiel #18
0
        /// <summary>
        /// Retrieves all of the simulators currently registered with all
        /// simulator gateways within this workspace.
        /// </summary>
        /// <remarks>
        /// The deployment_mode appears in the query string. It can be one of
        /// Unspecified, Testing, or Hosted. If it has a 'neq:' prefix, that means
        /// "not;"
        /// e.g., {.../simulatorSessions?deployment_mode=neq:Hosted} means the response
        /// should not include
        /// simulators that are hosted.
        ///
        /// The session_status can be one of Attachable, Attached, Detaching, Rejected,
        /// and supports the neq: prefix.
        ///
        /// The collection appears in the query string
        ///
        /// The package appears in the query string
        ///
        /// The filter queries can appear together, like
        /// {.../simulatorSessions?deployment_mode=Hosted&amp;collection=1234-455-33333}
        /// </remarks>
        /// <param name='workspaceName'>
        /// The workspace identifier.
        /// </param>
        /// <param name='deploymentMode'>
        /// A specifier to filter on deployment mode
        /// </param>
        /// <param name='sessionStatus'>
        /// A specifier to filter on session status
        /// </param>
        /// <param name='collection'>
        /// If present, only sessions in this collection
        /// </param>
        /// <param name='package'>
        /// If present, only sessions in this package
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ProblemDetailsException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <IList <SimulatorSessionSummary> > > ListWithHttpMessagesAsync(string workspaceName, string deploymentMode = default(string), string sessionStatus = default(string), string collection = default(string), string package = default(string), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (workspaceName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "workspaceName");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("workspaceName", workspaceName);
                tracingParameters.Add("deploymentMode", deploymentMode);
                tracingParameters.Add("sessionStatus", sessionStatus);
                tracingParameters.Add("collection", collection);
                tracingParameters.Add("package", package);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v2/workspaces/{workspaceName}/simulatorSessions").ToString();

            _url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(workspaceName));
            List <string> _queryParameters = new List <string>();

            if (deploymentMode != null)
            {
                _queryParameters.Add(string.Format("deployment_mode={0}", System.Uri.EscapeDataString(deploymentMode)));
            }
            if (sessionStatus != null)
            {
                _queryParameters.Add(string.Format("session_status={0}", System.Uri.EscapeDataString(sessionStatus)));
            }
            if (collection != null)
            {
                _queryParameters.Add(string.Format("collection={0}", System.Uri.EscapeDataString(collection)));
            }
            if (package != null)
            {
                _queryParameters.Add(string.Format("package={0}", System.Uri.EscapeDataString(package)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new ProblemDetailsException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    ProblemDetails _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ProblemDetails>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <IList <SimulatorSessionSummary> >();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <IList <SimulatorSessionSummary> >(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Beispiel #19
0
        /// <summary>
        /// Advance the RL agent with the new state of the simulator, and returns an
        /// action computed by our policy.
        /// Simulatorsession is supposed to use the returned action for stepping inside
        /// the sim and thne getting the new state.false
        /// You can send the same state again, as long as you didn't get a Non-Idle
        /// Action back.
        /// </summary>
        /// <param name='workspaceName'>
        /// The workspace identifier.
        /// </param>
        /// <param name='sessionId'>
        /// Unique identifier for the simulator.
        /// </param>
        /// <param name='body'>
        /// The new state of the simulator.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ProblemDetailsException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <EventModel> > AdvanceWithHttpMessagesAsync(string workspaceName, string sessionId, SimulatorState body, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (workspaceName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "workspaceName");
            }
            if (sessionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "sessionId");
            }
            if (body == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "body");
            }
            if (body != null)
            {
                body.Validate();
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("workspaceName", workspaceName);
                tracingParameters.Add("sessionId", sessionId);
                tracingParameters.Add("body", body);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Advance", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v2/workspaces/{workspaceName}/simulatorSessions/{sessionId}/advance").ToString();

            _url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(workspaceName));
            _url = _url.Replace("{sessionId}", System.Uri.EscapeDataString(sessionId));
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (body != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8");
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new ProblemDetailsException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    ProblemDetails _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ProblemDetails>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <EventModel>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <EventModel>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }