public void AttributeStatement_Invalid_Attribute_AnyAttrSamlQualified()
        {
            Assertion saml20Assertion = AssertionUtil.GetBasicAssertion();
            List<StatementAbstract> statements = new List<StatementAbstract>(saml20Assertion.Items);
            AttributeStatement sas =
                (AttributeStatement)statements.Find(delegate(StatementAbstract ssa) { return ssa is AttributeStatement; });
            SamlAttribute sab = (SamlAttribute)sas.Items[0];
            XmlDocument doc = new XmlDocument();
            saml20Assertion.Items = statements.ToArray();

            foreach (string samlns in Saml20Constants.SAML_NAMESPACES)
            {
                sab.AnyAttr = new XmlAttribute[1] { doc.CreateAttribute("someprefix", "SamlQualified", samlns) };

                try
                {
                    CreateSaml20Token(saml20Assertion);
                    Assert.Fail("A SAML-qualified xml attribute extension on Attribute must not be valid");
                }
                catch (Saml20FormatException sfe)
                {
                    Assert.AreEqual(sfe.Message, "Attribute extension xml attributes MUST NOT use a namespace reserved by SAML");
                }
            }
        }
        public void SingleContestant()
        {
            List<Contestant> ContestantList = new List<Contestant>();   //List of contestants
            ContestantList.Add(new Contestant("Bill"));

            Contestant item = ContestantList.Find(o => o.name == "Will");
            Assert.IsNotNull(item);
            //Assert.AreSame("Bill", ContestantList.);
        }
        public void NewContestant()
        {
            string null_string = "";
            List<Contestant> ContestantList = new List<Contestant>();   //List of contestants
            ContestantList.Add(new Contestant(null_string));

            Contestant item = ContestantList.Find(o => o.name == "");
            Assert.IsNotNull(item);
            //Assert.AreSame("Bill", ContestantList.);
        }
예제 #4
0
		void AssertContainsProperty(string propertyName, IEnumerable items)
		{
			var itemsList = new List<Property>();
			foreach (Property property in items) {
				itemsList.Add(property);
			}
			var matchedProperty = itemsList.Find(p => p.Name == propertyName);
			
			Assert.AreEqual(propertyName, matchedProperty.Name);
		}
예제 #5
0
 public void DiscardEvent_EventCard_EventHandGetsShorterAndDiscardGetsLonger()
 {
     var cards = new List<EventCard> {new EventCard(Event.DevilishPower, true, EventType.Keep)};
     var discard = new List<EventCard>();
     dracula.TakeEvent(cards, discard);
     var cardCountBefore = dracula.EventHand.Count();
     dracula.DiscardEvent(Event.DevilishPower, discard);
     Assert.AreEqual(null, dracula.EventHand.Find(card => card.Event == Event.DevilishPower));
     Assert.AreNotEqual(null, discard.Find(card => card.Event == Event.DevilishPower));
     Assert.AreEqual(cardCountBefore - 1, dracula.EventHand.Count());
 }
예제 #6
0
        public void BucketRefreshTest()
        {
            List<Node> nodes = new List<Node>();
            for (int i = 0; i < 5; i++)
                nodes.Add(new Node(NodeId.Create(), new IPEndPoint(IPAddress.Any, i)));

            engine.TimeOut = TimeSpan.FromMilliseconds(25);
            engine.BucketRefreshTimeout = TimeSpan.FromMilliseconds(75);
            engine.MessageLoop.QuerySent += delegate(object o, SendQueryEventArgs e)
            {
                DhtEngine.MainLoop.Queue(delegate
                {
                    if (!e.TimedOut)
                        return;

                    Node current = nodes.Find(delegate(Node n) { return n.EndPoint.Port.Equals(e.EndPoint.Port); });
                    if (current == null)
                        return;

                    if (e.Query is Ping)
                    {
                        PingResponse r = new PingResponse(current.Id, e.Query.TransactionId);
                        listener.RaiseMessageReceived(r, current.EndPoint);
                    }
                    else if (e.Query is FindNode)
                    {
                        FindNodeResponse response = new FindNodeResponse(current.Id, e.Query.TransactionId);
                        response.Nodes = "";
                        listener.RaiseMessageReceived(response, current.EndPoint);
                    }
                });
            };

            engine.Add(nodes);
            engine.Start();

            System.Threading.Thread.Sleep(500);
            foreach (Bucket b in engine.RoutingTable.Buckets)
            {
                Assert.IsTrue(b.LastChanged > DateTime.UtcNow.AddSeconds(-2));
                Assert.IsTrue(b.Nodes.Exists(delegate(Node n) { return n.LastSeen > DateTime.UtcNow.AddMilliseconds(-900); }));
            }
        }
        public void can_get_a_seven_digit_number()
        {
            var tehNumbersFromTehCodez = new List<PhoneNumber>();

            for (int i = 2; i < 10; i++)
            {
                List<PhoneNumber> results = numberGenerator.GetNumbersStartingFrom(i);
                tehNumbersFromTehCodez.AddRange(results);
            }

            Console.WriteLine("We found {0} phone numbers", tehNumbersFromTehCodez.Count);
            Console.WriteLine("How many are distinct? {0}", tehNumbersFromTehCodez.Distinct().Count());

            PhoneNumber containsAFive = tehNumbersFromTehCodez.Find(c => c.ToString().Contains("5"));
            Assert.IsNull(containsAFive);

            foreach (PhoneNumber phoneNumber in tehNumbersFromTehCodez)
            {
                Console.WriteLine(phoneNumber);
            }
        }
 /// <summary>
 /// Convenience method for extracting the list of Attributes from the assertion.
 /// </summary>
 /// <param name="statements"></param>
 /// <returns></returns>
 private static AttributeStatement GetAttributeStatement(List<StatementAbstract> statements)
 {
     return (AttributeStatement) statements.Find(delegate(StatementAbstract ssa) { return ssa is AttributeStatement; });
 }
예제 #9
0
        public void JobWatcher_YieldsJobsInExpectedSequence()
        {
            IJobWatcher watcher = jobStore.CreateJobWatcher(SchedulerGuid);

            JobDetails orphaned = CreateOrphanedJob("orphaned", new DateTime(1970, 1, 3));
            JobDetails pending = CreatePendingJob("pending", new DateTime(1970, 1, 2));
            JobDetails triggered = CreateTriggeredJob("triggered", new DateTime(1970, 1, 6));
            JobDetails completed = CreateCompletedJob("completed", new DateTime(1970, 1, 1));
            JobDetails scheduled = CreateScheduledJob("scheduled", new DateTime(1970, 1, 4));

            // Ensure we tolerate a few odd cases where data may not be available like it should.
            JobDetails scheduled2 = CreateScheduledJob("scheduled2", new DateTime(1970, 1, 2));
            scheduled2.NextTriggerFireTimeUtc = null;
            jobStore.SaveJobDetails(scheduled2);

            JobDetails completed2 = CreateCompletedJob("completed2", new DateTime(1970, 1, 1));
            completed2.LastJobExecutionDetails = null;
            jobStore.SaveJobDetails(completed2);

            JobDetails orphaned2 = CreateOrphanedJob("orphaned2", new DateTime(1970, 1, 3));
            orphaned2.LastJobExecutionDetails.EndTimeUtc = null;
            jobStore.SaveJobDetails(orphaned2);

            // Populate a table of expected jobs.
            List<JobDetails> expectedJobs = new List<JobDetails>(new JobDetails[]
                                                                 	{
                                                                 		orphaned, pending, triggered, completed, scheduled, scheduled2
                                                                 		, completed2, orphaned2
                                                                 	});

            // Add in some extra jobs in other states that will not be returned.
            CreateRunningJob("running1");
            CreateStoppedJob("stopped1");
            CreateScheduledJob("scheduled-in-the-future", DateTime.MaxValue);

            // Ensure expected jobs are retrieved.
            while (expectedJobs.Count != 0)
            {
                JobDetails actualJob = watcher.GetNextJobToProcess();
                JobDetails expectedJob =
                    expectedJobs.Find(delegate(JobDetails candidate) { return candidate.JobSpec.Name == actualJob.JobSpec.Name; });
                Assert.IsNotNull(expectedJob, "Did expect job {0}", actualJob.JobSpec.Name);

                // All expected scheduled jobs will have been triggered.
                if (expectedJob.JobState == JobState.Scheduled)
                    expectedJob.JobState = JobState.Triggered;

                JobAssert.AreEqual(expectedJob, actualJob);

                if (expectedJobs.Count == 1)
                {
                    // Ensure same job is returned a second time until its status is changed.
                    // We wait for Count == 1 because that's the easiest case for which to verify
                    // this behavior.
                    JobDetails actualJob2 = watcher.GetNextJobToProcess();
                    JobAssert.AreEqual(expectedJob, actualJob2);
                }

                // Change the status to progress.
                actualJob.JobState = JobState.Stopped;
                jobStore.SaveJobDetails(actualJob);

                expectedJobs.Remove(expectedJob);
            }

            // Ensure next request blocks but is released by the call to dispose.
            ThreadPool.QueueUserWorkItem(delegate
            {
                Thread.Sleep(2);
                watcher.Dispose();
            });

            // This call blocks until the dispose runs.
            Assert.IsNull(watcher.GetNextJobToProcess());
        }
        public void SetUp()
        {
            // will be used in GetById and GetAll mocks
            var entities = new List<Product>();
            for (int i = 0; i < 100; i++)
                entities.Add(new Product { Id = i, Name = "Product" });

            // setup a fake repository for productService .. retrieves data from the above list.
            var mockProductRepo = new Mock<IRepository<Product>>();
            mockProductRepo
                .Setup(e => e.Add(It.IsAny<Product>()))
                .Callback(() => { productRepoCalls["Add"] += 1; })
                .Returns((Product entity) =>
                {
                    entity.Id = 1; // give this an ID so it registers as 'non transient'
                    return entity;
                });
            mockProductRepo
                .Setup(e => e.Update(It.IsAny<Product>()))
                .Callback(() => { productRepoCalls["Update"] += 1; })
                .Returns((Product entity) => { return entity; });
            mockProductRepo
                .Setup(e => e.Delete(It.IsAny<Product>()))
                .Callback(() => { productRepoCalls["Delete"] += 1; });
            mockProductRepo
                .Setup(e => e.GetById(It.IsAny<int>()))
                .Callback(() => { productRepoCalls["GetById"] += 1; })
                .Returns((int id) =>
                {
                    return entities.Find(e => e.Id == id);
                });
            mockProductRepo
                .Setup(e => e.GetAll())
                .Callback(() => { productRepoCalls["GetList"] += 1; })
                .Returns(entities);

            // we want our service to call all of it's real methods
            // they're all marked as virtual so we have to explicitally tell moq to call them.
            var mockProductService = new Mock<GenericService<Product>>(mockProductRepo.Object);
            mockProductService.Setup(e => e.New()).CallBase();

            mockProductService.Setup(e => e.Add(It.IsAny<Product>())).CallBase();
            mockProductService.Setup(e => e.Update(It.IsAny<Product>())).CallBase();
            // mockProductService.Setup(e => e.Delete(It.IsAny<Product>()));

            mockProductService.Setup(e => e.ValidateAdd(It.IsAny<Product>())).CallBase();
            mockProductService.Setup(e => e.ValidateUpdate(It.IsAny<Product>())).CallBase();
            mockProductService.Setup(e => e.ValidateDelete(It.IsAny<Product>())).CallBase();

            mockProductService.Setup(e => e.GetById(It.IsAny<int>())).CallBase();
            mockProductService.Setup(e => e.GetList()).CallBase();
            mockProductService.Setup(e => e.GetList(It.IsAny<int>(), It.IsAny<int>())).CallBase();

            productService = mockProductService.Object;
        }
예제 #11
0
        public void AttributeStatement_Invalid_EncryptedAttribute_WrongType()
        {
            Assertion saml20Assertion = AssertionUtil.GetBasicAssertion();
            List<StatementAbstract> statements = new List<StatementAbstract>(saml20Assertion.Items);
            AttributeStatement sas =
                (AttributeStatement)statements.Find(delegate(StatementAbstract ssa) { return ssa is AttributeStatement; });
            List<object> attributes = new List<object>(sas.Items);
            EncryptedElement ee = new EncryptedElement();
            ee.encryptedData = new EncryptedData();
            ee.encryptedData.Type = "SomeWrongType";
            attributes.Add(ee);
            sas.Items = attributes.ToArray();
            saml20Assertion.Items = statements.ToArray();

            CreateSaml20Token(saml20Assertion);
        }
예제 #12
0
        public void Init()
        {
            var requestDetailCommodity = new List<RequestDetailCommodity>()
                                             {
                                                 new RequestDetailCommodity
                                                     {
                                                         CommodityID = 1,
                                                         Amount = 20,
                                                         RequestCommodityID = 1,
                                                         RegionalRequestDetailID = 1,
                                                         Commodity=new Commodity(){CommodityID=1,Name="CSB"}

                                                     },

                                             };
            var regionalRequests = new List<RegionalRequest>()
                                       {
                                           new RegionalRequest
                                               {
                                                   ProgramId = 1
                                                   ,
                                                   Month = 1
                                                   ,
                                                   RegionID = 1
                                                   ,
                                                   RegionalRequestID = 1
                                                   ,
                                                   RequistionDate = DateTime.Parse("7/3/2013")
                                                   ,
                                                   Year = DateTime.Today.Year
                                                   ,
                                                   Status=1,
                                                   Program = new Program(){
                                                   Name="Program1",
                                                   ProgramID = 1

                                                   },
                                                   AdminUnit=new AdminUnit
                                                                 {
                                                                     Name="Region",
                                                                     AdminUnitID=1
                                                                 },
                                                                 Ration=new Ration()
                                                                            {
                                                                                RationID=1,
                                                                                RefrenceNumber="RE1",

                                                                            },
                                                   RegionalRequestDetails = new List<RegionalRequestDetail>
                                                                                {
                                                                                    new RegionalRequestDetail
                                                                                        {
                                                                                            Beneficiaries = 100
                                                                                            ,
                                                                                            Fdpid = 1,
                                                                                            Fdp = new FDP{FDPID=1,Name="FDP1",AdminUnit=new AdminUnit{AdminUnitID=1,Name="Admin1",AdminUnit2=new AdminUnit{AdminUnitID=2,Name="Admin2"}}}
                                                                                            ,
                                                                                            RegionalRequestID = 1
                                                                                            ,
                                                                                            RegionalRequestDetailID = 1,
                                                                                            RequestDetailCommodities=requestDetailCommodity
                                                                                        },
                                                                                    new RegionalRequestDetail
                                                                                        {
                                                                                            Beneficiaries = 100
                                                                                            ,
                                                                                            Fdpid = 2,
                                                                                            Fdp = new FDP{FDPID=2,Name="FDP1",AdminUnit=new AdminUnit{AdminUnitID=1,Name="Admin1",AdminUnit2=new AdminUnit{AdminUnitID=2,Name="Admin2"}}}
                                                                                            ,
                                                                                            RegionalRequestID = 1
                                                                                            ,
                                                                                            RegionalRequestDetailID = 2,
                                                                                             RequestDetailCommodities=requestDetailCommodity
                                                                                        }
                                                                                }
                                               }

                                       };

             //   regionalRequests[0].RegionalRequestDetails.First().RequestDetailCommodities = requestDetailCommodity;
            var adminUnit = new List<AdminUnit>()
                                {
                                    new AdminUnit
                                        {
                                            Name = "Temp Admin uni",
                                            AdminUnitID = 1
                                        }
                                };
            var plan = new List<Plan>
                {
                    new Plan {PlanID = 1,PlanName = "Plan1",ProgramID = 1,StartDate = new DateTime(12/12/12),EndDate =new DateTime(12/12/12) }
                };
               var _status = new List<Cats.Models.WorkflowStatus>()
                              {
                                  new WorkflowStatus()
                                      {
                                          Description = "Draft",
                                          StatusID = 1,
                                          WorkflowID = 1
                                      },
                                  new WorkflowStatus()
                                      {
                                          Description = "Approved",
                                          StatusID = 2,
                                          WorkflowID = 1
                                     },
                                  new WorkflowStatus()
                                      {
                                          Description = "Closed",
                                          StatusID = 3,
                                          WorkflowID = 1
                                      }
                              };
            var commonService = new Mock<ICommonService>();
            commonService.Setup(t => t.GetAminUnits(It.IsAny<Expression<Func<AdminUnit, bool>>>(),
                      It.IsAny<Func<IQueryable<AdminUnit>, IOrderedQueryable<AdminUnit>>>(),
                      It.IsAny<string>())).Returns(adminUnit);
            commonService.Setup(t => t.GetStatus(It.IsAny<WORKFLOW>())).Returns(_status);
            commonService.Setup(t => t.GetPlan(plan.First().ProgramID)).Returns(plan);
            var mockRegionalRequestService = new Mock<IRegionalRequestService>();
            mockRegionalRequestService.Setup(
                t => t.GetSubmittedRequest(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>())).Returns(
                    (int region, int month, int status) =>
                    {
                        return regionalRequests.FindAll(
                               t => t.RegionID == region && t.RequistionDate.Month == month && t.Status == status).ToList();
                    });
            mockRegionalRequestService.Setup(
                t =>
                t.Get(It.IsAny<Expression<Func<RegionalRequest, bool>>>(),
                      It.IsAny<Func<IQueryable<RegionalRequest>, IOrderedQueryable<RegionalRequest>>>(),
                      It.IsAny<string>())).Returns(
                          (Expression<Func<RegionalRequest, bool>> filter,
                           Func<IQueryable<RegionalRequest>, IOrderedQueryable<RegionalRequest>> sort, string includes)
                          =>
                          {
                              return regionalRequests.AsQueryable().Where(filter);
                              ;
                          });
            mockRegionalRequestService.Setup(t => t.FindById(It.IsAny<int>())).Returns(
                (int requestId) => regionalRequests.Find(t => t.RegionalRequestID == requestId));
            mockRegionalRequestService.Setup(t => t.ApproveRequest(It.IsAny<int>())).Returns((int reqId) =>
                                                                                                 {
                                                                                                     regionalRequests.
                                                                                                         Find
                                                                                                         (t =>
                                                                                                          t.
                                                                                                              RegionalRequestID
                                                                                                          == reqId).
                                                                                                         Status
                                                                                                         =
                                                                                                         (int)
                                                                                                         RegionalRequestStatus
                                                                                                             .Approved;
                                                                                                     return true;
                                                                                                 });
            mockRegionalRequestService.Setup(t => t.AddRegionalRequest(It.IsAny<RegionalRequest>())).Returns(
                (RegionalRequest rRequest) =>
                {
                    regionalRequests.Add(rRequest);
                    return true;
                });
            mockRegionalRequestService.Setup(t => t.GetAllRegionalRequest()).Returns(regionalRequests);
            mockRegionalRequestService.Setup(t => t.PlanToRequest(It.IsAny<HRDPSNPPlan>())).Returns(new HRDPSNPPlanInfo()
                                                                                                        {
                                                                                                            BeneficiaryInfos
                                                                                                                =
                                                                                                                new List
                                                                                                                <
                                                                                                                BeneficiaryInfo
                                                                                                                >()
                                                                                                                    {
                                                                                                                        new BeneficiaryInfo
                                                                                                                            ()
                                                                                                                            {
                                                                                                                                Beneficiaries
                                                                                                                                    =
                                                                                                                                    1,
                                                                                                                                FDPID
                                                                                                                                    =
                                                                                                                                    1,
                                                                                                                                FDPName
                                                                                                                                    =
                                                                                                                                    "F1",
                                                                                                                                Selected
                                                                                                                                    =
                                                                                                                                    true
                                                                                                                            }
                                                                                                                    }
                                                                                                            ,
                                                                                                            HRDPSNPPlan
                                                                                                                =
                                                                                                                new HRDPSNPPlan
                                                                                                                    {
                                                                                                                        DonorID
                                                                                                                            =
                                                                                                                            1,
                                                                                                                        Month
                                                                                                                            =
                                                                                                                            1,
                                                                                                                        PlanID
                                                                                                                            =
                                                                                                                            1,
                                                                                                                        ProgramID
                                                                                                                            =
                                                                                                                            1,
                                                                                                                        PSNPPlanID
                                                                                                                            =
                                                                                                                            1,
                                                                                                                        RationID
                                                                                                                            =
                                                                                                                            1,
                                                                                                                        RegionID
                                                                                                                            =
                                                                                                                            1,
                                                                                                                        Round
                                                                                                                            =
                                                                                                                            1,
                                                                                                                        SeasonID
                                                                                                                            =
                                                                                                                            1,
                                                                                                                        Year
                                                                                                                            =
                                                                                                                            1
                                                                                                                    }
                                                                                                        });
            var mockAdminUnitService = new Mock<IAdminUnitService>();
            mockAdminUnitService.Setup(t => t.FindBy(It.IsAny<Expression<Func<AdminUnit, bool>>>())).Returns(adminUnit);

            mockAdminUnitService.Setup(t => t.GetRegions()).Returns(adminUnit);

            var workflowService = new Mock<IWorkflowStatusService>();

            workflowService.Setup(t => t.GetStatus(It.IsAny<Cats.Models.Constant.WORKFLOW>())).Returns(_status);
            workflowService.Setup(t => t.GetStatusName(It.IsAny<Cats.Models.Constant.WORKFLOW>(), It.IsAny<int>())).
                Returns((Cats.Models.Constant.WORKFLOW workflow, int statusId) =>
                            {
                                return _status.Find(t => t.StatusID == statusId && t.WorkflowID == (int)workflow).Description;
                            });

            commonService.Setup(t => t.GetPrograms(It.IsAny<Expression<Func<Program, bool>>>(),
                      It.IsAny<Func<IQueryable<Program>, IOrderedQueryable<Program>>>(),
                      It.IsAny<string>())).Returns(new List<Program>()
                                                                     {
                                                                         new Program()
                                                                             {ProgramID = 1, Description = "Relief"}
                                                                     });

            commonService.Setup(t => t.GetRations(It.IsAny<Expression<Func<Ration, bool>>>(),
                      It.IsAny<Func<IQueryable<Ration>, IOrderedQueryable<Ration>>>(),
                      It.IsAny<string>())).Returns(new List<Ration>()
                                                                   {
                                                                       new Ration
                                                                           {RationID = 1, RefrenceNumber = "R-00983"}
                                                                   });

            var fdpService = new Mock<IFDPService>();
            fdpService.Setup(t => t.FindBy(It.IsAny<Expression<Func<FDP, bool>>>())).Returns(new List<FDP>()
                                                                           {
                                                                               new FDP()
                                                                                   {
                                                                                       FDPID = 1,
                                                                                       Name = "FDP1",
                                                                                       AdminUnitID = 1
                                                                                   }
                                                                           });
            var requestDetailService = new Mock<IRegionalRequestDetailService>();
            requestDetailService.Setup(t => t.Get(It.IsAny<Expression<Func<RegionalRequestDetail, bool>>>(), null, It.IsAny<string>())).Returns(regionalRequests.First().RegionalRequestDetails);

            commonService.Setup(t => t.GetCommodities(It.IsAny<Expression<Func<Commodity, bool>>>(),
                      It.IsAny<Func<IQueryable<Commodity>, IOrderedQueryable<Commodity>>>(),
                      It.IsAny<string>())).Returns(new List<Commodity>() { new Commodity { CommodityID = 1, Name = "CSB" } });

            var hrds = new List<HRD>
                          {
                              new HRD()
                                  {
                                      Year = 2013,
                                      Season = new Season() {Name = "Mehere", SeasonID = 1},
                                      RationID = 1,
                                      HRDDetails =
                                          new List<HRDDetail>()
                                              {
                                                  new HRDDetail()
                                                      {
                                                          DurationOfAssistance = 2,
                                                          HRDDetailID = 1,
                                                          NumberOfBeneficiaries = 300,
                                                          WoredaID = 1,
                                                          AdminUnit =
                                                              new AdminUnit()
                                                                  {
                                                                      Name = "Woreda",
                                                                      AdminUnitID = 2,
                                                                      AdminUnit2 =
                                                                          new AdminUnit()
                                                                              {
                                                                                  Name = "Zone",
                                                                                  AdminUnitID = 3,
                                                                                  AdminUnit2 =
                                                                                      new AdminUnit()
                                                                                          {
                                                                                              Name = "Region",
                                                                                              AdminUnitID = 6
                                                                                          }
                                                                              }
                                                                  }
                                                      }
                                              }
                                  }
                          };
            var hrdService = new Mock<IHRDService>();
            var appService = new Mock<IApplicationSettingService>();
            hrdService.Setup(
                t =>
                t.Get(It.IsAny<Expression<Func<HRD, bool>>>(), It.IsAny<Func<IQueryable<HRD>, IOrderedQueryable<HRD>>>(),
                      It.IsAny<string>())).Returns(hrds);
            var userAccountService = new Mock<IUserAccountService>();
            userAccountService.Setup(t => t.GetUserInfo(It.IsAny<string>())).Returns(new UserInfo()
                                                                                         {
                                                                                             UserName = "******",
                                                                                             DatePreference = "en"
                                                                                         });
            var fakeContext = new Mock<HttpContextBase>();
            var identity = new GenericIdentity("User");
            var principal = new GenericPrincipal(identity,null);
            fakeContext.Setup(t => t.User).Returns(principal);
            var controllerContext = new Mock<ControllerContext>();
            controllerContext.Setup(t => t.HttpContext).Returns(fakeContext.Object);
            var log = new Mock<ILog>();
            log.Setup(t => t.Error(It.IsAny<object>()));

            var hrdServiceDetail = new Mock<IHRDDetailService>();
            var RegionalPSNPPlanDetailService = new Mock<IRegionalPSNPPlanDetailService>();
            var RegionalPSNPPlanService = new Mock<IRegionalPSNPPlanService>();

            _requestController = new RequestController(
                mockRegionalRequestService.Object,
                fdpService.Object, requestDetailService.Object,
                commonService.Object, hrdService.Object,
                appService.Object, userAccountService.Object,
                log.Object, hrdServiceDetail.Object,
                RegionalPSNPPlanDetailService.Object,
                RegionalPSNPPlanService.Object,null,null,null);
               _requestController.ControllerContext = controllerContext.Object;
        }
예제 #13
0
            public void ThrowsExceptionWhenXmlAttributeStatementEncryptedAttributeWrongType()
            {
                // Arrange
                var saml20Assertion = AssertionUtil.GetBasicAssertion();
                var statements = new List<StatementAbstract>(saml20Assertion.Items);
                var attributeStatments = (AttributeStatement)statements.Find(x => x is AttributeStatement);

                var attributes = new List<object>(attributeStatments.Items);
                var ee = new EncryptedElement
                             {
                                 EncryptedData = new EncryptedData
                                                     {
                                                         Type = "SomeWrongType"
                                                     }
                             };
                attributes.Add(ee);
                attributeStatments.Items = attributes.ToArray();
                saml20Assertion.Items = statements.ToArray();

                // Act
                var assertion = new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false, TestConfiguration.Configuration);
            }
예제 #14
0
            public void ThrowsExceptionWhenXmlAttributeStatementAttributeAnyAttrSamlQualified()
            {
                // Arrange
                var saml20Assertion = AssertionUtil.GetBasicAssertion();
                var statements = new List<StatementAbstract>(saml20Assertion.Items);
                var attributeStatments = (AttributeStatement)statements.Find(x => x is AttributeStatement);
                var attribute = (SamlAttribute)attributeStatments.Items[0];

                var doc = new XmlDocument();
                saml20Assertion.Items = statements.ToArray();

                foreach (var samlns in Saml20Constants.SamlNamespaces)
                {
                    attribute.AnyAttr = new[] { doc.CreateAttribute("someprefix", "SamlQualified", samlns) };

                    try
                    {
                        // Act
                        var assertion = new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false, TestConfiguration.Configuration);
                        Assert.Fail("A SAML-qualified xml attribute extension on Attribute must not be valid");
                    }
                    catch (Saml20FormatException sfe)
                    {
                        Assert.AreEqual(sfe.Message, "Attribute extension xml attributes MUST NOT use a namespace reserved by SAML");
                    }
                }
            }
		void AssertPropertiesContainProperty(string expectedPropertyName)
		{
			var propertiesList = new List<Property>(properties);
			Property property = propertiesList.Find(p => p.Name == expectedPropertyName);
			Assert.IsNotNull(property, "Unable to find property: " + expectedPropertyName);
		}
        public void AddPost_Post_Url_Contains_No_Punctuation()
        {
            //arrange
            var blogRepository = new Mock<IBlogPostsRepository>();
            var submittedPosts = new List<BlogPost>();
            blogRepository.Setup(b => b.Save(It.IsAny<BlogPost>()))
                .Callback((BlogPost p) =>
                {
                    if (submittedPosts.Find(x => x.Url == p.Url) != null)
                    {
                        throw new Exception();
                    }
                    submittedPosts.Add(p);
                }
                );

            var blogManagement = new BlogManagementController(blogRepository.Object);
            var model = new BlogPost { Title = "Hey, Joe.!:;" };

            //act
            var result = blogManagement.AddPost(model) as ViewResult;

            //post
            var post = submittedPosts.First();
            Assert.That(model.Url, Is.EqualTo("hey-joe"));
        }
        public void AddPost_Post_CreatedDate_Contains_HourMinutesSeconds()
        {
            //arrange
            var blogRepository = new Mock<IBlogPostsRepository>();
            var submittedPosts = new List<BlogPost>();
            blogRepository.Setup(b => b.Save(It.IsAny<BlogPost>()))
                .Callback((BlogPost p) =>
                {
                    if (submittedPosts.Find(x => x.Url == p.Url) != null)
                    {
                        throw new Exception();
                    }
                    submittedPosts.Add(p);
                }
                );

            var blogManagement = new BlogManagementController(blogRepository.Object);
            var model = new BlogPost { Title = "Hey Joe" };

            //act
            var result = blogManagement.AddPost(model) as ViewResult;

            //post
            var post = submittedPosts.First();
            Assert.That(post.CreatedDate, Is.Not.Null);
            Assert.That(post.CreatedDate.ToLongTimeString(), Is.Not.EqualTo("00:00:00"));
        }
        public void AddPost_Post_NotAddPost_With_SameUrl()
        {
            //arrange
            var blogRepository = new Mock<IBlogPostsRepository>();
            var submittedPosts = new List<BlogPost>();
            blogRepository.Setup(b => b.Save(It.IsAny<BlogPost>()))
                .Callback((BlogPost p) => 
                {
                    if (submittedPosts.Find(x => x.Url == p.Url) != null)
                    {
                        throw new Exception();
                    }
                    submittedPosts.Add(p); 
                }
                );

            var blogManagement = new BlogManagementController(blogRepository.Object);
            var model = new BlogPost { Title = "Hey Joe" };
            
            //act
            var result = blogManagement.AddPost(model) as ViewResult;
            result = blogManagement.AddPost(model) as ViewResult;

            //post
            Assert.That(blogManagement.ModelState[""].Errors[0].ErrorMessage, Is.EqualTo("Post could not be added. Exception of type 'System.Exception' was thrown."));
        }
 public void VerifyAgendaItems(List<RegisterManager.CustomFieldResponses> cfResponses, int registrationID)
 {
     this.VerifyAgendaItems(cfResponses.Find(responses => responses.RegistrationID == registrationID).customFields);
 }
 public void VerifyMerchandise(List<RegisterManager.MerchandiseResponses> merchResponses, int registrationID)
 {
     this.VerifyMerchandise(merchResponses.Find(responses => responses.RegistrationID == registrationID).merchandises);
 }
예제 #21
0
        public void SetUp()
        {
            string connection = "mongodb://localhost:27017";
            _client = new MongoClient(connection);
            _server = _client.GetServer();
            _database = _server.GetDatabase("local", WriteConcern.Unacknowledged);
            _corporations = _database.GetCollection<Corporation>("Corporations");

            var corpo = new Corporation
            {

                Id = ObjectId.Parse("564db279b99f725971d81658"),
                Name = "MockNome",
                Nation = "MockNation",
                RealEstates = new List<RealEstate>()
                    {
                        new RealEstate()
                        {
                            city = "MockCity",
                            code = 123,
                            state = "MockState",
                            street = "MockStreet",
                            zip = 123
                        }
                    }

            };

            _corpoList = new List<Corporation>()
            {
                //new Corporation()
                //{
                //    Id = ObjectId.Parse("564db279b99f725971d81658"),
                //    Name = "MockNome",
                //    Nation = "MockNation",
                //    RealEstates = new List<RealEstate>()
                //    {
                //        new RealEstate()
                //        {
                //            city = "MockCity",
                //            code = 123,
                //            state = "MockState",
                //            street = "MockStreet",
                //            zip = 123
                //        }
                //    }
                //},
                new Corporation()
                {
                    Id = ObjectId.GenerateNewId(),
                    Name = "MockNome2",
                    Nation="MockNation2",
                    RealEstates = new List<RealEstate>()
                    {
                        new RealEstate()
                        {
                            city = "MockCity2",
                            code=456,
                            state="MockState2",
                            street="MockStreet2",
                            zip=456
                        }
                    }
                }
            };
            _corpoList.Add(corpo);

            _repositoryMock = new Mock<IRepository>();

            _repositoryMock.Setup(x => x.AddCorporation(It.IsAny<Corporation>())).Returns(new ObjectId("564db279b99f725971d81658"));

            _repositoryMock.Setup(x => x.AddRealEstate(It.IsAny<string>(), It.IsAny<RealEstate>()))
                //.Returns(new RealEstate());
                .Returns(true);

            _repositoryMock.Setup(x => x.GetAllCorporations()).Returns(_corpoList);

            _repositoryMock.Setup(x => x.GetCorporation(It.IsAny<ObjectId>())).Returns(_corpoList.Find(x => x.Id == corpo.Id));

            _repositoryMock.Setup(x => x.GetCorporation(It.IsAny<string>()))
                .Returns(_corpoList.Find(x => x.Id == corpo.Id));

            _repositoryMock.Setup(x => x.RemoveCorporation(It.IsAny<string>()));

            _repositoryMock.Setup(x => x.UpdateCorporation(It.IsAny<string>(), It.IsAny<Corporation>()))
                .Returns(true);

            _filterManager = new Mock<IFilterManager>();

            _filterManager.Setup(x => x.FilterCorporation(It.IsAny<List<Corporation>>(), It.IsAny<Corporation>()))
                .Returns(It.IsAny<List<Corporation>>());

            _filterManager.Setup(x => x.FilterRealEstates(It.IsAny<Corporation>(), It.IsAny<RealEstate>()))
                .Returns(It.IsAny<List<RealEstate>>());

            _filterAddManager = new Mock<IAddCorporationManager>();

            _filterAddManager.Setup(x => x.AddCorporation(It.IsAny<IRepository>(), It.IsAny<Corporation>()))
                .Returns(new ObjectId("564db279b99f725971d81658"));

            _filterAddManager.Setup(
                x => x.AddRealEstate(It.IsAny<IRepository>(), It.IsAny<string>(), It.IsAny<RealEstate>()))
                .Returns(true);

            _filterAddManager.Setup(
                x => x.UpdateCorporation(It.IsAny<IRepository>(), It.IsAny<string>(), It.IsAny<Corporation>()))
                .Returns(true);

            _filterAddManager.Setup(
                x =>
                    x.UpdateRealEstate(It.IsAny<IRepository>(), It.IsAny<string>(), It.IsAny<int>(),
                        It.IsAny<RealEstate>()))
                .Returns(true);
        }
        public void CreateNewUser_ApiToken_Created()
        {
            // arrange
            var usersRepository = new Mock<IUsersRepository>();
            var forms = new Mock<IFormsAuthentication>();
            var hash = new HashService();
            var service = new AuthenticationService(usersRepository.Object, forms.Object, hash);

            var users = new List<User>();
            usersRepository.Setup(u => u.Users).Returns(users.AsQueryable());
            usersRepository.Setup(u => u.Save(It.IsAny<User>())).Callback((User u) => users.Add(u));

            // act
            service.RegisterNewUser("*****@*****.**", "mypass");

            // assert
            Assert.That(users.Count, Is.GreaterThan(0));
            var found = users.Find((u) => u.Email == "*****@*****.**");
            Assert.That(found.ApiToken.Length, Is.EqualTo(32));

        }
예제 #23
0
 private static List<string> GetSetThatDoesntHaveTheBook(string book, List<List<string>> resultSet)
 {
     var foundSet = resultSet.Find(set => !set.Contains(book));
     return foundSet;
 }
예제 #24
0
		public void GetEnumerator_FindCopyToOutputDirectoryPropertyInAllProperties_ReturnsPropertyWithCopyToOutputDirectoryName()
		{
			CreateProjectItemProperties();
			
			var projectItemProperties = new List<Property>(properties);
			var property = projectItemProperties.Find(p => p.Name == "CopyToOutputDirectory");
			
			Assert.AreEqual("CopyToOutputDirectory", property.Name);
		}
예제 #25
0
            public void ThrowsExceptionWhenXmlAttributeStatementAttributeAnyAttrUnqualified()
            {
                // Arrange
                var saml20Assertion = AssertionUtil.GetBasicAssertion();
                var statements = new List<StatementAbstract>(saml20Assertion.Items);
                var attributeStatments = (AttributeStatement)statements.Find(x => x is AttributeStatement);
                var attribute = (SamlAttribute)attributeStatments.Items[0];

                var doc = new XmlDocument();
                attribute.AnyAttr = new[] { doc.CreateAttribute(string.Empty, "Nonqualified", string.Empty) };

                saml20Assertion.Items = statements.ToArray();

                // Act
                new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false, TestConfiguration.Configuration);
            }
예제 #26
0
		public void GetEnumerator_FindCustomToolInAllProperties_ReturnsCustomToolProperty()
		{
			CreateProjectItemProperties();
			
			var projectItemProperties = new List<Property>(properties);
			var property = projectItemProperties.Find(p => p.Name == "CustomTool");
			
			Assert.AreEqual("CustomTool", property.Name);
		}
예제 #27
0
        public void Init()
        {
            var rationDetails = new List<RationDetail>()
                              {
                                  new RationDetail() {RationID = 1, CommodityID = 1, Amount = 15},
                                  new RationDetail {RationID = 2, CommodityID = 2, Amount = 1},
                                  new RationDetail() {RationID =3, CommodityID = 3, Amount = 2},
                                  new RationDetail {RationID = 4, CommodityID = 4, Amount = 4}
                              };
            var rations = new List<Ration>()
                              {
                                  new Ration()
                                      {
                                          CreatedBy = 1,
                                          RationID = 1,
                                          CreatedDate = DateTime.Today,
                                          IsDefaultRation = true,
                                          RationDetails = rationDetails,
                                          UpdatedBy = 1,
                                          UpdatedDate = DateTime.Today
                                      },

                              };

            var commodities = new List<Commodity>
                                  {
                                      new Commodity {CommodityID = 1, CommodityCode = "1", Name = "commodity 1"},
                                      new Commodity {CommodityID = 2, CommodityCode = "2", Name = "commodity 2"},
                                      new Commodity {CommodityID = 3, CommodityCode = "3", Name = "commodity 3"},
                                      new Commodity {CommodityID = 4, CommodityCode = "4", Name = "commodity 4"},
                                      new Commodity {CommodityID = 5, CommodityCode = "5", Name = "commodity 5"},
                                  };
            var rationService = new Mock<IRationService>();
            rationService.Setup(t => t.Get(It.IsAny<Expression<Func<Ration, bool>>>(), It.IsAny<Func<IQueryable<Ration>, IOrderedQueryable<Ration>>>(), It.IsAny<string>())).Returns(
                rations);
            rationService.Setup(t => t.GetAllRation()).Returns(rations);

            var rationDetailService = new Mock<IRationDetailService>();

            rationDetailService.Setup(t => t.AddRationDetail(It.IsAny<RationDetail>())).Returns((RationDetail rationDetail) =>
                                                                                  {
                                                                                      rationDetails.Add(rationDetail);
                                                                                      return true;
                                                                                  });
            rationDetailService.Setup(t => t.EditRationDetail(It.IsAny<RationDetail>())).Returns((RationDetail rationDetail) =>
                                                                                   {
                                                                                       var target =
                                                                                           rationDetails.Find(
                                                                                               t =>
                                                                                               t.RationID ==
                                                                                               rationDetail.RationID);
                                                                                       target.Amount = rationDetail.Amount;
                                                                                       return true;
                                                                                   });
            rationDetailService.Setup(t => t.FindById(It.IsAny<int>())).Returns(
                (int id) => rationDetails.Find(t => t.RationDetailID == id));

            rationDetailService.Setup(t => t.DeleteById(It.IsAny<int>())).Returns((int id) =>
                                                                                {
                                                                                    var origin =
                                                                                        rationDetails.Find(
                                                                                            t => t.RationDetailID == id);
                                                                                    rationDetails.Remove(origin);
                                                                                    return true;
                                                                                });

            var commodityService = new Mock<ICommodityService>();
            commodityService.Setup(t => t.FindById(It.IsAny<int>())).Returns((int id) => commodities.Find(t => t.CommodityID == id));

            var fakeContext = new Mock<HttpContextBase>();
            var identity = new GenericIdentity("User");
            var principal = new GenericPrincipal(identity, null);
            fakeContext.Setup(t => t.User).Returns(principal);
            var controllerContext = new Mock<ControllerContext>();
            controllerContext.Setup(t => t.HttpContext).Returns(fakeContext.Object);

            var userAccountService = new Mock<IUserAccountService>();
            userAccountService.Setup(t => t.GetUserInfo(It.IsAny<string>())).Returns(new Models.Security.UserInfo() { UserName = "******", DatePreference = "AM" });
            var logService = new Mock<ILog>();
            _rationController = new RationController(rationService.Object, commodityService.Object, rationDetailService.Object,userAccountService.Object,logService.Object);
            _rationController.ControllerContext = controllerContext.Object;
        }
예제 #28
0
		public void GetEnumerator_FindFullPathPropertyInAllProperties_ReturnsPropertyWithFullPathName()
		{
			CreateProjectItemProperties();
			
			var projectItemProperties = new List<Property>(properties);
			var property = projectItemProperties.Find(p => p.Name == "FullPath");
			
			Assert.AreEqual("FullPath", property.Name);
		}
예제 #29
0
 private SPFieldInfo FindByName( List<SPFieldInfo> list, string s )
 {
     return list.Find( delegate( SPFieldInfo o ) { return o.Name == s; } );
 }
예제 #30
0
        public void AttributeStatement_Invalid_Attribute_AnyAttrUnqualified()
        {
            Assertion saml20Assertion = AssertionUtil.GetBasicAssertion();
            List<StatementAbstract> statements = new List<StatementAbstract>(saml20Assertion.Items);
            AttributeStatement sas =
                (AttributeStatement)statements.Find(delegate(StatementAbstract ssa) { return ssa is AttributeStatement; });
            SamlAttribute sab = (SamlAttribute)sas.Items[0];
            XmlDocument doc = new XmlDocument();
            sab.AnyAttr = new XmlAttribute[1] { doc.CreateAttribute(String.Empty, "Nonqualified", String.Empty) };

            saml20Assertion.Items = statements.ToArray();

            CreateSaml20Token(saml20Assertion);
        }