public void TestIndex()
        {
            // Arrange
            var movies = new List<Movie> {
                new Movie {Title="Star Wars", Director="Lucas"},
                new Movie {Title="Star Wars II", Director="Lucas"},
                new Movie {Title="Star Wars III", Director="Lucas"}
            };

            var mockMovieRepository = new Mock<IMovieRepository>();

            mockMovieRepository.Setup(r => r.ListAllMovies()).Returns(movies);
            var controller = new HomeController(mockMovieRepository.Object);

            var vm = new List<IndexViewModel>();
            movies.ToList().ForEach(m => vm.Add(new IndexViewModel {
                Id = m.Id,
                Title = m.Title,
                Director = m.Director
            }));

            // Act
            var result = (ViewResult)controller.Index();
            var model = (List<IndexViewModel>)result.Model;

            // Assert
            Assert.AreEqual(vm[0].Title, model[0].Title);
        }
Example #2
0
            List<int> BubbleSort(List<int> l)
            {
                var result = l.ToList();

                swapped = true;
                while (swapped)
                {
                    i = 0;
                    swapped = false;
                    while (i < result.Count - 1)
                    {
                        if (result[i] > result[i + 1])
                        {
                            t = result[i];
                            result[i] = result[i + 1];
                            result[i + 1] = t;
                            swapped = true;
                        }

                        i = i + 1;
                    }
                }

                return result;
            }
        public void TestComponentAbilityFiltering()
        {
            // targeted test data
            var provoke = new TestBattleAbility("Provoke", true, false, false);
            var fire = new TestBattleAbility("Fire", true, false, false);

            // Buffs test data
            var protect = new TestBattleAbility("Protect", true, true, true);
            var shell = new TestBattleAbility("Shell", true, true, true);

            // Enabled test data
            var water = new TestBattleAbility("Water", false, false, false);

            var testData = new List<TestBattleAbility>
            {
                provoke,
                protect,
                shell,
                fire,
                water
            };

            // Create the desired outcome with water removed since
            // it won't be enabled.
            var desiredOutcome = testData.ToList();
            desiredOutcome.Remove(water);

            var ordering = testData
                .Where(x => x.Enabled)
                .Where(x => x.IsBuff && x.HasEffectWore || !x.IsBuff);

            Assert.IsTrue(ordering.SequenceEqual(desiredOutcome));
        }
Example #4
0
        public void DeleteTheBest()
        {
            Random r = new Random();

            List<int> values = new List<int>();
            for (int i = 0; i < 100; i++)
            {
                values.Add(r.Next(100) - r.Next(100));
            }

            foreach (int value in values)
            {
                heap.Insert(value);
            }

            int deleteCount = r.Next(values.Count);

            List<int> sortedValues = values.ToList();
            sortedValues.Sort(comparision);
            sortedValues.Reverse();
            int expectedTheBestValue = sortedValues.Skip(deleteCount).FirstOrDefault();

            for (int i = 0; i < deleteCount; i++)
            {
                Assert.IsTrue(heap.DeleteTheBest());
            }

            Assert.AreEqual(values.Count - deleteCount, heap.Count);
            Assert.AreEqual(expectedTheBestValue, heap.GetTheBest());
        }
        public void OrderByNameDescendingTest()
        {
            var expextedResult = new List<Employee>() { employeeB, employeeA, employeeC }.AsQueryable();

            var result = employeeList.AsQueryable().SortListBy(x => x.FirstName, ListSortDirection.Descending);

            Assert.IsTrue(expextedResult.ToList().SequenceEqual(result.ToList(), new EmployeeListComparer()));
        }
        public void EmptySequenceList()
        {
            IList<Bid> expected = new List<Bid>();

            IList<BiddingSequence> biddingSequences = new List<BiddingSequence>();

            var result = BiddingConverter.Convert(biddingSequences);

            CollectionAssert.AreEqual(expected.ToList(), result.ToList());
        }
        public void AddFieldsForReturnsErrorWhenEmptyFieldDisplayIsAdded()
        {
            // Setup
            const string Tenant = "tenant";
            var mockTenant = new Mock<Tenant>();
            var metadata = new UDFMetadata { Name = "name", Display = string.Empty };
            var mockTenantStore = new Mock<ITenantStore>();
            mockTenantStore.Setup(m => m.GetTenant(Tenant)).Returns(mockTenant.Object);

            IEnumerable<UDFMetadataError> errors = new List<UDFMetadataError>();
            var udfDictionary = new UDFDictionary(mockTenantStore.Object);

            // Act
            var result = udfDictionary.AddFieldFor<TestExtension>(Tenant, metadata, out errors);

            // Assert
            Assert.IsFalse(result);
            Assert.IsTrue(errors.Count() > 0);
            Assert.AreEqual(UDFMetadataField.Display, errors.ToList()[0].Field);
            Assert.AreEqual("Cannot be empty", errors.ToList()[0].Message);
        }
        public void TiposItemController_AgregarTipoDeItemAProyecto()
        {
            HelperTestSistema.LimpiarArchivoBD();
            HelperTestSistema.IniciarServidor();

            //Creamos 1 proyecto1 directamente en la BD con dos tipos de item
            var tiposDeItemProyecto1 = HelperInstanciacionItems.GetTiposDeItem( "Proyecto 1", 2 );
            var proyecto = HelperInstanciacionProyectos.GetProyectos( 1 )[0];

            proyecto.AgregarTipoDeItem( tiposDeItemProyecto1[0] );
            proyecto.AgregarTipoDeItem( tiposDeItemProyecto1[1] );

            //Guardamos los objetos en la BD
            using ( IContextoProceso contexto = new ContextoProceso( HelperTestSistema.ObjectFactory ) )
            {
                contexto.ContenedorObjetos.Store( proyecto );
            }

            HelperTestSistema.ReiniciarConexion();

            //Creamos un tipo de item y lo agregamos al proyecto a traves de la API
            var controller = new TiposItemController( HelperTestSistema.ObjectFactory );

            //Obtenemos el 2 ya que tenemos que simular un nuevo tipo de item
            var nuevoTipoItem = HelperInstanciacionItems.GetTiposDeItem( "Proyecto 1" ,3 )[2];

            controller.Post( "P1", nuevoTipoItem );
            HelperTestSistema.ReiniciarConexion();

            //Obtenemos los datos directamente de la base de datos para verificarlos

            var proyectosBD = new List<Proyecto>();

            using ( IContextoProceso contexto = new ContextoProceso(HelperTestSistema.ObjectFactory) )
            {
                 proyectosBD = (from Proyecto p in contexto.ContenedorObjetos select p).ToList();
            }

            HelperTestSistema.ReiniciarConexion();
            HelperTestSistema.FinalizarServidor();

            //Asserts
            Assert.Inconclusive( "Refactorizar y terminar este test" );
            //Debe haber un solo proyecto en la base de datos
            Assert.AreEqual( 1, proyectosBD.ToList().Count );
            //El proyecto debe tener 3 tipos de item
            Assert.AreEqual( 3, proyectosBD[0].TiposDeItem.Count() );
            //El tercer tipo de item debe ser el que agregamos
            Assert.AreEqual( "Proyecto 1-Tipo de item de prueba 3", proyectosBD[0].TiposDeItem.ToList()[2].Descripcion );
        }
        public void GetAllSuperheroes_WhenThereAreSuperheroes()
        {
            var superherosList = new List<Superhero>()
                .AsQueryable();
            Mock.Arrange(() => this.mockSuperheroes.Entities)
                .Returns(superherosList);

            var service = new SuperheroesService(this.mockUnitOfWork, this.mockSuperheroes, this.mockPowers, this.mockCities);

            var superheroes = service.GetAllSuperheroes()
                .ToList();

            CollectionAssert.AreEqual(superherosList.ToList(), superheroes);
        }
Example #10
0
        static DatamodelTests()
        {
            var binary = new byte[16];
            new Random().NextBytes(binary);
            var quat = Quaternion.Normalize(new Quaternion(1, 2, 3, 4)); // dmxconvert will normalise this if I don't!

            TestValues_V1 = new List<object>(new object[] { "hello_world", 1, 1.5f, true, binary, null, System.Drawing.Color.Blue,
                new Vector2(1,2), new Vector3(1,2,3), new Vector4(1,2,3,4), quat, new Matrix4x4(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16) });

            TestValues_V2 = TestValues_V1.ToList();
            TestValues_V2[5] = TimeSpan.FromMinutes(5) + TimeSpan.FromTicks(TimeSpan.TicksPerMillisecond / 2);

            TestValues_V3 = TestValues_V1.Concat(new object[] { (byte)0xFF, (UInt64)0xFFFFFFFF }).ToList();
        }
Example #11
0
        public void AutoMapperTest()
        {
            List<User> users = new List<User>
                {
                    new User("1","1",null),
                    new User("2","2",null)
                };

            Mapper.CreateMap<User, UserDTO>();
            Mapper.AssertConfigurationIsValid();
            List<UserDTO> userDtos = Mapper.Map<List<User>, List<UserDTO>>(users.ToList());

            Assert.IsTrue(userDtos.Count == 2);
        }
        public void Search_Empty_Query_Expected_View_Result_Returned()
        {
            // Arrange
            string query = string.Empty;
            var stubResultsExpected = new List<SearchResultItem>();
            _mockSearchService.Setup(x => x.Search(query)).Returns(stubResultsExpected.ToList());

            // Act
            var result = _controller.Search(string.Empty);
            var model = result.Model as SearchResultViewModel;

            // Assert
            model.SearchQuery.Should().Be(query, " because that was the query we entered");
            model.Results.ShouldAllBeEquivalentTo(stubResultsExpected, " we expect the method to return the result from ISearchService unchanged");
        }
        public void DeckInitialisedWithCorrectCardsFromCardList()
        {
            List<Card> cards = new List<Card>();
            cards.Add(new Card() { Name = "TestCard1" });
            cards.Add(new Card() { Name = "TestCard2" });
            cards.Add(new Card() { Name = "TestCard2" });
            cards.Add(new Card() { Name = "TestCard3" });

            Deck deck = Deck.CreateFromCardList(cards);

            CollectionAssert.AreEquivalent(
                deck.Cards.ToList(),
                cards.ToList(),
                "Deck contains correct list of cards.");
        }
Example #14
0
            List<int> Reverse(List<int> l)
            {
                var result = l.ToList();

                i = 0;
                s = result.Count;
                while (i < s)
                {
                    t = result[i];
                    result.RemoveAt(i);
                    result.Insert(0, t);
                    i = i + 1;
                }

                return result;
            }
        public void SeveralTheatres_ListTheatres_ShouldReturnListedTheatres()
        {
            //Arrange
            var database = new PerformanceDatabase();

            //Act
            database.AddTheatre("Theatre Gosho");
            database.AddTheatre("Theatre Petka");
            database.AddTheatre("Ivana Theatre");

            var listed = database.ListTheatres();
            var expected = new List<IEnumerable> { "Ivana Theatre", "Theatre Gosho", "Theatre Petka" };
        
            //Assert
            CollectionAssert.AreEqual(expected.ToList(), listed.ToList());
        }
Example #16
0
        public void OrderBy()
        {
            var sigilTypes = typeof(Emit<>).Assembly.GetTypes();
            var linq = sigilTypes.Single(t => t.Name == "LinqAlternative");

            var sigilListGeneric = sigilTypes.Single(t => t.Name == "LinqList`1");
            var sigilListT = sigilListGeneric.MakeGenericType(typeof(Tuple<int, double>));
            var sigilListCons = sigilListT.GetConstructor(new[] { typeof(List<Tuple<int, double>>) });

            var sigilFuncGeneric = sigilTypes.Single(t => t.Name == "SigilFunc`2");
            var sigilFunc = sigilFuncGeneric.MakeGenericType(typeof(Tuple<int, double>), typeof(double));

            var asEnumerable = sigilListT.GetMethod("AsEnumerable");

            var orderByGeneric = sigilListT.GetMethod("OrderBy");
            var orderBy = orderByGeneric.MakeGenericMethod(typeof(double));

            var toSort = new List<Tuple<int, double>>();

            var rand = new Random();

            for (var i = 0; i < 1000; i++)
            {
                toSort.Add(Tuple.Create(i, rand.NextDouble()));
            }

            Func<Tuple<int, double>, double> p1 = _OrderSelect;
            var p2 = Delegate.CreateDelegate(sigilFunc, this.GetType().GetMethod("_OrderSelect"));

            var asSigilList = sigilListCons.Invoke(new object[] { toSort });

            var sigilOrderedInternal = orderBy.Invoke(asSigilList, new object[] { p2 });
            var sigilOrdered = (IEnumerable<Tuple<int, double>>)asEnumerable.Invoke(sigilOrderedInternal, new object[0]);
            var linqOrdered = toSort.ToList().OrderBy(p1);

            var sigilList = sigilOrdered.ToList();
            var linqList = linqOrdered.ToList();

            Assert.AreEqual(linqList.Count, sigilList.Count);

            for (var i = 0; i < linqList.Count; i++)
            {
                Assert.AreEqual(linqList[i], sigilList[i]);
            }
        }
Example #17
0
        public void CodeGen_ObjectTo_List()
        {
            List<String> list = new List<string> { "1", "2" };

            ArrayList arrayList = new ArrayList(list);
            List<String> list2 = Utils.ObjectToList<string>(arrayList);
            CheckOutputList(list, list2);

            string[] array = list.ToArray();
            List<String> list3 = Utils.ObjectToList<string>(array);
            CheckOutputList(list, list3);

            List<string> listCopy = list.ToList();
            List<String> list4 = Utils.ObjectToList<string>(listCopy);
            CheckOutputList(list, list4);

            IReadOnlyList<string> readOnlyList = list.ToList();
            List<String> list5 = Utils.ObjectToList<string>(readOnlyList);
            CheckOutputList(list, list5);
        }
        public void Search_NonEmpty_Query_Expected_View_Result_Returned()
        {
            // Arrange
            string query = "TFS";
            var stubResultsExpected = new List<SearchResultItem>
                                  {
                                      new SearchResultItem("p1", "e1", "en1"),
                                      new SearchResultItem("p2", "e2", "en2")
                                  };

            _mockSearchService.Setup(x => x.Search(query)).Returns(stubResultsExpected.ToList());

            // Act
            var result = _controller.Search(query);

            // Assert
            var model = result.Model as SearchResultViewModel;
            model.SearchQuery.Should().Be(query, " because that was the query we entered");
            model.Results.ShouldBeEquivalentTo(stubResultsExpected, options => options.WithStrictOrdering(), " we expect the method to return the result from ISearchService unchanged");
        }
Example #19
0
        public void ClrNamespace()
        {
            var type = typeof(DummyClass);
            string clrNamespace = $"clr-namespace:{type.Namespace};Assembly={type.GetTypeInfo().Assembly.GetName().Name}";
            var prefix = "prefix";
            var input = new List<ProtoXamlInstruction>
            {
                P.NamespacePrefixDeclaration(prefix, clrNamespace),
                P.EmptyElement(type, RootNs),
            };

            var expectedInstructions = new List<XamlInstruction>
            {
                X.NamespacePrefixDeclaration(clrNamespace, prefix),
                X.StartObject<DummyClass>(),
                X.EndObject(),
            };

            var actualNodes = sut.Parse(input);

            CollectionAssert.AreEqual(expectedInstructions.ToList(), actualNodes.ToList());
        }
Example #20
0
        public void TestKruskalWith9VerticesAnd11Edges()
        {
            int numberOfVertices = 9;
            var graphEdges = new List<Edge>
            {
                new Edge(0, 3, 9),
                new Edge(0, 5, 4),
                new Edge(0, 8, 5),
                new Edge(1, 4, 8),
                new Edge(1, 7, 7),
                new Edge(2, 6, 12),
                new Edge(3, 5, 2),
                new Edge(3, 6, 8),
                new Edge(3, 8, 20),
                new Edge(4, 7, 10),
                new Edge(6, 8, 7)
            };

            var minimumSpanningForest = KruskalAlgorithm.Kruskal(numberOfVertices, graphEdges.ToList());
            var totalWeight = minimumSpanningForest.Sum(edge => edge.Weight);

            var expectedTotalWeight = 45;
            var expectedForest = new[]
            {
                graphEdges[6],
                graphEdges[1],
                graphEdges[2],
                graphEdges[4],
                graphEdges[10],
                graphEdges[3],
                graphEdges[5]
            };

            Assert.AreEqual(expectedTotalWeight, totalWeight, "Weights should match.");
            CollectionAssert.AreEqual(
                expectedForest,
                minimumSpanningForest,
                "The correct edges should be present in the MST in the correct order.");
        }
        public void AddFieldsForReturnsErrorWhenDuplicateFieldIsAdded()
        {
            // Setup
            const string Tenant = "tenant";
            var mockTenant = new Mock<Tenant>();
            var metadata = new UDFMetadata { Name = "custom", Display = "custom" };
            var duplicateMetadata = new UDFMetadata { Name = "custom", Display = "custom" };
            var mockTenantStore = new Mock<ITenantStore>();
            mockTenantStore.Setup(m => m.GetTenant(Tenant)).Returns(mockTenant.Object);

            IEnumerable<UDFMetadataError> errors = new List<UDFMetadataError>();
            var udfDictionary = new UDFDictionary(mockTenantStore.Object);
            udfDictionary.AddFieldFor<TestExtension>(Tenant, metadata, out errors);

            // Act
            var result = udfDictionary.AddFieldFor<TestExtension>(Tenant, duplicateMetadata, out errors);

            // Assert
            Assert.IsFalse(result);
            Assert.IsTrue(errors.Count() > 0);
            Assert.IsTrue(errors.ToList()[0].Field == UDFMetadataField.Name);
        }
Example #22
0
        public void NamespaceDeclarationOnly()
        {
            var input = new List<ProtoXamlInstruction>
            {
                P.NamespacePrefixDeclaration(RootNs),
            };

            var expectedInstructions = new List<XamlInstruction>
            {
                X.NamespacePrefixDeclaration(RootNs),
            };

            var actualNodes = sut.Parse(input);

            CollectionAssert.AreEqual(expectedInstructions.ToList(), actualNodes.ToList());
        }
        public void TestGetFilmById()
        {
            var filmData = new List<DatabaseClient.TableEntity.Film>
            {
                new Film { description = "Most anticipated film this year", film_id = 1, length = 47, release_year = 2015, title = "Brazzers best shots" },
                new Film { description = "Wystraczy Cię na śmierć", film_id = 2, length = 97, release_year = 2001, title = "Jumanji" },
                new Film { description = "Na faktach autentycznych", film_id = 3, length = 97, release_year = 2011, title = "Wysyp żywych trupów" }
            }.AsQueryable();

            var filmSet = new Mock<DbSet<Film>>();
            filmSet.As<IQueryable<Film>>().Setup(m => m.Provider).Returns(filmData.Provider);
            filmSet.As<IQueryable<Film>>().Setup(m => m.Expression).Returns(filmData.Expression);
            filmSet.As<IQueryable<Film>>().Setup(m => m.ElementType).Returns(filmData.ElementType);
            filmSet.As<IQueryable<Film>>().Setup(m => m.GetEnumerator()).Returns(filmData.GetEnumerator());

            var categoryData = new List<DatabaseClient.TableEntity.Category>
            {
               new Category{category_id=11,last_update=DateTime.Now, name="Horror"},
               new Category{category_id=4,last_update=DateTime.Now, name="Biography"}
            }.AsQueryable();

            var categorySet = new Mock<DbSet<Category>>();
            categorySet.As<IQueryable<Category>>().Setup(m => m.Provider).Returns(categoryData.Provider);
            categorySet.As<IQueryable<Category>>().Setup(m => m.Expression).Returns(categoryData.Expression);
            categorySet.As<IQueryable<Category>>().Setup(m => m.ElementType).Returns(categoryData.ElementType);
            categorySet.As<IQueryable<Category>>().Setup(m => m.GetEnumerator()).Returns(categoryData.GetEnumerator());

            var mockContext = new Mock<DVDRentalContext>();
            mockContext.Setup(context => context.Films).Returns(filmSet.Object);
            mockContext.Setup(context => context.Categorys).Returns(categorySet.Object);

            List<FilmToCategory> ftc = new List<FilmToCategory>()
            {
                new FilmToCategory{category_id=4,film_id=2},
                new FilmToCategory{category_id=11,film_id=2}
            };

            mockContext.Setup(context => context.FillEntity<FilmToCategory>(It.IsAny<string>()))
                .Returns(ftc);

            repository = new FilmContext(mockContext.Object);

            var result = repository.GetFilmById(2);

            var expectedFilm = filmData.ToList()[1];

            Assert.AreEqual(expectedFilm.film_id, result.Id);
            Assert.AreEqual(expectedFilm.length, result.Length);
            Assert.AreEqual(expectedFilm.release_year, result.ReleaseYear);
            Assert.AreEqual(expectedFilm.title, result.Title);
            Assert.AreEqual(expectedFilm.description, result.Description);

            Assert.AreEqual(typeof(Models.Film), result.GetType()); // testowanie mapowania

            Assert.AreEqual(2, result.Categories.Count());
            Assert.AreEqual(typeof(List<Models.Category>), result.Categories.ToList().GetType()); // testowanie mapowania
        }
        public void GetAllByDate_WhenValid_ShouldReturnBugsCollection()
        {
            var repo = Mock.Create<IRepository<Bug>>();
            var bugs =
                new List<Bug> { new Bug() { LogDate = DateTime.Now, Status = Status.Pending, Text = "Tralala 1" } }
                    .AsQueryable();

            Mock.Arrange(() => repo.All()).Returns(() => bugs);

            var controller = new BugsController(repo);
            var result = controller.GetAfterDate("20-02-2014");
            CollectionAssert.AreEqual(
                                      bugs.ToList(),
                                      (result as OkNegotiatedContentResult<IQueryable<Bug>>).Content.ToList());
        }
Example #25
0
        public void SubscriberServicesModel_When_MaxBandwidth_variable_is_null_MaxBandwidthList_matches_count_of_values_from_configuration_file_and_the_values_match_too()
        {
            // Arrange
            var output = new StringBuilder();
            Assert.IsNotNull(_expectedBandwidthValues, "The appSettings key MaxBandwidthValues is missing from the unit test App.Config file");

            // First item is empty string for the UI
            var expectedMaxBandwidthList = new List<string>
                {
                    string.Empty
                };

            // Other items are coming from the MaxBandwidthValues appSettings
            expectedMaxBandwidthList.AddRange(_expectedBandwidthValues.Split(','));

            // Act
            var actualSubscriberServicesModel = new SubscriberServicesModel();
            actualSubscriberServicesModel.MaxBandwidth = null;

            // Assert
            if (expectedMaxBandwidthList.Count != actualSubscriberServicesModel.MaxBandwidthList.Count())
            {
                output.AppendLine();
                output.AppendFormat("The expected and actual lists have different number of items, {0} compared to {1} respectively", expectedMaxBandwidthList.Count, actualSubscriberServicesModel.MaxBandwidthList.Count());
                output.AppendLine();
                output.AppendFormat("The expected list has the following values {0}", string.Join(", ", expectedMaxBandwidthList.ToList()));
                output.AppendLine();
                output.AppendFormat("The actual list has the following values {0}", string.Join(", ", actualSubscriberServicesModel.MaxBandwidthList.ToList()));
            }

            foreach (var expectedIndividualString in expectedMaxBandwidthList)
            {
                if (!actualSubscriberServicesModel.MaxBandwidthList.Contains(expectedIndividualString))
                {
                    output.AppendLine();
                    output.AppendFormat("The actual results is missing the value {0}", expectedIndividualString);
                }
            }

            if (output.Length != 0)
            {
                Assert.Fail(output.ToString());
            }
        }
        public void ValidationConstraints_Validate()
        {
            const string errorMessage = "The object should not have been saved given its constraints";
            //var transac = SessionManagement.Db.StartTransaction();
            IList<ValidationConstraint> testConstraints = new List<ValidationConstraint>();
            try
            {
                var accor = SessionManagement.Db.GetAllAssets().SingleOrDefault(a => a.Name == "ACCOR");
                var total = SessionManagement.Db.GetAllAssets().SingleOrDefault(a => a.Name == "TOTAL");
                Assert.IsNotNull(total);
                var nameConstraint = new ValidationConstraint
                {
                    ConstraintType = trkValidationConstraintType.Equal,
                    ObjectType = _typeOfAssetEditable,
                    Property = "Name",
                    PropertyType = _typeOfString,
                    MainArgument = "ACCOR"
                };
                testConstraints.Add(nameConstraint);
                var savedNameConstraint = ValidationConstraintService.Instance.SaveOrUpdateList(testConstraints).SingleOrDefault();
                //Should succeed
                ValidationConstraintService.Instance.ValidateObject(accor);
                //Should fail
                try
                {
                    ValidationConstraintService.Instance.ValidateObject(total);
                    Assert.Fail(errorMessage);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

                //Second Level
                var idConstraint1 = new ValidationConstraint
                {
                    ConstraintType = trkValidationConstraintType.Greater,
                    ObjectType = _typeOfAssetEditable,
                    Property = "Id",
                    PropertyType = _typeOfString,
                    MainArgument = "0",
                    ParentConstraint = savedNameConstraint
                };
                testConstraints.Add(idConstraint1);
                ValidationConstraintService.Instance.SaveOrUpdateList(testConstraints);
                //Should succeed
                ValidationConstraintService.Instance.ValidateObject(accor);

                //Should Fail (Id = 122)
                var idConstraint2 = new ValidationConstraint
                {
                    ConstraintType = trkValidationConstraintType.Lower,
                    ObjectType = _typeOfAssetEditable,
                    Property = "Id",
                    PropertyType = _typeOfString,
                    MainArgument = "30",
                    ParentConstraint = savedNameConstraint
                };
                testConstraints.Add(idConstraint2);
                testConstraints = ValidationConstraintService.Instance.SaveOrUpdateList(testConstraints);
                try
                {
                    ValidationConstraintService.Instance.ValidateObject(accor);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
                //Remove it now that it has been tested
                testConstraints.ToList().ForEach(c =>
                {
                    if (c == idConstraint2)
                        c.RequiresDeletion = true;
                });

                var handlingQuotesConstraint = new ValidationConstraint
                {
                    ConstraintType = trkValidationConstraintType.True,
                    ObjectType = _typeOfAssetEditable,
                    Property = "HandlingQuotes",
                    PropertyType = _typeOfBool,
                    ParentConstraint = savedNameConstraint
                };
                testConstraints.Add(handlingQuotesConstraint);
                var thirdLevel = ValidationConstraintService.Instance.SaveOrUpdateList(testConstraints).SingleOrDefault(c => c.ToString() == handlingQuotesConstraint.ToString());
                //Should succeed
                ValidationConstraintService.Instance.ValidateObject(accor);

                var betweenConstraint = new ValidationConstraint
                {
                    ConstraintType = trkValidationConstraintType.Between,
                    ObjectType = _typeOfAssetEditable,
                    Property = "Id",
                    PropertyType = _typeOfInt,
                    MainArgument = "0",
                    SecondaryArgument = "100000000",
                    ParentConstraint = thirdLevel
                };
                testConstraints.Add(betweenConstraint);
                ValidationConstraintService.Instance.SaveOrUpdateList(testConstraints);
                //Should succeed
                ValidationConstraintService.Instance.ValidateObject(accor);

                var notNullConstraint = new ValidationConstraint
                {
                    ConstraintType = trkValidationConstraintType.NotNull,
                    ObjectType = _typeOfAssetEditable,
                    Property = "Status",
                    PropertyType = _typeOfAssetStatus,
                    ParentConstraint = thirdLevel
                };
                testConstraints.Add(notNullConstraint);
                ValidationConstraintService.Instance.SaveOrUpdateList(testConstraints);

                //Should succeed
                ValidationConstraintService.Instance.ValidateObject(accor);

                var differentConstraint = new ValidationConstraint
                {
                    ConstraintType = trkValidationConstraintType.Different,
                    ObjectType = _typeOfAssetEditable,
                    Property = "Id",
                    PropertyType = _typeOfInt,
                    MainArgument = "1",
                    ParentConstraint = thirdLevel
                };

                testConstraints.Add(differentConstraint);
                ValidationConstraintService.Instance.SaveOrUpdateList(testConstraints);
                //Should succeed
                ValidationConstraintService.Instance.ValidateObject(accor);

                var nullConstraint = new ValidationConstraint
                {
                    ConstraintType = trkValidationConstraintType.Null,
                    ObjectType = _typeOfAssetEditable,
                    Property = "AssetType",
                    PropertyType = _typeOfAssetType,
                    ParentConstraint = thirdLevel
                };
                testConstraints.Add(nullConstraint);
                ValidationConstraintService.Instance.SaveOrUpdateList(testConstraints);
                try
                {
                    //Should fail.
                    ValidationConstraintService.Instance.ValidateObject(accor);
                    Assert.Fail(errorMessage);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
                //If you want to add constraint remove the top one from the list.
            }
            finally
            {
                //SessionManagement.Db.RollbackTrans(transac);
            }
        }
Example #27
0
        public void SortTest()
        {
            var list = new List<int>();
            for (int i = 0; i < 100; i++)
            {
                list.Add(RandomUtils.GetRandom(0, 1000));
            }

            var watch = Stopwatch.StartNew();

            watch.Restart();
            for (int i = 0; i < 100; i++)
            {
                var copyList = list.ToList();
                copyList.QuickSort((a, b) => a.CompareTo(b));
            }
            Trace.WriteLine("QuickSort:" + watch.ElapsedMilliseconds);

            watch.Restart();
            for (int i = 0; i < 100; i++)
            {
                var copyList = list.ToList();
                var temp = copyList.OrderBy(t => t);
            }
            Trace.WriteLine("OrderBy:" + watch.ElapsedMilliseconds);

            watch.Restart();
            for (int i = 0; i < 100; i++)
            {
                var copyList = list.ToList();
                copyList.Sort((a, b) => a.CompareTo(b));
            }
            Trace.WriteLine("sort:" + watch.ElapsedMilliseconds);

        }
Example #28
0
 public void TestToGuidList_StringList()
 {
     var list = new List<string>
                    {
                        "83B0233C-A24F-49FD-8083-1337209EBC9A",
                        "EAB523C6-2FE7-47BE-89D5-C6D440C3033A"
                    };
     Assert.AreEqual(2, list.ToList<Guid>().Count);
     Assert.AreEqual(new Guid("83B0233C-A24F-49FD-8083-1337209EBC9A"), list.ToList<Guid>()[0]);
     Assert.AreEqual(new Guid("EAB523C6-2FE7-47BE-89D5-C6D440C3033A"), list.ToList<Guid>()[1]);
 }
        public void WhereIfTest_IQueryable()
        {
            IQueryable<int> source = new List<int> { 1, 2, 3, 4, 5, 6, 7 }.AsQueryable();
            CollectionAssert.AreEqual(source.WhereIf(m => m > 5, false).ToList(), source.ToList());

            List<int> actual = new List<int> { 6, 7 };
            CollectionAssert.AreEqual(source.WhereIf(m => m > 5, true).ToList(), actual);
        }
        public void GetExecutionPlan_WhereTaskHasInitializationAndCleanup_ReturnsInitializationFirstAndCleanupLast()
        {
            // Arrange
            var taskblock = typeof(InitializationAndCleanup);
            var host = new Host
            {
                Hostname = SomeHostname
            };
            var config = new DeploymentConfig
            {
                Hosts = new[]
                {
                    host
                }
            };

            var expected = new List<ExecutionPlan>
            {
                new ExecutionPlan(host, taskblock.GetObjMethods("Init", "Task1", "Cleanup"))
            };

            // Act
            var manager = new DeploymentManager<InitializationAndCleanup>(config);
            var actual = manager.GetExecutionPlans();

            // Assert
            CollectionAssert.AreEqual(expected.ToList(), actual.ToList());
        }