Example #1
0
        public void GNU()
        {
            List<ITarHeader> list = new List<ITarHeader>();
            TarReader reader = new TarReader(gnuStream);

            while (reader.MoveNext(true))
            {
                list.Add(reader.FileInfo);
                Trace.WriteLine($"{reader.FileInfo.EntryType}: {reader.FileInfo.FileName}");
            }

            Assert.IsNotNull(list.FirstOrDefault(x => x.FileName == "hello/"));
            Assert.IsNotNull(list.FirstOrDefault(x => x.FileName == "hello/world/"));
            Assert.IsNotNull(list.FirstOrDefault(x => x.FileName == "hello/world/hello"));
        }
        public void Controller_ExpenseReports_GetById_ReturnsNotFound()
        {
            // Arrange
            int id = 3;
            List<ExpenseReportModel> expenseReports = new List<ExpenseReportModel>()
            {
                new ExpenseReportModel(){ Id = 1 },
                new ExpenseReportModel(){ Id = 2 }
            };
            var mockQueryService = new Mock<IExpenseReportQueryService>();
            mockQueryService
                .Setup(x => x.GetExpenseReportById(id))
                .Returns(expenseReports.FirstOrDefault(x => x.Id == id));
            var mockEntryService = new Mock<IExpenseReportEntryService>();

            // Act
            ExpenseReportsController controller = new ExpenseReportsController(mockQueryService.Object, mockEntryService.Object);
            try
            {
                var result = controller.GetById(id);
            }
            catch (HttpResponseException ex)
            {
                // Assert
                Assert.AreEqual(ex.Response.StatusCode, HttpStatusCode.NotFound);
                throw;
            }
        }
        public void GetById_ReturnsMatchingTransaction()
        {
            // arrange
            var allTransactions = new List<Transaction>(){
                new Transaction
                {
                    TransactionId = 1
                },
                new Transaction
                {
                    TransactionId = 2
                },
            };

            _transactionRepositoryMock.Setup(x => x.GetById(It.IsAny<long>()))
                .Returns<long>((id) => allTransactions.FirstOrDefault(t=>t.TransactionId == id));

            var subject = new Api.Controllers.TransactionsController(_transactionService);

            // act
            var result = subject.Get(2);

            // assert
            Assert.IsNotNull(result);
            Assert.AreEqual(2,result.TransactionId);
            _transactionRepositoryMock.Verify(x => x.GetById(2), Times.Once);
            _transactionRepositoryMock.Verify(x => x.All(), Times.Never);
        }
        public void Compare(List<XElement> expectXElements, List<XElement> actualXElements)
        {
            Assert.AreEqual(expectXElements.Count(), actualXElements.Count(), "Unexpected number of Csdl files!");

            // extract EntityContainers into one place
            XElement expectedContainers = CsdlElementExtractor.ExtractElementByName(expectXElements, "EntityContainer");
            XElement actualContainers = CsdlElementExtractor.ExtractElementByName(actualXElements, "EntityContainer");

            // compare just the EntityContainers
            Console.WriteLine("Expected: " + expectedContainers.ToString());
            Console.WriteLine("Actual: " + actualContainers.ToString());
            csdlXElementComparer.Compare(expectedContainers, actualContainers);

            foreach (var expectXElement in expectXElements)
            {
                string schemaNamespace = expectXElement.Attribute("Namespace") == null ? string.Empty : expectXElement.Attribute("Namespace").Value;
                XElement actualXElement = actualXElements.FirstOrDefault(e => schemaNamespace == (e.Attribute("Namespace") == null ? string.Empty : e.Attribute("Namespace").Value));

                Assert.IsNotNull(actualXElement, "Cannot find schema for '{0}' in result Csdls!", schemaNamespace);

                Console.WriteLine("Expected: " + expectXElement.ToString());
                Console.WriteLine("Actual: " + actualXElement.ToString());

                csdlXElementComparer.Compare(expectXElement, actualXElement);
                // TODO: Extend the TaupoModelComparer for the Constructible APIs instead of using CsdlXElementComparer. 
            }
        }
        public void AddOrderEntryTest()
        {
            List<Order> orders = new List<Order>();
            List<BookType> bookTypeList = new List<BookType>();
            NMock.Actions.InvokeAction saveOrUpdateAction = new NMock.Actions.InvokeAction(() => orders.Add(order));
            orderManagementDaoMock.Expects.Any.MethodWith(x => x.SaveOrUpdate(order)).Will(saveOrUpdateAction);

            bool isInList = false;
            order.OrderEntries = new List<OrderEntry>();
            oms.CreateNewOrder(order);
            orderInformationDaoMock.Expects.Any.MethodWith(x => x.GetOrderById(order.Id)).WillReturn(orders.First(x => x.Id == order.Id));

            getOrder = ois.GetOrderById(order.Id);

            NMock.Actions.InvokeAction saveBookType = new NMock.Actions.InvokeAction(new Action(() => bookTypeList.Add(testBook)));
            storehouseManagementDaoMock.Expects.Any.MethodWith(x => x.SaveBookType(testBook)).Will(saveBookType);

            sms.SaveBookType(testBook);
            booksInformationServiceMock.Expects.Any.MethodWith(x => x.GetBookTypeById(testBook.Id)).WillReturn(bookTypeList.FirstOrDefault(x => x.Id == testBook.Id));

            oms.AddOrderEntry(order, testBook.Id, TEST_AMOUNT);

            foreach (var item in order.OrderEntries)
            {
                if (item.Amount.Equals(TEST_AMOUNT) &&
                    item.BookType.Equals(testBook) &&
                    item.Price.Equals(testBook.Price)) isInList = true;
            };

            Assert.IsTrue(isInList);
        }
        public async Task TestFindShortestRouteBetweenAsyncProgress()
        {
            var cities = new Cities();
            cities.ReadCities(CitiesTestFile);

            var routes = new Routes(cities);
            routes.ReadRoutes(LinksTestFile);

            // do synchronous execution
            var linksExpected = routes.FindShortestRouteBetween("Basel", "Zürich", TransportMode.Rail);

            // do asynchronous execution
            var messages = new List<string>();
            var progress = new Progress<string>(msg => messages.Add(msg));
            var linksActual = await routes.FindShortestRouteBetweenAsync("Basel", "Zürich", TransportMode.Rail, progress);

            // let pending tasks execute
            await Task.Yield();

            // ensure that at least 5 progress calls are made
            Assert.IsTrue(messages.Distinct().Count()>=5, "Less than 5 distinct progress messages");

            // ensure that all progress messages end with " done"
            Assert.IsTrue(messages.All(m => m.EndsWith(" done")),
                string.Format("Progress message \"{0}\" does not end with \" done\"",
                    messages.FirstOrDefault(m => !m.EndsWith(" done"))));
        }
        public void ExpectUpdateAttributes_ShouldHave_Services()
        {
            var updateAttrTypes = ReflectionUtils.GetTypesFromAssembly<ExpectUpdate>(typeof(ExpectUpdate).Assembly);

            var updateAttrServices = new List<ExpectUpdateValueServiceBase>();
            updateAttrServices.AddRange(ReflectionUtils.GetTypesFromAssembly<ExpectUpdateValueServiceBase>(typeof(ExpectUpdateValueServiceBase).Assembly)
                                                         .Select(t => Activator.CreateInstance(t) as ExpectUpdateValueServiceBase));

            TraceUtils.WithScope(trace =>
            {
                foreach (var attr in updateAttrTypes)
                {
                    var targetServices = updateAttrServices.FirstOrDefault(s => s.TargetType == attr);

                    if (targetServices != null)
                    {
                        trace.WriteLine(string.Format("ExpectUpdate: [{0}] has service: [{1}]", attr,
                            targetServices.GetType()));
                    }
                    else
                    {
                        trace.WriteLine(string.Format("ExpectUpdate: [{0}] misses  service impl", attr));
                        Assert.Fail();
                    }
                }
            });
        }
        public void CreateContest_WithValidData_ShouldSuccessfullyAddTheContest()
        {
            var contests = new List<Contest>();
            var organizator = this.mocks
                .UserRepositoryMock
                .Object
                .All()
                .FirstOrDefault();
            if (organizator == null)
            {
                Assert.Fail("Cannot perform test - no users available");
            }

            this.mocks.ContestRepositoryMock.Setup(c => c.Add(It.IsAny<Contest>()))
                .Callback((Contest contest) =>
                {
                    contest.Owner = organizator;
                    contests.Add(contest);
                });

            var mockContext = new Mock<IPhotoContestData>();
            mockContext.Setup(c => c.Contests)
                .Returns(this.mocks.ContestRepositoryMock.Object);
            mockContext.Setup(c => c.Users)
                .Returns(this.mocks.UserRepositoryMock.Object);

            var contestController = new ContestController(mockContext.Object,null);

            string contestTitle = "Title";
            contests.AddRange(mocks.ContestRepositoryMock.Object.All().ToList());

            var newContest = new ContestInputModel
            {
                Title = contestTitle,
                Description = "Test contest",
                MaxNumberOfParticipants = 10,
                DeadlineDate = DateTime.Now.AddDays(1),
                Status = ContestStatusType.Active,
                ParticipationStrategyType = ParticipationStrategyType.Open,
                VotingStrategyType = VotingStrategyType.Open,
                WinnersCount = 1
            };

            newContest.Prizes.Add(10);

            Mapper.CreateMap<ContestInputModel, Contest>();
            ActionResult response = contestController.Create(newContest);

            var contestFromRepo = contests.FirstOrDefault(c => c.Title == newContest.Title);
            if (contestFromRepo == null)
            {
                Assert.Fail();
            }

            Assert.AreEqual(1, contests.Count);
            Assert.AreEqual(newContest.Description, contestFromRepo.Description);
        }
        public void AddContestShouldInsertOneRecordToTheRepository()
        {
            var contests = new List<Contest>();

            var fakeUser = this.mocks.FakeUserRepository.Object.GetAll().FirstOrDefault();
            if (fakeUser == null)
            {
                Assert.Fail();
            }

            this.mocks.FakeContestRepository
                .Setup(r => r.Add(It.IsAny<Contest>()))
                .Callback(
                    (Contest contest) =>
                        {
                            contest.Organizer = fakeUser;
                            contests.Add(contest);
                        });

            var mockContext = new Mock<IPhotoBattlesData>();
            mockContext.Setup(c => c.Users)
                       .Returns(this.mocks.FakeUserRepository.Object);
            mockContext.Setup(c => c.Contests)
                       .Returns(this.mocks.FakeContestRepository.Object);

            var mockIdProvider = new Mock<IUserIdProvider>();
            mockIdProvider.Setup(ip => ip.GetUserId())
                          .Returns(fakeUser.Id);

            var contestController = new ContestsController(mockContext.Object, mockIdProvider.Object);

            var newContest = new ContestBindingModel()
            {
                Title = "Contest three",
                Description = "Contests three description",
                VotingStrategyEnum = VotingStrategyEnum.Open,
                ParticipationStrategyEnum = ParticipationStrategyEnum.Open,
                RewardStrategyEnum = RewardStrategyEnum.SingleWinner,
                DeadlineStrategyEnum = DeadlineStrategyEnum.ParticipantsLimit,
                ParticipantsLimit = 3
            };

            var response = contestController.AddContest(newContest);

            var expected = contests.FirstOrDefault(c => c.Title == newContest.Title);
            if (expected == null)
            {
                Assert.Fail();
            }

            mockContext.Verify(c => c.SaveChanges(), Times.Once);
            Assert.IsInstanceOfType(response, typeof(RedirectToRouteResult));
            Assert.AreEqual(1, contests.Count);
            Assert.AreEqual(newContest.Description, expected.Description);
        }
        public void Setup()
        {
            var products = new List<Product>();
            products.Add(new Product() { Description = "Product A Description", Price = 9.99M, ProductCode = "PA001", ProductId = 1, ProductName = "Product A", ReleaseDate = DateTime.Now });
            products.Add(new Product() { Description = "Product B Description", Price = 6.75M, ProductCode = "PB001", ProductId = 2, ProductName = "Product B", ReleaseDate = DateTime.Now });
            products.Add(new Product() { Description = "Product C Description", Price = 19.50M, ProductCode = "PC001", ProductId = 3, ProductName = "Product C", ReleaseDate = DateTime.Now });

            _mockedRepository = new Mock<IProductRepository>();
            _mockedRepository.Setup(m => m.GetAll()).Returns(products);
            _mockedRepository.Setup(m => m.GetById(It.IsAny<int>())).Returns((int x) => products.FirstOrDefault(p => p.ProductId == x));
        }
        private void SetupFakeAdTypes()
        {
            var fakeAdTypes = new List<AdType>()
            {
                new AdType(){Name = "Normal" ,Index = 100,PricePerDay = 10,Id = 0},
                new AdType(){Name = "Premium" ,Index = 200,PricePerDay = 20,Id = 1},
                new AdType(){Name = "Diamond" ,Index = 300,PricePerDay = 30,Id = 2}
            };       

            this.AdTypeRepositoryMock = new Mock<IRepository<AdType>>();
            this.AdTypeRepositoryMock.Setup(a => a.All())
                .Returns(fakeAdTypes.AsQueryable());

            this.AdTypeRepositoryMock.Setup(a => a.Find(It.IsAny<int>()))
                .Returns((int id) =>
                {
                    return fakeAdTypes.FirstOrDefault(a => a.Id == id);
                });
        }
Example #12
0
        public void GetDivisionTeamsTest2()
        {
            var divisions = new List<Division>();
            using (var context = new CSBCDbContext())
            {
                var repSeason = new SeasonRepository(context);
                var currentSeason = repSeason.GetCurrentSeason(1);
                var repDivision = new DivisionRepository(context);
                divisions = repDivision.GetDivisions(currentSeason.SeasonID).ToList<Division>();
            }
            var division = divisions.FirstOrDefault();
            var rep = new TeamVM();
            var teams = rep.GetDivisionTeams(division.DivisionID);

            Assert.IsTrue(teams.Any());

            var team = teams.FirstOrDefault();
            Assert.IsTrue(team.DivisionID > 0);
        }
        public void ComplexObjectDescriptorListTests()
        {
            var data = Mockup.Data.GetComplexTwoLevelMockupData();

            var factory = new FlatDTO.FlatDTOFactory();

            var propertyString = Mockup.Data.GetComplexTwoLevelListMockupDataPropertyStrings().ToList();

            propertyString.Add("ComplexProperty");
            propertyString.Add("ComplexPropertyList.ComplexProperty");

            var descriptors = new List<IComplexObjectDescriptor>();
            descriptors.Add(new Mockup.Data.ComplexPropertyDescriptor(typeof(Mockup.Data.ComplexPropertyLevel1)));
            descriptors.Add(new Mockup.Data.ComplexPropertyLevel2Descriptor(typeof(Mockup.Data.ComplexPropertyLevel2)));

            var mapper = factory.Create<Mockup.Data.DTOBase>(data[0].GetType(), propertyString.ToArray(), GetMappingEngine(descriptors));
            var dtoList = mapper.Map(data.ToArray());

            Assert.IsTrue(dtoList.Count() == 4);

            var value = dtoList[0];
            var rootType = value.GetType();
            Assert.IsTrue(((string)rootType.GetProperty(propertyString[0]).GetValue(value, null)).Equals(data[0].StringValue, StringComparison.InvariantCultureIgnoreCase), "The string property was not correct");
            Assert.IsTrue(((decimal)rootType.GetProperty(propertyString[1]).GetValue(value, null)) == data[0].DecimalValue, "The decimal property was not correct");
            Assert.IsTrue(((int)rootType.GetProperty(propertyString[2]).GetValue(value, null)) == data[0].IntegerValue, "The int property was not correct");
            Assert.IsTrue(((string)rootType.GetProperty(propertyString[7]).GetValue(value, null)).Equals(descriptors.FirstOrDefault().Describe(data[0].ComplexProperty), StringComparison.InvariantCultureIgnoreCase), "The string property was not correct");

            Assert.IsTrue(((string)rootType.GetProperty(propertyString[8].Replace(".", "_")).GetValue(value, null)).Equals(descriptors[1].Describe(data[0].ComplexPropertyList[0].ComplexProperty), StringComparison.InvariantCultureIgnoreCase), "The string property was not correct");

            //Get the complex property
            var propertyPath = propertyString[3].Replace(".", "_");

            var property = rootType.GetProperty(propertyPath);

            Assert.IsTrue(((string)property.GetValue(value, null)).Equals(data[0].ComplexProperty.StringValue, StringComparison.InvariantCultureIgnoreCase), "The value on Complex type on level 1 do not match");

            propertyPath = propertyString[4].Replace(".", "_");

            property = rootType.GetProperty(propertyPath);

            Assert.IsTrue(((string)property.GetValue(value, null)).Equals(data[0].ComplexProperty.ComplexProperty.StringValue, StringComparison.InvariantCultureIgnoreCase), "The value on Complex type on level 2 do not match");
        }
        private static Facility GetValidated(string requirementFile)
        {
            const string ifcTestFile = @"Lakeside_Restaurant_fabric_only.ifczip";
            Facility sub = null;

            //create validation file from IFC
            using (var m = new XbimModel())
            {
                var xbimTestFile = Path.ChangeExtension(ifcTestFile, "xbim");
                m.CreateFrom(ifcTestFile, xbimTestFile, null, true, true);
                var facilities = new List<Facility>();
                var ifcToCoBieLiteUkExchanger = new IfcToCOBieLiteUkExchanger(m, facilities);
                facilities = ifcToCoBieLiteUkExchanger.Convert();
                sub = facilities.FirstOrDefault();
            }
            Assert.IsTrue(sub!=null);
            var vd = new FacilityValidator();
            var req = Facility.ReadJson(requirementFile);
            var validated = vd.Validate(req, sub);
            return validated;
        }
        public void Controller_ExpenseReports_GetById_ReturnsSingle()
        {
            // Arrange
            int id = 1;
            List<ExpenseReportModel> expenseReports = new List<ExpenseReportModel>()
            {
                new ExpenseReportModel(){ Id = 1 },
                new ExpenseReportModel(){ Id = 2 }
            };
            var mockQueryService = new Mock<IExpenseReportQueryService>();
            mockQueryService
                .Setup(x => x.GetExpenseReportById(id))
                .Returns(expenseReports.FirstOrDefault(x => x.Id == id));
            var mockEntryService = new Mock<IExpenseReportEntryService>();

            // Act
            ExpenseReportsController controller = new ExpenseReportsController(mockQueryService.Object, mockEntryService.Object);
            var result = controller.GetById(id);

            // Assert
            Assert.AreEqual(id, result.Id);
        }
        public void Initialize()
        {
            var categoriesRepository = new Mock<ICategoriesRepository>();
            var categories = new List<Category>
            {
                new Category {Id = 1, Name = "Category1"},
                new Category {Id = 2, Name = "Category2", ParentId = 1},
                new Category {Id = 3, Name = "Category3", ParentId = 2},
                new Category {Id = 4, Name = "Category4", ParentId = 1},
                new Category {Id = 5, Name = "Category5"}
            };

            categoriesRepository.Setup(r => r.Get()).ReturnsAsync(categories);
            categoriesRepository.Setup(r => r.Get(It.IsAny<int>())).Returns((int id) => Task.FromResult(categories.FirstOrDefault(c => c.Id == id)));
            categoriesRepository.Setup(r => r.Create(It.IsAny<Category>())).ReturnsAsync(true);
            categoriesRepository.Setup(r => r.Update(It.IsAny<Category>())).ReturnsAsync(true);
            categoriesRepository.Setup(r => r.GetChildren(It.IsAny<int>())).Returns(
                (int id) => Task.FromResult(categories.Where(c => c.ParentId == id).ToList() as IEnumerable<Category>));
            categoriesRepository.Setup(r => r.GetRoot()).ReturnsAsync(categories.Where(c => c.ParentId == null).ToList());
            categoriesRepository.Setup(r => r.Delete(It.IsAny<int>())).Returns((int id) => Task.FromResult(categories.RemoveAll(c => c.Id == id) > 0));

            _categoriesService = new CategoriesService(categoriesRepository.Object);
        }
		public void AddWhenRequestIsValidShouldAddRequest()
		{
			var repository = Mock.Create<ITwsData>();

			var requestEntity = Entities.GetValidTeamWorkRequest();
			var teamWorkEntity = Entities.GetValidTeamWork();
			IList<TeamWork> teamworkEntities = new List<TeamWork>();
			teamworkEntities.Add(teamWorkEntity);

			var requestEntities = new List<TeamWorkRequest>();
			requestEntities.Add(requestEntity);
			Mock.Arrange(() => repository.TeamWorkRequests.All())
				.Returns(() => requestEntities.AsQueryable());
			Mock.Arrange(() => repository.TeamWorks.Find(0))
				.Returns(() => teamworkEntities.FirstOrDefault());

			var userProvider = Mock.Create<IUserIdProvider>();

			var controller = new RequestController(repository, userProvider);
			var requestModels = controller.ByTeamwork(0);
			var negotiatedResult = requestModels as OkNegotiatedContentResult<IQueryable<RequestModel>>;
			Assert.IsNotNull(negotiatedResult);
			Assert.AreEqual<string>(requestEntity.Message, negotiatedResult.Content.FirstOrDefault().Message);
		}
        public void CheckWhetherLanguagesAreGettingUpdatedInEmployeeSave()
        {
            // ARRANGE
            var uow = Mock.Create<IQTecUnitOfWork>(Behavior.Loose);

            var employeeToBeUpdated = new Employee
            {
                DateOfBirth = new DateTime(2012, 1, 1),
                DesignationId = 2,
                Email = "*****@*****.**",
                FirstName = "Abc",
                LastName = "XYZ"
            };

            var employeePersonalDtoinParamater = new EmployeePersonalInfo
            {
                DateOfBirth = new DateTime(2012, 1, 1),
                DesignationId = 2,
                Email = "*****@*****.**",
                FirstName = "AbcDef", // firstname is changed
                LastName = "XYZ"
            };
            Mock.Arrange(() => uow.EmployeeRepository.GetById(Arg.AnyInt)).Returns(employeeToBeUpdated);

            var currentEmployeeLanguagesKnown = new List<EmployeeLanguages>
                                                    {
                                                        new EmployeeLanguages
                                                            {
                                                                EmployeeId = 1,
                                                                Fluency = 1,
                                                                LanguageId = 1
                                                            },
                                                        new EmployeeLanguages
                                                            {
                                                                EmployeeId = 1,
                                                                Fluency = 1,
                                                                LanguageId = 2
                                                            }
                                                    };

            Mock.Arrange(() => uow.EmployeeLanguagesRepository.GetAll()).Returns(currentEmployeeLanguagesKnown.AsQueryable);

            //// updating fluency from 1 to 2
            var employeeLanguagesInfoParamater = new List<EmployeeLanguageInfo>
                                                     {
                                                         new EmployeeLanguageInfo
                                                             {
                                                                 EmployeeId = 1,
                                                                 Fluency = (Fluency)2,
                                                                 LanguageId = 1
                                                             },
                                                         new EmployeeLanguageInfo
                                                             {
                                                                 EmployeeId = 1,
                                                                 Fluency = (Fluency)2,
                                                                 LanguageId = 2
                                                             }
                                                     };

            Mock.Arrange(() => uow.EmployeeLanguagesRepository.Update(Arg.IsAny<EmployeeLanguages>())).DoInstead(
                () =>
                    {
                        foreach (var employeeLanguageInfo in employeeLanguagesInfoParamater)
                        {
                            var languageToBeUpdated =
                                currentEmployeeLanguagesKnown.FirstOrDefault(
                                    lang => lang.EmployeeId == 1 && lang.LanguageId == employeeLanguageInfo.LanguageId);

                            if (languageToBeUpdated != null)
                            {
                                languageToBeUpdated.Fluency = (int)employeeLanguageInfo.Fluency;

                            }
                        }
                    });

            // ACT
            var classunderTest = new EmployeeManager(uow);
            classunderTest.SaveEmployee(1, employeePersonalDtoinParamater, employeeLanguagesInfoParamater);

            // ASSERT
            var firstOrDefault = currentEmployeeLanguagesKnown.FirstOrDefault();
            if (firstOrDefault != null)
            {
                Assert.AreEqual(2, firstOrDefault.Fluency);
            }

            Mock.Assert(uow);
        }
        private ProductDescription GetProductDescription(List<CompanyGroup.Domain.MaintainModule.ProductDescription> descriptions, string key, string langId)
        {
            ProductDescription description = descriptions.FirstOrDefault(d => d.ProductId.ToLower() == key.ToLower() && d.LangId == langId);

            return description != null ? description : new ProductDescription("", "", "");
        }
        private Manufacturer GetManufacturer(List<CompanyGroup.Domain.MaintainModule.Manufacturer> manufacturers, string key)
        {
            Manufacturer manufacturer = manufacturers.FirstOrDefault(manu => manu.ManufacturerId.ToLower() == key.ToLower());

            return manufacturer != null ? manufacturer : new Manufacturer("", "", "", "");
        }
        private ThirdLevelCategory GetThirdLevelCategory(List<CompanyGroup.Domain.MaintainModule.ThirdLevelCategory> categories, string key)
        {
            ThirdLevelCategory thirdLevelCategory = categories.FirstOrDefault(category => category.Category3Id.ToLower() == key.ToLower());

            return thirdLevelCategory != null ? thirdLevelCategory : new ThirdLevelCategory("", "", "", "");
        }
        private SecondLevelCategory GetSecondLevelCategory(List<CompanyGroup.Domain.MaintainModule.SecondLevelCategory> categories, string key)
        {
            SecondLevelCategory secondLevelCategory = categories.FirstOrDefault(category => category.Category2Id.ToLower() == key.ToLower());

            return secondLevelCategory != null ? secondLevelCategory : new SecondLevelCategory("", "", "", "");
        }
        private FirstLevelCategory GetFirstLevelCategory(List<CompanyGroup.Domain.MaintainModule.FirstLevelCategory> categories, string key)
        {
            FirstLevelCategory firstLevelCategory = categories.FirstOrDefault(category => category.Category1Id.ToLower() == key.ToLower());

            return firstLevelCategory != null ? firstLevelCategory : new FirstLevelCategory("", "", "", "");
        }
        private string GetInventNameEnglish(List<CompanyGroup.Domain.MaintainModule.InventName> inventNames, string key)
        {
            CompanyGroup.Domain.MaintainModule.InventName inventName = inventNames.FirstOrDefault(x => x.ItemId == key);

            return (inventName != null) ? inventName.ItemName : String.Empty;
        }
        private static IProcessDefinition CreateInheritedProcess(ISectionDefinition section, string processNameWithSection)
        {
            var processes = new List<IProcessDefinition>(3) { new ProcessDefinition(BaseBaseProcessName) };
            processes.Add(new ProcessDefinition(BaseProcessName) { BaseProcess = processes[0] });
            processes.Add(new ProcessDefinition(ProcessName) { BaseProcess = processes[1] });

            if (section != null && !string.IsNullOrEmpty(processNameWithSection))
            {
                var processWithSection = processes.FirstOrDefault(p => p.Name.Equals(processNameWithSection));
                if (processWithSection == null)
                {
                    return null;
                }

                processWithSection.Sections.Add(section);
            }

            return processes[2];
        }
Example #26
0
        public void TestVerifySearchOrderedBySequentialNumber()
        {
            CertificateController controller = new CertificateController();
            CertificateListModel model = new CertificateListModel();
            ActionResult result = controller.SearchCertificateGrid(model, 1);
            Assert.IsNotNull(result);
            Assert.IsNotNull(model);
            IList<int> sequentials = new List<int>();
            int onlyNumber = 0;
            int itemFound = 0;

            foreach (var itemCollection in model.Certificates.Collection)
            {
               //Get the number from the string
               onlyNumber = Convert.ToInt32(String.Concat(itemCollection.Certificate.Sequential.Where(Char.IsDigit)));
                //Verify if there is a previous number less than the current one then ERROR
               itemFound = sequentials.FirstOrDefault(item => item < onlyNumber);
               Assert.AreEqual(itemFound, 0);
               sequentials.Add(onlyNumber);
            }
        }
        static void Verify_DebugSelectionChanged(ActivitySelectionType selectionType, Type selectedActivityType, bool selectsModelItem = true)
        {
            //----------------------- Setup -----------------------//
            var ID = Guid.NewGuid();
            var states = new List<IDebugState> { new DebugState { DisplayName = "SelectionChangedTest1", ID = ID, WorkSurfaceMappingId = ID } };
            ID = Guid.NewGuid();
            if (selectionType == ActivitySelectionType.Add || selectionType == ActivitySelectionType.Remove)
            {

                states.Add(new DebugState { DisplayName = "SelectionChangedTest2", ID = ID, WorkSurfaceMappingId = ID });
            }

            #region Setup workflow

            FlowNode prevNode = null;

            var nodes = new List<FlowNode>();
            foreach (var node in states.Select(state => CreateFlowNode(state.ID, state.DisplayName, selectsModelItem, selectedActivityType)))
            {
                if (prevNode != null)
                {
                    var flowStep = prevNode as FlowStep;
                    if (flowStep != null)
                    {
                        flowStep.Next = node;
                    }
                }
                nodes.Add(node);
                prevNode = node;
            }

            var workflow = new ActivityBuilder
            {
                Implementation = new Flowchart
                {
                    StartNode = nodes[0]
                }
            };

            #endregion

            #region Setup viewModel

            var resourceRep = new Mock<IResourceRepository>();
            resourceRep.Setup(r => r.All()).Returns(new List<IResourceModel>());
            resourceRep.Setup(r => r.FetchResourceDefinition(It.IsAny<IEnvironmentModel>(), It.IsAny<Guid>(), It.IsAny<Guid>(), It.IsAny<bool>())).Returns(new ExecuteMessage());

            var resourceModel = new Mock<IContextualResourceModel>();
            resourceModel.Setup(m => m.Environment.ResourceRepository).Returns(resourceRep.Object);
            resourceModel.Setup(m => m.ResourceName).Returns("Some resource name 5");
            var workflowHelper = new Mock<IWorkflowHelper>();
            workflowHelper.Setup(h => h.CreateWorkflow(It.IsAny<string>())).Returns(workflow);

            var viewModel = new WorkflowDesignerViewModelMock(resourceModel.Object, workflowHelper.Object);
            viewModel.InitializeDesigner(new Dictionary<Type, Type>());

            #endregion

            //----------------------- Execute -----------------------//
            var i = 0;
            foreach (var debugState in states)
            {
                if (selectionType == ActivitySelectionType.None || selectionType == ActivitySelectionType.Remove)
                {
                    // Ensure we have something to clear/remove
                    EventPublishers.Studio.Publish(new DebugSelectionChangedEventArgs { DebugState = debugState, SelectionType = ActivitySelectionType.Add });

                    // Only issue change event after all have been added
                    if (++i == states.Count)
                    {
                        var selectionBefore = viewModel.Designer.Context.Items.GetValue<Selection>();
                        Assert.AreEqual(states.Count, selectionBefore.SelectionCount);

                        EventPublishers.Studio.Publish(new DebugSelectionChangedEventArgs { DebugState = debugState, SelectionType = selectionType });
                    }
                }
                else
                {
                    EventPublishers.Studio.Publish(new DebugSelectionChangedEventArgs { DebugState = debugState, SelectionType = selectionType });
                }
            }

            //----------------------- Assert -----------------------//

            var selection = viewModel.Designer.Context.Items.GetValue<Selection>();

            switch (selectionType)
            {
                case ActivitySelectionType.None:
                    Assert.AreEqual(0, selection.SelectionCount);
                    Assert.AreEqual(1, viewModel.BringIntoViewHitCount); // 1 because we had to add something first!
                    Assert.AreEqual(0, viewModel.SelectedDebugModelItems.Count);
                    break;

                case ActivitySelectionType.Single:
                    Assert.AreEqual(1, selection.SelectionCount);
                    Assert.AreEqual(1, viewModel.BringIntoViewHitCount);
                    Assert.AreEqual(1, viewModel.SelectedDebugModelItems.Count);
                    break;

                case ActivitySelectionType.Add:
                    Assert.AreEqual(2, selection.SelectionCount);
                    Assert.AreEqual(2, viewModel.BringIntoViewHitCount);
                    Assert.AreEqual(2, viewModel.SelectedDebugModelItems.Count);
                    break;

                case ActivitySelectionType.Remove:
                    Assert.AreEqual(2, selection.SelectionCount);
                    Assert.AreEqual(2, viewModel.BringIntoViewHitCount); // 2 because we had to add something first!
                    Assert.AreEqual(1, viewModel.SelectedDebugModelItems.Count);
                    break;
            }

            foreach (var modelItem in selection.SelectedObjects)
            {
                Assert.AreEqual(selectedActivityType, modelItem.ItemType);
                if (selectsModelItem)
                {
                    var actualID = selectedActivityType == typeof(FlowDecision)
                        ? Guid.Parse(((TestDecisionActivity)modelItem.GetProperty("Condition")).UniqueID)
                        : ModelItemUtils.GetUniqueID(modelItem);

                    var actualState = states.FirstOrDefault(s => s.ID == actualID);
                    Assert.IsNotNull(actualState);
                }
            }

            viewModel.Dispose();
        }
Example #28
0
        private Mock<IStoreContext> SetupMock()
        {
            var data = new List<Product> {
                new Product { Id= 1, Name="P1" }
            }.AsQueryable();

            var mock = new Mock<IDbSet<Product>>();
            mock.Setup(m => m.Provider).Returns(data.Provider);
            mock.Setup(m => m.Expression).Returns(data.Expression);
            mock.Setup(m => m.ElementType).Returns(data.ElementType);
            mock.Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
            mock.Setup(m => m.Find(It.IsAny<Int32>())).Returns(data.FirstOrDefault(p => p.Id == 1));

            var dbMock = new Mock<IStoreContext>();
            dbMock.Setup(m => m.Products).Returns(mock.Object);
            return dbMock;
        }
        IEnumerable<IDataListItemModel> CreateDataListItems(IDataListViewModel viewModel, IEnumerable<IDataListVerifyPart> parts, bool isAdd)
        {
            var results = new List<IDataListItemModel>();

            foreach(var part in parts)
            {
                IDataListItemModel item;
                if(part.IsScalar)
                {
                    item = DataListItemModelFactory.CreateDataListItemViewModel
                        (viewModel, part.Field, part.Description, null);

                    results.Add(item);
                }
                else if(string.IsNullOrEmpty(part.Field))
                {
                    AddRecordSetItem(viewModel, part, results);
                }
                else
                {
                    IDataListItemModel recset
                        = results.FirstOrDefault(c => c.IsRecordset && c.Name == part.Recordset) ?? viewModel.DataList.FirstOrDefault(c => c.IsRecordset && c.Name == part.Recordset);

                    if(recset == null && isAdd)
                    {
                        AddRecordSetItem(viewModel, part, results);
                    }

                    if(recset != null)
                    {
                        if(isAdd)
                        {
                            item = DataListItemModelFactory.CreateDataListItemViewModel(viewModel, part.Field, part.Description, recset);

                            recset.Children.Add(item);
                        }
                        else
                        {
                            IDataListItemModel removeItem = recset.Children.FirstOrDefault(c => c.Name == part.Field);
                            if(removeItem != null)
                            {
                                if(recset.Children.Count == 1)
                                {
                                    recset.Children[0].DisplayName = "";
                                    recset.Children[0].Description = "";
                                }
                                else
                                {
                                    recset.Children.Remove(removeItem);
                                }
                            }
                        }
                    }
                }
            }
            return results;
        }
 private static void AssertTemplateContents( List<Template> templates, string key, string culture, bool hasHtml = false)
 {
     var t = templates.FirstOrDefault(x => x.Key == key && x.Language.Name.StartsWith(culture));
     if (hasHtml)
     {
         Assert.AreEqual(key + culture + "subjectcontents.html", t.Content.Subject);
         Assert.AreEqual(key + culture + "summarysubjectcontents.html", t.Content.SummarySubject);
     }
     else
     {
         Assert.AreEqual(key + culture + "subjectcontents.txt", t.Content.Subject);
         Assert.AreEqual(key + culture + "summarysubjectcontents.txt", t.Content.SummarySubject); 
     }
     Assert.AreEqual(key + culture + "bodycontents.txt", t.Content.TextBody);
     Assert.AreEqual(key + culture + "summarybodycontents.txt", t.Content.SummaryTextBody);
     Assert.AreEqual(key + culture + "summaryfootercontents.txt", t.Content.SummaryTextFooter);
     Assert.AreEqual(key + culture + "summaryheadercontents.txt", t.Content.SummaryTextHeader);
     if (!hasHtml)
     {
         Assert.AreEqual(null, t.Content.Body);
         Assert.AreEqual(null, t.Content.SummaryFooter);
         Assert.AreEqual(null, t.Content.SummaryHeader);
         Assert.AreEqual(null, t.Content.SummaryBody);
     }
     else
     {
         Assert.AreEqual(key + culture + "bodycontents.html", t.Content.Body);
         Assert.AreEqual(key + culture + "summaryfootercontents.html", t.Content.SummaryFooter);
         Assert.AreEqual(key + culture + "summaryheadercontents.html", t.Content.SummaryHeader);
         Assert.AreEqual(key + culture + "summarybodycontents.html", t.Content.SummaryBody);
     }
 }