コード例 #1
0
        public void WhenAGETByIdRequestIsSubmittedToTheCompositeWithAnInvalidResourceIdentifier(
            string compositeCategoryName,
            string compositeName,
            string resourceIdentifier)
        {
            // Default the category to test, if not specified
            compositeCategoryName = GetCompositeCategoryName(compositeCategoryName);

            var httpClient = FeatureContext.Current.Get<HttpClient>();

            var pluralizedCompositeName = CompositeTermInflector.MakePlural(compositeName);

            ScenarioContext.Current.Set(pluralizedCompositeName, ScenarioContextKeys.PluralizedCompositeName);

            var uri = OwinUriHelper.BuildCompositeUri(
                string.Format(
                    "{0}/{1}/{2}",
                    compositeCategoryName,
                    pluralizedCompositeName,
                    resourceIdentifier));

            var getResponseMessage = httpClient.GetAsync(uri)
                                               .GetResultSafely();

            // Save the response, and the resource collection name for the scenario
            ScenarioContext.Current.Set(getResponseMessage);
        }
コード例 #2
0
        public async Task <HttpResponseMessage> GetAll(string elementName, int offset = 0)
        {
            var contentType = BuildJsonMimeType(elementName);
            var resource    = CompositeTermInflector.MakePlural(elementName);

            var uriBuilder = new UriBuilder(Path.Combine(_configuration.Url, resource, $"?offset={offset}"));

            return(await Get(uriBuilder, contentType));
        }
コード例 #3
0
        public async Task <HttpResponseMessage> GetResourceByExample(string json, string elementName)
        {
            var contentType = BuildJsonMimeType(elementName);
            var resource    = CompositeTermInflector.MakePlural(elementName);

            var uriBuilder = new UriBuilder(Path.Combine(_configuration.Url, resource))
            {
                Query = Utilities.ConvertJsonToQueryString(json)
            };

            return(await Get(uriBuilder, contentType));
        }
コード例 #4
0
        public async Task <HttpResponseMessage> PostResource(string json, string elementName,
                                                             string elementSchemaName = "", bool refreshToken = false)
        {
            var contentType = BuildJsonMimeType(elementName);
            var content     = new StringContent(json, Encoding.UTF8, contentType);
            var resource    = CompositeTermInflector.MakePlural(elementName);

            if (_log.IsDebugEnabled)
            {
                _log.Debug($"json: {json}");
                _log.Debug($"elementName: {elementName}");
            }

            try
            {
                string uri = $"{_configuration.Url.TrimEnd('/')}/{GetResourcePath(resource, elementSchemaName)}";

                _log.Debug($"Posting to {uri}");

                var uriBuilder = new UriBuilder(uri);

                var request = new HttpRequestMessage(HttpMethod.Post, uriBuilder.Uri)
                {
                    Content = content
                };

                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
                request.Headers.Authorization = GetAuthHeaderValue(refreshToken);

                var response = await _httpClient.SendAsync(request).ConfigureAwait(false);

                return(response);
            }
            catch (WebException ex)
            {
                // Handling intermittent network issues
                _log.Error("Unexpected WebException on resource post", ex);
                return(CreateFakeErrorResponse(HttpStatusCode.ServiceUnavailable));
            }
            catch (TaskCanceledException ex)
            {
                // Handling web timeout
                _log.Error("Http Client timeout.", ex);
                return(CreateFakeErrorResponse(HttpStatusCode.RequestTimeout));
            }
            catch (Exception ex)
            {
                // Handling other issues
                _log.Error("Unexpected Exception on resource post", ex);
                return(CreateFakeErrorResponse(HttpStatusCode.SeeOther));
            }
        }
        public async Task <UpstreamEdFiApiResponse> Get(
            Type upstreamModelType,
            HttpRequestHeaders requestHeaders,
            IEnumerable <KeyValuePair <string, string> > queryParameters,
            short schoolYearFromRoute,
            Guid?id = null)
        {
            string resourceCollectionName =
                CompositeTermInflector.MakePlural(upstreamModelType.Name)
                .ToCamelCase();

            string requestUrl = GetRequestUrl(resourceCollectionName, queryParameters, schoolYearFromRoute, id);

            var passthroughRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUrl);

            passthroughRequestMessage.Headers.Authorization = AuthenticationHeaderValue.Parse(requestHeaders.Authorization.ToString());

            HttpResponseMessage response;

            try
            {
                response = await _httpClient.SendAsync(passthroughRequestMessage).ConfigureAwait(false);
            }
            catch (WebException ex)
            {
                return(new UpstreamEdFiApiResponse
                {
                    Status = (ex.Response as HttpWebResponse)?.StatusCode ?? HttpStatusCode.InternalServerError,
                    ResponseStream = ex.Response.GetResponseStream(),
                });
            }

            return(new UpstreamEdFiApiResponse
            {
                Status = response.StatusCode,
                ReasonPhrase = response.ReasonPhrase,
                ResponseHeaders = response.Headers.Where(IsPassthroughResponseHeader).ToArray(),
                ResponseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false),
            });
        }
        public async Task <UpstreamEdFiApiResponse> Put <TResourceWriteModel>(Guid id, HttpRequestHeaders requestHeaders, object v2RequestBody, short schoolYearFromRoute)
        {
            string resourceCollectionName =
                CompositeTermInflector.MakePlural(typeof(TResourceWriteModel).Name)
                .ToCamelCase();

            string resourceUrl = GetResourceUrl(resourceCollectionName, schoolYearFromRoute);

            var requestUri = new Uri($"{resourceUrl}/{id:N}");
            var jsonBytes  = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(v2RequestBody, _serializerSettings));

            var passthroughRequestMessage = new HttpRequestMessage(HttpMethod.Put, requestUri);

            passthroughRequestMessage.Content = new ByteArrayContent(jsonBytes);
            passthroughRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            passthroughRequestMessage.Headers.Authorization       = AuthenticationHeaderValue.Parse(requestHeaders.Authorization.ToString());

            HttpResponseMessage response;

            try
            {
                response = await _httpClient.SendAsync(passthroughRequestMessage).ConfigureAwait(false);
            }
            catch (WebException ex)
            {
                return(new UpstreamEdFiApiResponse
                {
                    Status = (ex.Response as HttpWebResponse)?.StatusCode ?? HttpStatusCode.InternalServerError,
                    ResponseStream = ex.Response.GetResponseStream(),
                });
            }

            return(new UpstreamEdFiApiResponse
            {
                Status = response.StatusCode,
                ReasonPhrase = response.ReasonPhrase,
                ResponseHeaders = response.Headers.Where(IsPassthroughResponseHeader).ToArray(),
                ResponseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false),
            });
        }
コード例 #7
0
        public async Task WhenAGETByIdRequestIsSubmittedToTheComposite(string compositeName)
        {
            // Default the category to test, if not specified
            var compositeCategoryName = "test";

            var httpClient = StepsHelper.GetHttpClient();

            var subjectId = _scenarioContext.Get <Guid>(ScenarioContextKeys.CompositeSubjectId);

            var pluralizedCompositeName = CompositeTermInflector.MakePlural(compositeName);

            string correlationId = Guid.NewGuid().ToString("n");

            SetCorrelationId(correlationId);

            string requestUrl = _edFiTestUriHelper.BuildCompositeUri(
                $"{compositeCategoryName}/{pluralizedCompositeName}/{subjectId:n}{StepsHelper.GetQueryString(correlationId)}");

            var response = await httpClient.GetAsync(requestUrl, _cancellationToken.Value);

            response.StatusCode.ShouldBe(HttpStatusCode.OK);
        }
        public async Task <UpstreamEdFiApiResponse> Delete <TResourceWriteModel>(Guid id, HttpRequestHeaders requestHeaders, short schoolYearFromRoute)
        {
            string resourceCollectionName =
                CompositeTermInflector.MakePlural(typeof(TResourceWriteModel).Name)
                .ToCamelCase();

            string resourceUrl = GetResourceUrl(resourceCollectionName, schoolYearFromRoute);

            var requestUri = new Uri($"{resourceUrl}/{id:N}");

            var passthroughRequestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri);

            passthroughRequestMessage.Headers.Authorization = AuthenticationHeaderValue.Parse(requestHeaders.Authorization.ToString());

            HttpResponseMessage response;

            try
            {
                response = await _httpClient.SendAsync(passthroughRequestMessage).ConfigureAwait(false);
            }
            catch (WebException ex)
            {
                return(new UpstreamEdFiApiResponse
                {
                    Status = (ex.Response as HttpWebResponse)?.StatusCode ?? HttpStatusCode.InternalServerError,
                    ResponseStream = ex.Response.GetResponseStream(),
                });
            }

            return(new UpstreamEdFiApiResponse
            {
                Status = response.StatusCode,
                ReasonPhrase = response.ReasonPhrase,
                ResponseHeaders = response.Headers.Where(IsPassthroughResponseHeader).ToArray(),
                ResponseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false),
            });
        }
コード例 #9
0
        // Generates a list of assigned profiles that can be used by the client for the sent resource
        private IEnumerable <string> GetApplicableContentTypes(
            IEnumerable <string> assignedProfiles,
            string resourceCollectionName,
            string resourceItemName,
            HttpMethod httpMethod)
        {
            ContentTypeUsage contentTypeUsage = httpMethod == HttpMethod.Get
                ? ContentTypeUsage.Readable
                : ContentTypeUsage.Writable;

            var assignedContentTypes = assignedProfiles
                                       .Select(x => ProfilesContentTypeHelper.CreateContentType(resourceCollectionName, x, contentTypeUsage));

            return(assignedContentTypes
                   .Intersect(
                       _profileResourceNamesProvider.GetProfileResourceNames()
                       .Where(x => x.ResourceName.EqualsIgnoreCase(resourceItemName))
                       .Select(
                           x => ProfilesContentTypeHelper.CreateContentType(
                               CompositeTermInflector.MakePlural(x.ResourceName),
                               x.ProfileName,
                               contentTypeUsage)))
                   .ToList());
        }
コード例 #10
0
        public void WhenAGETByExampleRequestIsSubmittedToTheCompositeUsingTheFollowingParameters(
            string requestPattern,
            string compositeCategoryName,
            string resourceName,
            Table parameters)
        {
            // Default the category to test, if not specified
            compositeCategoryName = GetCompositeCategoryName(compositeCategoryName);

            ScenarioContext.Current.Set(requestPattern, ScenarioContextKeys.RequestPattern);

            var valueByName = parameters.Rows.ToDictionary(
                r => r["Name"],
                r => (object) r["Value"],
                StringComparer.InvariantCultureIgnoreCase);

            ScenarioContext.Current.Set(valueByName, ScenarioContextKeys.RequestParameters);

            var pluralizedCompositeName = CompositeTermInflector.MakePlural(resourceName);
            ScenarioContext.Current.Set(pluralizedCompositeName, ScenarioContextKeys.PluralizedCompositeName);

            var uri = OwinUriHelper.BuildCompositeUri(
                string.Format(
                    "{0}/{1}?{2}",
                    compositeCategoryName,
                    pluralizedCompositeName,
                    string.Join("&", valueByName.Select(kvp => Uri.EscapeDataString(kvp.Key) + "=" + Uri.EscapeDataString(kvp.Value.ToString())))));

            var httpClient = FeatureContext.Current.Get<HttpClient>();

            var getResponseMessage = httpClient.GetAsync(uri)
                                               .GetResultSafely();

            // Save the response, and the resource collection name for the scenario
            ScenarioContext.Current.Set(getResponseMessage);
        }
コード例 #11
0
        public void WhenAGetAlldRequestIsSubmittedToTheCompositeWithAFilteredQuery(
            string compositeCategoryName,
            string compositeName,
            string hasParameters)
        {
            var httpClient = FeatureContext.Current.Get<HttpClient>();

            var pluralizedCompositeName = CompositeTermInflector.MakePlural(compositeName);

            compositeCategoryName = GetCompositeCategoryName(compositeCategoryName);

            var queryParameterDictionary = new Dictionary<string, QueryParameterObject>();

            if (!string.IsNullOrEmpty(hasParameters))
            {
                queryParameterDictionary =
                    ScenarioContext.Current.Get<Dictionary<string, QueryParameterObject>>(ScenarioContextKeys.CompositeQueryParameterDictionary);
            }

            ScenarioContext.Current.Set(pluralizedCompositeName, ScenarioContextKeys.PluralizedCompositeName);

            string queryStringParameterText = string.Join(
                "&",

                // Add the criteria 
                queryParameterDictionary.Select(
                                             kvp =>
                                             {
                                                 string parameterName = kvp.Value.Name;

                                                 if (IsDescriptorParameter(kvp.Value.Name))
                                                 {
                                                     parameterName = ScenarioContext.Current.Get<string>(
                                                         ScenarioContextKeys.CompositeQueryStringDescriptorParameter);
                                                 }

                                                 return $"{parameterName}={Uri.EscapeDataString(kvp.Value.Value.ToString())}";
                                             })

                                         // Add the correlation Id
                                        .Concat(
                                             new[]
                                             {
                                                 SpecialQueryStringParameters.CorrelationId + "=" + EstablishRequestCorrelationIdForScenario()
                                             }));

            var uri = OwinUriHelper.BuildCompositeUri(
                string.Format(
                    "{0}/{1}{2}{3}",
                    compositeCategoryName,
                    pluralizedCompositeName,
                    queryStringParameterText.Length > 0
                        ? "?"
                        : string.Empty,
                    queryStringParameterText));

            var getResponseMessage = httpClient.GetAsync(uri)
                                               .GetResultSafely();

            // Save the response, and the resource collection name for the scenario
            ScenarioContext.Current.Set(getResponseMessage);
        }
コード例 #12
0
        public void WhenAGETRequestIsSubmittedToTheCompositeWithParameters(
            string requestPattern,
            string compositeCategoryName,
            string compositeName,
            string excludeCorrelationText,
            Table parametersTable)
        {
            ScenarioContext.Current.Set(requestPattern, ScenarioContextKeys.RequestPattern);

            // Default the category to test, if not specified
            compositeCategoryName = GetCompositeCategoryName(compositeCategoryName);

            var httpClient = FeatureContext.Current.Get<HttpClient>();

            var subjectId = ScenarioContext.Current.Get<Guid>(ScenarioContextKeys.CompositeSubjectId);

            var pluralizedCompositeName = CompositeTermInflector.MakePlural(compositeName);

            ScenarioContext.Current.Set(pluralizedCompositeName, ScenarioContextKeys.PluralizedCompositeName);

            bool includeCorrelation = string.IsNullOrEmpty(excludeCorrelationText);

            string requestUrl = null;

            if (requestPattern.EqualsIgnoreCase("id"))
            {
                var dictionary = new Dictionary<string, object>();
                ScenarioContext.Current.Set(dictionary, ScenarioContextKeys.RequestParameters);

                requestUrl = OwinUriHelper.BuildCompositeUri(
                    string.Format(
                        "{0}/{1}/{2}{3}",
                        compositeCategoryName,
                        pluralizedCompositeName,
                        subjectId.ToString("n"),
                        GetQueryString(parametersTable, includeCorrelation)));
            }
            else if (requestPattern.EqualsIgnoreCase("key"))
            {
                var valueByName = parametersTable == null
                    ? ScenarioContext.Current.Get<Dictionary<string, object>>(ScenarioContextKeys.CompositeSubjectKey)
                    : parametersTable.Rows.ToDictionary(
                        r => r["Name"],
                        r => (object) r["Value"],
                        StringComparer.InvariantCultureIgnoreCase);

                ScenarioContext.Current.Set(valueByName, ScenarioContextKeys.RequestParameters);

                requestUrl = OwinUriHelper.BuildCompositeUri(
                    string.Format(
                        "{0}/{1}?{2}",
                        compositeCategoryName,
                        pluralizedCompositeName,
                        string.Join("&", valueByName.Select(kvp => kvp.Key + "=" + Uri.EscapeDataString(kvp.Value.ToString())))));
            }
            else
            {
                throw new NotSupportedException(
                    string.Format("Request pattern '{0}' is not yet explicity supported by the test step definition.", requestPattern));
            }

            if (!includeCorrelation)
            {
                ScenarioContext.Current.Remove(ScenarioContextKeys.RequestCorrelationId);
            }

            var getResponseMessage = httpClient.GetAsync(requestUrl)
                                               .GetResultSafely();

            // Save the response, and the resource collection name for the scenario
            ScenarioContext.Current.Set(getResponseMessage);
        }