public void GetJobData_ReturnsResult_WhenJobExists()
        {
            var job = Job.FromExpression(() => HangfireTestJobs.SampleMethod("wrong"));

            var jobDto = new JobDto
            {
                Id             = Guid.NewGuid().ToString(),
                InvocationData = SerializationHelper.Serialize(InvocationData.SerializeJob(job)),
                Arguments      = "[\"\\\"Arguments\\\"\"]",
                StateName      = SucceededState.StateName,
                Created        = DateTime.UtcNow
            };
            var realm = _storage.GetRealm();

            realm.Write(() => { realm.Add(jobDto); });

            var result = _connection.GetJobData(jobDto.Id.ToString());

            Assert.NotNull(result);
            Assert.NotNull(result.Job);
            Assert.AreEqual(SucceededState.StateName, result.State);
            Assert.AreEqual("Arguments", result.Job.Args[0]);
            Assert.Null(result.LoadException);
            Assert.True(DateTime.UtcNow.AddMinutes(-1) < result.CreatedAt);
            Assert.True(result.CreatedAt < DateTime.UtcNow.AddMinutes(1));
        }
        public void GetJobData_ReturnsResult_WhenJobExists()
        {
            var job = Job.FromExpression(() => HangfireTestJobs.SampleMethod("wrong"));

            var jobDto = new JobDto
            {
                Id             = ObjectId.GenerateNewId(),
                InvocationData = JobHelper.ToJson(InvocationData.Serialize(job)),
                Arguments      = "[\"\\\"Arguments\\\"\"]",
                StateName      = SucceededState.StateName,
                CreatedAt      = DateTime.UtcNow
            };

            _dbContext.JobGraph.InsertOne(jobDto);

            var result = _connection.GetJobData(jobDto.Id.ToString());

            Assert.NotNull(result);
            Assert.NotNull(result.Job);
            Assert.Equal(SucceededState.StateName, result.State);
            Assert.Equal("Arguments", result.Job.Args[0]);
            Assert.Null(result.LoadException);
            Assert.True(DateTime.UtcNow.AddMinutes(-1) < result.CreatedAt);
            Assert.True(result.CreatedAt < DateTime.UtcNow.AddMinutes(1));
        }
        public void CreateExpiredJob_ThrowsAnException_WhenParametersCollectionIsNull()
        {
            var exception = Assert.Throws <ArgumentNullException>(
                () => _connection.CreateExpiredJob(
                    Job.FromExpression(() => HangfireTestJobs.SampleMethod("hello")),
                    null,
                    DateTime.UtcNow,
                    TimeSpan.Zero));

            Assert.Equal("parameters", exception.ParamName);
        }
        public void CreateExpiredJob_CreatesAJobInTheStorage_AndSetsItsParameters()
        {
            var createdAt = new DateTime(2012, 12, 12, 0, 0, 0, 0, DateTimeKind.Utc);
            var jobId     = _connection.CreateExpiredJob(
                Job.FromExpression(() => HangfireTestJobs.SampleMethod("Hello")),
                new Dictionary <string, string> {
                { "Key1", "Value1" }, { "Key2", "Value2" }
            },
                createdAt,
                TimeSpan.FromDays(1));

            Assert.NotNull(jobId);
            Assert.NotEmpty(jobId);

            var databaseJob = _dbContext.JobGraph.OfType <JobDto>().Find(new BsonDocument()).ToList().Single();

            Assert.Equal(jobId, databaseJob.Id.ToString());
            Assert.Equal(createdAt, databaseJob.CreatedAt);
            Assert.Null(databaseJob.StateName);

            var invocationData = JobHelper.FromJson <InvocationData>(databaseJob.InvocationData);

            invocationData.Arguments = databaseJob.Arguments;

            var job = invocationData.Deserialize();

            Assert.Equal(typeof(HangfireTestJobs), job.Type);
            Assert.Equal(nameof(HangfireTestJobs.SampleMethod), job.Method.Name);
            Assert.Equal("Hello", job.Args[0]);

            Assert.True(createdAt.AddDays(1).AddMinutes(-1) < databaseJob.ExpireAt);
            Assert.True(databaseJob.ExpireAt < createdAt.AddDays(1).AddMinutes(1));

            var parameters = _dbContext
                             .JobGraph.OfType <JobDto>()
                             .Find(Builders <JobDto> .Filter.Eq(_ => _.Id, ObjectId.Parse(jobId)))
                             .Project(j => j.Parameters)
                             .ToList()
                             .SelectMany(j => j)
                             .ToDictionary(p => p.Key, x => x.Value);

            Assert.NotNull(parameters);
            Assert.Equal("Value1", parameters["Key1"]);
            Assert.Equal("Value2", parameters["Key2"]);
        }
        public void CreateExpiredJob_CreatesAJobInTheStorage_AndSetsItsParameters()
        {
            var createdAt = new DateTime(2012, 12, 12, 0, 0, 0, 0, DateTimeKind.Utc);
            var jobId     = _connection.CreateExpiredJob(
                Job.FromExpression(() => HangfireTestJobs.SampleMethod("Hello")),
                new Dictionary <string, string> {
                { "Key1", "Value1" }, { "Key2", "Value2" }
            },
                createdAt,
                TimeSpan.FromDays(1));
            var realm = _storage.GetRealm();

            Assert.NotNull(jobId);
            Assert.IsNotEmpty(jobId);

            var databaseJob = realm.Find <JobDto>(jobId);

            Assert.AreEqual(jobId, databaseJob.Id.ToString());
            Assert.AreEqual(createdAt, databaseJob.Created.DateTime);
            Assert.Null(databaseJob.StateName);

            var invocationData = SerializationHelper.Deserialize <InvocationData>(databaseJob.InvocationData);

            invocationData.Arguments = databaseJob.Arguments;

            var job = invocationData.DeserializeJob();

            Assert.AreEqual(typeof(HangfireTestJobs), job.Type);
            Assert.AreEqual(nameof(HangfireTestJobs.SampleMethod), job.Method.Name);
            Assert.AreEqual("Hello", job.Args[0]);

            Assert.True(createdAt.AddDays(1).AddMinutes(-1) < databaseJob.ExpireAt);
            Assert.True(databaseJob.ExpireAt < createdAt.AddDays(1).AddMinutes(1));

            var parameters = realm.Find <JobDto>(jobId).Parameters;
            Dictionary <string, string> paramDictionary = parameters.ToDictionary(_ => _.Key, _ => _.Value);

            Assert.NotNull(parameters);
            Assert.AreEqual("Value1", paramDictionary["Key1"]);
            Assert.AreEqual("Value2", paramDictionary["Key2"]);
        }
Exemplo n.º 6
0
        public void Clean_Database_Filled()
        {
            var connectionString = "mongodb://localhost";
            var databaseName     = "Mongo-Hangfire-Filled";

            // Make sure we start from scratch
            using (HangfireDbContext context = new HangfireDbContext(connectionString, databaseName))
            {
                context.Database.Client.DropDatabase(databaseName);
            }

            var storageOptions = new MongoStorageOptions
            {
                MigrationOptions = new MongoMigrationOptions
                {
                    Strategy       = MongoMigrationStrategy.None,
                    BackupStrategy = MongoBackupStrategy.None
                },
                QueuePollInterval = TimeSpan.FromMilliseconds(500)
            };
            var serverOptions = new BackgroundJobServerOptions
            {
                ShutdownTimeout = TimeSpan.FromSeconds(15)
            };

            JobStorage.Current = new MongoStorage(connectionString, databaseName, storageOptions);

            using (new BackgroundJobServer(serverOptions))
            {
                // Recurring Job
                RecurringJob.AddOrUpdate(() => HangfireTestJobs.ExecuteRecurringJob("Recurring job"), Cron.Minutely);

                // Scheduled job
                BackgroundJob.Schedule(() => HangfireTestJobs.ExecuteScheduledJob("Scheduled job"), TimeSpan.FromSeconds(30));

                // Enqueued job
                BackgroundJob.Enqueue(() => HangfireTestJobs.ExecuteEnqueuedJob("Enqueued job"));

                // Continued job
                var parentId = BackgroundJob.Schedule(() => HangfireTestJobs.ExecuteContinueWithJob("ContinueWith job", false), TimeSpan.FromSeconds(15));
                BackgroundJob.ContinueWith(parentId, () => HangfireTestJobs.ExecuteContinueWithJob("ContinueWith job continued", true));

                // Now the waiting game starts
                HangfireTestJobs.ScheduleEvent.WaitOne();
                BackgroundJob.Schedule(() => HangfireTestJobs.ExecuteScheduledJob("Scheduled job (*)"), TimeSpan.FromMinutes(30));

                HangfireTestJobs.ContinueWithEvent.WaitOne();
                HangfireTestJobs.RecurringEvent.WaitOne();

                HangfireTestJobs.EnqueueEvent.WaitOne();
                BackgroundJob.Enqueue(() => HangfireTestJobs.ExecuteEnqueuedJob("Enqueued job (*)"));
            }


            // Some data are cleaned up when hangfire shuts down.
            // Grab a copy so we can write it back - needed for migration tests.
            var connection = JobStorage.Current.GetConnection();

            connection.AnnounceServer("test-server", new ServerContext
            {
                WorkerCount = serverOptions.WorkerCount,
                Queues      = serverOptions.Queues
            });

            connection.AcquireDistributedLock("test-lock", TimeSpan.FromSeconds(30));

            // Create database snapshot in zip file
            var schemaVersion = (int)MongoMigrationManager.RequiredSchemaVersion;

            using (var stream = new FileStream($@"Hangfire-Mongo-Schema-{schemaVersion:000}.zip", FileMode.Create))
            {
                var allowedEmptyCollections = new List <string>();

                if (MongoMigrationManager.RequiredSchemaVersion >= MongoSchema.Version09 &&
                    MongoMigrationManager.RequiredSchemaVersion <= MongoSchema.Version13)
                {
                    // Signal collection work was initiated in schema version 9,
                    // and still not put to use in schema version 13.
                    allowedEmptyCollections.Add($@"{storageOptions.Prefix}.signal");
                }
                BackupDatabaseToStream(connectionString, databaseName, stream, allowedEmptyCollections.ToArray());
            }
        }
        private JobDto CreateJobInState(HangfireDbContext database, ObjectId jobId, string stateName, Func <JobDto, JobDto> visitor = null)
        {
            var job = Job.FromExpression(() => HangfireTestJobs.SampleMethod("wrong"));

            Dictionary <string, string> stateData;

            if (stateName == EnqueuedState.StateName)
            {
                stateData = new Dictionary <string, string> {
                    ["EnqueuedAt"] = $"{DateTime.UtcNow:o}"
                };
            }
            else if (stateName == ProcessingState.StateName)
            {
                stateData = new Dictionary <string, string>
                {
                    ["ServerId"]  = Guid.NewGuid().ToString(),
                    ["StartedAt"] = JobHelper.SerializeDateTime(DateTime.UtcNow.Subtract(TimeSpan.FromMilliseconds(500)))
                };
            }
            else if (stateName == FailedState.StateName)
            {
                stateData = new Dictionary <string, string>
                {
                    ["ExceptionDetails"] = "Test_ExceptionDetails",
                    ["ExceptionMessage"] = "Test_ExceptionMessage",
                    ["ExceptionType"]    = "Test_ExceptionType",
                    ["FailedAt"]         = JobHelper.SerializeDateTime(DateTime.UtcNow.Subtract(TimeSpan.FromMilliseconds(10)))
                };
            }
            else
            {
                stateData = new Dictionary <string, string>();
            }

            var jobState = new StateDto()
            {
                Name      = stateName,
                Reason    = null,
                CreatedAt = DateTime.UtcNow,
                Data      = stateData
            };

            var jobDto = new JobDto
            {
                Id             = jobId,
                InvocationData = JobHelper.ToJson(InvocationData.Serialize(job)),
                Arguments      = "[\"\\\"Arguments\\\"\"]",
                StateName      = stateName,
                CreatedAt      = DateTime.UtcNow,
                StateHistory   = new[] { jobState }
            };

            if (visitor != null)
            {
                jobDto = visitor(jobDto);
            }
            database.Job.InsertOne(jobDto);

            var jobQueueDto = new JobQueueDto
            {
                FetchedAt = null,
                JobId     = jobId,
                Queue     = DefaultQueue
            };

            if (stateName == FetchedStateName)
            {
                jobQueueDto.FetchedAt = DateTime.UtcNow;
            }

            database.JobQueue.InsertOne(jobQueueDto);

            return(jobDto);
        }
        private JobDto CreateJobInState(string stateName, DateTime created = default(DateTime), Action <JobDto> visitor = null)
        {
            var job = Common.Job.FromExpression(() => HangfireTestJobs.SampleMethod("wrong"));

            if (created == default(DateTime))
            {
                created = DateTime.Now;
            }

            Dictionary <string, string> stateData;

            if (stateName == EnqueuedState.StateName)
            {
                stateData = new Dictionary <string, string> {
                    ["EnqueuedAt"] = $"{DateTime.UtcNow:o}"
                };
            }
            else if (stateName == ProcessingState.StateName)
            {
                stateData = new Dictionary <string, string>
                {
                    ["ServerId"]  = Guid.NewGuid().ToString(),
                    ["StartedAt"] = JobHelper.SerializeDateTime(DateTime.UtcNow.Subtract(TimeSpan.FromMilliseconds(500)))
                };
            }
            else if (stateName == FailedState.StateName)
            {
                stateData = new Dictionary <string, string>
                {
                    ["ExceptionDetails"] = "Test_ExceptionDetails",
                    ["ExceptionMessage"] = "Test_ExceptionMessage",
                    ["ExceptionType"]    = "Test_ExceptionType",
                    ["FailedAt"]         = JobHelper.SerializeDateTime(DateTime.UtcNow.Subtract(TimeSpan.FromMilliseconds(10)))
                };
            }
            else
            {
                stateData = new Dictionary <string, string>();
            }

            var jobState = new StateDto()
            {
                Name   = stateName,
                Reason = null
            };

            foreach (var item in stateData)
            {
                jobState.Data.Add(new StateDataDto(item));
            }

            var jobDto = new JobDto
            {
                Id             = Guid.NewGuid().ToString(),
                Created        = created,
                InvocationData = SerializationHelper.Serialize(InvocationData.SerializeJob(job)),
                Arguments      = "[\"\\\"Arguments\\\"\"]",
                StateName      = stateName
            };

            jobDto.StateHistory.Add(jobState);

            visitor?.Invoke(jobDto);

            _realm.Write(() => _realm.Add(jobDto));

            var jobQueueDto = new JobQueueDto
            {
                Id        = Guid.NewGuid().ToString(),
                FetchedAt = null,
                JobId     = jobDto.Id,
                Queue     = DefaultQueue
            };

            if (stateName == FetchedStateName)
            {
                jobQueueDto.FetchedAt = DateTime.UtcNow;
            }
            _realm.Write(() => _realm.Add(jobQueueDto));

            return(jobDto);
        }