public async Task DiscoverMessageHandlers_RegistersMessageHandler()
        {
            // Arrange
            var queueClient        = new Mock <IQueueClient>();
            var queueClientFactory = new Mock <IQueueClientFactory>();

            queueClientFactory.Setup(o => o.GetQueueReference(QueueName)).Returns(queueClient.Object);

            var job = new TestJob();

            var services = new ServiceCollection();

            services.AddSingleton(job);
            services.AddSingleton(queueClientFactory.Object);
            services.AddSingleton <QueueManager>();
            var serviceProvider = services.BuildServiceProvider();

            // Act
            await serviceProvider.DiscoverMessageHandlers(Assembly.GetAssembly(typeof(TestJob)));

            // Assert
            queueClientFactory.Verify(
                o => o.GetQueueReference(QueueName),
                Times.Once);

            queueClient.Verify(
                o => o.RegisterMessageHandler(It.IsAny <Func <IQueueMessage, CancellationToken, Task> >(), It.IsAny <MessageHandlerOptions>()),
                Times.Once);
        }
Пример #2
0
        public void TestException2Handling()
        {
            var job1 = new TestJob("Job1")
            {
                ThrowException = true
            };
            var job1a = new TestJob("Job1-a");
            var job2  = new TestJob("Job2-a", job1);

            var graph = new GraphMap <string, JobBase <string>, IGraphEdge <string> >
            {
                job1,
                job1a,
                job2,
                new GraphEdge <string>(job1.Key, job2.Key)
            };

            var jobHost = new OrchestratorBuilder <string, JobBase <string>, IGraphEdge <string> >(graph)
                          .Build()
                          .Start(_workContext);

            jobHost.Wait(_workContext);
            jobHost.RunningTask.IsCompleted.Should().BeTrue();
            jobHost.GetProcessedNodeKeys().ForEach(x => _output.WriteLine($"ProcessNode: {x}"));
            jobHost.GetProcessedNodeKeys().Count.Should().Be(1);
            jobHost.GetStopNodeKeys().Count.Should().Be(1);
            jobHost.GetProcessedNodeKeys().Last().Should().Be(job1a.Key);
        }
Пример #3
0
        public unsafe void IJobEntityBatch_Scheduling([Values(100, 10000, 5000000)] int entityCount, [Values(10, 100)] int archetypeCount)
        {
            var archetypes = CreateUniqueArchetypes(archetypeCount);

            for (int archetypeIndex = 0; archetypeIndex < archetypeCount; ++archetypeIndex)
            {
                m_Manager.CreateEntity(archetypes[archetypeIndex], entityCount / archetypeCount, Allocator.Temp);
            }

            var basicQuery = m_Manager.CreateEntityQuery(typeof(EcsTestData));

            var handle = default(JobHandle);

            Measure.Method(() =>
            {
                handle = new TestJob
                {
                    EcsTestDataRW = m_Manager.GetComponentTypeHandle <EcsTestData>(false)
                }.ScheduleParallel(basicQuery, 1, handle);
            })
            .CleanUp(() =>
            {
                handle.Complete();
            })
            .WarmupCount(1)
            .Run();

            archetypes.Dispose();
        }
Пример #4
0
        void ITestService.TestFailedTestsOfTestcaseOfTestsuite(int testerId, int testsystemId, int testsuiteId, int testcaseId)
        {
            Testsuite testsuite = _testsuiteRepository.GetById(testsuiteId);
            Testcase  testcase  = testsuite.Testcases.Single(t => t.ID == testcaseId);

            IList <Result> errorResults = _resultRepository.GetErrorResultsOfTestsuite(testsystemId, testsuite.Browsers, new List <Testcase> {
                testcase
            },
                                                                                       testsuite.Languages);
            Testsystem testsystem = _testsystemRepository.GetById(testsystemId);
            Tester     tester     = _testerRepository.GetById(testerId);

            TestJob testjob = CreateTestJob("Repeat failed of " + "Testcase " + testcase.Name + "(Testsuite " + testsuite.Name + ")", testsuite, testsystem, tester);

            ITestJobManager testjobManager = new TestJobManager(testjob);

            ICollection <WorkItem> workItems = (from result in errorResults
                                                select new WorkItem(testjobManager)
            {
                Testcase = result.Testcase,
                Browser = result.Browser,
                Language = result.Language,
                Testsystem = testsystem,
                Tester = tester
            }).ToList();

            _testPool.AddTestJob(testjobManager, workItems);
        }
Пример #5
0
        public void CustomTester_SingleCharacterValue()
        {
            TrafficViewerFile  mockSite           = new TrafficViewerFile();
            MockTestController mockTestController = new MockTestController(mockSite);


            string          testRequest = "GET /search.aspx?txtSearch=a&a1=a HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n";
            string          paramName   = "txtSearch";
            string          paramName2  = "a1";
            CustomTestsFile file        = GetCustomTestFile();
            Tester          tester      = new Tester(mockTestController, file);
            CustomTestDef   def         = file.GetCustomTests()["Path Traversal"];
            HttpRequestInfo original    = new HttpRequestInfo(testRequest, true);
            Uri             uri         = new Uri(original.FullUrl);

            string          entityId       = tester.GetEntityId(uri, paramName);
            string          entityString   = tester.GetEntityString(testRequest, uri, paramName, original.QueryVariables[paramName]);
            TestJob         testJob        = new TestJob(paramName, original.QueryVariables[paramName], RequestLocation.Query, def);
            string          mutatedRequest = tester.GenerateMutatedRequestList(testRequest, testJob, entityString, entityId)[0];
            HttpRequestInfo mutatedReqInfo = new HttpRequestInfo(mutatedRequest, true);

            Assert.IsTrue(mutatedReqInfo.QueryVariables.ContainsKey(paramName), "Could no longer find parameter");
            Assert.AreEqual(original.QueryVariables[paramName] + MockTestController.PATH_TRAVERSAL, mutatedReqInfo.QueryVariables[paramName], "Incorrect test value");
            Assert.AreEqual(original.QueryVariables[paramName2], mutatedReqInfo.QueryVariables[paramName2], "Incorrect non-test value");
        }
Пример #6
0
    private IEnumerator Start()
    {
        dataStruct = new TestDataStruct()
        {
            list    = new NativeList <int>(100, Allocator.Persistent),
            hashMap = new NativeHashMap <int2, int>(100, Allocator.Persistent)
        };

        for (int i = 0; i < 100; i++)
        {
            dataStruct.list.Add(i);
            dataStruct.hashMap.TryAdd(new int2(i, i), i);
        }

        var job = new TestJob()
        {
            dataStruct = dataStruct
        };

        var jobHandler = job.Schedule(100, 10);

        yield return(new WaitUntil(() => jobHandler.IsCompleted));

        for (int i = 0; i < 100; i++)
        {
            print(dataStruct.list[i]);
        }
    }
Пример #7
0
        public void CustomTester_MatchHeaderValidation()
        {
            TrafficViewerFile  mockSite           = new TrafficViewerFile();
            MockTestController mockTestController = new MockTestController(mockSite);


            string testRequest = "GET /search.aspx?txtSearch=a&a1=a HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n";
            string paramName   = "txtSearch";

            CustomTestsFile file   = GetCustomTestFile();
            Tester          tester = new Tester(mockTestController, file);
            CustomTestDef   def    = file.GetCustomTests()["Path Traversal"];



            def.Validation = "$header=" + "root:\\s?:";

            HttpRequestInfo original = new HttpRequestInfo(testRequest, true);
            Uri             uri      = new Uri(original.FullUrl);

            string  entityId       = tester.GetEntityId(uri, paramName);
            string  entityString   = tester.GetEntityString(testRequest, uri, paramName, original.QueryVariables[paramName]);
            TestJob testJob        = new TestJob(paramName, original.QueryVariables[paramName], RequestLocation.Query, def);
            string  mutatedRequest = tester.GenerateMutatedRequestList(testRequest, testJob, entityString, entityId)[0];

            Assert.IsFalse(tester.ValidateSingleTest(testRequest, "HTTP/1.1 200 OK\r\nbla", new Uri("http://demo.testfire.net/search.aspx"),
                                                     paramName, entityId, def, mutatedRequest, "HTTP/1.1 200 OK\r\n\r\nroot::"));
            Assert.IsTrue(tester.ValidateSingleTest(testRequest, "HTTP/1.1 200 OK\r\nbla", new Uri("http://demo.testfire.net/search.aspx"),
                                                    paramName, entityId, def, mutatedRequest, "HTTP/1.1 200 OK\r\nroot::\r\n\r\nbody"));
        }
Пример #8
0
        public void CustomTester_TestMultiEncoding()
        {
            TrafficViewerFile mockSite = new TrafficViewerFile();
            string            payload  = "<'\0a";
            CustomTestDef     def      = new CustomTestDef("LT", "LT",
                                                           payload, "");
            TestJob         job  = new TestJob("x", "y", RequestLocation.Query, def);
            CustomTestsFile file = GetCustomTestFile();

            file.GenerateAllEncodings = true;
            Tester tester = new Tester(new MockTestController(mockSite), file);

            var list = tester.GeneratePayloadListFromMutation("GET /x=y HTTP/1.1\r\n", job, false, "don't care");

            Assert.IsNotNull(list);
            Assert.AreEqual(7, list.Count);

            Assert.AreEqual(payload, list[0]);
            Assert.AreEqual(Utils.UrlEncode(payload), list[1]);
            Assert.AreEqual(Utils.UrlEncode(Utils.UrlEncode(payload)), list[2]);
            Assert.AreEqual(Utils.UrlEncodeAll(payload), list[3]);
            Assert.AreEqual(Utils.JSONEncode(payload), list[4]);
            Assert.AreEqual(Utils.HtmlEncode(payload), list[5]);
            Assert.AreEqual(Utils.Base64Encode(payload), list[6]);
        }
Пример #9
0
 public IActionResult Index()
 {
     TestJob.TestEnqueueJob();
     TestJob.TestScheduleJob();
     TestJob.TestRecurringJob();
     return(View());
 }
Пример #10
0
        public async Task WorkerPool()
        {
            DivvyUp.RegisterJobsFromAssembly(typeof(TestJob));
            var service = new Service(new MockRedisDatabase());
            var pool    = new WorkerPool(service);

            pool.AddWorker("test");
            pool.AddWorkers(3, "test");
            foreach (var worker in pool.Workers)
            {
                worker.CheckinInterval         = 1;
                worker.DelayAfterInternalError = 0;
                worker.NoWorkCheckInterval     = 0;
            }
            pool.WorkInBackground();
            for (int i = 0; i < 40; i++)
            {
                await service.Enqueue(new TestJob("delay"));
            }

            var start = DateTime.UtcNow;

            while (DateTime.UtcNow - start < TimeSpan.FromSeconds(3.5))
            {
                ;
            }

            await pool.Stop();

            Assert.Equal(40, TestJob.Count("delay"));
        }
Пример #11
0
        public void ThreeMix1JobTest()
        {
            var job1  = new TestJob("Job1");
            var job1a = new TestJob("Job1-a");
            var job2  = new TestJob("Job2-a", job1);

            var graph = new GraphMap <string, JobBase <string>, IGraphEdge <string> >
            {
                job1,
                job1a,
                job2,
                new GraphEdge <string>(job1.Key, job2.Key)
            };

            var jobHost = new OrchestratorBuilder <string, JobBase <string>, IGraphEdge <string> >(graph)
                          .Build()
                          .Start(_workContext);

            jobHost.Wait(_workContext);
            jobHost.RunningTask.IsCompleted.Should().BeTrue();
            jobHost.GetProcessedNodeKeys().ForEach(x => _output.WriteLine($"ProcessNode: {x}"));
            jobHost.GetProcessedNodeKeys().Count.Should().Be(3);
            jobHost.GetProcessedNodeKeys().Last().Should().Be(job2.Key);

            graph.Nodes.Values
            .All(x => x.GetResult(_workContext).Status == JobStatus.Completed)
            .Should()
            .BeTrue();
        }
Пример #12
0
        public void TestExceptionHandling()
        {
            var job1 = new TestJob("Job1")
            {
                ThrowException = true
            };

            var graph = new GraphMap <string, JobBase <string>, IGraphEdge <string> >
            {
                job1,
            };

            var jobHost = new OrchestratorBuilder <string, JobBase <string>, IGraphEdge <string> >(graph)
                          .Build()
                          .Start(_workContext);

            jobHost.Wait(_workContext);

            jobHost.RunningTask.IsCompleted.Should().BeTrue();
            jobHost.GetProcessedNodeKeys().Count.Should().Be(0);
            jobHost.GetStopNodeKeys().Count.Should().Be(1);

            graph.Nodes.Values
            .All(x => x.GetResult(_workContext).Status == JobStatus.Failed)
            .Should()
            .BeTrue();
        }
        public void SingleWriterEnforced()
        {
            var cmds = new EntityCommandBuffer(Allocator.TempJob);
            var job  = new TestJob {
                Buffer = cmds
            };

            cmds.CreateEntity();
            cmds.AddComponent(new EcsTestData {
                value = 42
            });

            var handle = job.Schedule();

            Assert.Throws <InvalidOperationException>(() => { cmds.CreateEntity(); });
            Assert.Throws <InvalidOperationException>(() => { job.Buffer.CreateEntity(); });

            handle.Complete();

            cmds.Playback(m_Manager);
            cmds.Dispose();

            var group = m_Manager.CreateComponentGroup(typeof(EcsTestData));
            var arr   = group.GetComponentDataArray <EcsTestData>();

            Assert.AreEqual(2, arr.Length);
            Assert.AreEqual(42, arr[0].value);
            Assert.AreEqual(1, arr[1].value);
            group.Dispose();
        }
Пример #14
0
        static void FrameworkEXE(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usage:Framework.exe /p:projectConfig /f:frameworkConfig");
                return;
            }

            string frameworkConfigFile = null;
            string projectConfigFile   = null;

            foreach (string p in args)
            {
                if (p.StartsWith("/p:", StringComparison.InvariantCultureIgnoreCase))
                {
                    projectConfigFile = p.Remove(0, 3);
                }
                else if (p.StartsWith("/f:", StringComparison.InvariantCultureIgnoreCase))
                {
                    frameworkConfigFile = p.Remove(0, 3);
                }
                else
                {
                    Console.WriteLine("Error: Unsupported Argument: " + p);
                    return;
                }
            }

            TestJob myTestJob = new TestJob();

            myTestJob.ProjectConfigFile   = projectConfigFile;
            myTestJob.FrameworkConfigFile = frameworkConfigFile;

            myTestJob.StartTesting();
        }
Пример #15
0
        private void JobStartTrigger(object source, Client client, string jobID)
        {
            // Remove player from current team to start a new one.
            if (client.HasData(EntityData.ActiveMission))
            {
                if ((client.GetData(EntityData.ActiveMission) is Mission mission))
                {
                    mission.RemoveActivePlayer(client);
                }
            }

            if (!client.HasData(EntityData.MissionCooldown))
            {
                client.SetData(EntityData.MissionCooldown, DateTime.Now);
            }

            DateTime lastClientTime = client.GetData(EntityData.MissionCooldown);

            if (DateTime.Compare(DateTime.Now, lastClientTime) <= 0)
            {
                client.SendChatMessage("Please wait a moment before starting a new mission...");
                return;
            }

            client.SetData(EntityData.MissionCooldown, DateTime.Now.AddSeconds(25));


            // Check through registered jobs to determine where our job starting point will be.
            switch (jobID.ToLower())
            {
            case "testjob1":
                TestJob.StartJob(client);
                break;
            }
        }
Пример #16
0
    void ISystem <State> .AdvanceTick(State state, float deltaTime)
    {
        var count = state.points.Count;

        if (count < 100)
        {
            for (int i = 0; i < count; ++i)
            {
                var data = this.world.RunComponents(state.points[i], deltaTime, i);
                state.points[i] = data;
                Worlds <State> .currentWorld.UpdateEntityCache(data);
            }
        }
        else
        {
            var job = new TestJob()
            {
                deltaTime = deltaTime
            };
            var jobHandle = job.Schedule(state.points.Count, 64);
            jobHandle.Complete();
        }

        this.world.RemoveComponents <IncreaseUnitsOnce>(Entity.Create <Point>(1));
    }
Пример #17
0
        public async Task <bool> Deploy(TestJob testJob)
        {
            Messenger.Default.Send($"{DateTime.Now.ToString("T")} - Deploy {testJob.BatchJobId}", "RunningLog");

            BatchSharedKeyCredentials credentials = new BatchSharedKeyCredentials(BatchServiceUrl, BatchAccountName, BatchAccountKey);

            using (BatchClient batchClient = await BatchClient.OpenAsync(credentials))
            {
                batchClient.CustomBehaviors.Add(RetryPolicyProvider.LinearRetryProvider(TimeSpan.FromSeconds(10), 3));

                try
                {
                    Messenger.Default.Send($"{DateTime.Now.ToString("T")} - Create Pool ({testJob.NumofVm} core)", "RunningLog");
                    await CreatePoolIfNotExistAsync(batchClient, StorageAccount, testJob);

                    Messenger.Default.Send(
                        new DeployStatusUpdateMessage()
                    {
                        Phase  = DeployPhase.PoolCreated,
                        Status = PhaseStatus.Succeeded
                    }, "DeployStatus");
                }
                catch (Exception ex)
                {
                    Messenger.Default.Send($"{DateTime.Now.ToString("T")} - delete test due to {ex.Message}", "RunningLog");
                    Messenger.Default.Send(
                        new DeployStatusUpdateMessage()
                    {
                        Phase  = DeployPhase.PoolCreated,
                        Status = PhaseStatus.Failed
                    }, "DeployStatus");
                    await batchClient.DeleteTest(testJob);
                }
                try
                {
                    Messenger.Default.Send($"{DateTime.Now.ToString("T")} - Submit job", "RunningLog");
                    await SubmitJobIfNotExistAsync(batchClient, StorageAccount, testJob);

                    Messenger.Default.Send(
                        new DeployStatusUpdateMessage()
                    {
                        Phase  = DeployPhase.JobCreated,
                        Status = PhaseStatus.Succeeded
                    }, "DeployStatus");
                }
                catch (Exception ex)
                {
                    Messenger.Default.Send($"{DateTime.Now.ToString("T")} - delete test due to {ex.Message}", "RunningLog");
                    Messenger.Default.Send(
                        new DeployStatusUpdateMessage()
                    {
                        Phase  = DeployPhase.JobCreated,
                        Status = PhaseStatus.Failed
                    }, "DeployStatus");
                    await batchClient.DeleteTest(testJob);
                }
            }

            return(true);
        }
Пример #18
0
        async Task DeployAndStartStressLoad(IConfigurationProvider provider)
        {
            try
            {
                var     devicePerVm = int.Parse(provider.GetConfigValue("DevicePerVm"));
                var     numofVM     = int.Parse(provider.GetConfigValue("NumofVm"));
                TestJob job         = new TestJob
                {
                    JobId                = DateTime.UtcNow.Ticks,
                    ConfigureProvider    = provider,
                    DevicePerVm          = devicePerVm,
                    Message              = provider.GetConfigValue("Message"),
                    Transport            = provider.GetConfigValue("Transport"),
                    MessagePerMin        = int.Parse(provider.GetConfigValue("MessagePerMin")),
                    NumofVm              = numofVM,
                    SizeOfVM             = (VmSize)Enum.Parse(typeof(VmSize), provider.GetConfigValue("SizeOfVM")),
                    DeviceClientEndpoint = provider.GetConfigValue("DeviceClientEndpoint"),
                    DurationInMin        = int.Parse(provider.GetConfigValue("DurationInMin"))
                };
                var batch = new BatchConnector(provider);
                BatchHelper.Connector = batch;
                await job.Deploy();

                //StartRead();
                await job.DeleteTest();
            }
            catch (Exception e)
            {
                Messenger.Default.Send($"Terminated Due to error '{e.Message}', please check all your inputs are correct.", "RunningLog");
            }
        }
Пример #19
0
        public async Task RetryTest()
        {
            var service = new Service(new MockRedisDatabase());

            DivvyUp.RegisterJobsFromAssembly(typeof(TestJob));
            var       worker          = new Worker(service, "test");
            Exception workerException = null;

            worker.OnError                += (exc) => workerException = exc;
            worker.CheckinInterval         = 1;
            worker.DelayAfterInternalError = 0;
            var job = new TestJob("fail");

            job.Retries = 1;
            await service.Enqueue(job);

            await worker.Work(false);

            Assert.NotNull(workerException);
            workerException = null;
            await worker.Work(false);

            Assert.NotNull(workerException);

            await worker.Work(false);
        }
Пример #20
0
        public static IJob GetJob(ICloudStampyLogger logger, CloudStampyParameters args, StampyJobType requestedJobType)
        {
            IJob job = null;

            switch (requestedJobType)
            {
            case StampyJobType.None:
                break;

            case StampyJobType.CreateService:
                job = new ServiceCreationJob(logger, args);
                break;

            case StampyJobType.Build:
                job = new BuildJob(logger, args);
                break;

            case StampyJobType.Deploy:
                job = new DeploymentJob(logger, args);
                break;

            case StampyJobType.Test:
                job = new TestJob(logger, args);
                break;

            case StampyJobType.RemoveResources:
                job = new ScavengerJob(logger, args);
                break;

            default:
                break;
            }

            return(job);
        }
Пример #21
0
 public JobBuilder()
 {
     _job = new TestJob
     {
         Id          = Guid.NewGuid(),
         Description = Guid.NewGuid().ToString()
     };
 }
Пример #22
0
        private void StartTestJob()
        {
            TestJob job = new TestJob();

            job.ProjectConfigFile = this._projectConfigFile;
            job.OnNewMsg         += new TestJob._newMsgDelegate(_monitor.AddLog);
            job.StartTesting();
        }
 public void ActivateJobCallsSimpleInjector()
 {
     var theJob = new TestJob();
     container.RegisterSingle<TestJob>(theJob);
     var activator = new SimpleInjectorJobActivator(container);
     var result = activator.ActivateJob(typeof(TestJob));
     Assert.AreEqual(theJob, result);
 }
Пример #24
0
        public async Task <bool> DeleteTest(TestJob testJob)
        {
            BatchSharedKeyCredentials credentials = new BatchSharedKeyCredentials(BatchServiceUrl, BatchAccountName, BatchAccountKey);

            using (BatchClient batchClient = await BatchClient.OpenAsync(credentials))
            {
                return(await batchClient.DeleteTest(testJob));
            }
        }
Пример #25
0
    protected JobHandle OnUpdate2(JobHandle inputDeps)
    {
        var job = new TestJob {
            tt = jobTT
        };

        inputDeps = job.Schedule(inputDeps);
        return(inputDeps);
    }
Пример #26
0
    private IEnumerator Start()
    {
        Debug.Log(Time.time);
        tjob = new TestJob();
        tjob.Start();
        yield return(StartCoroutine(tjob.WaitFor()));

        tjob = null;
    }
Пример #27
0
        public void ShouldReturnJobNameWithPrefix()
        {
            var job = new TestJob();

            var result = _target.GetJobName(job);

            result.Should().NotBeNullOrEmpty();
            result.Should().BeEquivalentTo("Job.TestJob");
        }
Пример #28
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="testjob">the testJob to manage</param>
 public TestJobManager(TestJob testjob)
 {
     if (testjob == null)
     {
         throw new ArgumentNullException("testjob");
     }
     TestJob   = testjob;
     WorkItems = new List <WorkItem>();
 }
Пример #29
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            TestJob job      = new TestJob {
            };
            JobHandle handle = job.Schedule(this, inputDeps);

            //handle.Complete();
            //Debug.LogError("Called once!");
            return(handle);
        }
Пример #30
0
        int IBuildTaskService.GetTestJobResult(int testJobId)
        {
            TestJob testjob = _testJobRepository.GetById(testJobId);

            if (testjob == null)
            {
                return((int)TestState.NotAvailable);
            }
            return((int)testjob.ResultCode);
        }
Пример #31
0
        public void ActivateJobCallsSimpleInjector()
        {
            var theJob = new TestJob();

            container.RegisterInstance <TestJob>(theJob);
            var activator = new SimpleInjectorJobActivator(container);
            var result    = activator.ActivateJob(typeof(TestJob));

            Assert.AreEqual(theJob, result);
        }
Пример #32
0
        public void JobBase()
        {
            TestJob job = new TestJob();

            job.OnExecute = () => true;
            Assert.That(job.Execute(), Is.True);

            job.OnExecute = null;
            Assert.That(job.Execute(), Is.False);

            job.OnShouldDeleteJob = (ex) => true;
            Assert.That(job.Execute(), Is.True);
        }
        public void Should_run_every_scheduled_second()
        {
            var container = new WindsorContainer();
            var testJob = new TestJob();
            container.Register(Component.For<TestJob>().Instance(testJob));

            var scheduler = new DefaultSchedulerFactory().UseContainer(() => new WindsorServiceLocator(container)).Create();

            scheduler.Setup(
                Job.Run<TestJob>(x => x.RunJob()).Every(1.Second())
                ).Start();

            Thread.Sleep(TimeSpan.FromSeconds(5));
            scheduler.Stop();

            Assert.That(testJob.TimesCalled, Is.EqualTo(5));

            container.Dispose();
        }
Пример #34
0
            public static void Start()
            {
                var scheduler = StdSchedulerFactory.GetDefaultScheduler();
                scheduler.Start();
                {
                    var job = JobBuilder.Create<TestJob>().Build();
                    var trigger = TriggerBuilder.Create()
                        .StartNow()
                        .WithDailyTimeIntervalSchedule(s => 
                            s.WithIntervalInHours(24)
                            .OnEveryDay()
                            .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(0, 0)))
                        .Build();
                    scheduler.ScheduleJob(job, trigger);
                }
                {
                    var job = JobBuilder.Create<RemindJob>().Build();
                    var trigger = TriggerBuilder.Create()
                        .WithDailyTimeIntervalSchedule(x =>
                            x.OnEveryDay()
                                .WithIntervalInHours(8)
                                .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(5, 30)))
                        .Build();
                    scheduler.ScheduleJob(job, trigger);
                }

                var testJob = new TestJob();
                testJob.Execute(null);
            }
Пример #35
0
        public void TestSpeedJobPreemptsNonSpeedJobs ()
        {
            scheduler = new Scheduler ();
            TestJob a = new TestJob (200, PriorityHints.None, Resource.Cpu);
            TestJob b = new TestJob (200, PriorityHints.None, Resource.Disk);
            TestJob c = new TestJob (200, PriorityHints.LongRunning, Resource.Database);
            scheduler.Add (a);
            scheduler.Add (b);
            scheduler.Add (c);

            // Test that three jobs got started
            AssertJobsRunning (3);

            scheduler.Add (new TestJob (200, PriorityHints.SpeedSensitive, Resource.Cpu, Resource.Disk));

            // Make sure the SpeedSensitive jobs has caused the Cpu and Disk jobs to be paused
            AssertJobsRunning (2);
            Assert.AreEqual (true, a.IsScheduled);
            Assert.AreEqual (true, b.IsScheduled);
            Assert.AreEqual (true, c.IsRunning);
        }