private static IEnumerable<long> Eratostenes() { const int max = 2000000; var primes = new List<long>(); var crossedOff = new HashSet<long>(); long candidate = 1; while (candidate < max) { candidate++; if (crossedOff.Contains(candidate)) { continue; } primes.Add(candidate); // remove multiples of candidate for (var i = candidate; i < max + 1; i += candidate) { crossedOff.Add(i); } } return primes.ToArray(); }
public void GetAllShouldReturnTodos() { var data = new List<Todo> { new Todo {Id = 1}, new Todo {Id = 2}, new Todo {Id = 3}, }.AsQueryable(); var mockSet = new Mock<DbSet<Todo>>(); mockSet.As<IQueryable<Todo>>().Setup(m => m.Provider).Returns(data.Provider); mockSet.As<IQueryable<Todo>>().Setup(m => m.Expression).Returns(data.Expression); mockSet.As<IQueryable<Todo>>().Setup(m => m.ElementType).Returns(data.ElementType); mockSet.As<IQueryable<Todo>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); var mockContext = new Mock<ApplicationDbContext>(); mockContext.Setup(c => c.Todos).Returns(mockSet.Object); var service = new TodoRepository(mockContext.Object); var todos = service.GetAll().ToList(); Assert.AreEqual(3, todos.Count); Assert.AreEqual(1, todos[0].Id); Assert.AreEqual(2, todos[1].Id); Assert.AreEqual(3, todos[2].Id); }
public void TestLoadAndRunDynamic() { var cities = new Cities(); cities.ReadCities(CitiesTestFile); IRoutes routes = RoutesFactory.Create(cities); routes.ReadRoutes(LinksTestFile); Assert.AreEqual(11, cities.Count); // test available cities List<Link> links = routes.FindShortestRouteBetween("Zürich", "Basel", TransportModes.Rail); var expectedLinks = new List<Link>(); expectedLinks.Add(new Link(new City("Zürich", "Switzerland", 7000, 1, 2), new City("Aarau", "Switzerland", 7000, 1, 2), 0)); expectedLinks.Add(new Link(new City("Aarau", "Switzerland", 7000, 1, 2), new City("Liestal", "Switzerland", 7000, 1, 2), 0)); expectedLinks.Add(new Link(new City("Liestal", "Switzerland", 7000, 1, 2), new City("Basel", "Switzerland", 7000, 1, 2), 0)); Assert.IsNotNull(links); Assert.AreEqual(expectedLinks.Count, links.Count); for (int i = 0; i < links.Count; i++) { Assert.AreEqual(expectedLinks[i].FromCity.Name, links[i].FromCity.Name); Assert.AreEqual(expectedLinks[i].ToCity.Name, links[i].ToCity.Name); } links = routes.FindShortestRouteBetween("doesNotExist", "either", TransportModes.Rail); Assert.IsNull(links); }
public void CalcualteSubsidy() { int year = 2015; string state = "CA"; decimal income = 24750M; int rateAreaId = 4; var family = new List<Person>( new Person[] { new Person() { Dob = DateTime.Today.AddYears(-56), Relationship = Relationship.Self }, new Person() { Dob = DateTime.Today.AddYears(-52), Relationship = Relationship.Spouse }, new Person() { Dob = DateTime.Today.AddYears(-2), Relationship = Relationship.Dependent }, new Person() { Dob = DateTime.Today.AddYears(-21), Relationship = Relationship.Dependent }, new Person() { Dob = DateTime.Today.AddYears(-22), Relationship = Relationship.Dependent }, new Person() { Dob = DateTime.Today.AddYears(-4), Relationship = Relationship.Dependent }, new Person() { Dob = DateTime.Today.AddYears(-6), Relationship = Relationship.Dependent }, new Person() { Dob = DateTime.Today.AddYears(-18), Relationship = Relationship.Dependent }, } ); var calc = GetCalculator(); var input = new GetFinancialAssistanceRequest() { County = "", EffectiveDate = DateTime.Now.AddMonths(1), FamilyMembers = family, FamilySize = 4, FamilyTaxableIncome = 26000, ZipCode = "94154" }; var result = calc.CalculateSubsidy(input); Assert.IsNotNull(result); }
public void Test_All_Items_For_Correct_Return_Paths_Abbreviated_Syntax() { var values = new List<KeyValuePair<string, string>>() { new KeyValuePair<string,string>("/" , "root::node()"), new KeyValuePair<string,string>("/doc/chapter[position()=5]/section[position()=2]" , "root::node()/child::doc/(child::chapter)[position()=5]/(child::section)[position()=2]"), new KeyValuePair<string,string>("@*" , "attribute::*"), new KeyValuePair<string,string>("@name" , "attribute::name"), new KeyValuePair<string,string>("*" , "child::*"), new KeyValuePair<string,string>("*/child::para" , "child::*/child::para"), new KeyValuePair<string,string>("*[self::chapter or self::appendix]" , "(child::*)[self::chapter or self::appendix]"), new KeyValuePair<string,string>("*[self::chapter or self::appendix][position()=last()]" , "((child::*)[self::chapter or self::appendix])[position()=last()]"), new KeyValuePair<string,string>("chapter/descendant::para" , "child::chapter/descendant::para"), new KeyValuePair<string,string>("chapter[title='Introduction']" , "(child::chapter)[child::title='Introduction']"), new KeyValuePair<string,string>("chapter[title]" , "(child::chapter)[child::title]"), new KeyValuePair<string,string>("node()" , "child::node()"), new KeyValuePair<string,string>("para" , "child::para"), new KeyValuePair<string,string>("para[@type='warning']" , "(child::para)[attribute::type='warning']"), new KeyValuePair<string,string>("para[@type='warning'][position()=5]" , "((child::para)[attribute::type='warning'])[position()=5]"), new KeyValuePair<string,string>("para[1]" , "(child::para)[1]"), new KeyValuePair<string,string>("para[position()=5][@type='warning']" , "((child::para)[position()=5])[attribute::type='warning']"), new KeyValuePair<string,string>("para[position()=last()-1]" , "(child::para)[position()=last()-1]"), new KeyValuePair<string,string>("para[position()=last()]" , "(child::para)[position()=last()]"), new KeyValuePair<string,string>("para[position()>1]" , "(child::para)[position()>1]"), new KeyValuePair<string,string>("text()" , "child::text()"), }; foreach (var item in values) { var result = new XPathParser<string>().Parse(item.Key, new XPathStringBuilder()); Assert.AreEqual<string>(item.Value, result); } }
private EntityCollection GenerateRandomAccountCollection() { var collection = new List<Entity>(); for (var i = 0; i < 10; i++) { var rgn = new Random((int)DateTime.Now.Ticks); var entity = new Entity("account"); entity["accountid"] = entity.Id = Guid.NewGuid(); entity["address1_addressid"] = Guid.NewGuid(); entity["modifiedon"] = DateTime.Now; entity["lastusedincampaign"] = DateTime.Now; entity["donotfax"] = rgn.NextBoolean(); entity["new_verybignumber"] = rgn.NextInt64(); entity["exchangerate"] = rgn.NextDecimal(); entity["address1_latitude"] = rgn.NextDouble(); entity["numberofemployees"] = rgn.NextInt32(); entity["primarycontactid"] = new EntityReference("contact", Guid.NewGuid()); entity["revenue"] = new Money(rgn.NextDecimal()); entity["ownerid"] = new EntityReference("systemuser", Guid.NewGuid()); entity["industrycode"] = new OptionSetValue(rgn.NextInt32()); entity["name"] = rgn.NextString(15); entity["description"] = rgn.NextString(300); entity["statecode"] = new OptionSetValue(rgn.NextInt32()); entity["statuscode"] = new OptionSetValue(rgn.NextInt32()); collection.Add(entity); } return new EntityCollection(collection); }
public void TestWithAnEmptyCollection() { List<int> collection = new List<int>(); Quicksorter<int> sorter = new Quicksorter<int>(); sorter.Sort(collection); Assert.AreEqual(0, collection.Count); }
public void Upper_Limit_Is_999() { var inQueue = new List<int> { 999, 1 }; var expectedOutQueue = new List<int> { 999 }; AssertAddOutputMatches(inQueue, expectedOutQueue); }
public void UntilItemConstTest() { var items = new List<UntilItemClass> { new UntilItemClass { Name = "Alice", LastItem = "Nope", Description = "She's just a girl in the world" }, new UntilItemClass { Name = "Bob", LastItem = "Not yet", Description = "Well, he's just this guy, you know?" }, new UntilItemClass { Name = "Charlie", LastItem = "Yep", Description = "What?? That's a great idea!" } }; var expected = new UntilItemContainer {Items = items, ItemsLastItemExcluded = items, BoundItems = items}; var actual = Roundtrip(expected); Assert.AreEqual(expected.Items.Count, actual.Items.Count); Assert.AreEqual(expected.ItemsLastItemExcluded.Count - 1, actual.ItemsLastItemExcluded.Count); }
public static CompilerResults CompileFile(string input, string output, params string[] references) { CreateOutput(output); List<string> referencedAssemblies = new List<string>(references.Length + 3); referencedAssemblies.AddRange(references); referencedAssemblies.Add("System.dll"); referencedAssemblies.Add(typeof(IModule).Assembly.CodeBase.Replace(@"file:///", "")); referencedAssemblies.Add(typeof(ModuleAttribute).Assembly.CodeBase.Replace(@"file:///", "")); CSharpCodeProvider codeProvider = new CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(referencedAssemblies.ToArray(), output); using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(input)) { if (stream == null) { throw new ArgumentException("input"); } StreamReader reader = new StreamReader(stream); string source = reader.ReadToEnd(); CompilerResults results = codeProvider.CompileAssemblyFromSource(cp, source); ThrowIfCompilerError(results); return results; } }
public void EnumerateValues() { var filterItems = new List<string>(); AnswerCollection anss = new AnswerCollection(); Answer ta = anss.CreateAnswer<TextValue>("my answer"); ta.UserExtendible = false; // user should not be able to add/remove/reorder iterations in the interview ta.SetValue<TextValue>(new TextValue("val1", false), 0); // user should not be able to modify this answer ta.SetValue<TextValue>(new TextValue("val2", true), 1); // user will be able to modify this answer ta.SetValue<TextValue>(new TextValue("val3"), 2); // user will be able to modify this answer ta.SetValue<TextValue>("val4", 3); // user will be able to modify this answer // now enumerate the values AnswerValueEnumerator(ta); // now enumerate some Number values Answer tn = anss.CreateAnswer<NumberValue>("my num answer"); tn.SetValue<NumberValue>(new NumberValue(3), 0); AnswerValueEnumerator(tn); // now enumerate some Date values Answer td = anss.CreateAnswer<DateValue>("my date answer"); td.SetValue<DateValue>(new DateValue(DateTime.Now), 0); AnswerValueEnumerator(td); }
public void DistinctByLambda_OneListReversedEmpty_ExpectTheOneListValues() { List<Member> emptyList = new List<Member>(); var result = this.dozenPeopleList.Union(emptyList).Distinct((l1, l2) => l1.FirstName == l2.FirstName); Assert.IsTrue(result.Count() > 1); }
public void PutIdentifiable() { DoBaseline(); var entries = new List<TestIdentifiableTable>(); for (var i = 0; i < 1000; i++) { entries.Add(new TestIdentifiableTable { SomeData = i.ToString() + 1 }); } var identifiableTables = CrudService .PutIdentifiable<TestIdentifiableTable>(entries); entries = new List<TestIdentifiableTable>(); for (var i = 0; i < 1000; i++) { entries.Add(new TestIdentifiableTable { SomeData = i.ToString() + 1 }); } identifiableTables = CrudService .PutIdentifiable<TestIdentifiableTable>(entries); Assert.IsTrue(identifiableTables.All(t => t.Id > 0)); DoBaseline(); }
public void Addition_Within_Limits_Works() { var inQueue = new List<int> { 1, -1, 1, 1, -999, 1, -999, 0, 999, -999, 999, -333 }; var expectedOutQueue = new List<int> { 0, 2, -998, -999, 0, 666 }; AssertAddOutputMatches(inQueue, expectedOutQueue); }
public void EtwFileSourceTest() { var observable = EtwObservable.FromFiles(FileName); var source = new TimeSource<EtwNativeEvent>(observable, e => e.TimeStamp); var parsed = from p in source where p.Id == 2 select p.TimeStamp; var buf = parsed.Take(13).Buffer(TimeSpan.FromSeconds(1), source.Scheduler); var list = new List<IList<DateTimeOffset>>(); ManualResetEvent completed = new ManualResetEvent(false); buf.Subscribe( t => list.Add(t), ()=>completed.Set()); source.Connect(); completed.WaitOne(); Assert.AreEqual(2, list.Count()); Assert.AreEqual(7, list.First().Count); Assert.AreEqual(6, list.Skip(1).First().Count); }
public void CreateEventsFor_Test() { // Arrange _eventRepo.Setup(x => x.GetEventsOn(It.IsAny<DateTime>())).Returns(new List<Event>()); var start = new DateTime(2014, 2, 16); // start.DayOfWeek = Sunday var end = start.AddDays(6); var basketball = new Activity { DayOfWeek = "Saturday", Name = "Basketball" }; var frisbee = new Activity { DayOfWeek = "Sunday", Name = "Frisbee" }; var activities = new List<Activity> { basketball, frisbee }; var count = 0; _eventRepo.Setup(x => x.Insert(It.IsAny<Event>())).Callback((Event ev) => { count++; }); _activtyRepo.Setup(x => x.GetAll()).Returns(activities); // Act _sut.CreateEventsFor(start, end); // Assert Assert.AreEqual(2, count); }
/// <summary> /// Specifically use to query single entry or multi entries(query with $expand) /// </summary> /// <param name="requestUri"></param> /// <param name="mimeType"></param> /// <returns></returns> public List<ODataEntry> QueryEntries(string requestUri, string mimeType) { List<ODataEntry> entries = new List<ODataEntry>(); ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings() { BaseUri = baseUri }; var requestMessage = new HttpWebRequestMessage(new Uri(baseUri.AbsoluteUri + requestUri, UriKind.Absolute)); requestMessage.SetHeader("Accept", mimeType); var responseMessage = requestMessage.GetResponse(); Assert.AreEqual(200, responseMessage.StatusCode); if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata)) { using (var messageReader = new ODataMessageReader(responseMessage, readerSettings, model)) { var reader = messageReader.CreateODataEntryReader(); while (reader.Read()) { if (reader.State == ODataReaderState.EntryEnd) { entries.Add(reader.Item as ODataEntry); } } Assert.AreEqual(ODataReaderState.Completed, reader.State); } } return entries; }
public void ListContainsTest() { var list = new List<char>(); list.Add('o'); Assert.IsTrue(list.Contains('o')); Assert.IsFalse(list.Contains('l')); }
//[TestMethod] public void TestRedirectFileGeneration() { var originalFile = @"E:\Index\mscorlib\A.html"; var lines = File.ReadAllLines(originalFile); var list = new List<KeyValuePair<string, string>>(); var map = new Dictionary<string, string>(); foreach (var line in lines) { if (line.Length > 25 && line[0] == 'm') { if (line[22] == '"') { var id = line.Substring(3, 16); var file = line.Substring(23, line.Length - 25); list.Add(new KeyValuePair<string, string>(id, file)); map[id] = file; } else if (line[22] == 'm') { var id = line.Substring(3, 16); var other = line.Substring(25, 16); list.Add(new KeyValuePair<string, string>(id, map[other])); } } } Microsoft.SourceBrowser.HtmlGenerator.ProjectGenerator.GenerateRedirectFile( @"E:\Solution", @"E:\Solution\Project", list.ToDictionary(kvp => kvp.Key, kvp => (IEnumerable<string>)new List<string> { kvp.Value })); }
public void GetFirstUnsentAddress_ShouldReturnNull_IfNoUserWithNotSentStatusExistsInDatabase() { // Arrange var stubContext = new Mock<Context>(); var stubRecipients = new List<Recipient> { new Recipient("*****@*****.**"), new Recipient("*****@*****.**"), new Recipient("*****@*****.**"), }.AsQueryable(); stubRecipients.ElementAt(0).MarkAsSent(DateTime.Now); stubRecipients.ElementAt(1).MarkAsSent(DateTime.Now); stubRecipients.ElementAt(2).MarkAsFailed("sending failed", DateTime.Now); var stubDbSet = new Mock<DbSet<Recipient>>(); stubDbSet.As<IQueryable<Recipient>>().Setup(m => m.Provider).Returns(stubRecipients.Provider); stubDbSet.As<IQueryable<Recipient>>().Setup(m => m.Expression).Returns(stubRecipients.Expression); stubDbSet.As<IQueryable<Recipient>>().Setup(m => m.ElementType).Returns(stubRecipients.ElementType); stubDbSet.As<IQueryable<Recipient>>().Setup(m => m.GetEnumerator()).Returns(stubRecipients.GetEnumerator()); stubContext.Setup(c => c.Recipients).Returns(stubDbSet.Object); // Act var repository = new Repository(stubContext.Object); var recipient = repository.GetFirstUnsentAddress(); // Assert Assert.IsNull(recipient); }
public void GetFirstUnsentAddress_ShouldReturnFirstRecipientWithNotSentStatus_IfItExistsInDatabase() { // Arrange var stubContext = new Mock<Context>(); var stubRecipients = new List<Recipient> { new Recipient("*****@*****.**"), new Recipient("*****@*****.**"), new Recipient("*****@*****.**"), }.AsQueryable(); stubRecipients.First().MarkAsSent(DateTime.Now); var stubDbSet = new Mock<DbSet<Recipient>>(); stubDbSet.As<IQueryable<Recipient>>().Setup(m => m.Provider).Returns(stubRecipients.Provider); stubDbSet.As<IQueryable<Recipient>>().Setup(m => m.Expression).Returns(stubRecipients.Expression); stubDbSet.As<IQueryable<Recipient>>().Setup(m => m.ElementType).Returns(stubRecipients.ElementType); stubDbSet.As<IQueryable<Recipient>>().Setup(m => m.GetEnumerator()).Returns(stubRecipients.GetEnumerator()); stubContext.Setup(c => c.Recipients).Returns(stubDbSet.Object); // Act var repository = new Repository(stubContext.Object); var recipient = repository.GetFirstUnsentAddress(); // Assert Assert.AreEqual("*****@*****.**", recipient.Email); }
public void TesteListarFabricantes() { //ARRANGE List<Modelo> listaModelos = new List<Modelo>{ new Modelo(Faker.NameFaker.Name(),4,"V9",Categorias.Minivan,TipoCombustivel.Diesel,TipoCambio.Manual,new Fabricante("UM","AI")), new Modelo(Faker.NameFaker.Name(),4,"V10",Categorias.SUV,TipoCombustivel.Diesel,TipoCambio.Manual,new Fabricante("UM","AI")), new Modelo(Faker.NameFaker.Name(),4,"V11",Categorias.Intermediario,TipoCombustivel.Gasolina,TipoCambio.Automatico,new Fabricante("UM","AI")) }; var mockCtx = new Mock<IContext>(); var mockDAO = new Mock<IDAO<Modelo>>(); var fabMock = new Mock<IDAO<Fabricante>>(); mockCtx.Setup(x => x.Modelos).Returns(new FakeSET<Modelo>{ listaModelos[0], listaModelos[1], listaModelos[2] }); mockDAO.Setup(x => x.List()).Returns(listaModelos); var service = new ModeloService(mockDAO.Object,fabMock.Object); //ACT List<Modelo> listaEsperada = (List<Modelo>)mockDAO.Object.List(); int contEsperado = listaEsperada.Count; List<Modelo> listaReal = (List<Modelo>)service.Listar(); int contReal = listaReal.Count; //ASSERT Assert.AreEqual(contEsperado, contReal); }
public void TestSave() { var random = new Random(); // test saving and reloading var list = new List<TestCompositeClass>(); for (var x = 0; x < 100; x++) { var testClass = new TestCompositeClass { Key1 = random.Next(), Key2 = random.Next().ToString(), Key3 = Guid.NewGuid(), Key4 = DateTime.Now.AddMinutes(-1 * random.Next(100)), Data = Guid.NewGuid().ToString() }; list.Add(testClass); _databaseInstance.SaveAsync( testClass ).Wait(); } for (var x = 0; x < 100; x++) { var actual = _databaseInstance.LoadAsync<TestCompositeClass>( new TestCompositeKeyClass( list[ x ].Key1, list[x].Key2,list[x].Key3,list[x].Key4)).Result; Assert.IsNotNull(actual, "Load failed."); Assert.AreEqual(list[x].Data, actual.Data, "Load failed: data mismatch."); } }
public void TestCourseStudentAdd() { Student student = new Student("Mitko Mitev",61614); List<Student> list = new List<Student>(); list.Add(student); Assert.IsTrue(list.Contains(student)); }
public void BVT_VSSOperateShadowCopySet_ClusterSharePath_NonOwnerNode() { string nonOwnerNode = ""; List<string> shareUncPaths = new List<string>(); shareUncPaths.Add(@"\\" + TestConfig.ClusteredFileServerName + @"\" + TestConfig.ClusteredFileShare); BaseTestSite.Log.Add(LogEntryKind.TestStep, "Get one non-owner node of the clustered file server."); string ownerNode = GetClusterOwnerNode(TestConfig.ClusteredFileServerName).ToUpper(); if (!ownerNode.Contains(TestConfig.DomainName.ToUpper())) { ownerNode += "." + TestConfig.DomainName.ToUpper(); } if (ownerNode == TestConfig.ClusterNode01.ToUpper()) { nonOwnerNode = TestConfig.ClusterNode02; } else { nonOwnerNode = TestConfig.ClusterNode01; } BaseTestSite.Log.Add(LogEntryKind.Debug, "Select {0} as non-owner node.", nonOwnerNode); shareUncPaths.Add(@"\\" + nonOwnerNode + @"\" + TestConfig.BasicFileShare); TestShadowCopySet((ulong)FsrvpContextValues.FSRVP_CTX_BACKUP | (ulong)FsrvpShadowCopyAttributes.FSRVP_ATTR_AUTO_RECOVERY, shareUncPaths, FsrvpStatus.None, FsrvpSharePathsType.OnClusterAndNonOwnerNode); }
public void CollisionComparison() { CollisionDictionary d = new CollisionDictionary(); List<PhysicalObject2D> allSprites = new List<PhysicalObject2D>(); for (int i=0; i<1000000; i++) { Sprite s = new Sprite(this, "blocky"); s.Size = new Vector2(10); s.Position = i * s.Size; d.Add(s.Bounds); allSprites.Add(s); } Sprite firstSprite = new Sprite(this, "blocky"); firstSprite.Size = new Vector2(50); firstSprite.Position = new Vector2(300); allSprites.Add(firstSprite); Stopwatch sw = Stopwatch.StartNew(); DoConventionalCollisionCheck(firstSprite, allSprites); Console.WriteLine(sw.ElapsedMilliseconds); sw = Stopwatch.StartNew(); d.CalculateCollisions(firstSprite.Bounds); Console.WriteLine(sw.ElapsedMilliseconds); }
public void RowToIndexConverter_Convert_FindsValue_ReturnsIndex() { //------------Setup for test-------------------------- var converter = new RowToIndexConverter(); var activityDtos = new List<ActivityDTO> { new ActivityDTO("name", "value", 0), new ActivityDTO("name1", "value1", 1), new ActivityDTO("name2", "value2", 2) }; DsfMultiAssignActivity multiAssign = new DsfMultiAssignActivity(); multiAssign.FieldsCollection = activityDtos; dynamic modelItem = ModelItemUtils.CreateModelItem(multiAssign); ModelItemCollection collection = modelItem.FieldsCollection as ModelItemCollection; //------------Execute Test--------------------------- if(collection != null) { var result = converter.Convert(collection[1], typeof(int), null, CultureInfo.CurrentCulture); //------------Assert Results------------------------- Assert.AreEqual(2, result); } else { Assert.Fail(); } }
public async Task VerifyGetFixesWhenUsingSystemDoesNotExist() { var code = File.ReadAllText( $@"Targets\{nameof(IsBusinessObjectSerializableMakeSerializableCodeFixTests)}.{(nameof(this.VerifyGetFixesWhenUsingSystemDoesNotExist))}.cs"); var document = TestHelpers.Create(code); var tree = await document.GetSyntaxTreeAsync(); var diagnostics = await TestHelpers.GetDiagnosticsAsync(code, new IsBusinessObjectSerializableAnalyzer()); var sourceSpan = diagnostics[0].Location.SourceSpan; var actions = new List<CodeAction>(); var codeActionRegistration = new Action<CodeAction, ImmutableArray<Diagnostic>>( (a, _) => { actions.Add(a); }); var fix = new IsBusinessObjectSerializableMakeSerializableCodeFix(); var codeFixContext = new CodeFixContext(document, diagnostics[0], codeActionRegistration, new CancellationToken(false)); await fix.RegisterCodeFixesAsync(codeFixContext); Assert.AreEqual(2, actions.Count, nameof(actions.Count)); await TestHelpers.VerifyActionAsync(actions, IsBusinessObjectSerializableMakeSerializableCodeFixConstants.AddSystemSerializableDescription, document, tree, $"{Environment.NewLine}[System.Serializable]"); await TestHelpers.VerifyActionAsync(actions, IsBusinessObjectSerializableMakeSerializableCodeFixConstants.AddSerializableAndUsingDescription, document, tree, $"using System;{Environment.NewLine}{Environment.NewLine}[Serializable]"); }
public void RowToIndexConverter_Convert_DoesntFindValue_ReturnsMinusOne() { var converter = new RowToIndexConverter(); var activityDtos = new List<ActivityDTO> { new ActivityDTO("name", "value", 0), new ActivityDTO("name1", "value1", 1), new ActivityDTO("name2", "value2", 2) }; DsfMultiAssignActivity multiAssign = new DsfMultiAssignActivity(); multiAssign.FieldsCollection = activityDtos; ModelItem modelItemThatdoesntExist = ModelItemUtils.CreateModelItem(new ActivityDTO("thing", "stuff", 8)); dynamic modelItem = ModelItemUtils.CreateModelItem(multiAssign); ModelItemCollection collection = modelItem.FieldsCollection as ModelItemCollection; //------------Execute Test--------------------------- if(collection != null) { var result = converter.Convert(modelItemThatdoesntExist, typeof(int), null, CultureInfo.CurrentCulture); //------------Assert Results------------------------- Assert.AreEqual(-1, result); } else { Assert.Fail(); } }
public void TestGroupingsAnnualAndQuarterlyGroupingsGiveTwoGroupRoots() { List<Grouping> grouping = new List<Grouping>(); grouping.Add(new Grouping { IndicatorId = 1, SexId = 1, BaselineYear = 2001, BaselineQuarter = -1, DataPointYear = 2001, DataPointQuarter = -1 }); grouping.Add(new Grouping { IndicatorId = 1, SexId = 1, BaselineYear = 2001, BaselineQuarter = 1, DataPointYear = 2001, DataPointQuarter = 1 }); GroupRootBuilder builder = new GroupRootBuilder(); IList<GroupRoot> roots = builder.BuildGroupRoots(grouping); Assert.AreEqual(2, roots.Count); }