public void Test_Parse() { ExifDataType?dataType = EnumHelper.Parse(4, ExifDataType.Undefined); Assert.AreEqual(ExifDataType.Long, dataType); dataType = EnumHelper.Parse(42, ExifDataType.Long); Assert.AreEqual(ExifDataType.Long, dataType); dataType = EnumHelper.Parse(string.Empty, ExifDataType.Byte); Assert.AreEqual(ExifDataType.Byte, dataType); dataType = EnumHelper.Parse("Long", ExifDataType.Undefined); Assert.AreEqual(ExifDataType.Long, dataType); dataType = EnumHelper.Parse("Longer", ExifDataType.Short); Assert.AreEqual(ExifDataType.Short, dataType); dataType = EnumHelper.Parse <ExifDataType>(string.Empty); Assert.IsNull(dataType); dataType = EnumHelper.Parse <ExifDataType>("Long"); Assert.AreEqual(ExifDataType.Long, dataType); dataType = EnumHelper.Parse <ExifDataType>("Longer"); Assert.IsNull(dataType); dataType = (ExifDataType?)EnumHelper.Parse(typeof(ExifDataType), string.Empty); Assert.IsNull(dataType); dataType = (ExifDataType?)EnumHelper.Parse(typeof(ExifDataType), "Long"); Assert.AreEqual(ExifDataType.Long, dataType); dataType = (ExifDataType?)EnumHelper.Parse(typeof(ExifDataType), "Longer"); Assert.IsNull(dataType); }
[Test] // .ctor (String, Int32) public void Constructor6_Port_OutOfRange() { try { new UdpClient("local", IPEndPoint.MaxPort + 1); Assert.Fail("#A1"); } catch (ArgumentOutOfRangeException ex) { // Specified argument was out of the range of valid values Assert.AreEqual(typeof(ArgumentOutOfRangeException), ex.GetType(), "#A2"); Assert.IsNull(ex.InnerException, "#A3"); Assert.IsNotNull(ex.Message, "#A4"); Assert.AreEqual("port", ex.ParamName, "#A5"); } try { new UdpClient("local", IPEndPoint.MinPort - 1); Assert.Fail("#A1"); } catch (ArgumentOutOfRangeException ex) { // Specified argument was out of the range of valid values Assert.AreEqual(typeof(ArgumentOutOfRangeException), ex.GetType(), "#A2"); Assert.IsNull(ex.InnerException, "#A3"); Assert.IsNotNull(ex.Message, "#A4"); Assert.AreEqual("port", ex.ParamName, "#A5"); } }
public void EntityNotFound() { // Arrange var validatorFactory = new Mock<IValidatorEngine>(); var mappingEngine = new Mock<IMappingEngine>(); var repository = new Mock<IRepository>(); var searchCache = new Mock<ISearchCache>(); var service = new SourceSystemService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object); var message = new AmendMappingRequest { EntityId = 12, Mapping = new EnergyTrading.Mdm.Contracts.MdmId { SystemName = "Test", Identifier = "A" } }; validatorFactory.Setup(x => x.IsValid(It.IsAny<AmendMappingRequest>(), It.IsAny<IList<IRule>>())).Returns(true); // Act var candidate = service.UpdateMapping(message); // Assert Assert.IsNull(candidate); }
public void FindAndModifyTest4() { string entryMessage1 = "entry 1"; AddMongoEntry(entryMessage1, MONGO_COLLECTION_1_NAME); List <Entry> results = new List <Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now)); Assert.AreEqual(1, results.Count()); Assert.AreEqual(entryMessage1, results[0].Message); var searchQuery = Query.EQ("Message", entryMessage1); var update = Update.Set("Message", MONGO_EDITED_TEXT); var sortBy = SortBy.Descending("TimeStamp"); IMongoFields fields = Fields.Include("TimeStamp"); FindAndModifyArgs findAndModifyArgs = new FindAndModifyArgs(); findAndModifyArgs.Query = searchQuery; findAndModifyArgs.SortBy = sortBy; findAndModifyArgs.Update = update; findAndModifyArgs.Fields = fields; findAndModifyArgs.Upsert = true; findAndModifyArgs.VersionReturned = FindAndModifyDocumentVersion.Modified; var findAndModifyResult = _databaseUpdaterT.FindAndModify(MONGO_COLLECTION_1_NAME, findAndModifyArgs); Assert.IsTrue(findAndModifyResult.Ok, "FindAndModifyResult from FindAndModify not OK"); Assert.IsNull(findAndModifyResult.ErrorMessage); Assert.IsNotNull(findAndModifyResult.ModifiedDocument); results = new List <Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now)); Assert.AreEqual(1, results.Count()); Assert.AreEqual(MONGO_EDITED_TEXT, results[0].Message);/*This field we modified via FindAndModify...*/ }
private void TestBreakingBadSeasonOneEpisodeOneBaseProperties(TvEpisode tvEpisode) { Assert.AreEqual(62085, tvEpisode.Id); Assert.IsTrue(tvEpisode.AirDate.HasValue); Assert.AreEqual(new DateTime(2008, 1, 19), tvEpisode.AirDate.Value.Date); Assert.AreEqual(1, tvEpisode.EpisodeNumber); Assert.AreEqual("Pilot", tvEpisode.Name); Assert.IsNotNull(tvEpisode.Overview); Assert.IsNull(tvEpisode.ProductionCode); Assert.AreEqual(1, tvEpisode.SeasonNumber); Assert.IsNotNull(tvEpisode.StillPath); Assert.IsNotNull(tvEpisode.Crew); Crew crew = tvEpisode.Crew.SingleOrDefault(s => s.CreditId == "52542275760ee313280006ce"); Assert.IsNotNull(crew); Assert.AreEqual(66633, crew.Id); Assert.AreEqual("52542275760ee313280006ce", crew.CreditId); Assert.AreEqual("Vince Gilligan", crew.Name); Assert.AreEqual("Writing", crew.Department); Assert.AreEqual("Writer", crew.Job); Assert.IsTrue(TestImagesHelpers.TestImagePath(crew.ProfilePath), "crew.ProfilePath was not a valid image path, was: " + crew.ProfilePath); Assert.IsNotNull(tvEpisode.GuestStars); Cast star = tvEpisode.GuestStars.SingleOrDefault(s => s.CreditId == "52542273760ee3132800068e"); Assert.IsNotNull(star); Assert.AreEqual(92495, star.Id); Assert.AreEqual("John Koyama", star.Name); Assert.AreEqual("52542273760ee3132800068e", star.CreditId); Assert.AreEqual("Emilio Koyama", star.Character); Assert.AreEqual(1, star.Order); Assert.IsTrue(TestImagesHelpers.TestImagePath(star.ProfilePath), "star.ProfilePath was not a valid image path, was: " + star.ProfilePath); }
private void Validate(TelemetryItem<RemoteDependencyData> itemToValidate, string targetExpected, string commandNameExpected, TimeSpan accessTimeMax, bool successFlagExpected, string sqlErrorCodeExpected, string sqlErrorMessageExpected) { // For http name is validated in test itself Assert.IsTrue(itemToValidate.data.baseData.target.Contains(targetExpected), "The remote dependancy target is incorrect. Expected: " + targetExpected + ". Collected: " + itemToValidate.data.baseData.target); Assert.AreEqual(sqlErrorCodeExpected, itemToValidate.data.baseData.resultCode); //If the command name is expected to be empty, the deserializer will make the CommandName null if ("rddp" == DeploymentAndValidationTools.ExpectedSqlSDKPrefix) { // Additional checks for profiler collection if (!string.IsNullOrEmpty(sqlErrorMessageExpected)) { Assert.AreEqual(sqlErrorMessageExpected, itemToValidate.data.baseData.properties["ErrorMessage"]); } if (string.IsNullOrEmpty(commandNameExpected)) { Assert.IsNull(itemToValidate.data.baseData.data); } else { Assert.IsTrue(itemToValidate.data.baseData.data.Equals(commandNameExpected), "The command name is incorrect"); } } DeploymentAndValidationTools.Validate(itemToValidate, accessTimeMax, successFlagExpected, sqlErrorCodeExpected); }
public void TestSelectWhereJoined3SceneTwo() { String stmtText = "select (select id from S0#length(1000) where p00=s1.p10 and p00=s3.p30 and p00=s2.p20) as ids0 " + "from S1#keepall as s1, S2#keepall as s2, S3#keepall as s3 where s1.id = s2.id and s2.id = s3.id"; EPStatement stmt = _epService.EPAdministrator.CreateEPL(stmtText); stmt.Events += _listener.Update; _epService.EPRuntime.SendEvent(new SupportBean_S1(10, "s0_1")); _epService.EPRuntime.SendEvent(new SupportBean_S2(10, "s0_1")); _epService.EPRuntime.SendEvent(new SupportBean_S3(10, "s0_1")); Assert.IsNull(_listener.AssertOneGetNewAndReset().Get("ids0")); _epService.EPRuntime.SendEvent(new SupportBean_S0(99, "s0_1")); _epService.EPRuntime.SendEvent(new SupportBean_S1(11, "s0_1")); _epService.EPRuntime.SendEvent(new SupportBean_S2(11, "xxx")); _epService.EPRuntime.SendEvent(new SupportBean_S3(11, "s0_1")); Assert.IsNull(_listener.AssertOneGetNewAndReset().Get("ids0")); _epService.EPRuntime.SendEvent(new SupportBean_S0(98, "s0_2")); _epService.EPRuntime.SendEvent(new SupportBean_S1(12, "s0_x")); _epService.EPRuntime.SendEvent(new SupportBean_S2(12, "s0_2")); _epService.EPRuntime.SendEvent(new SupportBean_S3(12, "s0_1")); Assert.IsNull(_listener.AssertOneGetNewAndReset().Get("ids0")); _epService.EPRuntime.SendEvent(new SupportBean_S1(13, "s0_2")); _epService.EPRuntime.SendEvent(new SupportBean_S2(13, "s0_2")); _epService.EPRuntime.SendEvent(new SupportBean_S3(13, "s0_x")); Assert.IsNull(_listener.AssertOneGetNewAndReset().Get("ids0")); _epService.EPRuntime.SendEvent(new SupportBean_S1(14, "s0_2")); _epService.EPRuntime.SendEvent(new SupportBean_S2(14, "s0_2")); _epService.EPRuntime.SendEvent(new SupportBean_S3(14, "s0_2")); Assert.AreEqual(98, _listener.AssertOneGetNewAndReset().Get("ids0")); }
public void AdapterAssociatesSelectorWithRegionActiveViews() { var control = new ContentControl(); IRegionAdapter adapter = new TestableContentControlRegionAdapter(); MockPresentationRegion region = (MockPresentationRegion)adapter.Initialize(control, "Region1"); Assert.IsNotNull(region); Assert.IsNull(control.Content); region.MockActiveViews.Items.Add(new object()); Assert.IsNotNull(control.Content); Assert.AreSame(control.Content, region.ActiveViews.ElementAt(0)); region.MockActiveViews.Items.Add(new object()); Assert.AreSame(control.Content, region.ActiveViews.ElementAt(0)); region.MockActiveViews.Items.RemoveAt(0); Assert.AreSame(control.Content, region.ActiveViews.ElementAt(0)); region.MockActiveViews.Items.RemoveAt(0); Assert.IsNull(control.Content); }
public async Task DBFiles_StringDictionary_01_Set() { byte[] ByteArray = new byte[] { 1, 2, 3, 4, 5 }; Simple Obj = DBFilesBTreeTests.CreateSimple(100); this.file["Key1"] = "Value1"; this.file["Key2"] = "Value2"; this.file["Key3"] = "Value3"; this.file["Key4"] = null; this.file["Key5"] = Obj; this.file["Key6"] = ByteArray; Assert.IsTrue(await this.file.ContainsKeyAsync("Key1")); Assert.IsTrue(await this.file.ContainsKeyAsync("Key2")); Assert.IsTrue(await this.file.ContainsKeyAsync("Key3")); Assert.IsTrue(await this.file.ContainsKeyAsync("Key4")); Assert.IsTrue(await this.file.ContainsKeyAsync("Key5")); Assert.IsTrue(await this.file.ContainsKeyAsync("Key6")); AssertEx.Same(this.file["Key1"], "Value1"); AssertEx.Same(this.file["Key2"], "Value2"); AssertEx.Same(this.file["Key3"], "Value3"); Assert.IsNull(this.file["Key4"]); DBFilesObjectSerializationTests.AssertEqual(this.file["Key5"] as Simple, Obj); AssertEx.Same(this.file["Key6"], ByteArray); }
public void TestSelection() { Point p1, p2, p3; List <Point> l; Selection s; p1 = new Point(2, 2); p2 = new Point(3, 5); p3 = new Point(6, 8); l = new List <Point> (); l.Add(p1); l.Add(p2); l.Add(p3); MultiPoints m = new MultiPoints(l); s = m.GetSelection(new Point(3, 5), 1); Assert.AreEqual(SelectionPosition.All, s.Position); s = m.GetSelection(new Point(0, 5), 1); Assert.IsNull(s); s = m.GetSelection(new Point(5, 12), 1); Assert.IsNull(s); }
public void ExportPropertyOfT_ShouldGenerateExportForPropertySelectedWithTAsContractType() { var builder = new PartBuilder<FooImpl>(t => true); builder. ExportProperty<string>(p => p.P1). Export<IFoo>(); IEnumerable<Attribute> typeAtts; List<Tuple<object, List<Attribute>>> configuredMembers; GetConfiguredMembers(builder, out configuredMembers, out typeAtts); Assert.AreEqual(1, typeAtts.Count()); Assert.AreEqual(1, configuredMembers.Count); var tuple = configuredMembers[0]; Assert.AreEqual(typeof(FooImpl).GetProperty("P1"), tuple.Item1); var atts = tuple.Item2; Assert.AreEqual(1, atts.Count); var expAtt = atts[0] as ExportAttribute; Assert.IsNull(expAtt.ContractName); Assert.AreEqual(typeof(string), expAtt.ContractType); }
public void Cannot_Edit_Nonexistent_Product() { // Arrange - create the mock repository Mock <IProductsRepository> mock = new Mock <IProductsRepository>(); mock.Setup(m => m.Products).Returns(new Product[] { new Product { ProductID = 1, Name = "P1" }, new Product { ProductID = 2, Name = "P2" }, new Product { ProductID = 3, Name = "P3" }, }.AsQueryable()); // Arrange - create the controller AdminController target = new AdminController(mock.Object); // Act Product result = (Product)target.Edit(4).ViewData.Model; // Assert Assert.IsNull(result); }
public void PublishPostFailWhenInvalidDate() { //Create mocks var postCADMock = new Mock<IPostCAD>(); var pickCADMock = new Mock<IPickCAD>(); //Prepare data to be returned by mocks List<int> pick_ids = new List<int>(); pick_ids.Add(1); PickEN pick = new PickEN(); Event_EN eventPick = new Event_EN(); eventPick.Date = new DateTime(2016, 1, 16, 15, 0, 0); pick.Event_rel = eventPick; List<PickEN> picks = new List<PickEN>(); picks.Add(pick); PostEN expectedPost = null; //Setup mock methods postCADMock.Setup(mock => mock.NewPost(It.IsAny<PostEN>())).Returns(1); postCADMock.Setup(mock => mock.GetByID(It.IsAny<int>())).Returns(expectedPost); pickCADMock.Setup(mock => mock.GetByID(It.IsAny<int>())).Returns(pick); PostCEN postCEN = new PostCEN(postCADMock.Object); PickCEN pickCEN = new PickCEN(pickCADMock.Object); PostEN actualPost = postCEN.PublishPost(It.IsAny<TimeSpan>(), It.IsAny<TimeSpan>(), It.IsAny<Double>(), It.IsAny<string>(), It.IsAny<bool>(), pick_ids, It.IsAny<int>(), It.IsAny<double>(), It.IsAny<PickResultEnum>(), pickCEN); //Test method (check if picks are equal) Assert.IsNull(expectedPost); //Verify mocks postCADMock.Verify(mock => mock.NewPost(It.IsAny<PostEN>()), Times.Never); postCADMock.Verify(mock => mock.GetByID(It.IsAny<int>()), Times.Never); pickCADMock.Verify(mock => mock.GetByID(It.IsAny<int>()), Times.AtLeastOnce); }
public void FacetTypeSchema() { var schema = FacetSchemaExample(); Assert.AreEqual(2, schema.Properties.Length); foreach (var prop in schema.Properties) { Assert.IsTrue(prop.Type.IsObject); Assert.IsNull(prop.Type.CustomMembers); switch (prop.Name) { case "complexTypeA": Assert.IsTrue(prop.Type.IsObject); Assert.AreEqual("resource.a", prop.Type.CustomTypeName); break; case "complexTypeB": Assert.IsTrue(prop.Type.IsObject); Assert.AreEqual("resource.b", prop.Type.CustomTypeName); break; } } }
public void TestBrand() { Uri url = new Uri("http://localhost/cmis/atom"); string path1 = "/brand/1.png"; DateTime date1 = DateTime.Now; string path2 = "/brand/2.png"; DateTime date2 = DateTime.Now; // Create new config file with default values Config config = Config.CreateInitialConfig(this.configPath); Assert.IsNull(config.Brand); config.Brand = new Brand(); config.Brand.Server = url; config.Brand.Files = new List <BrandFile>(); BrandFile file1 = new BrandFile(); file1.Path = path1; file1.Date = date1; BrandFile file2 = new BrandFile(); file2.Path = path2; file2.Date = date2; config.Brand.Files.Add(file1); config.Brand.Files.Add(file2); config.Save(); config = Config.CreateOrLoadByPath(this.configPath); Assert.AreEqual(url.ToString(), config.Brand.Server.ToString()); Assert.AreEqual(2, config.Brand.Files.Count); Assert.AreEqual(path1, config.Brand.Files[0].Path); Assert.AreEqual(date1, config.Brand.Files[0].Date); Assert.AreEqual(path2, config.Brand.Files[1].Path); Assert.AreEqual(date2, config.Brand.Files[1].Date); }
public void ImageSearchWhenAsyncAndTimeoutTest() { var request = new ImageSearchRequest { Key = this.ApiKey, SearchEngineId = this.SearchEngineId, Query = "google" }; var exception = Assert.Throws <AggregateException>(() => { var result = GoogleSearch.ImageSearch.QueryAsync(request, TimeSpan.FromMilliseconds(1)).Result; Assert.IsNull(result); }); Assert.IsNotNull(exception); Assert.AreEqual(exception.Message, "One or more errors occurred."); var innerException = exception.InnerException; Assert.IsNotNull(innerException); Assert.AreEqual(innerException.GetType(), typeof(TaskCanceledException)); Assert.AreEqual(innerException.Message, "A task was canceled."); }
private void ValidateVMAccessExtension(string vmName, string serviceName, bool enabled) { var vmExtension = GetAzureVMAccessExtesnion(vmName, serviceName); Utilities.PrintContext(vmExtension); if(enabled) { Console.WriteLine("Verifying the enabled extension"); Assert.AreEqual("Enable", vmExtension.State, "State is not Enable"); //Assert.IsFalse(string.IsNullOrEmpty(vmExtension.PublicConfiguration), "PublicConfiguration is empty."); XmlDocument doc = new XmlDocument(); doc.LoadXml(vmExtension.PublicConfiguration); XmlDocument inputPublicConfigDoc = new XmlDocument(); inputPublicConfigDoc.LoadXml(publicConfiguration); Assert.AreEqual(inputPublicConfigDoc.GetElementsByTagName("PublicConfig")[0].InnerXml, doc.GetElementsByTagName("PublicConfig")[0].InnerXml); Console.WriteLine("Verifed the enabled extension successfully."); } else { Console.WriteLine("Verifying the disabled extension"); Assert.AreEqual("Disable", vmExtension.State, "State is not Disable"); Console.WriteLine("Verifed the disabled extension successfully."); } Assert.IsNull(vmExtension.PrivateConfiguration); }
// TODO: throws UnauthorizedAccessException [DataRow(nameof(ProvisioningTransportHandlerAmqp))] // [DataRow(nameof(ProvisioningTransportHandlerMqtt))] public async Task ProvisioningDeviceClient_InvalidRegistrationId_Register_Fail(string transportType) { using (ProvisioningTransportHandler transport = CreateTransportHandlerFromName(transportType, TransportFallbackType.TcpOnly)) using (SecurityClient security = new SecurityClientTpmSimulator("invalidregistrationid")) { ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create( Configuration.Provisioning.IdScope, security, transport); var cts = new CancellationTokenSource(PassingTimeoutMiliseconds); _log.WriteLine("ProvisioningClient RegisterAsync . . . "); DeviceRegistrationResult result = await provClient.RegisterAsync(cts.Token); _log.WriteLine($"{result.Status}"); Assert.AreEqual(ProvisioningRegistrationStatusType.Failed, result.Status); Assert.IsNull(result.AssignedHub); Assert.IsNull(result.DeviceId); Assert.AreEqual("Not Found", result.ErrorMessage); Assert.AreEqual(0x00062ae9, result.ErrorCode); } }
public void TestConsume2() { var consumerConfig = new ConsumerConfig(); consumerConfig.GroupId = "cg"; consumerConfig.ClientId = "cg-0"; var supplier = new MockKafkaSupplier(2); var producer = supplier.GetProducer(new ProducerConfig()); producer.Produce("topic", new Message<byte[], byte[]> { Key = new byte[1] { 42 }, Value = new byte[1] { 12 } }); producer.Produce("topic", new Message<byte[], byte[]> { Key = new byte[1] { 42 }, Value = new byte[1] { 20 } }); producer.Produce("topic", new Message<byte[], byte[]> { Key = new byte[1] { 32 }, Value = new byte[1] { 12 } }); var c1 = supplier.GetConsumer(consumerConfig, null); c1.Subscribe(new List<string> { "topic" }); var item = c1.Consume(); Assert.IsNotNull(item); item = c1.Consume(); Assert.IsNotNull(item); item = c1.Consume(); Assert.IsNotNull(item); item = c1.Consume(); Assert.IsNull(item); }
public void TestTvSeasonAccountStateRatingSet() { _config.Client.SetSessionInformation(_config.UserSessionId, SessionType.UserSession); // Rate episode 1, 2 and 3 of BreakingBad Assert.IsTrue(_config.Client.TvEpisodeSetRatingAsync(IdHelper.BreakingBad, 1, 1, 5).Result); Assert.IsTrue(_config.Client.TvEpisodeSetRatingAsync(IdHelper.BreakingBad, 1, 2, 7).Result); Assert.IsTrue(_config.Client.TvEpisodeSetRatingAsync(IdHelper.BreakingBad, 1, 3, 3).Result); // Wait for TMDb to un-cache our value Thread.Sleep(2000); // Fetch out the seasons state ResultContainer <TvEpisodeAccountState> state = _config.Client.GetTvSeasonAccountStateAsync(IdHelper.BreakingBad, 1).Result; Assert.IsNotNull(state); Assert.IsTrue(Math.Abs(5 - (state.Results.Single(s => s.EpisodeNumber == 1).Rating ?? 0)) < double.Epsilon); Assert.IsTrue(Math.Abs(7 - (state.Results.Single(s => s.EpisodeNumber == 2).Rating ?? 0)) < double.Epsilon); Assert.IsTrue(Math.Abs(3 - (state.Results.Single(s => s.EpisodeNumber == 3).Rating ?? 0)) < double.Epsilon); // Test deleting Ratings Assert.IsTrue(_config.Client.TvEpisodeRemoveRatingAsync(IdHelper.BreakingBad, 1, 1).Result); Assert.IsTrue(_config.Client.TvEpisodeRemoveRatingAsync(IdHelper.BreakingBad, 1, 2).Result); Assert.IsTrue(_config.Client.TvEpisodeRemoveRatingAsync(IdHelper.BreakingBad, 1, 3).Result); // Wait for TMDb to un-cache our value Thread.Sleep(2000); state = _config.Client.GetTvSeasonAccountStateAsync(IdHelper.BreakingBad, 1).Result; Assert.IsNotNull(state); Assert.IsNull(state.Results.Single(s => s.EpisodeNumber == 1).Rating); Assert.IsNull(state.Results.Single(s => s.EpisodeNumber == 2).Rating); Assert.IsNull(state.Results.Single(s => s.EpisodeNumber == 3).Rating); }
public void BuildTicketBetCashoutTest() { var tb = TicketCashoutBuilder.Create(); var ticket = tb.SetTicketId("ticket-" + SR.I1000P) .SetBookmakerId(SR.I1000) .AddBetCashout("bet-id-01", 1000, 2132) .AddBetCashout("bet-id-02", 1000, null) .BuildTicket(); var dto = new TicketCashoutMapper().Map(ticket); Assert.IsNotNull(ticket); Assert.IsTrue(ticket.Timestamp > DateTime.Today.ToUniversalTime()); Assert.IsNull(ticket.CashoutStake); Assert.IsNull(ticket.CashoutPercent); Assert.IsNotNull(ticket.BetCashouts); Assert.AreEqual(2, ticket.BetCashouts.Count()); Assert.AreEqual(ticket.CashoutPercent, dto.CashoutPercent); Assert.AreEqual("bet-id-01", dto.BetCashout.First().Id); Assert.AreEqual("bet-id-02", dto.BetCashout.ToList()[1].Id); Assert.AreEqual(1000, dto.BetCashout.First().CashoutStake); Assert.AreEqual(1000, dto.BetCashout.ToList()[1].CashoutStake); Assert.AreEqual(2132, dto.BetCashout.First().CashoutPercent); Assert.IsNull(dto.BetCashout.ToList()[1].CashoutPercent); }
public void Query_Retry_Success() { var attemptCount = 0; _db = new DbRepository( _dbResources.Object, _cache.Object, _ => { attemptCount++; if (attemptCount < 2) { throw new InvalidOperationException(); } return(_connection.Object); }); _db.OnError += (sender, args) => _onErrorEvents.Add(args); _db.OnQueryComplete += (sender, args) => _onQueryCompleteEvents.Add(args); var result = _db.Query(new FakeStoredProc(), "foo"); Assert.AreEqual(_expectedRows, result); Assert.AreEqual(2, attemptCount); _dbResources.Verify(x => x.ChooseDb("mobile_ro").SelectRandomly(), Times.Exactly(2)); Assert.AreEqual(1, _onErrorEvents.Count); Assert.IsInstanceOf <InvalidOperationException>(_onErrorEvents[0].Error); Assert.AreEqual(1, _onErrorEvents[0].AttemptCount); Assert.AreEqual(2, _onQueryCompleteEvents.Count); Assert.IsInstanceOf <FakeStoredProc>(_onQueryCompleteEvents[0].StoredProc); Assert.IsInstanceOf <FakeStoredProc>(_onQueryCompleteEvents[1].StoredProc); Assert.IsNotNull(_onQueryCompleteEvents[0].Error); Assert.IsNull(_onQueryCompleteEvents[1].Error); }
public void Constructor_ExpectedValues() { // Setup const double targetProbability = 1.0 / 10000; const int sectionId = 1; const long hydraulicBoundaryLocationId = 1234; // Call var assessmentLevelCalculationInput = new AssessmentLevelCalculationInput(sectionId, hydraulicBoundaryLocationId, targetProbability); // Assert double expectedBeta = StatisticsConverter.ProbabilityToReliability(targetProbability); Assert.IsInstanceOf<ReliabilityIndexCalculationInput>(assessmentLevelCalculationInput); Assert.AreEqual(HydraRingFailureMechanismType.AssessmentLevel, assessmentLevelCalculationInput.FailureMechanismType); Assert.AreEqual(9, assessmentLevelCalculationInput.CalculationTypeId); Assert.AreEqual(26, assessmentLevelCalculationInput.VariableId); Assert.AreEqual(1, assessmentLevelCalculationInput.FaultTreeModelId); Assert.AreEqual(hydraulicBoundaryLocationId, assessmentLevelCalculationInput.HydraulicBoundaryLocationId); Assert.IsNotNull(assessmentLevelCalculationInput.Section); CollectionAssert.IsEmpty(assessmentLevelCalculationInput.ProfilePoints); CollectionAssert.IsEmpty(assessmentLevelCalculationInput.ForelandPoints); Assert.IsNull(assessmentLevelCalculationInput.BreakWater); Assert.AreEqual(expectedBeta, assessmentLevelCalculationInput.Beta); HydraRingSection section = assessmentLevelCalculationInput.Section; Assert.AreEqual(sectionId, section.SectionId); Assert.IsNaN(section.SectionLength); Assert.IsNaN(section.CrossSectionNormal); HydraRingVariable[] variables = assessmentLevelCalculationInput.Variables.ToArray(); Assert.AreEqual(1, variables.Length); HydraRingVariable waterLevelVariable = variables.First(); Assert.IsInstanceOf<DeterministicHydraRingVariable>(waterLevelVariable); Assert.AreEqual(26, waterLevelVariable.VariableId); Assert.AreEqual(0.0, waterLevelVariable.Value); }
public void CacheIdentifierListWithRunner_SimpleCase() { DiscoveredDatabase db; CohortIdentificationConfiguration cic; DataTable dt; SetupCohort(out db, out cic, out dt); var compiler = new CohortCompiler(cic); var runner = new CohortCompilerRunner(compiler, 5000); runner.Run(new CancellationToken()); Assert.AreEqual(CohortCompilerRunner.Phase.Finished, runner.ExecutionPhase); var rootTask = runner.Compiler.Tasks.Single(t => t.Key is AggregationContainerTask); Assert.IsTrue(rootTask.Value.IsResultsForRootContainer); Assert.IsNull(rootTask.Key.CrashMessage); Assert.AreEqual(CompilationState.Finished, rootTask.Key.State); Assert.AreEqual(dt.Rows.Count, rootTask.Value.Identifiers.Rows.Count); }
public void Should_be_possible_to_create_itemtype_defined_with_filepath_entity() { var objectType = ProbeHelper.GetDefinitionObjectTypeByID("definitionsSimple", "920"); var filepaths = new string[] { @"c:\windows\win.ini" }; var patterns = new string[] { "VERSION.*" }; var instances = new string[] { "1" }; var createdFileObjects = new TextFileContentObjectFactory() .CreateFileObjects((textfilecontent54_object)objectType, filepaths, null, null, patterns, instances); Assert.IsNotNull(createdFileObjects, "The file objects were not created."); Assert.AreEqual(1, createdFileObjects.Count()); var firstObject = (textfilecontent54_object)createdFileObjects.First(); Assert.IsNull(firstObject.GetItemValue(textfilecontent54_ItemsChoices.path)); Assert.IsNull(firstObject.GetItemValue(textfilecontent54_ItemsChoices.filename)); AssertEntityNamesOrder(firstObject); AssertTextFileContentObjectEntity(firstObject, textfilecontent54_ItemsChoices.filepath, filepaths.Single()); AssertTextFileContentObjectEntity(firstObject, textfilecontent54_ItemsChoices.pattern, patterns.Single()); AssertTextFileContentObjectEntity(firstObject, textfilecontent54_ItemsChoices.instance, instances.First()); }
public void GaussianMixtureModelTest3() { Accord.Math.Tools.SetupGenerator(0); var gmm = new GaussianMixtureModel(3); Assert.AreEqual(3, gmm.Gaussians.Count); Assert.IsNull(gmm.Gaussians[0].Covariance); Assert.IsNull(gmm.Gaussians[0].Mean); double[][] B = Matrix.Random(56, 12).ToJagged(); Accord.Math.Tools.SetupGenerator(0); gmm.Options.Robust = true; var result = gmm.Compute(B, new GaussianMixtureModelOptions() { NormalOptions = new NormalOptions { Robust = true } }); }
public async Task GetCustomerBySubdomain_IncorrectCustomerIdSpecified_ReturnsNull() { // Arrange var testCustomer1 = new Customer { Id = 3000, Subdomain = "TestCustomer1" }; var testCustomer2 = new Customer { Id = 3001, Subdomain = "TestCustomer2" }; this.customersRepository.Refresh(new List <Customer> { testCustomer1, testCustomer2 }); // Act var actual = await this.sut.GetCustomerBySubdomain(testCustomer1.Subdomain, testCustomer2.Id); // Assert Assert.IsNull(actual); }
public async Task GetByAsync() { MobileServiceInvalidOperationException exception = null; try { var table = AzureMobileService.CarsService.GetTable <Car>(); var items = await table.ToListAsync(); Assert.IsNotNull(items); Car item = null; if (items.Any()) { item = await table.LookupAsync(items.First().Id); Assert.IsNotNull(item); } else { Assert.IsNotNull(items); Assert.IsNull(item); } } catch (MobileServiceInvalidOperationException mobileServiceInvalidOperationException) { exception = mobileServiceInvalidOperationException; } if (exception != null) { var content = await exception.Response.Content.ReadAsStringAsync(); Debug.WriteLine(content); Assert.Fail(content); } Assert.IsNull(exception); }
public async Task ProvisioningDeviceClient_InvalidRegistrationId_TpmRegister_Fail(string transportType) { using (ProvisioningTransportHandler transport = CreateTransportHandlerFromName(transportType, TransportFallbackType.TcpOnly)) using (SecurityProvider security = new SecurityProviderTpmSimulator("invalidregistrationid")) { ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create( s_globalDeviceEndpoint, Configuration.Provisioning.IdScope, security, transport); var cts = new CancellationTokenSource(FailingTimeoutMiliseconds); _log.WriteLine("ProvisioningDeviceClient RegisterAsync . . . "); DeviceRegistrationResult result = await provClient.RegisterAsync(cts.Token).ConfigureAwait(false); _log.WriteLine($"{result.Status}"); Assert.AreEqual(ProvisioningRegistrationStatusType.Failed, result.Status); Assert.IsNull(result.AssignedHub); Assert.IsNull(result.DeviceId); Assert.AreEqual(404201, result.ErrorCode); } }
public void RecordsAreNotSavedWhenStoredProcWithParameterAndTransactionIsRolledBack() { Database db = DatabaseFactory.CreateDatabase("OracleTest"); IDataReader dbReaderAddCountry = null; using (DbConnection connection = db.CreateConnection()) { connection.Open(); DbTransaction transaction = connection.BeginTransaction(); try { using (db.ExecuteReader(transaction, "UpdateCountryListAll", new object[] { "US", "United States of America", "" })) { } dbReaderAddCountry = db.ExecuteReader(transaction, "AddCountryListAll", new object[] { "IN", "India", "" }); transaction.Commit(); Assert.Fail("Exception should have been thrown"); } catch (Exception) { transaction.Rollback(); Assert.IsFalse("United States of America" == (string)db.ExecuteScalar(CommandType.Text, "select CountryName from Country where CountryCode='US'")); Assert.IsNull(dbReaderAddCountry); } } }
public TestResult VerifyCloseOnProjectOpenCheckbox(Application application, Log log) { const string prefix = "Close welcome tab on project open"; var result = new TestResult(); var assert = new Assert(result, log); try { var startPage = TabProxies.GetStartPageTabItem(application, log); if (startPage == null) { log.Info(prefix, "Opening start page."); MenuProxies.SwitchToStartPageViaViewStartPageMenuItem(application, log); } startPage = TabProxies.GetStartPageTabItem(application, log); if (startPage == null) { var message = "Failed to get the start page."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return result; } try { if (!startPage.IsSelected) { log.Info(prefix, "Setting focus to start page."); startPage.Select(); } } catch (Exception e) { var message = string.Format( CultureInfo.InvariantCulture, "Failed to select the start page tab. Error was: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); return result; } // Check 'keep open' flag WelcomePageControlProxies.UncheckCloseWelcomePageOnProjectOpen(application, log); // New button var newProjectSearchCriteria = SearchCriteria .ByAutomationId(WelcomeViewAutomationIds.NewProject); var newProjectButton = (Button)startPage.Get(newProjectSearchCriteria); if (newProjectButton == null) { var message = "Failed to get the 'New Project' button."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return result; } newProjectButton.Click(); // Check that the start page hasn't been closed var currentStartPage = TabProxies.GetStartPageTabItem(application, log); assert.IsNotNull(currentStartPage, prefix + " - Start page does not exist after opening project"); assert.IsFalse(currentStartPage.IsSelected, prefix + " - Start page is selected after opening project"); var currentProjectPage = TabProxies.GetProjectPageTabItem(application, log); assert.IsNotNull(currentProjectPage, prefix + " - Project page does not exist after opening project"); assert.IsTrue(currentProjectPage.IsSelected, prefix + " - Project page is not selected after opening project"); // Check that File - close has been enabled var fileCloseMenu = MenuProxies.GetFileCloseMenuItem(application, log); assert.IsTrue(fileCloseMenu.Enabled, prefix + " - File - Close menu is not enabled"); // HACK: It seems that the File menu stays open when we check the File - close menu item var fileMenu = MenuProxies.GetFileMenuItem(application, log); if (fileMenu == null) { var message = "Failed to get the file menu."; log.Error(prefix, message); result.AddError(prefix + " - " + message); return result; } if (fileMenu.IsFocussed) { fileMenu.Click(); } // Close the project via the close button on the tab page TabProxies.CloseProjectPageTab(application, log); WelcomePageControlProxies.CheckCloseWelcomePageOnProjectOpen(application, log); // New button newProjectButton.Click(); // Check that the start page has been closed currentStartPage = TabProxies.GetStartPageTabItem(application, log); assert.IsNull(currentStartPage, prefix + " - Start page exists after opening project"); // Close the project via the close button on the tab page TabProxies.CloseProjectPageTab(application, log); WelcomePageControlProxies.UncheckCloseWelcomePageOnProjectOpen(application, log); } catch (RegressionTestFailedException e) { var message = string.Format( CultureInfo.InvariantCulture, "Failed with exception. Error: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); } return result; }
public TestResult VerifyShowWelcomePageCheckbox(Application application, Log log) { const string prefix = "Verify show welcome page"; var result = new TestResult(); var assert = new Assert(result, log); try { var startPage = TabProxies.GetStartPageTabItem(application, log); assert.IsNull(startPage, prefix + " - Start page was open on application start."); WelcomePageControlProxies.CheckShowWelcomePageOnApplicationStart(application, log); } catch (RegressionTestFailedException e) { var message = string.Format( CultureInfo.InvariantCulture, "Failed with exception. Error: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); } return result; }
/// <summary> /// Verifies that the 'File' menu works as expected. /// </summary> /// <param name="application">The application.</param> /// <param name="log">The log object.</param> /// <returns>The test result for the current test case.</returns> public TestResult VerifyFileMenu(Application application, Log log) { const string prefix = "File menu"; var result = new TestResult(); var assert = new Assert(result, log); try { var projectPage = TabProxies.GetProjectPageTabItem(application, log); if (projectPage != null) { TabProxies.CloseProjectPageTab(application, log); } projectPage = TabProxies.GetProjectPageTabItem(application, log); assert.IsNull(projectPage, prefix + " - The project page was not closed."); MenuProxies.CreateNewProjectViaFileNewMenuItem(application, log); projectPage = TabProxies.GetProjectPageTabItem(application, log); assert.IsNotNull(projectPage, prefix + " - A new project was not created."); var fileCloseMenu = MenuProxies.GetFileCloseMenuItem(application, log); assert.IsTrue(fileCloseMenu.Enabled, prefix + " - File - Close menu is not enabled"); MenuProxies.CloseProjectViaFileCloseMenuItem(application, log); projectPage = TabProxies.GetProjectPageTabItem(application, log); assert.IsNull(projectPage, prefix + " - The project page was not closed."); } catch (RegressionTestFailedException e) { var message = string.Format( CultureInfo.InvariantCulture, "Failed with exception. Error: {0}", e); log.Error(prefix, message); result.AddError(prefix + " - " + message); } return result; }