public void WhenPopulateMergedImageInfo_ThenPopulateVouchers() { var vouchers = new List<DipsNabChq> { new DipsNabChq {S_TRACE = "000000000001"}, new DipsNabChq {S_TRACE = "000000000002"}, }; ExpectDirectory(imageDirectory); ExpectDirectory(targetDirectory); ExpectImageFiles(); ExpectMergedImageFiles(); ExpectImageMetadataFile(); var sut = CreateHelper(); sut.PopulateMergedImageInfo(JobIdentifier, BatchNumber, vouchers); var firstVoucher = vouchers.Single(x => x.S_TRACE == "000000000001"); Assert.AreEqual("0", firstVoucher.S_IMG1_OFF.Trim()); Assert.AreEqual("1", firstVoucher.S_IMG1_LEN.Trim()); Assert.AreEqual("0", firstVoucher.S_IMG2_OFF.Trim()); Assert.AreEqual("2", firstVoucher.S_IMG2_LEN.Trim()); var secondVoucher = vouchers.Single(x => x.S_TRACE == "000000000002"); Assert.AreEqual("1", secondVoucher.S_IMG1_OFF.Trim()); Assert.AreEqual("3", secondVoucher.S_IMG1_LEN.Trim()); Assert.AreEqual("2", secondVoucher.S_IMG2_OFF.Trim()); Assert.AreEqual("4", secondVoucher.S_IMG2_LEN.Trim()); }
public RepositoryMock() { List<Reply> replies = new List<Reply> { new Reply(){Body = "bdy1", Id = 1, TopicId = 1, Created = DateTime.Now}, new Reply(){Body = "bdy2", Id = 2, TopicId = 1, Created = DateTime.Now}, new Reply(){Body = "bdy3", Id = 3, TopicId = 1, Created = DateTime.Now}, new Reply(){Body = "bdy4", Id = 4, TopicId = 1, Created = DateTime.Now} }; Mock<IMsgRepo> mockRepo = new Mock<IMsgRepo>(); mockRepo.Setup(m => m.GetReplies()).Returns(replies.AsQueryable); mockRepo.Setup(m => m.FindById( It.IsAny<int>())) .Returns((int i) => replies.Single(x => x.Id == i)); mockRepo.Setup(m => m.DeleteReply(It.IsAny<int>())) .Returns( (int deleteId) => { var replyToDelete = replies.Single(r => r.Id == deleteId); replies.Remove(replyToDelete); return true; }); mockRepo.Setup(m => m.InsertReply( It.IsAny<Reply>())).Returns( (Reply target) => { DateTime now = DateTime.Now; if (target.Id.Equals(default(int))) { target.Created = now; target.Id = replies.Count() + 1; replies.Add(target); } else { var orig = replies.Single(r => r.Id == target.Id); if (orig == null) return false; orig.Body = target.Body; orig.Created = now; orig.TopicId = target.TopicId; } return true; } ); MockRepo = mockRepo.Object; }
/// <summary> /// The call cleanup actions. /// </summary> /// <exception cref="Exception">Cleanup action failed. /// </exception> /// <exception cref="AggregateException">Multiple exceptions occured in Cleanup. See test log for more details. /// </exception> private void CallCleanupActions() { this.cleanupActions.Reverse(); var exceptions = new List<Exception>(); foreach (var action in this.cleanupActions) { try { action(); } catch (Exception ex) { exceptions.Add(ex); Console.WriteLine("Cleanup action failed: " + ex); } } if (exceptions.Count == 0) { return; } if (exceptions.Count == 1) { throw exceptions.Single(); } throw new AggregateException( "Multiple exceptions occured in Cleanup. See test log for more details", exceptions); }
public void TrackEventWillSendPropertiesIfProvidedInline() { var sentTelemetry = new List<ITelemetry>(); var client = this.InitializeTelemetryClient(sentTelemetry); client.TrackEvent("Test", new Dictionary<string, string> { { "blah", "yoyo" } }); var eventTelemetry = (EventTelemetry)sentTelemetry.Single(); Assert.Equal("yoyo", eventTelemetry.Properties["blah"]); }
public void TrackEventSendsEventTelemetryWithSpecifiedObjectTelemetry() { var sentTelemetry = new List<ITelemetry>(); var client = this.InitializeTelemetryClient(sentTelemetry); client.TrackEvent(new EventTelemetry("TestEvent")); var eventTelemetry = (EventTelemetry)sentTelemetry.Single(); Assert.Equal("TestEvent", eventTelemetry.Name); }
public void TrackEventSendsEventTelemetryWithSpecifiedNameToProvideSimplestWayOfSendingEventTelemetry() { var sentTelemetry = new List<ITelemetry>(); var client = this.InitializeTelemetryClient(sentTelemetry); client.TrackEvent("TestEvent"); var eventTelemetry = (EventTelemetry)sentTelemetry.Single(); Assert.Equal("TestEvent", eventTelemetry.Name); }
public void TrackEventWillUseRequiredFieldTextForTheEventNameWhenTheEventNameIsEmptyToHideUserErrors() { var sentTelemetry = new List<ITelemetry>(); var client = this.InitializeTelemetryClient(sentTelemetry); client.TrackEvent((string)null); var eventTelemetry = (EventTelemetry)sentTelemetry.Single(); Assert.Contains(RequiredFieldText, eventTelemetry.Name, StringComparison.OrdinalIgnoreCase); }
public void ComplexType_CustomValidator_MultipleMemberNames() { // ensure TDPs are registered DomainServiceDescription.GetDescription(typeof(ComplexTypes_TestService)); ComplexType_Parent entity = new ComplexType_Parent { ID = 1, ContactInfo = new ContactInfo { Name = "Mathew", HomeAddress = new Address { AddressLine1 = "47 South Wynn Rd.", City = "Oregon", State = "OH" }, PrimaryPhone = new Phone { AreaCode = "419", Number = "693-6096" } }, }; // configure multi member validation errors DynamicTestValidator.ForcedValidationResults.Clear(); ValidationResult contactResult = new ValidationResult("ContactInfo", new string[] { "Name", "PrimaryPhone" }); ValidationResult phoneResult = new ValidationResult("Phone", new string[] { "AreaCode", "Number" }); DynamicTestValidator.ForcedValidationResults[entity.ContactInfo] = contactResult; DynamicTestValidator.ForcedValidationResults[typeof(Phone)] = phoneResult; ValidationContext validationContext = ValidationUtilities.CreateValidationContext(entity, null); List<ValidationResult> results = new List<ValidationResult>(); bool isValid = ValidationUtilities.TryValidateObject(entity, validationContext, results); Assert.IsFalse(isValid); // Verify that the member names have been transformed into full paths ValidationResult result = results.Single(q => q.ErrorMessage == "ContactInfo-ContactInfo"); string[] memberNames = result.MemberNames.ToArray(); Assert.AreEqual(2, memberNames.Length); Assert.IsTrue(memberNames.Contains("ContactInfo.Name")); Assert.IsTrue(memberNames.Contains("ContactInfo.PrimaryPhone")); // here we expect member names to be transformed into full paths result = results.Single(q => q.ErrorMessage == "Phone-TypeLevel"); memberNames = result.MemberNames.ToArray(); Assert.AreEqual(2, memberNames.Length); Assert.IsTrue(memberNames.Contains("ContactInfo.PrimaryPhone.AreaCode")); Assert.IsTrue(memberNames.Contains("ContactInfo.PrimaryPhone.Number")); }
public void FirstOrDefaultAndSigle_Test() { IList<User> list = new List<User>(); list.Add(new User() { Id = 1, Name = "zhangsan1", Age = 18, Address = "四川" }); list.Add(new User() { Id = 2, Name = "zhangsan2", Age = 18, Address = "四川" }); list.Add(new User() { Id = 3, Name = "zhangsan3", Age = 18, Address = "四川" }); list.Add(new User() { Id = 4, Name = "zhangsan4", Age = 18, Address = "四川" }); list.Add(new User() { Id = 5, Name = "zhangsan5", Age = 18, Address = "四川" }); IQueryable<User> query = list.AsQueryable(); Assert.AreEqual(list.First(), query.FirstOrDefault()); Assert.AreEqual(null, query.FirstOrDefault(o => o.Age == 2)); Assert.AreEqual(list.Single(), query.Single()); Assert.AreEqual(null, query.Single(o => o.Age == 2)); }
public void GetTest1() { _repository = new Mock<IBookRepository>(); _library = new List<Book> { new Book() {ID = 1, Title = "Developing ASP.NET MVC 4 Web Applications",VolumeId = "7thhkgEACAAJ"}, new Book() {ID = 2, Title = "Developing Web Applications with Visual Basic.NET and ASP.NET",VolumeId = "L7071Dj5et4C"}, new Book() {ID = 3, Title = "The Kill Bill Diary",VolumeId = "5EGJAwAAQBAJ"} }; _repository.Setup(x => x.Get(It.IsAny<int>())) .Returns((int i) => _library.Single(bo => bo.ID == i)); var bookThatExists = _repository.Object.Get(1); Assert.IsNotNull(bookThatExists); }
public DoesRepositoryWork() { List<Products> products = new List<Products>() { new Products { Id = 1, Name = "Margaritha", Price = (decimal) 10.0 }, new Products { Id = 2, Name = "Fuji", Price = (decimal) 20.0 }, new Products { Id = 3, Name = "User", Price = (decimal) 30.0 }, }; Mock<IRepository<Products>> mockRepo = new Mock<IRepository<Products>>(); mockRepo.Setup(m => m.GetList()).Returns(products); mockRepo.Setup(m => m.GetEntity(It.IsAny<int>())) .Returns((int i) => products.Single(x => x.Id == i)); mockRepo.Setup(m => m.AddEntity(It.IsAny<Products>())).Returns((Products product) => { products.Add(product); return product; }); mockRepo.Setup(m => m.DeleteEntity(It.IsAny<Products>())).Returns((Products product) => { products.Remove(product); return product; }); this.repository = mockRepo.Object; }
public void PingLocalhostWillNotFail() { const string HOST = "127.0.0.1"; List<ToolPing> responseList = new List<ToolPing>(); Exception responseException = null; ITikCommand pingCommand = Connection.LoadAsync<ToolPing>( ping => responseList.Add(ping), //read callback exception => responseException = exception, //exception callback Connection.CreateParameter("address", HOST), Connection.CreateParameter("count", "1"), Connection.CreateParameter("size", "64")); Thread.Sleep(2 * 1000); Assert.IsNull(responseException); Assert.AreEqual(responseList.Count, 1); Assert.AreEqual(responseList.Single().Host, HOST); }
public async Task GetUserStock_with_id_must_return_stock_from_context() { var data = new List<UserStock> { new UserStock {ID = 0, Name = "DAX"}, new UserStock {ID = 1, Name = "NYSE"} }.AsQueryable(); var mockSet = new Mock<DbSet<UserStock>>(); mockSet.Setup(m => m.FindAsync(It.IsAny<object[]>())).Returns<object[]>((key) => Task.FromResult(data.SingleOrDefault(us => us.ID == (int)key[0]))); var mockContext = new Mock<IStockExchangeDbContext>(); mockContext.Setup(c => c.UserStocks).Returns(mockSet.Object); var service = new UserStocksController(mockContext.Object); var result = await service.GetUserStock(0); Assert.IsInstanceOfType(result, typeof(OkNegotiatedContentResult<UserStock>)); var conResult = result as OkNegotiatedContentResult<UserStock>; Assert.IsNotNull(conResult); Assert.AreEqual(data.Single(us => us.ID == 0), conResult.Content); }
internal static string GetRefactoringResult(string language, CodeRefactoringProvider codeRefactoringProvider, string oldSource, TextSpan span, string equivalenceKey) { var document = CodeAnalysisHelper.CreateDocument(oldSource, language); var actions = new List<CodeAction>(); var context = new CodeRefactoringContext(document, span, (a) => actions.Add(a), CancellationToken.None); codeRefactoringProvider.ComputeRefactoringsAsync(context).Wait(); if (equivalenceKey != null) { document = CodeAnalysisHelper.ApplyFix(document, actions.Single(n => n.EquivalenceKey == equivalenceKey)); } else { document = CodeAnalysisHelper.ApplyFix(document, actions[0]); } var newSource = CodeAnalysisHelper.GetStringFromDocument(document); return newSource; }
public void TrackTraceSendsTraceTelemetryWithSpecifiedObjectTelemetry() { var sentTelemetry = new List<ITelemetry>(); var client = this.InitializeTelemetryClient(sentTelemetry); client.TrackTrace(new TraceTelemetry { Message = "TestTrace" }); var trace = (TraceTelemetry)sentTelemetry.Single(); Assert.Equal("TestTrace", trace.Message); }
public CommodityTypeRepositoryTest() { List<CommodityType> testCommoditTypes = new List<CommodityType> { new CommodityType { CommodityTypeID = 1,Name = "Food" }, new CommodityType { CommodityTypeID = 2, Name = "Non Food"}, new CommodityType { CommodityTypeID = 3, Name = "Equipments"} }; // Mock the Commoditytype Repository using Moq Mock<IUnitOfWork> mockCommodityTypeRepository = new Mock<IUnitOfWork>(); // Return all the Commodity types mockCommodityTypeRepository.Setup(mr => mr.CommodityType.GetAll()).Returns(testCommoditTypes); // return a Commoditytype by CommoditytypeId mockCommodityTypeRepository.Setup(mr => mr.CommodityType.FindById( It.IsAny<int>())).Returns((int i) => testCommoditTypes.Where(x => x.CommodityTypeID == i).Single()); //return a commoditytype by it's name mockCommodityTypeRepository.Setup(mr => mr.CommodityType.GetCommodityByName( It.IsAny<string>())).Returns((string i) => testCommoditTypes.Where(x => x.Name == i).Single()); // delete a Commoditytype by CommodityId mockCommodityTypeRepository.Setup(mr => mr.CommodityType.DeleteByID( It.IsAny<int>())).Returns( (int i) => { var original = testCommoditTypes.Single (q => q.CommodityTypeID == i); //see if there is a reference in side the commodity table var testCommodities = new UnitOfWork().Commodity.GetAll(); var childsCount = testCommodities.Count(c => c.CommodityTypeID == i); if (original == null || childsCount != 0) { return false; } else { testCommoditTypes.Remove(original); return true; } }); //test deletion of commodity mockCommodityTypeRepository.Setup(mr => mr.CommodityType.Delete( It.IsAny<CommodityType>())).Returns( (CommodityType target) => { var original = testCommoditTypes.Single (q => q.CommodityTypeID == target.CommodityTypeID); //var childsCount = testCommodities.Count(c => c.ParentID == target.CommodityID); //see if there is a reference in side the commodity table var testCommoditiesCollection = new UnitOfWork().Commodity.GetAll(); var childsCount = testCommoditiesCollection.Count(c => c.CommodityTypeID == target.CommodityTypeID); if (original == null || childsCount != 0) { return false; } else { testCommoditTypes.Remove(original); return true; } }); //returns bool if we can save one (editing )scheme mockCommodityTypeRepository.Setup(mr => mr.CommodityType.SaveChanges(It.IsAny<CommodityType>())).Returns( (CommodityType target) => { var original = testCommoditTypes.Single (q => q.CommodityTypeID == target.CommodityTypeID); if (original == null) { return false; } original.Name = target.Name; return true; }); //TODO remove the lines below duplicate of the mockCommodityTypeRepository.Setup(mr => mr.CommodityType.Add(It.IsAny<CommodityType>())).Returns( (CommodityType target) => { if (target.CommodityTypeID.Equals(default(int))) { target.CommodityTypeID = testCommoditTypes.Count() + 1; testCommoditTypes.Add(target); } else { var original = testCommoditTypes.Single (q => q.CommodityTypeID == target.CommodityTypeID); if (original == null) { return false; } original.Name = target.Name; } return true; }); this.MockCommodityTypeRepository = mockCommodityTypeRepository.Object; }
/// <summary> /// Apply codefixes and returns reslt. /// Creates a Document from the source string, then gets diagnostics on it and applies the relevant codefixes. /// Note: If any codefix causes new diagnostics to show up, the test fails unless allowNewCompilerDiagnostics is set to true. /// </summary> /// <param name="language">The language the source code is in</param> /// <param name="analyzer">The analyzer to be applied to the source code</param> /// <param name="codeFixProvider">The codefix to be applied to the code wherever the relevant Diagnostic is found</param> /// <param name="oldSource">A class in the form of a string before the CodeFix was applied to it</param> /// <param name="equivalenceKey">CodeAction.EquivalenceKey determining which codefix to apply if there are multiple</param> /// <param name="allowNewCompilerDiagnostics">A bool controlling whether or not the test will fail if the CodeFix introduces other warnings after being applied</param> internal static string GetFixResult(string language, DiagnosticAnalyzer analyzer, CodeFixProvider codeFixProvider, string oldSource, string equivalenceKey, bool allowNewCompilerDiagnostics) { var document = CodeAnalysisHelper.CreateDocument(oldSource, language); var analyzerDiagnostics = CodeAnalysisHelper.GetSortedDiagnosticsFromDocuments(analyzer, new[] { document }); var compilerDiagnostics = CodeAnalysisHelper.GetCompilerDiagnostics(document); var attempts = analyzerDiagnostics.Length; for (int i = 0; i < attempts; ++i) { var actions = new List<CodeAction>(); var context = new CodeFixContext(document, analyzerDiagnostics[0], (a, d) => actions.Add(a), CancellationToken.None); codeFixProvider.RegisterCodeFixesAsync(context).Wait(); if (!actions.Any()) { break; } if (equivalenceKey != null) { document = CodeAnalysisHelper.ApplyFix(document, actions.Single(n => n.EquivalenceKey == equivalenceKey)); break; } document = CodeAnalysisHelper.ApplyFix(document, actions.ElementAt(0)); analyzerDiagnostics = CodeAnalysisHelper.GetSortedDiagnosticsFromDocuments(analyzer, new[] { document }); var newCompilerDiagnostics = CodeAnalysisHelper.GetNewDiagnostics(compilerDiagnostics, CodeAnalysisHelper.GetCompilerDiagnostics(document)); //check if applying the code fix introduced any new compiler diagnostics if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any()) { // Format and get the compiler diagnostics again so that the locations make sense in the output document = document.WithSyntaxRoot(Formatter.Format(document.GetSyntaxRootAsync().Result, Formatter.Annotation, document.Project.Solution.Workspace)); newCompilerDiagnostics = CodeAnalysisHelper.GetNewDiagnostics(compilerDiagnostics, CodeAnalysisHelper.GetCompilerDiagnostics(document)); Assert.IsTrue(false, string.Format("Fix introduced new compiler diagnostics:\r\n{0}\r\n\r\nNew document:\r\n{1}\r\n", string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString())), document.GetSyntaxRootAsync().Result.ToFullString())); } //check if there are analyzer diagnostics left after the code fix if (!analyzerDiagnostics.Any()) { break; } } var newSource = CodeAnalysisHelper.GetStringFromDocument(document); return newSource; }
public void SendUserInfoInSqlContext_WriteWithUser() { var testUser = new TestUserInfo { IsUserRecognized = true, UserName = "******", Workstation = "HAL9000" }; var sqlExecuter = new OracleSqlExecuter(SqlUtility.ConnectionString, new ConsoleLogProvider(), testUser); string table = GetRandomTableName(); var result = new List<string>(); sqlExecuter.ExecuteSql(new [] { @"CREATE TABLE " + table + " AS SELECT SYS_CONTEXT('USERENV','CLIENT_INFO') ClientInfo FROM DUAL" }); sqlExecuter.ExecuteReader(@"SELECT * FROM " + table, reader => result.Add(reader[0].ToString())); var clientInfo = result.Single(); TestUtility.AssertContains(clientInfo, testUser.UserName, "CLIENT_INFO should contain username."); TestUtility.AssertContains(clientInfo, testUser.Workstation, "CLIENT_INFO should contain client workstation."); Assert.AreEqual(SqlUtility.UserContextInfoText(testUser), clientInfo); }
public void GroupingAddAndRemoveItem() { EnqueueCallback(() => { this._dds.AutoLoad = false; this._dds.QueryName = "GetCitiesQuery"; this._dds.DomainContext = new CityDomainContext(); this._dds.GroupDescriptors.Add(new GroupDescriptor("StateName")); this._dds.Load(); }); this.AssertLoadingData(); EnqueueCallback(() => { this.ResetLoadState(); City toAddAndRemove = new City { Name = "Add and Remove", StateName = "ST", CountyName = "County" }; int originalCount = this._view.Count; this._view.Add(toAddAndRemove); Assert.AreEqual<int>(originalCount + 1, this._view.Count, "The count should increment by one after adding the city"); Assert.IsTrue(this._view.Contains(toAddAndRemove), "The added city should be in the view"); List<NotifyCollectionChangedEventArgs> actions = new List<NotifyCollectionChangedEventArgs>(); this._collectionView.CollectionChanged += (s, e) => actions.Add(e); this._view.Remove(toAddAndRemove); Assert.AreEqual<int>(originalCount, this._view.Count, "The count should decrement by one after removing the city"); Assert.IsFalse(this._view.Contains(toAddAndRemove), "The removed city should no longer be in the view"); Assert.AreEqual<int>(1, actions.Count, "There should have been one CollectionChanged event removing the city"); Assert.AreEqual<NotifyCollectionChangedAction>(NotifyCollectionChangedAction.Remove, actions.Single().Action, "The single CollectionChanged event action should have been a Remove"); Assert.AreEqual<int>(1, actions.Single().OldItems.Count, "There should have been one element in OldItems"); Assert.AreEqual<City>(toAddAndRemove, actions.Single().OldItems.Cast<City>().Single(), "The OldItems item should have been our city that was removed"); }); EnqueueTestComplete(); }
public void ThatShapeIsAssociatedWithRoute() { var route = RouteServices.WithDto(GetRouteDto()).Get(); var shape = ShapeServices.WithDto(ShapeTestFixtures.GetValidDtoWithRoutes()).Get(); var list = new List<IRoute>(shape.Routes); Assert.AreEqual(list.Single(p => p.Name == route.Name), route); }
public void SendUserInfoInSqlContext_NoUser() { var sqlExecuter = new OracleSqlExecuter(SqlUtility.ConnectionString, new ConsoleLogProvider(), new NullUserInfo()); var result = new List<object>(); sqlExecuter.ExecuteReader("SELECT SYS_CONTEXT('USERENV','CLIENT_INFO') FROM DUAL", reader => result.Add(reader[0])); Console.WriteLine(result.Single()); Assert.AreEqual(typeof(DBNull), result.Single().GetType()); }
public void TrackPageViewSendsGivenPageViewTelemetryToTelemetryChannel() { var sentTelemetry = new List<ITelemetry>(); TelemetryClient client = this.InitializeTelemetryClient(sentTelemetry); var pageViewTelemetry = new PageViewTelemetry("TestName"); client.TrackPageView(pageViewTelemetry); var channelPageView = (PageViewTelemetry)sentTelemetry.Single(); Assert.Same(pageViewTelemetry, channelPageView); }
public void GetInstance_ServiceRegisteredUsingRegisterSingleInstanceNonGeneric_CallsExpressionBuildingWithConstantExpression() { // Arrange var expressionsBuilding = new List<Expression>(); var container = ContainerFactory.New(); container.RegisterSingleton(typeof(IUserRepository), new SqlUserRepository()); container.ExpressionBuilding += (s, e) => { expressionsBuilding.Add(e.Expression); }; // Act container.GetInstance<IUserRepository>(); // Assert Assert.AreEqual(1, expressionsBuilding.Count); AssertThat.IsInstanceOfType(typeof(ConstantExpression), expressionsBuilding.Single()); }
public void TrackPageViewSendsPageViewTelemetryWithGivenNameToTelemetryChannel() { var sentTelemetry = new List<ITelemetry>(); TelemetryClient client = this.InitializeTelemetryClient(sentTelemetry); client.TrackPageView("TestName"); var pageView = (PageViewTelemetry)sentTelemetry.Single(); Assert.Equal("TestName", pageView.Name); }
public void TrackTraceWillSendSeverityLevelIfProvidedInline() { var sentTelemetry = new List<ITelemetry>(); var client = this.InitializeTelemetryClient(sentTelemetry); client.TrackTrace("Test", SeverityLevel.Error); var trace = (TraceTelemetry)sentTelemetry.Single(); Assert.Equal(SeverityLevel.Error, trace.SeverityLevel); }
public void TrackRequestSendsGivenRequestTelemetryToTelemetryChannel() { var sentTelemetry = new List<ITelemetry>(); TelemetryClient client = this.InitializeTelemetryClient(sentTelemetry); var clientRequest = new RequestTelemetry(); client.TrackRequest(clientRequest); var channelRequest = (RequestTelemetry)sentTelemetry.Single(); Assert.Same(clientRequest, channelRequest); }
public void TrackRequestSendsRequestTelemetryWithGivenNameTimestampDurationAndSuccessToTelemetryChannel() { var sentTelemetry = new List<ITelemetry>(); TelemetryClient client = this.InitializeTelemetryClient(sentTelemetry); var timestamp = DateTimeOffset.Now; client.TrackRequest("name", timestamp, TimeSpan.FromSeconds(42), "500", false); var request = (RequestTelemetry)sentTelemetry.Single(); Assert.Equal("name", request.Name); Assert.Equal(timestamp, request.Timestamp); Assert.Equal("500", request.ResponseCode); Assert.Equal(TimeSpan.FromSeconds(42), request.Duration); Assert.Equal(false, request.Success); }
public void TrackTraceSendsTraceTelemetryWithSpecifiedNameToProvideSimplestWayOfSendingTraceTelemetry() { var sentTelemetry = new List<ITelemetry>(); var client = this.InitializeTelemetryClient(sentTelemetry); client.TrackTrace("TestTrace"); var trace = (TraceTelemetry)sentTelemetry.Single(); Assert.Equal("TestTrace", trace.Message); }
public void TestEntityValidation_ComplexTypes() { // ensure TDPs are registered DomainServiceDescription.GetDescription(typeof(ComplexTypes_TestService)); ComplexType_Parent entity = new ComplexType_Parent { ID = 1, ContactInfo = new ContactInfo { Name = "Mathew", HomeAddress = new Address { AddressLine1 = "47 South Wynn Rd.", City = "Oregon", State = "OH" }, PrimaryPhone = new Phone { AreaCode = "419", Number = "693-6096" } }, }; ValidationContext validationContext = ValidationUtilities.CreateValidationContext(entity, null); List<ValidationResult> results = new List<ValidationResult>(); bool isValid = ValidationUtilities.TryValidateObject(entity, validationContext, results); Assert.IsTrue(isValid && results.Count == 0); // set an invalid property and revalidate entity.ContactInfo.PrimaryPhone.AreaCode = "Invalid"; results = new List<ValidationResult>(); isValid = ValidationUtilities.TryValidateObject(entity, validationContext, results); Assert.IsTrue(!isValid && results.Count == 1); ValidationResult result = results.Single(); Assert.AreEqual("The field AreaCode must be a string with a maximum length of 3.", result.ErrorMessage); Assert.AreEqual("ContactInfo.PrimaryPhone.AreaCode", result.MemberNames.Single()); // create TWO validation errors entity.ContactInfo.PrimaryPhone.AreaCode = "Invalid"; entity.ContactInfo.HomeAddress.State = "Invalid"; results = new List<ValidationResult>(); isValid = ValidationUtilities.TryValidateObject(entity, validationContext, results); Assert.IsTrue(!isValid && results.Count == 2); Assert.AreEqual("The field State must be a string with a maximum length of 2.", results[0].ErrorMessage); Assert.AreEqual("ContactInfo.HomeAddress.State", results[0].MemberNames.Single()); Assert.AreEqual("The field AreaCode must be a string with a maximum length of 3.", results[1].ErrorMessage); Assert.AreEqual("ContactInfo.PrimaryPhone.AreaCode", results[1].MemberNames.Single()); // verify custom validation was called at CT type and property levels entity.ContactInfo.PrimaryPhone.AreaCode = "419"; entity.ContactInfo.HomeAddress.State = "OH"; DynamicTestValidator.Monitor(true); results = new List<ValidationResult>(); isValid = ValidationUtilities.TryValidateObject(entity, validationContext, results); Assert.AreEqual(3, DynamicTestValidator.ValidationCalls.Count); Assert.IsNotNull(DynamicTestValidator.ValidationCalls.Single(v => v.MemberName == null && v.ObjectType == typeof(ContactInfo))); Assert.IsNotNull(DynamicTestValidator.ValidationCalls.Single(v => v.MemberName == "ContactInfo" && v.ObjectType == typeof(ComplexType_Parent))); Assert.IsNotNull(DynamicTestValidator.ValidationCalls.Single(v => v.MemberName == null && v.ObjectType == typeof(Phone))); DynamicTestValidator.Monitor(false); // verify deep CT collection validation List<ComplexType_Recursive> children = new List<ComplexType_Recursive> { new ComplexType_Recursive { P1 = "1", P4 = -1 }, // invalid element new ComplexType_Recursive { P1 = "2", P3 = new List<ComplexType_Recursive> { new ComplexType_Recursive { P1 = "3", P4 = -5 } // invalid element in nested collection } } }; ComplexType_Scenarios_Parent parent = new ComplexType_Scenarios_Parent { ID = 1, ComplexType_Recursive = new ComplexType_Recursive { P1 = "1", P3 = children } }; validationContext = ValidationUtilities.CreateValidationContext(parent, null); results = new List<ValidationResult>(); isValid = ValidationUtilities.TryValidateObject(parent, validationContext, results); Assert.AreEqual(2, results.Count); result = results.Single(p => p.MemberNames.Single() == "ComplexType_Recursive.P3().P4"); Assert.AreEqual("The field P4 must be between 0 and 5.", result.ErrorMessage); result = results.Single(p => p.MemberNames.Single() == "ComplexType_Recursive.P3().P3().P4"); Assert.AreEqual("The field P4 must be between 0 and 5.", result.ErrorMessage); }
public void TrackTraceWillNotSetSeverityLevelIfCustomerProvidedOnlyName() { var sentTelemetry = new List<ITelemetry>(); var client = this.InitializeTelemetryClient(sentTelemetry); client.TrackTrace("Test"); var trace = (TraceTelemetry)sentTelemetry.Single(); Assert.Equal(null, trace.SeverityLevel); }