public async Task GivenValidRequest_WhenTheArticleExists_ReturnsArticleViewModel() { // Arrange/Act var response = await Client.GetAsync($"{ArticlesEndpoint}/how-to-train-your-dragon"); var responseContent = await ContentHelper.GetResponseContent <ArticleViewModel>(response); // Assert response.EnsureSuccessStatusCode(); responseContent.ShouldNotBeNull(); responseContent.ShouldBeOfType <ArticleViewModel>(); responseContent.Article.ShouldNotBeNull(); responseContent.Article.ShouldBeOfType <ArticleDto>(); responseContent.Article.Author.Username.ShouldBe("joey.mckenzie"); responseContent.Article.TagList.ShouldNotBeEmpty(); responseContent.Article.TagList.ShouldContain("dragons"); }
public async Task ChangeUserPhoto_Cant_ChangeUserProfilePhoto_WrongFile() { //Arrange string userIdHimSelf = UnitTestDataInput.userLoggedInId; var fileMock = new Mock <IFormFile>(); var fileName = "5a3a2a02-7bbf-41f1-b401-25e7be899d24.jpg"; var ms = new MemoryStream(); var writer = new StreamWriter(ms); writer.Flush(); ms.Position = 0; fileMock.Setup(o => o.OpenReadStream()).Returns(ms); fileMock.Setup(o => o.FileName).Returns(fileName); fileMock.Setup(o => o.Length).Returns(ms.Length); byte[] data; using (var br = new BinaryReader(fileMock.Object.OpenReadStream())) data = br.ReadBytes((int)fileMock.Object.OpenReadStream().Length); ByteArrayContent bytes = new ByteArrayContent(data); MultipartFormDataContent multipartFormData = new MultipartFormDataContent(); multipartFormData.Add(bytes, "File", fileMock.Object.FileName); var request = new { Url = $"/site/user/{UnitTestDataInput.SiteAdminVersion}/Users/{userIdHimSelf}/photos", Body = new PhotoFromUserProfileDto { PublicId = "1", Url = "https://google.com" } }; multipartFormData.Add(ContentHelper.GetStringContent(request.Body)); //Act _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AToken); var response = await _client.PostAsync(request.Url, multipartFormData); //Assert response.StatusCode.Should().Be(HttpStatusCode.BadRequest); }
public async Task Login_InvalidCredentials_ReturnsBadRequestResultWithCredentialsInvalidError( string username, string password) { var url = "api/users/login"; var expected = HttpStatusCode.BadRequest; var userDto = new UserDto() { Username = username, Password = password }; var response = await Server.PostAsync(url, ContentHelper.GetStringContent(userDto)); Assert.Equal(expected, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.Equal(DiceApi.Properties.resultMessages.CredentialsInvalid, content); }
public async Task Register_PasswordInvalidLength_ReturnBadRequestResultWithPasswordLengthError( string password) { var url = "api/users"; var expected = HttpStatusCode.BadRequest; var userDto = new UserDto() { Username = "******", Password = password }; var response = await Server.PostAsync(url, ContentHelper.GetStringContent(userDto)); Assert.Equal(expected, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.Equal(DiceApi.Properties.resultMessages.PasswordLength, content); }
public async Task GivenValidRequest_WhenTheArticleDoesNotExist_ReturnsErrorViewModelWithNotFound() { // Arrange await ContentHelper.GetRequestWithAuthorization(Client, IntegrationTestConstants.BackupUser); // Act var response = await Client.PostAsync($"{ArticlesEndpoint}/how-to-not-train-your-dragon/favorite", null); var responseContent = await ContentHelper.GetResponseContent <ErrorViewModel>(response); // Assert response.StatusCode.ShouldBe(HttpStatusCode.NotFound); responseContent.ShouldNotBeNull(); responseContent.ShouldBeOfType <ErrorViewModel>(); responseContent.Errors.ShouldNotBeNull(); responseContent.Errors.ShouldBeOfType <ErrorDto>(); }
public override SpriteFontContent Process(FontDescription input, ContentProcessorContext context) { // Fallback if we aren't buiding for iOS. var platform = ContentHelper.GetMonoGamePlatform(); if (platform != MonoGamePlatform.iOS) { return(base.Process(input, context)); } SpriteFontContent content = base.Process(input, context); FieldInfo TextureField = typeof(SpriteFontContent).GetField("texture", BindingFlags.Instance | BindingFlags.NonPublic); Texture2DContent texture = (Texture2DContent)TextureField.GetValue(content); // TODO: This is a very lame way of doing this as we're getting compression artifacts twice, but is the quickest way to get // Compressed fonts up and running. The SpriteFontContent/Processor contains a ton // of sealed/internal classes riddled with private fields, so overriding CompressFontTexture // or even Process is tricky. This works for now, but should be replaced when the content pipeline // moves a bit further var texWidth = ContentHelper.NextPOT(texture.Faces[0][0].Width); var texHeight = ContentHelper.NextPOT(texture.Faces[0][0].Height); // Resize to square, power of two if necessary. if (texWidth != texHeight || texture.Faces[0][0].Width != texture.Faces[0][0].Height || texWidth != texture.Faces[0][0].Width || texHeight != texture.Faces[0][0].Height) { texHeight = texWidth = Math.Max(texHeight, texWidth); var resizedBitmap = (BitmapContent)Activator.CreateInstance(typeof(PixelBitmapContent <Color>), new object[] { texWidth, texHeight }); var textureRegion = new Rectangle(0, 0, texture.Faces[0][0].Width, texture.Faces[0][0].Height); BitmapContent.Copy(texture.Faces[0][0], textureRegion, resizedBitmap, textureRegion); texture.Faces[0].Clear(); texture.Faces[0].Add(resizedBitmap); context.Logger.LogImportantMessage(string.Format("Resized font texture {0} to {1}x{2}", input.Name, resizedBitmap.Width, resizedBitmap.Height)); } else { texture.ConvertBitmapType(typeof(PixelBitmapContent <Color>)); } MGTextureProcessor.ConvertToPVRTC(texture, 1, true, MGCompressionMode.PVRTCFourBitsPerPixel); return(content); }
public static void Initialize(TMBAW_Game game1) { _font8 = ContentHelper.LoadFont("Fonts/x8"); _font32 = ContentHelper.LoadFont("Fonts/x32"); _chooseLevel = new TextButton(Vector2.Zero, "Choose a Level", false); _chooseLevel.MouseClicked += chooseLevel_MouseClicked; _buttons.Add(_chooseLevel); _quit = new TextButton(Vector2.Zero, "Quit", false); _quit.MouseClicked += quit_MouseClicked; _buttons.Add(_quit); _options = new TextButton(Vector2.Zero, "Options", false); _options.MouseClicked += options_MouseClicked; _buttons.Add(_options); _multiplayer = new TextButton(Vector2.Zero, "Multiplayer", false); _multiplayer.MouseClicked += multiplayer_MouseClicked; _buttons.Add(_multiplayer); _storyModeButton = new TextButton(Vector2.Zero, "Story Mode", false); _storyModeButton.MouseClicked += storyMode_MouseClicked; _buttons.Add(_storyModeButton); _backButton = new TextButton(Vector2.Zero, "Back", false); _backButton.MouseClicked += backButton_MouseClicked; _buttons.Add(_backButton); _startMultiplayerGame = new TextButton(Vector2.Zero, "Start Game", false); _startMultiplayerGame.MouseClicked += StartMultiplayerGame_MouseClicked; _buttons.Add(_startMultiplayerGame); foreach (var button in _buttons) { button.ChangeDimensions(new Vector2(TextButton.Width * 2, TextButton.Height * 2)); button.Color = new Color(196, 69, 69); } _levelSelection = new LevelSelection(); SaveSelector.Initialize(); GraphicsRenderer.OnResolutionChanged += SetElementPositions; SetElementPositions(TMBAW_Game.UserResWidth, TMBAW_Game.UserResHeight); }
public void Process(CreateCommentArgs args) { Assert.IsNotNull(args.Database, "Database cannot be null"); Assert.IsNotNull(args.Comment, "Comment cannot be null"); Assert.IsNotNull(args.EntryID, "Entry ID cannot be null"); var entryItem = args.Database.GetItem(args.EntryID, args.Language); if (entryItem != null) { // End at end of today to make sure we cover comments from today properly var dateEnd = System.DateTime.UtcNow.Date.AddDays(1); var dateStart = dateEnd - TimeSpan; var blog = ManagerFactory.BlogManagerInstance.GetCurrentBlog(entryItem); if (blog != null) { var commentTemplate = blog.BlogSettings.CommentTemplateID; var query = "{0}//*[@@templateid='{1}' and @__created > '{2}' and @__created < '{3}']".FormatWith( ContentHelper.EscapePath(entryItem.Paths.FullPath), commentTemplate, DateUtil.ToIsoDate(dateStart), DateUtil.ToIsoDate(dateEnd)); var comments = args.Database.SelectItems(query); var match = false; foreach (var item in comments) { var commentItem = (CommentItem)item; if (string.Compare(commentItem.AuthorName, args.Comment.AuthorName, StringComparison.OrdinalIgnoreCase) == 0 && string.Compare(commentItem.Email.Raw, args.Comment.AuthorEmail, StringComparison.OrdinalIgnoreCase) == 0 && string.Compare(commentItem.Comment.Raw, args.Comment.Text, StringComparison.OrdinalIgnoreCase) == 0) { match = true; Log.Warn("[WeBlog] Duplicate comment submission. Existing item: {0}".FormatWith(commentItem.ID), this); } } if (match) { args.AbortPipeline(); } } } }
public async Task Post_UpdateRole_DoesReturnOk_RoleExists() { // Arrange var request = new { Url = "/api/admin/3c", Body = new RoleChangeViewModel { Role = "Manager" } }; // Act var response = await client.PutAsync(request.Url, ContentHelper.GetStringContent(request.Body)); // Assert response.EnsureSuccessStatusCode(); }
public async Task GivenInvalidRequest_WhenTheUserDoesNotExistInTheRequestPath_ReturnsErrorViewModelWithUnsupportedMedia() { // Arrange var userUnfollowEndpoint = $"{ProfilesEndpoint}/ /follow"; await ContentHelper.GetRequestWithAuthorization(Client, IntegrationTestConstants.SecondaryUser); // Act var response = await Client.DeleteAsync(userUnfollowEndpoint); var responseContent = await ContentHelper.GetResponseContent <ErrorViewModel>(response); // Assert response.StatusCode.ShouldBe(HttpStatusCode.UnsupportedMediaType); responseContent.ShouldNotBeNull(); responseContent.ShouldBeOfType <ErrorViewModel>(); responseContent.Errors.ShouldNotBeNull(); responseContent.Errors.ShouldBeOfType <ErrorDto>(); }
public async Task GivenValidRequest_WhenTheUserTriesToFollowThemselves_ReturnsErrorViewModelWithBadRequest() { // Arrange var userUnfollowEndpoint = $"{ProfilesEndpoint}/test.user/follow"; await ContentHelper.GetRequestWithAuthorization(Client, IntegrationTestConstants.SecondaryUser); // Act var response = await Client.DeleteAsync(userUnfollowEndpoint); var responseContent = await ContentHelper.GetResponseContent <ErrorViewModel>(response); // Assert response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); responseContent.ShouldNotBeNull(); responseContent.ShouldBeOfType <ErrorViewModel>(); responseContent.Errors.ShouldNotBeNull(); responseContent.Errors.ShouldBeOfType <ErrorDto>(); }
public async Task GivenValidRequest_WhenTheUserDoesNotExist_ReturnsErrorViewModelWithNotFound() { // Arrange var userUnfollowEndpoint = $"{ProfilesEndpoint}/joey.mckenzie.is.a.clone/follow"; await ContentHelper.GetRequestWithAuthorization(Client, IntegrationTestConstants.SecondaryUser); // Act var response = await Client.DeleteAsync(userUnfollowEndpoint); var responseContent = await ContentHelper.GetResponseContent <ErrorViewModel>(response); // Assert response.StatusCode.ShouldBe(HttpStatusCode.NotFound); responseContent.ShouldNotBeNull(); responseContent.ShouldBeOfType <ErrorViewModel>(); responseContent.Errors.ShouldNotBeNull(); responseContent.Errors.ShouldBeOfType <ErrorDto>(); }
public async Task PaymentHappyPath_Test(string method) { //Arrange var paymenet = new PaymentDto { CreditCardNumber = "4111111111111111", CardHolder = "RahulSR", ExpirationDate = DateTime.Now.AddYears(1), Amount = 100m, SecurityCode = "965" }; //act var response = await client.PostAsync("api/payment/ProcessPayment", ContentHelper.GetStringContent(paymenet)); //assert response.EnsureSuccessStatusCode(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); }
private void Refresh() { double amount = GetBillCount(); _noRecordRoot.SetActive(_curTab == selectTab.noRecord); _remainRoot.SetActive(_curTab != selectTab.noRecord && amount > 0); _payOffRoot.SetActive(_curTab != selectTab.noRecord && amount == 0); _totalText.gameObject.SetActive(_curTab != selectTab.noRecord); _remainText.text = amount.ToString("0.00"); _totalText.text = string.Format(ContentHelper.Read(ContentHelper.AntMonthCount), GetBillCount()); int month = DateTime.Now.Month == 12 ? 1 : DateTime.Now.Month + 1; _deadlineText.text = string.Format(ContentHelper.Read(ContentHelper.AntDeadline), month, 9); _content.anchoredPosition = Vector3.zero; _content.sizeDelta = _normalSize; ClearGrid(); ShowGrid(); }
public async Task GivenValidRequest_WhenTheRequestContainsQueryParamsThatDoNotReturnResults_ReturnsArticlesViewModelWithNoArticles() { // Arrange await ContentHelper.GetRequestWithAuthorization(Client); // Act var response = await Client.GetAsync($"{ArticlesEndpoint}?favorited=iDoNotExist"); var responseContent = await ContentHelper.GetResponseContent <ArticleViewModelList>(response); // Assert response.EnsureSuccessStatusCode(); responseContent.ShouldNotBeNull(); responseContent.ShouldBeOfType <ArticleViewModelList>(); responseContent.Articles.ShouldNotBeNull(); responseContent.Articles.ShouldBeOfType <List <ArticleDto> >(); responseContent.Articles.ShouldBeEmpty(); }
public async System.Threading.Tasks.Task TestPutProjectAsync_BadRequestError() { // Arrange var request = new { Url = "/api/Project", Body = new { Id = "fgfgf" } }; // Act var response = await _client.PutAsync(request.Url, ContentHelper.GetStringContent(request.Body)); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); }
protected override void OnLoadContents() { base.OnLoadContents(); var game = Game.ToBaseGame(); var graphics = game.GraphicsDevice; var config = ConfigurationStore.Get <ComboTextConfig>(); _textImage = ContentHelper.LoadTexture(graphics, config.Data.Image.FileName); var clientSize = graphics.Viewport; var layout = config.Data.Layout; var x = layout.X.ToActualValue(clientSize.Width); var y = layout.Y.ToActualValue(clientSize.Height); Location = new Vector2(x, y); }
public async Task GivenValidRequest_WhenTheArticleExistsAndUserHasNotFavorited_ReturnsArticleViewModelWithSuccessfulResponse() { // Arrange await ContentHelper.GetRequestWithAuthorization(Client, IntegrationTestConstants.SecondaryUser); // Act var response = await Client.DeleteAsync($"{ArticlesEndpoint}/why-beer-is-gods-gift-to-the-world/favorite"); var responseContent = await ContentHelper.GetResponseContent <ArticleViewModel>(response); // Assert response.EnsureSuccessStatusCode(); responseContent.ShouldNotBeNull(); responseContent.ShouldBeOfType <ArticleViewModel>(); responseContent.Article.ShouldNotBeNull(); responseContent.Article.ShouldBeOfType <ArticleDto>(); responseContent.Article.Favorited.ShouldBeFalse(); }
public async Task Join_ValidObjectNotJoinedRoom_ReturnOkResultWithRoomDetails() { var url = "api/rooms/105"; var expected = HttpStatusCode.OK; var roomDto = new RoomDto() { Password = "******" }; var response = await Server.PostAuthorizedAsync(url, User101Token, ContentHelper.GetStringContent(roomDto)); Assert.Equal(expected, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); var roomDetails = JsonConvert.DeserializeObject <RoomDetailsDto>(content); Assert.IsType <RoomDetailsDto>(roomDetails); }
public async Task GivenValidUpdateRequest_WhenTheArticleDtoIsInvalid_ReturnsErrorViewModelWithUnsupportedMediaType() { // Arrange var updateArticleCommand = new UpdateArticleCommand { Slug = "this-is-not-an-article" }; var requestContent = await ContentHelper.GetRequestContentWithAuthorization(updateArticleCommand, Client, IntegrationTestConstants.SecondaryUser); // Act var response = await Client.PutAsync($"{ArticlesEndpoint}/{updateArticleCommand.Slug}", requestContent); var responseContent = await ContentHelper.GetResponseContent <ErrorViewModel>(response); // Assert response.StatusCode.ShouldBe(HttpStatusCode.UnsupportedMediaType); responseContent.Errors.ShouldNotBeNull(); }
/// <summary> /// 一天收益 /// </summary> public void RecalculationOneDayProfit() { assetsData.yuEBaoYesterday = (float)Math.Round(assetsData.yuEBao * GameDefine.TenThousandProfit / 10000 > 0.01 ? assetsData.yuEBao * GameDefine.TenThousandProfit / 10000 : 0, 2); assetsData.yuEBaoProfit += assetsData.yuEBaoYesterday; assetsData.yuEBao += assetsData.yuEBaoYesterday; if (assetsData.yuEBaoYesterday > 0) { TransactionSaveData actionData = new TransactionSaveData(); actionData.timeStr = DateTime.Now.ToString(); actionData.streamType = TransactionStreamType.Income; actionData.iconType = TransactionIconType.YuEBao; actionData.payway = PaywayType.None; actionData.remarkStr = ContentHelper.Read(ContentHelper.FinanceText); actionData.detailStr = string.Format(ContentHelper.Read(ContentHelper.YuEBaoProfitAdd), DateTime.Now.ToString("MM.dd")); actionData.money = assetsData.yuEBaoYesterday; AddTransactionData(actionData); } }
// // Public fields // // // Constructor // public PauseMenu(Game1 parent) { this.parent = parent; pausePanel = ContentHelper.GetTexture("grey_panel"); // widthBuffer = (ScaleHelper.BackBufferWidth - ScaleHelper.ScaleWidth(pausePanel.Width)) / 2; heightBuffer = (ScaleHelper.BackBufferHeight - ScaleHelper.ScaleHeight(pausePanel.Height)) / 2; int buttonWidthBuffer = widthBuffer + (widthBuffer - 200) / 2; int buttonHeightBuffer = heightBuffer + (heightBuffer - 50) / 2; // Init buttons continueButton = new GuiButton(new Point(buttonWidthBuffer, buttonHeightBuffer), new Point(200, 50), "Continue"); continueButton.GuiButtonClicked += Unpause; optionsButton = new GuiButton(new Point(buttonWidthBuffer, buttonHeightBuffer * 2), new Point(200, 50), "Options"); }
private static HtmlLink LinkViewModelFromRelatedLink(RelatedLink relatedLink) { try { return(new HtmlLink() { Text = relatedLink.Caption, Url = ContentHelper.TransformUrl(new Uri(relatedLink.Link, UriKind.RelativeOrAbsolute)) }); } catch (UriFormatException) { return(new HtmlLink() { Text = relatedLink.Caption }); } }
public async Task ChangeUserPassword_Cant_ChangeUserPasswordAnotherUser() { //Arrange string UserIdAnotherUser = UnitTestDataInput.userUnLoggedInId; var request = new { Url = $"/site/user/{UnitTestDataInput.SiteAdminVersion}/user/ChangeUserPassword/" + UserIdAnotherUser, Body = UnitTestDataInput.passwordForChange_CorrectOldPassword }; _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AToken); //Act var response = await _client.PutAsync(request.Url, ContentHelper.GetStringContent(request.Body)); //Assert response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); }
public bool Create([FromUri] int appId, [FromUri] string path, [FromBody] ContentHelper content, bool global = false) { Log.Add($"create a#{appId}, path:{path}, global:{global}, cont-length:{content.Content?.Length}"); path = path.Replace("/", "\\"); var thisApp = new App(new DnnTenant(PortalSettings.Current), appId); if (content.Content == null) { content.Content = ""; } var isAdmin = UserInfo.IsInRole(PortalSettings.AdministratorRoleName); var assetEditor = new AssetEditor(thisApp, path, UserInfo.IsSuperUser, isAdmin, global); assetEditor.EnsureUserMayEditAsset(path); return(assetEditor.Create(content.Content)); }
public void GetToken_CorrectCredentials_ReturnsToken() { var request = new UserLoginRequest() { UserName = FakeDbUtilities.SeedUsers[0].UserName, Password = FakeDbUtilities.UserPassword }; var httpResponse = _client.PostAsync(_tokenUri, ContentHelper.GetStringContent(request)).Result; httpResponse.EnsureSuccessStatusCode(); var stringResponse = httpResponse.Content.ReadAsStringAsync().Result; var response = JsonConvert.DeserializeObject <UserLoginResponse>(stringResponse); response.UserId.Should().Be(FakeDbUtilities.SeedUsers[0].Id); response.Token.Should().NotBeNullOrWhiteSpace(); }
public async Task TestStoreFails() { var request = new { Url = "/stores", Body = new { Name = "Testing invalid store", Type = "InvalidType" } }; var response = await _client.PostAsync( request.Url, ContentHelper.GetStringContent(request.Body)); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); }
public async Task Obter_Endereco_Por_Id_Com_Sucesso() { // Arrange var fornecedorVM = FornecedorViewModelTestsHelper.ObterInstancia(1, "67701372083"); Guid fornecedorId = fornecedorVM.Id; await AdicionarObjsParaTestes(fornecedorVM); // Act HttpResponseMessage response = await base.Client.GetAsync($"{CommonUri}/obter-endereco/{fornecedorId}"); // Assert var result = await ContentHelper.ExtractObject <ResponseViewModel>(response.Content); Assert.True(response.IsSuccessStatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotNull(result.Data); }
public async Task TestPutOrganizationAsync() { // Arrange var request = new { Url = "/api/v1/Organization/Organization/1", Body = new { OrganizationID = 1 } }; // Act var response = await Client.PutAsync(request.Url, ContentHelper.GetStringContent(request.Body)); // Assert response.EnsureSuccessStatusCode(); }
public async Task <ActionResult> Add([FromForm] TmProductRequest productRequest) { if (!ModelState.IsValid) { return(BadRequest()); } Product product = new Product { Id = productRequest.Id, Code = productRequest.Code, Name = productRequest.Name, Price = productRequest.Price, UploadedImageFile = productRequest.UploadedImageFile }; var result = _productService.Add(product); if (result) { product.FilePath = await ContentHelper.SaveFormFile(product.UploadedImageFile, _hostingEnvironment.ContentRootPath); } return(Ok(result)); }