Exemplo n.º 1
0
            public async void ShouldReturnNotFound()
            {
                // Arrange
                var url = new UrlDto
                {
                    Id           = 2,
                    AccessCount  = 1,
                    ActualUrl    = "https://google.com",
                    ShortenedUrl = "GH65ff"
                };

                var urlDto = new UrlDto
                {
                    Id           = 8,
                    AccessCount  = 1,
                    ActualUrl    = "https://google.com",
                    ShortenedUrl = "GH65ff"
                };

                UrlServiceMock.Setup(x => x.UpdateUrl(url)).ReturnsAsync(url);

                // Act
                var result = await UrlControllerToTest.Put(urlDto);

                // Assert
                Assert.IsType <NotFoundResult>(result);
            }
Exemplo n.º 2
0
            public async void ShouldReturnOkResult()
            {
                // Arrange
                var url = new UrlCreate
                {
                    ActualUrl = "https://google.com"
                };

                var urlDto = new UrlDto
                {
                    Id           = 1,
                    ActualUrl    = "https://google.com",
                    ShortenedUrl = "fGwY73",
                    AccessCount  = 0
                };

                UrlServiceMock.Setup(x => x.AddUrl(url)).ReturnsAsync(urlDto);

                // Act
                var result = await UrlControllerToTest.Post(url);

                // Assert
                var okResult = Assert.IsType <OkObjectResult>(result);

                Assert.Same(urlDto, okResult.Value);
            }
Exemplo n.º 3
0
        public async Task <UrlDto> UpdateUrl(UrlDto url)
        {
            if (url == null)
            {
                throw new Exception("Not found");
            }
            var currentUrl = await _context.Urls.Where(u => u.Id == url.Id).FirstOrDefaultAsync();

            if (currentUrl == null)
            {
                throw new Exception("Not found");
            }

            currentUrl.ShortenedUrl = url.ShortenedUrl;
            currentUrl.ActualUrl    = url.ActualUrl;
            currentUrl.FriendlyName = url.FriendlyName;

            // An update should potentially clear down the access count? Left as is for now

            await _context.SaveChangesAsync();

            return(new UrlDto
            {
                Id = url.Id,
                ActualUrl = url.ActualUrl,
                ShortenedUrl = url.ShortenedUrl,
                AccessCount = currentUrl.AccessCount
            });
        }
Exemplo n.º 4
0
        public async Task <UrlDto> GetUrl(string shortened)
        {
            // Return the individual url specified.
            var url = await _context.Urls.Where(u => u.ShortenedUrl == shortened).FirstOrDefaultAsync();

            if (url == null)
            {
                throw new Exception("Not found");
            }

            // We should also update the access count here, as we can presume this is someone being redirected
            url.AccessCount += 1;
            _context.Urls.Update(url);
            await _context.SaveChangesAsync();

            UrlDto finalUrl = new UrlDto
            {
                Id           = url.Id,
                ActualUrl    = url.ActualUrl,
                FriendlyName = url.FriendlyName,
                ShortenedUrl = url.ShortenedUrl,
                AccessCount  = url.AccessCount
            };

            return(finalUrl);
        }
Exemplo n.º 5
0
        public async Task Should_Add_Url()
        {
            // Arrange
            var urlCreateDto = new UrlCreateBodyDto
            {
                Href       = "http://www.landesblasorchester.de",
                AnchorText = "Landesblasorchester Baden-Württemberg"
            };
            var expectedDto = new UrlDto()
            {
                Href       = urlCreateDto.Href,
                AnchorText = urlCreateDto.AnchorText,
                CreatedBy  = _staff.DisplayName,
                CreatedAt  = FakeDateTime.UtcNow
            };

            // Act
            HttpResponseMessage responseMessage = await _authenticatedServer
                                                  .CreateClient()
                                                  .AuthenticateWith(_staff)
                                                  .PostAsync(ApiEndpoints.ProjectsController.AddUrl(ProjectDtoData.HoorayForHollywood.Id), BuildStringContent(urlCreateDto));

            // Assert
            responseMessage.StatusCode.Should().Be(HttpStatusCode.Created);
            UrlDto result = await DeserializeResponseMessageAsync <UrlDto>(responseMessage);

            result.Should().BeEquivalentTo(expectedDto, opt => opt.Excluding(r => r.Id));
            result.Id.Should().NotBeEmpty();
            responseMessage.Headers.Location.AbsolutePath.Should().Be($"/{ApiEndpoints.UrlsController.Get(result.Id)}");
        }
Exemplo n.º 6
0
        public void GetLongUrlFor_ValidCode()
        {
            // Arrange
            var urlDto = new UrlDto
            {
                LongUrl  = _fixture.Create <string>(),
                ShortUrl = _fixture.Create <string>()
            };

            var mockedDal = new MockedDal(
                isShortCodeStored: true,
                getOriginalFor: urlDto.LongUrl);

            var service = new UrlService(mockedDal.GetObject);

            // Act
            var response = service.GetLongUrlFor(urlDto.ShortUrl);

            // Assert
            response
            .Should()
            .BeEquivalentTo(
                urlDto,
                "because the same long URL is returned by the program when using its code");
        }
Exemplo n.º 7
0
        public void GetShortUrlFor_UrlNotStored()
        {
            // Arrange
            var urlDto = new UrlDto
            {
                LongUrl  = $"http://{_fixture.Create<string>()}",
                ShortUrl = string.Empty
            };

            var mockedDal = new MockedDal(
                isUrlStored: false,
                getShortenedUrlFor: urlDto.ShortUrl);

            var service = new UrlService(mockedDal.GetObject);

            // Act
            service.GetShortUrlFor(urlDto.LongUrl);

            // Assert
            mockedDal.GetMock
            .Verify(_ =>
                    _.GetShortenedFor(It.IsAny <string>()),
                    Times.Never);

            mockedDal.GetMock
            .Verify(_ =>
                    _.IsUrlStored(It.IsAny <string>()),
                    Times.Once);

            mockedDal.GetMock
            .Verify(_ =>
                    _.StoreShortened(It.IsAny <string>(), It.IsAny <string>()),
                    Times.Once);
        }
        public async Task <IHttpActionResult> Post(UrlDto url)
        {
            try
            {
                Regex urlchk = new Regex(@"((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)+(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,15})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(/[a-zA-Z0-9\&amp;%_\./-~-]*)?", RegexOptions.Singleline | RegexOptions.IgnoreCase);
                if (urlchk.Match(url.Url).Length <= 0)
                {
                    return(this.BadRequest("Invalid URL"));
                }

                if (string.IsNullOrEmpty(url.Url))
                {
                    return(NotFound());
                }

                var shortUrl = this._utilityManager.ConvertToShortUrl(url.Url);
                var model    = await this._repository.Add(new UrlModel(shortUrl, url.Url));

                var cached = this._cacheManager.GetCached <UrlModel>(model.ShortUrl);
                if (cached == null)
                {
                    this._cacheManager.TryAddToCache <UrlModel>(model.ShortUrl, model);
                }
                return(this.Ok(model.ToWellFormattedObject()));
            }
            catch (Exception ex)
            {
                return(this.InternalServerError(ex));
            }
        }
Exemplo n.º 9
0
        public async Task <ActionResult <UrlDto> > GetUrlInfo([FromQuery] int count = 10)
        {
            var ret = new UrlDto
            {
                PercentWithUrl        = await _info.GetPercentWithUrl(),
                PercentWithUrlOfImage = await _info.GetPercentWithUrlOfPhoto(),
                TopDomainsOfUrls      = await _info.GetTopDomain(count)
            };

            return(Ok(ret));
        }
        public bool UpdateAvatar(int userId, UrlDto dto)
        {
            var userFromDb = db.Users.FirstOrDefault(x => x.Id == userId && !x.DelFlag);

            if (userFromDb == null)
            {
                return(false);
            }

            userFromDb.Avatar = dto.Url;

            db.SaveChanges();

            return(true);
        }
Exemplo n.º 11
0
        public async Task Should_Get_By_Id()
        {
            // Arrange
            UrlDto     expectedUrl = UrlDtoData.ArpaWebsite;
            HttpClient client      = _authenticatedServer.CreateClient().AuthenticateWith(_staff);

            // Act
            HttpResponseMessage responseMessage = await client
                                                  .GetAsync(ApiEndpoints.UrlsController.Get(expectedUrl.Id));

            // Assert
            responseMessage.StatusCode.Should().Be(HttpStatusCode.OK);
            UrlDto result = await DeserializeResponseMessageAsync <UrlDto>(responseMessage);

            result.Should().BeEquivalentTo(expectedUrl);
        }
Exemplo n.º 12
0
            public async void ShouldUpdate()
            {
                // Arrange
                UrlDto newUrl = new UrlDto
                {
                    Id           = 2,
                    ActualUrl    = "https://www.bbc.co.uk/news",
                    ShortenedUrl = "FG5tYi"
                };

                // Act
                var result = await UrlServiceToTest.UpdateUrl(newUrl);

                // Assert
                Assert.True(result.Id == newUrl.Id);
                Assert.True(result.ActualUrl == newUrl.ActualUrl);
            }
Exemplo n.º 13
0
        public IActionResult Create([FromBody] UrlDto urlDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var url = new Url()
            {
                Description = urlDto.Description, Redirect = urlDto.Redirect
            };

            _context.Urls.Add(url);
            _context.SaveChanges();

            return(Ok(url));
        }
Exemplo n.º 14
0
        public async Task Should_Modify()
        {
            // Arrange
            UrlDto urlToModify = UrlDtoData.GoogleDe;
            var    modifyDto   = new UrlModifyBodyDto
            {
                Href       = "http://google.de/modified",
                AnchorText = "modified anchor",
            };
            HttpClient client = _authenticatedServer.CreateClient().AuthenticateWith(_staff);

            // Act
            HttpResponseMessage responseMessage = await client
                                                  .PutAsync(ApiEndpoints.UrlsController.Put(urlToModify.Id), BuildStringContent(modifyDto));

            // Assert
            responseMessage.StatusCode.Should().Be(HttpStatusCode.NoContent);
        }
Exemplo n.º 15
0
        public async Task Should_Remove_Role()
        {
            // Arrange
            UrlDto expectedDto = UrlDtoData.ArpaWebsite;

            expectedDto.Roles.Clear();

            // Act
            HttpResponseMessage responseMessage = await _authenticatedServer
                                                  .CreateClient()
                                                  .AuthenticateWith(_staff)
                                                  .DeleteAsync(ApiEndpoints.UrlsController.RemoveRole(
                                                                   UrlSeedData.ArpaWebsite.Id,
                                                                   RoleSeedData.Staff.Id));

            // Assert
            responseMessage.StatusCode.Should().Be(HttpStatusCode.NoContent);
        }
Exemplo n.º 16
0
        public async Task <IActionResult> Put(UrlDto url)
        {
            try
            {
                var result = await _urlService.UpdateUrl(url);

                if (result == null)
                {
                    return(NotFound());
                }
                return(Ok(result));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error in Put", new Object[] { url });
                throw;
            }
        }
Exemplo n.º 17
0
        public async Task Should_Delete()
        {
            // Arrange
            UrlDto     urlToDelete = ProjectDtoData.HoorayForHollywood.Urls[0];
            HttpClient client      = _authenticatedServer.CreateClient().AuthenticateWith(_staff);

            // Act: delete url from projects list of urls
            HttpResponseMessage responseMessage = await client
                                                  .DeleteAsync(ApiEndpoints.UrlsController.Delete(urlToDelete.Id));

            // Assert
            responseMessage.StatusCode.Should().Be(HttpStatusCode.NoContent);

            HttpResponseMessage getResponseMessage = await client
                                                     .GetAsync(ApiEndpoints.UrlsController.Get(urlToDelete.Id));

            getResponseMessage.StatusCode.Should().Be(HttpStatusCode.NotFound);
        }
Exemplo n.º 18
0
        public async Task Should_Add_Role()
        {
            // Arrange
            UrlDto expectedDto = UrlDtoData.ArpaWebsite;

            expectedDto.Roles.Add(RoleDtoData.Performer);

            HttpClient client = _authenticatedServer.CreateClient().AuthenticateWith(_staff);

            HttpResponseMessage responseMessage = await client
                                                  .PostAsync(ApiEndpoints.UrlsController.AddRole(expectedDto.Id, RoleDtoData.Performer.Id), null);

            // Assert
            responseMessage.StatusCode.Should().Be(HttpStatusCode.OK);
            UrlDto result = await DeserializeResponseMessageAsync <UrlDto>(responseMessage);

            result.Should().BeEquivalentTo(expectedDto);
        }
Exemplo n.º 19
0
            public async void ShouldReturnOkWithResults()
            {
                // Arrange
                var url = new UrlDto
                {
                    Id           = 2,
                    AccessCount  = 1,
                    ActualUrl    = "https://google.com",
                    ShortenedUrl = "GH65ff"
                };

                UrlServiceMock.Setup(x => x.GetUrl("GH65ff")).ReturnsAsync(url);

                // Act
                var result = await UrlControllerToTest.Get("GH65ff");

                // Assert
                var okResult = Assert.IsType <OkObjectResult>(result);

                Assert.Same(url, okResult.Value);
            }
Exemplo n.º 20
0
        public void GetShortUrlFor_UrlAlreadyStored()
        {
            // Arrange
            var urlDto = new UrlDto
            {
                LongUrl  = $"http://{_fixture.Create<string>()}",
                ShortUrl = _fixture.Create <string>()
            };

            var mockedDal = new MockedDal(
                isUrlStored: true,
                getShortenedUrlFor: urlDto.ShortUrl);

            var service = new UrlService(mockedDal.GetObject);

            // Act
            var response = service.GetShortUrlFor(urlDto.LongUrl);

            // Assert
            response
            .Should()
            .BeEquivalentTo(
                urlDto,
                "because the fetched values should match the original ones");

            mockedDal.GetMock
            .Verify(_ =>
                    _.GetShortenedFor(It.IsAny <string>()),
                    Times.Once);

            mockedDal.GetMock
            .Verify(_ =>
                    _.IsUrlStored(It.IsAny <string>()),
                    Times.Once);

            mockedDal.GetMock
            .Verify(_ =>
                    _.StoreShortened(It.IsAny <string>(), It.IsAny <string>()),
                    Times.Never);
        }
        public IHttpActionResult UpdateAvatar(int userId, [FromBody] UrlDto dto)
        {
            if (dto == null)
            {
                return(BadRequest("Invalid or missing avatar url"));
            }

            var token = Request.Headers.GetValues("Authorization").First();

            if (!ValidatePermission(token, userId))
            {
                return(Unauthorized());
            }

            var result = _userService.UpdateAvatar(userId, dto);

            if (result == false)
            {
                return(BadRequest("Fail to update"));
            }

            return(Ok("Avatar is update"));
        }
Exemplo n.º 22
0
        public UrlDto Execute()
        {
            var url = new UrlDto();

            return(url);
        }
Exemplo n.º 23
0
 public static Url Build(UrlDto dto)
 {
     return(new Url(dto.Link, dto.ShortLink, dto.LinkCode));
 }
Exemplo n.º 24
0
        public async Task <ActionResult <UrlDto> > AddUrl(UrlCreateDto urlCreateDto)
        {
            UrlDto createdUrl = await _urlService.CreateAsync(urlCreateDto);

            return(CreatedAtAction(nameof(UrlsController.GetById), "Urls", new { id = createdUrl.Id }, createdUrl));
        }