public async void GetContent_given_albumid_with_images_of_invalid_type_returns_empty_album()
        {
            var mock = new Mock <ImgurRatelimiter>(null);

            mock.Setup(m => m.IsRequestAllowed()).Returns(true);
            mock.Setup(m => m.LimitsHaveBeenLoaded()).Returns(true);

            var albumId  = "example";
            var imageNum = 15;
            var album    = new ImgurAlbum {
                Images = new List <ImgurImage>(Enumerable.Repeat(new ImgurImage {
                    Type = "image/test"
                }, imageNum))
            };
            var handler = StubHttpClient.GetHandler();

            handler.AddResponse(new Uri($"https://api.imgur.com/3/album/{albumId}"), HttpStatusCode.OK, new ApiHelper <ImgurAlbum> {
                Data = album
            });

            var source = new ImgurAlbumSource(StubHttpClient.Create(handler), mock.Object);
            var result = await source.GetContent(albumId);

            Assert.NotNull(result);
            Assert.NotNull(result.Images);
            Assert.Equal(0, result.Images.Count);
            mock.Verify(i => i.LimitsHaveBeenLoaded(), Times.Once);
            mock.Verify(i => i.IsRequestAllowed(), Times.Once);
        }
Пример #2
0
        public async void GetContent_given_valid_url_of_invalid_imageformat_returns_null()
        {
            var mock = new Mock <ImgurRatelimiter>(null);

            mock.Setup(m => m.IsRequestAllowed()).Returns(true);
            mock.Setup(m => m.LimitsHaveBeenLoaded()).Returns(true);

            var imageId = "example";
            var output  = new ImgurImage {
                Height = 5, Width = 10, Title = "test", Link = $"i.imgur.com/{imageId}", Type = "image/png"
            };

            var handler = StubHttpClient.GetHandler();

            handler.AddResponse(new Uri($"https://api.imgur.com/3/image/{imageId}"), HttpStatusCode.OK, new ApiHelper <ImgurImage> {
                Data = output
            });

            var source = new ImgurImageSource(StubHttpClient.Create(handler), mock.Object);

            source.Settings = CreateSettings();
            var result = await source.GetContent(imageId);

            Assert.Null(result);
            mock.Verify(i => i.LimitsHaveBeenLoaded(), Times.Once);
            mock.Verify(i => i.IsRequestAllowed(), Times.Once);
        }
Пример #3
0
        public async void GetContent_given_url_for_listing_with_a_selfpost_returns_empty_album()
        {
            var tokenMock = new Mock <ITokenAcquirer <RedditToken> >();

            tokenMock.Setup(m => m.AcquireToken()).ReturnsAsync(new RedditToken {
                Access_token = "test"
            });

            var query        = "example.json";
            var returnedInfo = CreateApiReturnValue(new RedditPost {
                Is_self = true
            });

            var handler = StubHttpClient.GetHandler();

            handler.AddResponse(new Uri($"https://oauth.reddit.com/r/{query}?limit=1"), HttpStatusCode.OK, returnedInfo);
            var client = StubHttpClient.Create(handler);

            var source = new RedditSource(client, null, null, null, tokenMock.Object);
            var result = await source.GetContent(query, 1);

            Assert.NotNull(result);
            Assert.Empty(result.GetImages());
            Assert.Empty(result.GetCollections());
            tokenMock.Verify(i => i.AcquireToken(), Times.Once);
        }
Пример #4
0
        public async void GetContent_given_url_for_listing_with_link_containing_extension_but_nonsupported_domain_returns_album_with_image()
        {
            var tokenMock = new Mock <ITokenAcquirer <RedditToken> >();

            tokenMock.Setup(m => m.AcquireToken()).ReturnsAsync(new RedditToken {
                Access_token = "test"
            });

            var url = "example.com/test.jpg";

            var query        = "example.json";
            var returnedInfo =
                CreateApiReturnValue(new RedditPost
            {
                Domain = "example.com",
                Url    = url
            });

            var handler = StubHttpClient.GetHandler();

            handler.AddResponse(new Uri($"https://oauth.reddit.com/r/{query}?limit=1"), HttpStatusCode.OK, returnedInfo);
            var client = StubHttpClient.Create(handler);

            var source = new RedditSource(client, null, null, null, tokenMock.Object);

            source.Settings = CreateSettings();
            var result = await source.GetContent(query, 1);

            Assert.NotNull(result);
            Assert.Equal(1, result.GetImages().Count());
            Assert.NotNull(result.GetImages().First() as GenericImage);
            tokenMock.Verify(i => i.AcquireToken(), Times.Once);
        }
        public async void GetContent_given_username_with_1_image_of_invalid_type_returns_empty_album()
        {
            var mock = new Mock <ImgurRatelimiter>(null);

            mock.Setup(m => m.IsRequestAllowed()).Returns(true);
            mock.Setup(m => m.LimitsHaveBeenLoaded()).Returns(true);

            var username = "******";
            var image    = new ImgurImage {
                Height = 10, Width = 5, Title = "title", Type = "image/png"
            };
            var handler = StubHttpClient.GetHandler();

            handler.AddResponse(new Uri($"https://api.imgur.com/3/account/{username}/images/count"), HttpStatusCode.OK, new ApiHelper <int> {
                Data = 1
            });
            handler.AddResponse(new Uri($"https://api.imgur.com/3/account/{username}/images/0"), HttpStatusCode.OK, new ApiHelper <ICollection <ImgurImage> > {
                Data = new List <ImgurImage> {
                    image
                }
            });

            var source = new ImgurAccountImagesSource(StubHttpClient.Create(handler), mock.Object);

            source.Settings = CreateSettings();
            var result = await source.GetContent(username);

            Assert.NotNull(result);
            Assert.Empty(result.Images);

            mock.Verify(i => i.LimitsHaveBeenLoaded(), Times.Once);
            mock.Verify(i => i.IsRequestAllowed(), Times.Exactly(2));
        }
        public async void GetContent_given_nonexistant_url_returns_null()
        {
            var testUrl = "example.deviantart.com/testtesttest";
            var handler = StubHttpClient.GetHandler();

            handler.AddResponse(new Uri($"http://backend.deviantart.com/oembed?url={testUrl}"), HttpStatusCode.NotFound, new object());

            var source = new DeviantartImageSource(StubHttpClient.Create(handler));
            var result = await source.GetContent(testUrl);

            Assert.Null(result);
        }
Пример #7
0
        public async void GetContent_when_connection_forbidden_returns_response_with_statuscode()
        {
            var response = new ImgurRatelimitResponse();
            var handler  = StubHttpClient.GetHandler();

            handler.AddResponse(new Uri("https://api.imgur.com/3/credits"), HttpStatusCode.Forbidden, new ApiHelper <ImgurRatelimitResponse> {
                Data = response
            });

            var source = new ImgurRatelimitSource(StubHttpClient.Create(handler));
            var result = await source.GetContent();

            Assert.NotNull(result);
            Assert.Equal(HttpStatusCode.Forbidden, result.StatusCode);
        }
        public async void GetContent_given_valid_url_of_invalid_imageformat_returns_null()
        {
            var testUrl = "example.deviantart.com/testtesttest.ini";
            var output  = new DeviantartImage {
                Author_name = "example", Height = 5, Width = 10, Title = "test", Url = testUrl
            };

            var handler = StubHttpClient.GetHandler();

            handler.AddResponse(new Uri($"http://backend.deviantart.com/oembed?url={testUrl}"), HttpStatusCode.OK, output);

            var source = new DeviantartImageSource(StubHttpClient.Create(handler));

            source.Settings = CreateSettings();
            var result = await source.GetContent(testUrl);

            Assert.Null(result);
        }
        public async void GetContent_given_username_with_160_images_of_valid_type_returns_album_with_160_image()
        {
            var mock = new Mock <ImgurRatelimiter>(null);

            mock.Setup(m => m.IsRequestAllowed()).Returns(true);
            mock.Setup(m => m.LimitsHaveBeenLoaded()).Returns(true);

            var username = "******";
            var num      = 160;
            var list50   = new List <ImgurImage>(Enumerable.Repeat(new ImgurImage {
                Type = "image/jpg"
            }, 50));
            var list10 = new List <ImgurImage>(Enumerable.Repeat(new ImgurImage {
                Type = "image/jpg"
            }, 10));
            var handler = StubHttpClient.GetHandler();

            handler.AddResponse(new Uri($"https://api.imgur.com/3/account/{username}/images/count"), HttpStatusCode.OK, new ApiHelper <int> {
                Data = num
            });
            handler.AddResponse(new Uri($"https://api.imgur.com/3/account/{username}/images/0"), HttpStatusCode.OK, new ApiHelper <ICollection <ImgurImage> > {
                Data = list50
            });
            handler.AddResponse(new Uri($"https://api.imgur.com/3/account/{username}/images/1"), HttpStatusCode.OK, new ApiHelper <ICollection <ImgurImage> > {
                Data = list50
            });
            handler.AddResponse(new Uri($"https://api.imgur.com/3/account/{username}/images/2"), HttpStatusCode.OK, new ApiHelper <ICollection <ImgurImage> > {
                Data = list50
            });
            handler.AddResponse(new Uri($"https://api.imgur.com/3/account/{username}/images/3"), HttpStatusCode.OK, new ApiHelper <ICollection <ImgurImage> > {
                Data = list10
            });

            var source = new ImgurAccountImagesSource(StubHttpClient.Create(handler), mock.Object);

            source.Settings = CreateSettings();
            var result = await source.GetContent(username);

            Assert.NotNull(result);
            Assert.Equal(num, result.Images.Count);

            mock.Verify(i => i.LimitsHaveBeenLoaded(), Times.Once);
            mock.Verify(i => i.IsRequestAllowed(), Times.AtLeastOnce);
        }
Пример #10
0
        public async void GetContent_given_nonexistant_url_returns_null()
        {
            var mock = new Mock <ImgurRatelimiter>(null);

            mock.Setup(m => m.IsRequestAllowed()).Returns(true);
            mock.Setup(m => m.LimitsHaveBeenLoaded()).Returns(true);

            var imageId = "example";
            var handler = StubHttpClient.GetHandler();

            handler.AddResponse(new Uri($"https://api.imgur.com/3/image/{imageId}"), HttpStatusCode.NotFound, new object());

            var source = new ImgurImageSource(StubHttpClient.Create(handler), mock.Object);
            var result = await source.GetContent(imageId);

            Assert.Null(result);
            mock.Verify(i => i.LimitsHaveBeenLoaded(), Times.Once);
            mock.Verify(i => i.IsRequestAllowed(), Times.Once);
        }
Пример #11
0
        public async void GetContent_query_large_number_of_varying_posts()
        {
            var tokenMock = new Mock <ITokenAcquirer <RedditToken> >();

            tokenMock.Setup(m => m.AcquireToken()).ReturnsAsync(new RedditToken {
                Access_token = "test"
            });

            var imgurMock = new Mock <ISource <ImgurImage> >();

            imgurMock.Setup(m => m.GetContent(It.IsAny <string>())).ReturnsAsync(new ImgurImage());

            var return1 = CreateApiReturnValue(Enumerable.Repeat(new RedditPost {
                Domain = "imgur.com", Url = "imgur.com/test"
            }, 100).ToArray());

            return1.Data.After = nameof(return1);
            var return2 = CreateApiReturnValue(Enumerable.Repeat(new RedditPost {
                Is_self = true
            }, 100).ToArray());

            return2.Data.After = nameof(return2);
            var return3 = CreateApiReturnValue(Enumerable.Repeat(new RedditPost {
                Domain = "i.imgur.com", Url = "i.imgur.com/test"
            }, 40).ToArray());

            var query   = "example.json";
            var handler = StubHttpClient.GetHandler();

            handler.AddResponse(new Uri($"https://oauth.reddit.com/r/{query}?limit=100"), HttpStatusCode.OK, return1);
            handler.AddResponse(new Uri($"https://oauth.reddit.com/r/{query}?limit=100&after={nameof(return1)}&count=100"), HttpStatusCode.OK, return2);
            handler.AddResponse(new Uri($"https://oauth.reddit.com/r/{query}?limit=40&after={nameof(return2)}&count=200"), HttpStatusCode.OK, return3);
            var client = StubHttpClient.Create(handler);

            var source = new RedditSource(client, null, imgurMock.Object, null, tokenMock.Object);
            var result = await source.GetContent(query, 240);

            Assert.NotNull(result);
            Assert.Equal(140, result.GetImages().Count());
            imgurMock.Verify(i => i.GetContent(It.IsAny <string>()), Times.Exactly(140));
            tokenMock.Verify(i => i.AcquireToken(), Times.AtLeast(1));
        }
        public async void GetContent_when_ratelimiter_allows_request_given_nonexistant_username_returns_empty_album()
        {
            var mock = new Mock <ImgurRatelimiter>(null);

            mock.Setup(m => m.IsRequestAllowed()).Returns(true);
            mock.Setup(m => m.LimitsHaveBeenLoaded()).Returns(true);

            var username = "******";
            var handler  = StubHttpClient.GetHandler();

            handler.AddResponse(new Uri($"https://api.imgur.com/3/account/{username}/images/count"), HttpStatusCode.NotFound, new object());

            var source = new ImgurAccountImagesSource(StubHttpClient.Create(handler), mock.Object);
            var result = await source.GetContent(username);

            Assert.NotNull(result);
            Assert.Empty(result.Images);
            mock.Verify(i => i.LimitsHaveBeenLoaded(), Times.Once);
            mock.Verify(i => i.IsRequestAllowed(), Times.Once);
        }
Пример #13
0
        public async void GetContent_given_url_for_listing_with_link_to_imgur_album_returns_album_with_images()
        {
            var tokenMock = new Mock <ITokenAcquirer <RedditToken> >();

            tokenMock.Setup(m => m.AcquireToken()).ReturnsAsync(new RedditToken {
                Access_token = "test"
            });

            var albumId   = "test";
            var url       = $"imgur.com/a/{albumId}";
            var imgurMock = new Mock <ISource <ImgurAlbum> >();

            imgurMock.Setup(m => m.GetContent(albumId)).ReturnsAsync(new ImgurAlbum {
                Images = new List <ImgurImage> {
                    new ImgurImage()
                }
            });

            var query        = "example.json";
            var returnedInfo =
                CreateApiReturnValue(new RedditPost
            {
                Domain = "imgur.com",
                Url    = url
            });

            var handler = StubHttpClient.GetHandler();

            handler.AddResponse(new Uri($"https://oauth.reddit.com/r/{query}?limit=1"), HttpStatusCode.OK, returnedInfo);
            var client = StubHttpClient.Create(handler);

            var source = new RedditSource(client, imgurMock.Object, null, null, tokenMock.Object);
            var result = await source.GetContent(query, 1);

            Assert.NotNull(result);
            Assert.Equal(1, result.GetImages().Count());
            Assert.NotNull(result.GetImages().First() as ImgurImage);
            tokenMock.Verify(i => i.AcquireToken(), Times.Once);
            imgurMock.Verify(i => i.GetContent(albumId), Times.Once);
        }
Пример #14
0
        public async void GetContent_success_returns_ratelimit_response()
        {
            var response = new ImgurRatelimitResponse {
                ClientRemaining = 10, ClientLimit = 20, UserLimit = 30, UserRemaining = 40, UserReset = 50
            };
            var handler = StubHttpClient.GetHandler();

            handler.AddResponse(new Uri("https://api.imgur.com/3/credits"), HttpStatusCode.OK, new ApiHelper <ImgurRatelimitResponse> {
                Data = response
            });

            var source = new ImgurRatelimitSource(StubHttpClient.Create(handler));
            var result = await source.GetContent();

            Assert.NotNull(result);
            Assert.Equal(response.ClientRemaining, result.ClientRemaining);
            Assert.Equal(response.ClientLimit, result.ClientLimit);
            Assert.Equal(response.UserLimit, result.UserLimit);
            Assert.Equal(response.UserRemaining, result.UserRemaining);
            Assert.Equal(response.UserReset, result.UserReset);
            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
        }
Пример #15
0
        public ChatyApiServiceSpecs()
        {
            _httpClient = StubHttpClient.Create()
                          .Json("/chat/list/some_wx_id", new[] { "1556867244", "1556867241" })
                          .Json("/chat/detail/some_wx_id/1556867244", new[] {
                new ChatMessage
                {
                    SourceName      = "someone",
                    SourceTime      = "2018/12/02 12:00:08",
                    SourceTimestamp = 1547552931,
                    SourceWxId      = "Wx_879LJJKJGS",
                    Content         = new TextChatMessageContent()
                    {
                        Text = "text1"
                    }
                },
                new ChatMessage
                {
                    SourceName      = "Another one",
                    SourceTime      = "2018/12/02 12:00:09",
                    SourceTimestamp = 1547552932,
                    SourceWxId      = "Wx_879LKJGSJJ",
                    Content         = new TextChatMessageContent()
                    {
                        Text = "text2"
                    }
                }
            })
                          .Json("/chat/detail/some_wx_id/1556867241", new[] {
                new ChatMessage
                {
                    SourceName      = "someone",
                    SourceTime      = "2018/12/02 12:00:08",
                    SourceTimestamp = 1547552933,
                    SourceWxId      = "Wx_879LJJKJGS",
                    Content         = new FileChatMessageContent()
                    {
                        FileId   = "89257293",
                        FileName = "SomeFile.jpg"
                    }
                },
                new ChatMessage
                {
                    SourceName      = "Another one",
                    SourceTime      = "2018/12/02 12:00:09",
                    SourceTimestamp = 1547552934,
                    SourceWxId      = "Wx_879LKJGSJJ",
                    Content         = new UrlChatMessageContent()
                    {
                        Link = "http://dotnetclub"
                    }
                }
            })
                          .Json("/bot/info", new ChatyBotInfoViewModel
            {
                Name    = "Someone",
                QrCode  = "https://weixin.com/2o3kl3z",
                Weixin  = "wx_l09d",
                ChatyId = "34kds"
            }).Json("/bot/pair", new ChatyVerifyResultViewModel
            {
                Name = "Someone",
                Id   = "wx_l09d"
            }).When(req =>
            {
                if (req.RequestUri.PathAndQuery.StartsWith("/chat/file/"))
                {
                    var ms = new MemoryStream();
                    ms.Write(Encoding.UTF8.GetBytes("This is file content"));
                    ms.Seek(0, SeekOrigin.Begin);

                    return(new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StreamContent(ms)
                        {
                            Headers =
                            {
                                ContentType = new MediaTypeHeaderValue("application/octet-stream")
                            }
                        }
                    });
                }

                return(null);
            });

            var chatyOptions = new Mock <IOptions <ChatyOptions> >();

            chatyOptions.SetupGet(op => op.Value).Returns(new ChatyOptions
            {
                ServiceBaseUrl = "http://localhost:3000",
                AllowedUsers   = string.Format("{0},someone_else", _userAllowedToUseChaty)
            });
            _normalChatyApiService = new ChatyApiService(chatyOptions.Object, _httpClient, NullLogger <ChatyApiService> .Instance);
        }