Пример #1
0
        public void ShouldGetPropertyBag()
        {
            // Arrange
            var transformer = new Transformer <int>(null);
            var value       = new
            {
                key1 = new Uri("http://localhost/test"),
                key2 = "test", parameters = new Dictionary <string, object> {
                    { "key3", "test4" }, { "key4", 5.77f }
                },
                parameter = new KeyValuePair <string, object>("key5", 222),
                complex   = new { key7 = true, key8 = false },
                transformer
            };

            // Act
            var result = SpotifyObjectHelpers.GetPropertyBag(value);

            // Assert
            result.ShouldBeEquivalentTo(new[]
            {
                new KeyValuePair <string, object>("key1", new Uri("http://localhost/test")),
                new KeyValuePair <string, object>("key2", "test"),
                new KeyValuePair <string, object>("key3", "test4"),
                new KeyValuePair <string, object>("key4", 5.77f),
                new KeyValuePair <string, object>("key5", 222),
                new KeyValuePair <string, object>("key7", true),
                new KeyValuePair <string, object>("key8", false),
                new KeyValuePair <string, object>("transformer", transformer),
            });
        }
Пример #2
0
        protected IList <MockResult <T> > MockSend <T>(HttpMethod httpMethod, Func <int, T> factory = null)
        {
            int i           = 0;
            var mockResults = new List <MockResult <T> >();

            this.SpotifyHttpClientMock
            .Setup(x => x.SendAsync <T>(
                       It.IsAny <Core.Client.UriParts>(),
                       httpMethod,
                       It.IsAny <IEnumerable <KeyValuePair <string, string> > >(),
                       It.IsAny <object>(),
                       It.IsAny <CancellationToken>()))
            .Returns((Func <Core.Client.UriParts, HttpMethod, IEnumerable <KeyValuePair <string, string> >, object, CancellationToken, Task <T> >)((uriParts, innerHttpMehod, requestHeaders, requestBodyParameters, cancellationToken) =>
            {
                var result = factory == null ? (T)Activator.CreateInstance(typeof(T)) : factory(i++);

                mockResults.Add(new MockResult <T>()
                {
                    QueryParameters = ProcessQueryStringParameters(SpotifyObjectHelpers.GetPropertyBag(uriParts.QueryStringParameters)).Select((KeyValuePair <string, object> item) => (item.Key, item.Value)).ToList(),
                    RouteValues     = ProcessRouteValues(uriParts.RouteValues),
                    BodyParameters  = SpotifyObjectHelpers.GetPropertyBag(requestBodyParameters).Select((KeyValuePair <string, object> item) => (item.Key, item.Value)).ToList(),
                    Result          = result
                });

                return(Task.FromResult <T>(result));
            }));
Пример #3
0
 private static HttpContent CreateHttpFormUrlEncodedContent(object parameters)
 {
     return(parameters == null
         ?
            null
         :
            new FormUrlEncodedContent(SpotifyObjectHelpers.GetPropertyBag(parameters).Select(item => new KeyValuePair <string, string>(item.Key, item.Value.ToInvariantString()))));
 }
Пример #4
0
        public async Task ShouldNotMakeRepeatedCallsWithInvalidAccessTokenAsync()
        {
            // Arrange
            this.DateTimeOffsetProviderMock.Setup(x => x.GetUtcNow()).Returns(new DateTimeOffset(new DateTime(2005, 1, 1)));

            const string accessToken1    = "test access token 1";
            const string accessToken2    = "test access token 2";
            var          accessTokenDto1 = new AccessTokenDto {
                ExpiresIn = 3600, Token = accessToken1
            };
            var accessTokenDto2 = new AccessTokenDto {
                ExpiresIn = 3600, Token = accessToken2
            };

            const string userId        = "johnsmith";
            var          expectedUser1 = new PublicUser {
                Id = userId, DisplayName = "John Smith"
            };

            this.AuthorizationFlowsHttpClientMock
            .SetupSequence(x => x.SendAsync <AccessTokenDto>(
                               It.Is <UriParts>(item =>
                                                item.BaseUri == this.Options.TokenEndpoint &&
                                                item.QueryStringParameters == null &&
                                                item.RouteValues == null),
                               HttpMethod.Post,
                               It.Is <IEnumerable <KeyValuePair <string, string> > >((IEnumerable <KeyValuePair <string, string> > item) => item.Single().Equals(new KeyValuePair <string, string>("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{this.Options.ClientId}:{this.Options.ClientSecret}"))}"))),
                               It.Is <object>(item => SpotifyObjectHelpers.GetPropertyBag(item).Single().Equals(new KeyValuePair <string, object>("grant_type", "client_credentials"))),
                               It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(accessTokenDto1))
            .Throws(new SpotifyHttpResponseWithErrorCodeException(System.Net.HttpStatusCode.ServiceUnavailable, null, string.Empty))
            .Returns(Task.FromResult(accessTokenDto2));

            this.HttpClientWrapperMock
            .SetupSequence(x => x.SendAsync(
                               It.Is <HttpRequest <PublicUser> >(httpRequest => httpRequest.RequestHeaders.Contains(new KeyValuePair <string, string>("Authorization", $"Bearer {accessToken1}"))),
                               It.IsAny <CancellationToken>()))
            .Throws(new SpotifyHttpResponseWithErrorCodeException(System.Net.HttpStatusCode.Unauthorized, null, string.Empty));

            this.HttpClientWrapperMock
            .SetupSequence(x => x.SendAsync(
                               It.Is <HttpRequest <PublicUser> >(httpRequest => httpRequest.RequestHeaders.Contains(new KeyValuePair <string, string>("Authorization", $"Bearer {accessToken2}"))),
                               It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(expectedUser1));

            // Act + Assert
            ((Func <Task>)(() => this.Client.User(userId).GetAsync()))
            .ShouldThrow <SpotifyHttpResponseWithErrorCodeException>()
            .Which.ErrorCode.Should().Be(System.Net.HttpStatusCode.ServiceUnavailable);

            var user = await this.Client.User(userId).GetAsync();

            user.ShouldBeEquivalentTo(expectedUser1);
        }
Пример #5
0
        private static object CombineParameters(object parameters, object optionalParameters)
        {
            var optionalPropertyBag = SpotifyObjectHelpers.GetPropertyBag(optionalParameters).Where(item => item.Value != null).ToList();

            if (optionalPropertyBag.Any())
            {
                return(new { parameters = parameters, optionalParameters = optionalPropertyBag });
            }
            else
            {
                return(parameters);
            }
        }
Пример #6
0
 protected ISetupSequentialResult <Task <AccessTokenDto> > MockGetAccessToken(string refereshToken)
 {
     return(this.AuthorizationFlowsHttpClientMock
            .SetupSequence(x => x.SendAsync <AccessTokenDto>(
                               It.Is <UriParts>(item =>
                                                item.BaseUri == new Uri(this.tokenEndpoint) &&
                                                item.QueryStringParameters == null &&
                                                item.RouteValues == null),
                               HttpMethod.Post,
                               It.Is <IEnumerable <KeyValuePair <string, string> > >((IEnumerable <KeyValuePair <string, string> > item) => item.Single().Equals(new KeyValuePair <string, string>("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{ClientId}:{ClientSecret}"))}"))),
                               It.Is <object>(item =>
                                              SpotifyObjectHelpers.GetPropertyBag(item).Count() == 2 &&
                                              SpotifyObjectHelpers.GetPropertyBag(item).Contains(new KeyValuePair <string, object>("grant_type", "refresh_token")) &&
                                              SpotifyObjectHelpers.GetPropertyBag(item).Contains(new KeyValuePair <string, object>("refresh_token", refereshToken))),
                               It.IsAny <CancellationToken>())));
 }
Пример #7
0
        private static Uri GetCompleteUri(IList <KeyValuePair <Type, object> > transformersSourceValues, UriParts uriParts)
        {
            var relativeUri = string.Join("/", uriParts.RouteValues.EmptyIfNull().Select(item => GetOrTransform(item, transformersSourceValues)).Select(item => item.ToUrlString()));

            var uriBuilder = new UriBuilder(new Uri(uriParts.BaseUri, relativeUri));

            var queryString =
                SpotifyObjectHelpers.GetPropertyBag(uriParts.QueryStringParameters)
                .Select(item => new KeyValuePair <string, object>(item.Key, GetOrTransform(item.Value, transformersSourceValues)))
                .GetQueryString();

            if (!string.IsNullOrEmpty(queryString))
            {
                uriBuilder.Query = queryString;
            }

            return(uriBuilder.Uri);
        }