Example #1
0
        public async Task ShortenUrl_Success()
        {
            DeleteDatabase();
            using (var _dbContext = dbContext)
            {
                var TestData = GetTestData();
                foreach (var Data in TestData)
                {
                    _dbContext.Urls.Add(Data);
                }
                _dbContext.SaveChanges();
                _service = new ShortenerService(_dbContext, _config, _clientFactory, _helper);

                var input = GetShortenUrlInput();
                _helper.Encode(Arg.Any <int>()).Returns("hfRd");
                _helper.GetTitle(Arg.Any <string>()).Returns("Gmail");

                var resp = await _service.ShortenURL(input);

                Assert.IsNotNull(resp);
                Assert.IsNull(resp.Message);
                Assert.IsNotNull(resp.Url);
                Assert.AreEqual(resp.Url.OrignalUrl, input.Url);
            }
        }
Example #2
0
        public async Task Given_FriendlyUrl_When_ShortenAsync_Invoked_Then_It_Should_Return_Result(string hostname, int length, string original, string friendly)
        {
            var shortenUrl = new Mock <ShortenUrlSettings>();

            shortenUrl.SetupGet(p => p.Hostname).Returns(hostname);
            shortenUrl.SetupGet(p => p.Length).Returns(length);

            var settings = this._mocker.CreateAppSettingsInstance();

            settings.SetupGet(p => p.ShortenUrl).Returns(shortenUrl.Object);

            var query   = new Mock <IQuery>();
            var command = new Mock <ICommand>();

            var service = new ShortenerService(settings.Object, query.Object, command.Object);

            var payload = new ShortenerRequest()
            {
                Original = new Uri(original),
                Friendly = friendly
            };

            var result = await service.ShortenAsync(payload).ConfigureAwait(false);

            result.Original.ToString().TrimEnd('/').Should().Be(original.TrimEnd('/'));
            result.Shortened.ToString().TrimEnd('/').Should().Be($"https://{hostname}/{friendly.TrimEnd('/')}");
            result.ShortUrl.Should().Be(friendly);
        }
Example #3
0
 public PredictionController(ILogger <PredictionController> logger)
 {
     _logger = logger;
     predictionsRepository = new PredictionsRepository();
     boardsRepository      = new BoardsRepository();
     shortenerService      = new ShortenerService();
 }
Example #4
0
        public async Task ShortUrlMustBeNonEmpty()
        {
            var sourceUrl = "https://google.com/";

            var url = await ShortenerService.GetShortenUrlAsync(sourceUrl, Guid.Empty);

            Assert.That(url, Is.Not.Empty);
        }
Example #5
0
        public async Task DatabaseMustHaveGeneratedShortLinks()
        {
            var sourceUrl = "https://google.com/";

            await ShortenerService.GetShortenUrlAsync(sourceUrl, Guid.Empty);

            Assert.That(DatabaseContextStub.ShortLinks, Is.Not.Empty);
        }
Example #6
0
        public async Task DatabaseMustHaveRecordWithEqualShortUrl()
        {
            var sourceUrl = "https://google.com/";

            var url = await ShortenerService.GetShortenUrlAsync(sourceUrl, Guid.Empty);

            Assert.That(DatabaseContextStub.ShortLinks.Single().ShortUrl, Is.EqualTo(url));
        }
Example #7
0
        public async Task DatabaseMustHaveRecordWithEqualUserId()
        {
            var sourceUrl = "https://google.com/";
            var userId    = Guid.NewGuid();

            await ShortenerService.GetShortenUrlAsync(sourceUrl, userId);

            Assert.That(DatabaseContextStub.ShortLinks.Single().UserId, Is.EqualTo(userId));
        }
Example #8
0
        public async Task CreateShortUrlAsync_NonHttpUrl_ReturnsError(ShortenerService sut)
        {
            // When
            var result = await sut.CreateShortUrlAsync("ftp://ftp.shouldfail.com/");

            // Then
            Assert.IsNull(result.Item1);
            Assert.IsNotEmpty(result.Item2);
        }
Example #9
0
        public async Task EqualSourceUrlsMustHaveDifferentShortUrls()
        {
            var sourceUrl = "https://google.com/";

            var url1 = await ShortenerService.GetShortenUrlAsync(sourceUrl, Guid.Empty);

            var url2 = await ShortenerService.GetShortenUrlAsync(sourceUrl, Guid.Empty);

            Assert.That(url1, Is.Not.EqualTo(url2));
        }
Example #10
0
        public void Given_Null_When_ShortenAsync_Invoked_Then_It_Should_Throw_Exception()
        {
            var settings = this._mocker.CreateAppSettingsInstance();
            var query    = new Mock <IQuery>();
            var command  = new Mock <ICommand>();

            var service = new ShortenerService(settings.Object, query.Object, command.Object);

            Func <Task> func = async() => await service.ShortenAsync(null).ConfigureAwait(false);

            func.Should().Throw <ArgumentNullException>();
        }
Example #11
0
        public async Task SourceUrlMustBeReturned()
        {
            const string expectedSourceUrl = "https://google.com/";
            const string shortUrl          = "fh84ea";

            DatabaseContextStub.ShortLinks.Add(new ShortLink {
                ShortUrl = shortUrl, SourceUrl = expectedSourceUrl
            });

            var sourceUrl = await ShortenerService.GetSourceUrlByShortenUrlAsync(shortUrl);

            Assert.That(sourceUrl, Is.EqualTo(expectedSourceUrl));
        }
Example #12
0
        public async Task ReceiveCountIncrementShouldBeApplied()
        {
            const string shortUrl  = "fh84ea";
            var          shortLing = new ShortLink {
                ShortUrl = "fh84ea", SourceUrl = "https://google.com/"
            };

            DatabaseContextStub.ShortLinks.Add(shortLing);

            await ShortenerService.GetSourceUrlByShortenUrlAsync(shortUrl);

            Assert.That(shortLing.ReceiveCounter, Is.EqualTo(1));
        }
Example #13
0
        public async Task LargeSourceUrlProducesLessOrEqualSixLengthShortUrl()
        {
            var largeUrl = @"https://google.com/asdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweq
asdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweq
asdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweq
asdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweq
asdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweq
asdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweq
asdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweqasdweq";

            var url = await ShortenerService.GetShortenUrlAsync(largeUrl, Guid.Empty);

            Assert.That(url.Length, Is.LessThanOrEqualTo(6));
        }
Example #14
0
        public async Task CreateShortUrlAsync_ExistingLongUrl_ReturnsSameShortCode(
            string fakeShortCode,
            [Frozen] Mock <IShortenUrlRepository> mockShortUrlRepository,
            ShortenerService sut)
        {
            // Given
            mockShortUrlRepository.Setup(m => m.FindShortCode(It.IsAny <string>()))
            .Returns(fakeShortCode);

            // When
            var result = await sut.CreateShortUrlAsync("http://www.google.com/");

            // Then
            Assert.AreEqual(result.Item1, fakeShortCode); // shortcode result
            Assert.IsNull(result.Item2);                  // error should be null
        }
Example #15
0
        public async Task CreateShortUrlAsync_ValidLongUrl_ReturnsNewShortCode(
            [Frozen] Mock <IShortenUrlRepository> mockShortUrlRepository,
            ShortenerService sut)
        {
            // Given
            mockShortUrlRepository.Setup(m => m.FindShortCode(It.IsAny <string>()))
            .Returns(string.Empty);

            // When
            var result = await sut.CreateShortUrlAsync("http://www.google.com/");

            // Then
            mockShortUrlRepository.Verify(m => m.SaveAsync(result.Item1, It.IsAny <string>()));

            Assert.IsNotEmpty(result.Item1); // shortcode result
            Assert.IsNull(result.Item2);     // error should be null
        }
Example #16
0
        public async Task Given_ShortUrl_When_ExistsAsync_Invoked_Then_It_Should_Return_True(string shortUrl)
        {
            var settings = this._mocker.CreateAppSettingsInstance();

            var item = new UrlItemEntity();

            var query = new Mock <IQuery>();

            query.Setup(p => p.GetUrlItemEntityAsync(It.IsAny <string>())).ReturnsAsync(item);

            var command = new Mock <ICommand>();

            var service = new ShortenerService(settings.Object, query.Object, command.Object);

            var result = await service.ExistsAsync(shortUrl).ConfigureAwait(false);

            result.Should().BeTrue();
        }
        public static async Task <HttpResponseMessage> Run(HttpRequestMessage req)
        {
            // Get request body
            dynamic data = await req.Content.ReadAsAsync <object>();

            string longUrl = data?.url;

            if (string.IsNullOrWhiteSpace(longUrl))
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest));
            }

            var service = new ShortenerService();
            var result  = await service.CreateShortUrlAsync(longUrl.Trim());

            return(result.Item1 == null
                ? req.CreateErrorResponse(HttpStatusCode.BadRequest, result.Item2)
                : req.CreateResponse(HttpStatusCode.Created, result.Item1));
        }
        public static async Task <HttpResponseMessage> Run(HttpRequestMessage req, string shortCode)
        {
            var service = new ShortenerService();

            string longUrl = await service.GetLongUrlAsync(shortCode);

            if (string.IsNullOrEmpty(longUrl))
            {
                return(req.CreateResponse(HttpStatusCode.NotFound));
            }

            // analytics
            string clientIp = GetClientIpAddress(req);
            await service.LogView(shortCode, longUrl, req.Headers.UserAgent.ToString(), clientIp);

            var response = req.CreateResponse(HttpStatusCode.Redirect);

            response.Headers.Add("Location", longUrl);
            return(response);
        }
Example #19
0
        public async Task DeleteUrlById_URLNotFound()
        {
            DeleteDatabase();
            using (var _dbContext = dbContext)
            {
                var TestData = GetTestData();
                foreach (var Data in TestData)
                {
                    _dbContext.Urls.Add(Data);
                }
                _dbContext.SaveChanges();
                _service = new ShortenerService(_dbContext, _config, _clientFactory, _helper);

                var input = GetDeleteUrlInput();
                input.UrlId = 11;
                var resp = await _service.DeleteUrlById(input);

                Assert.IsNotNull(resp);
                Assert.AreEqual(resp.Message, "No url found to delete");
            }
        }
Example #20
0
        public static async Task <HttpResponseMessage> Run(HttpRequestMessage req)
        {
            var service = new ShortenerService();

            var data = await service.GetLastXDaysUrlHistory();

            if (data == null)
            {
                return(req.CreateResponse(HttpStatusCode.OK));
            }

            string json = JsonConvert.SerializeObject(data,
                                                      new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(json, Encoding.UTF8, "application/json")
            });
        }
Example #21
0
        public async Task GetUrlListById_Success()
        {
            DeleteDatabase();
            using (var _dbContext = dbContext)
            {
                var TestData = GetTestData();
                foreach (var Data in TestData)
                {
                    _dbContext.Urls.Add(Data);
                }
                _dbContext.SaveChanges();
                _service = new ShortenerService(_dbContext, _config, _clientFactory, _helper);

                var input = "9b495ebe-045f-494f-b813-17b363f4a859";

                var resp = await _service.GetUrlListById(input);

                Assert.IsNotNull(resp);
                Assert.IsNull(resp.Error);
                Assert.AreEqual(resp.UrlList.Count, 2);
                Assert.IsNotNull(resp.UrlList[0]);
                Assert.IsNotNull(resp.UrlList[1]);
            }
        }
Example #22
0
        public async Task Given_ShortUrl_When_UpsertAsync_Invoked_Then_It_Should_Return_Result(HttpStatusCode statusCode)
        {
            var settings = this._mocker.CreateAppSettingsInstance();

            var item  = new UrlItemEntity();
            var query = new Mock <IQuery>();

            var command = new Mock <ICommand>();

            command.Setup(p => p.UpsertItemEntityAsync <UrlItemEntity>(It.IsAny <UrlItemEntity>())).ReturnsAsync((int)statusCode);

            var service = new ShortenerService(settings.Object, query.Object, command.Object);

            var payload = new ShortenerResponse()
            {
                EntityId      = Guid.NewGuid(),
                DateGenerated = DateTimeOffset.UtcNow,
                DateUpdated   = DateTimeOffset.UtcNow
            };

            var result = await service.UpsertAsync(payload).ConfigureAwait(false);

            result.Should().Be((int)statusCode);
        }
Example #23
0
        public async Task OrignalUrl_InvalidInput()
        {
            DeleteDatabase();
            using (var _dbContext = dbContext)
            {
                var TestData = GetTestData();
                foreach (var Data in TestData)
                {
                    _dbContext.Urls.Add(Data);
                }
                _dbContext.SaveChanges();
                _service = new ShortenerService(_dbContext, _config, _clientFactory, _helper);

                string input = "a";
                _helper.Decode(Arg.Any <string>()).Returns(1000001);

                var resp = await _service.OrignalURL(input);

                Assert.IsNotNull(resp);
                Assert.IsNull(resp.Url);
                Assert.IsNotNull(resp.Message);
                Assert.AreEqual(resp.Message, "Invalid Input");
            }
        }
Example #24
0
 public UrlRedirect(ShortenerService shortener)
 {
     this.shortener = shortener;
 }
Example #25
0
 public ShortenerController(ILogger <ShortenerController> logger, ShortenerService shortenerService)
 {
     this.logger            = logger;
     this._shortenerService = shortenerService;
 }
Example #26
0
 public ShortenerController(ShortenerService shortenerService)
 {
     this.shortenerService = shortenerService;
 }
Example #27
0
 public ShortenerController(ShortenerService shortener)
 {
     this.shortener = shortener;
 }