Initial commit

This commit is contained in:
mukmyash
2018-08-24 23:33:51 +05:00
commit 8dbba8c64f
18 changed files with 879 additions and 0 deletions

63
.gitattributes vendored Normal file
View File

@@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain

261
.gitignore vendored Normal file
View File

@@ -0,0 +1,261 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
project.fragment.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
# publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
#*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc

58
QuartzHostedService.sln Normal file
View File

@@ -0,0 +1,58 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26124.0
MinimumVisualStudioVersion = 15.0.26124.0
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{DD437750-ADAF-4565-9B50-959A92A67100}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "QuartzHostedService", "src\QuartzHostedService\QuartzHostedService.csproj", "{08939639-5650-4141-9CC7-9B2956701488}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{EDF98575-67B2-4C80-87FC-051AAF2A9E8A}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "QuartzHostedService.Test", "test\QuartzHostedService.Test\QuartzHostedService.Test.csproj", "{B6BE5ED4-B7F3-48C3-8374-8B479F40F5F2}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{08939639-5650-4141-9CC7-9B2956701488}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{08939639-5650-4141-9CC7-9B2956701488}.Debug|Any CPU.Build.0 = Debug|Any CPU
{08939639-5650-4141-9CC7-9B2956701488}.Debug|x64.ActiveCfg = Debug|Any CPU
{08939639-5650-4141-9CC7-9B2956701488}.Debug|x64.Build.0 = Debug|Any CPU
{08939639-5650-4141-9CC7-9B2956701488}.Debug|x86.ActiveCfg = Debug|Any CPU
{08939639-5650-4141-9CC7-9B2956701488}.Debug|x86.Build.0 = Debug|Any CPU
{08939639-5650-4141-9CC7-9B2956701488}.Release|Any CPU.ActiveCfg = Release|Any CPU
{08939639-5650-4141-9CC7-9B2956701488}.Release|Any CPU.Build.0 = Release|Any CPU
{08939639-5650-4141-9CC7-9B2956701488}.Release|x64.ActiveCfg = Release|Any CPU
{08939639-5650-4141-9CC7-9B2956701488}.Release|x64.Build.0 = Release|Any CPU
{08939639-5650-4141-9CC7-9B2956701488}.Release|x86.ActiveCfg = Release|Any CPU
{08939639-5650-4141-9CC7-9B2956701488}.Release|x86.Build.0 = Release|Any CPU
{B6BE5ED4-B7F3-48C3-8374-8B479F40F5F2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B6BE5ED4-B7F3-48C3-8374-8B479F40F5F2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B6BE5ED4-B7F3-48C3-8374-8B479F40F5F2}.Debug|x64.ActiveCfg = Debug|Any CPU
{B6BE5ED4-B7F3-48C3-8374-8B479F40F5F2}.Debug|x64.Build.0 = Debug|Any CPU
{B6BE5ED4-B7F3-48C3-8374-8B479F40F5F2}.Debug|x86.ActiveCfg = Debug|Any CPU
{B6BE5ED4-B7F3-48C3-8374-8B479F40F5F2}.Debug|x86.Build.0 = Debug|Any CPU
{B6BE5ED4-B7F3-48C3-8374-8B479F40F5F2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B6BE5ED4-B7F3-48C3-8374-8B479F40F5F2}.Release|Any CPU.Build.0 = Release|Any CPU
{B6BE5ED4-B7F3-48C3-8374-8B479F40F5F2}.Release|x64.ActiveCfg = Release|Any CPU
{B6BE5ED4-B7F3-48C3-8374-8B479F40F5F2}.Release|x64.Build.0 = Release|Any CPU
{B6BE5ED4-B7F3-48C3-8374-8B479F40F5F2}.Release|x86.ActiveCfg = Release|Any CPU
{B6BE5ED4-B7F3-48C3-8374-8B479F40F5F2}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{08939639-5650-4141-9CC7-9B2956701488} = {DD437750-ADAF-4565-9B50-959A92A67100}
{B6BE5ED4-B7F3-48C3-8374-8B479F40F5F2} = {EDF98575-67B2-4C80-87FC-051AAF2A9E8A}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C92A5047-9DD9-4F11-9FEE-F1AB1679F94F}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,3 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("QuartzHostedService.Test")]

View File

@@ -0,0 +1,9 @@
using Microsoft.Extensions.DependencyInjection;
namespace QuartzHostedService
{
public interface IJobRegistrator
{
IServiceCollection Services { get; }
}
}

View File

@@ -0,0 +1,56 @@
using Microsoft.Extensions.DependencyInjection;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QuartzHostedService
{
public static class IJobRegistratorExtensions
{
public static IJobRegistrator RegiserCRONJob<TJob>(
this IJobRegistrator jobRegistrator,
Action<JobOptions> jobOptions)
where TJob : class, IJob
{
var options = new JobOptions();
jobOptions?.Invoke(options);
return jobRegistrator.RegiserJob<TJob>(
options.Triggers?.Select(n => n.CreateTriggerBuilder())
);
}
public static IJobRegistrator RegiserJob<TJob>(
this IJobRegistrator jobRegistrator,
Func<IEnumerable<TriggerBuilder>> triggers)
where TJob : class, IJob
{
return jobRegistrator.RegiserJob<TJob>(triggers());
}
public static IJobRegistrator RegiserJob<TJob>(
this IJobRegistrator jobRegistrator,
IEnumerable<TriggerBuilder> triggerBuilders)
where TJob : class, IJob
{
jobRegistrator.Services.AddTransient<TJob>();
var jobDetail = JobBuilder.Create<TJob>().Build();
List<ITrigger> triggers = new List<ITrigger>(triggerBuilders.Count());
foreach (var triggerBuilder in triggerBuilders)
{
triggers.Add(triggerBuilder.ForJob(jobDetail).Build());
}
jobRegistrator.Services.AddSingleton<IScheduleJob>(provider => new ScheduleJob(jobDetail, triggers));
return jobRegistrator;
}
}
}

View File

@@ -0,0 +1,11 @@
using System.Collections.Generic;
using Quartz;
namespace QuartzHostedService
{
internal interface IScheduleJob
{
IJobDetail JobDetail { get; set; }
IEnumerable<ITrigger> Triggers { get; set; }
}
}

View File

@@ -0,0 +1,33 @@
using Microsoft.Extensions.DependencyInjection;
using Quartz;
using Quartz.Impl;
using Quartz.Spi;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
namespace QuartzHostedService
{
public static class IServiceCollectionExtensions
{
public static IJobRegistrator UseQuartzHostedService(this IServiceCollection services,
Action<NameValueCollection> stdSchedulerFactoryOptions)
{
services.AddHostedService<QuartzHostedService>();
services.AddTransient<ISchedulerFactory>(provider =>
{
var options = new NameValueCollection();
stdSchedulerFactoryOptions?.Invoke(options);
var result = new StdSchedulerFactory();
if (options.Count > 0)
result.Initialize(options);
return new StdSchedulerFactory();
});
services.AddTransient<IJobFactory, ServiceCollectionJobFactory>();
return new JobRegistrator(services);
}
}
}

View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace QuartzHostedService
{
public class JobOptions
{
public TriggerOptions[] Triggers { get; set; }
}
}

View File

@@ -0,0 +1,17 @@
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
namespace QuartzHostedService
{
internal class JobRegistrator : IJobRegistrator
{
public JobRegistrator(IServiceCollection services)
{
Services = services;
}
public IServiceCollection Services { get; }
}
}

View File

@@ -0,0 +1,64 @@
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Quartz.Impl;
using Quartz;
using Quartz.Spi;
using System.Linq;
namespace QuartzHostedService
{
internal class QuartzHostedService : IHostedService
{
private IServiceProvider Services { get; }
private IScheduler _scheduler;
private ISchedulerFactory _schedulerFactory;
private IJobFactory _jobFactory { get; }
public QuartzHostedService(
IServiceProvider services,
ISchedulerFactory schedulerFactory,
IJobFactory jobFactory)
{
Services = services;
_schedulerFactory = schedulerFactory;
_jobFactory = jobFactory;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
var _scheduleJobs = Services.GetService<IEnumerable<IScheduleJob>>();
_scheduler = await _schedulerFactory.GetScheduler();
_scheduler.JobFactory = _jobFactory;
await _scheduler.Start(cancellationToken);
if (_scheduleJobs == null || !_scheduleJobs.Any())
return;
foreach (var scheduleJob in _scheduleJobs)
{
bool isNewJob = true;
foreach (var trigger in scheduleJob.Triggers)
{
if (isNewJob)
await _scheduler.ScheduleJob(scheduleJob.JobDetail, trigger, cancellationToken);
else
await _scheduler.ScheduleJob(trigger, cancellationToken);
isNewJob = false;
}
}
}
public async Task StopAsync(CancellationToken cancellationToken)
{
if (_scheduler.IsStarted)
await _scheduler.Shutdown(cancellationToken);
}
}
}

View File

@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="2.1.1" />
<PackageReference Include="Quartz" Version="3.0.6" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,18 @@
using Quartz;
using System;
using System.Collections.Generic;
namespace QuartzHostedService
{
internal class ScheduleJob : IScheduleJob
{
public ScheduleJob(IJobDetail jobDetail, IEnumerable<ITrigger> triggers)
{
JobDetail = jobDetail;
Triggers = triggers;
}
public IJobDetail JobDetail { get; set; }
public IEnumerable<ITrigger> Triggers { get; set; }
}
}

View File

@@ -0,0 +1,28 @@
using Quartz;
using Quartz.Spi;
using System;
using System.Collections.Generic;
using System.Text;
namespace QuartzHostedService
{
public class ServiceCollectionJobFactory : IJobFactory
{
protected readonly IServiceProvider Container;
public ServiceCollectionJobFactory(IServiceProvider container)
{
Container = container;
}
public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
return Container.GetService(bundle.JobDetail.JobType) as IJob;
}
public void ReturnJob(IJob job)
{
}
}
}

View File

@@ -0,0 +1,26 @@
using Quartz;
using System;
using System.Collections.Generic;
using System.Text;
namespace QuartzHostedService
{
public class TriggerOptions
{
public string CRONExpression { get; set; }
public int? Priority { get; set; }
public virtual TriggerBuilder CreateTriggerBuilder()
{
var result = TriggerBuilder.Create();
if (Priority.HasValue)
result.WithPriority(Priority.Value);
if(!string.IsNullOrEmpty(CRONExpression))
result.WithCronSchedule(CRONExpression);
return result;
}
}
}

View File

@@ -0,0 +1,75 @@
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Quartz;
using Quartz.Impl;
using Quartz.Spi;
using System;
using Xunit;
namespace QuartzHostedService.Test
{
public class IServiceCollectionExtensionsUnitTest
{
[Fact(DisplayName = "<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> HostedService")]
public void IServiceCollectionExtensions_Register_HostedService()
{
IServiceCollection serviceCollection = new ServiceCollection();
IServiceCollectionExtensions.UseQuartzHostedService(serviceCollection, null);
var testClass = serviceCollection.BuildServiceProvider().GetRequiredService<IHostedService>();
testClass.Should()
.NotBeNull()
.And.BeOfType<QuartzHostedService>();
}
[Fact(DisplayName = "<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> IJobFactory (<28><><EFBFBD> DI <20> Job'<27><>)")]
public void IServiceCollectionExtensions_Register_IJobFactory()
{
IServiceCollection serviceCollection = new ServiceCollection();
IServiceCollectionExtensions.UseQuartzHostedService(serviceCollection, null);
var testClass = serviceCollection.BuildServiceProvider().GetRequiredService<IJobFactory>();
testClass.Should()
.NotBeNull()
.And.BeOfType<ServiceCollectionJobFactory>();
}
[Fact(DisplayName = "<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> ISchedulerFactory (<28><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>)")]
public void IServiceCollectionExtensions_Register_ISchedulerFactory()
{
IServiceCollection serviceCollection = new ServiceCollection();
IServiceCollectionExtensions.UseQuartzHostedService(serviceCollection, null);
var testClass = serviceCollection.BuildServiceProvider().GetRequiredService<ISchedulerFactory>();
testClass.Should()
.NotBeNull()
.And.BeOfType<StdSchedulerFactory>();
}
[Fact(DisplayName = "<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> ISchedulerFactory (<28><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>)")]
public void IServiceCollectionExtensions_Register_ISchedulerFactory_WithParams()
{
IServiceCollection serviceCollection = new ServiceCollection();
IServiceCollectionExtensions.UseQuartzHostedService(serviceCollection, options => { options.Add("quartz.threadPool.threadCount", "1"); });
// TODO: <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
var testClass = serviceCollection.BuildServiceProvider().GetRequiredService<ISchedulerFactory>();
testClass.Should()
.NotBeNull()
.And.BeOfType<StdSchedulerFactory>();
}
[Fact(DisplayName = "<22><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> IJobRegistrator")]
public void IServiceCollectionExtensions_Return_IJobRegistrator()
{
IServiceCollection serviceCollection = new ServiceCollection();
var result = IServiceCollectionExtensions.UseQuartzHostedService(serviceCollection, null);
result.Should()
.NotBeNull()
.And.BeAssignableTo<IJobRegistrator>()
.Subject.Services.Should().Equal(serviceCollection);
}
}
}

View File

@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FakeItEasy" Version="4.0.0" />
<PackageReference Include="FluentAssertions" Version="5.3.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.1.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.8.0" />
<PackageReference Include="xunit" Version="2.4.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
<DotNetCliToolReference Include="dotnet-xunit" Version="2.3.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\QuartzHostedService\QuartzHostedService.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,111 @@
using FakeItEasy;
using Quartz;
using Quartz.Spi;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace QuartzHostedService.Test
{
public class QuartzHostedServiceUnitTest
{
[Fact(DisplayName = "Устанавливаем JobFactory (Для DI)")]
public async void IServiceCollectionExtensions_Register_HostedService()
{
IServiceProvider serviceProvider = A.Fake<IServiceProvider>();
A.CallTo(() => serviceProvider.GetService(typeof(IEnumerable<IScheduleJob>))).Returns(null);
ISchedulerFactory schedulerFactory = A.Fake<ISchedulerFactory>();
IScheduler scheduler = A.Fake<IScheduler>();
A.CallTo(() => schedulerFactory.GetScheduler(A<CancellationToken>.Ignored))
.Returns(Task.FromResult(scheduler));
IJobFactory jobFactory = A.Fake<IJobFactory>();
var testClass = new QuartzHostedService(serviceProvider, schedulerFactory, jobFactory);
await testClass.StartAsync(CancellationToken.None);
A.CallTo(scheduler)
.Where(a => a.Method.Name.Equals("set_JobFactory"));
}
[Fact(DisplayName = "Запустили все зарегистрированые Job")]
public async void IServiceCollectionExtensions_Register_RegisterJob()
{
// Зарегистрированные джобы
var scheduleJobc = new List<IScheduleJob>();
var jobDetail1 = A.Fake<IJobDetail>();
var jobDetail2 = A.Fake<IJobDetail>();
var jobDetail3 = A.Fake<IJobDetail>();
scheduleJobc.Add(new ScheduleJob(jobDetail1, new List<ITrigger>() { A.Fake<ITrigger>() }));
scheduleJobc.Add(new ScheduleJob(jobDetail2, new List<ITrigger>() { A.Fake<ITrigger>() }));
scheduleJobc.Add(new ScheduleJob(jobDetail3, new List<ITrigger>() { A.Fake<ITrigger>() }));
IServiceProvider serviceProvider = A.Fake<IServiceProvider>();
A.CallTo(() => serviceProvider.GetService(typeof(IEnumerable<IScheduleJob>))).Returns(scheduleJobc);
ISchedulerFactory schedulerFactory = A.Fake<ISchedulerFactory>();
IScheduler scheduler = A.Fake<IScheduler>();
A.CallTo(() => schedulerFactory.GetScheduler(A<CancellationToken>.Ignored))
.Returns(Task.FromResult(scheduler));
IJobFactory jobFactory = A.Fake<IJobFactory>();
var testClass = new QuartzHostedService(serviceProvider, schedulerFactory, jobFactory);
await testClass.StartAsync(CancellationToken.None);
A.CallTo(
() => scheduler.ScheduleJob(
A<IJobDetail>.That.Matches(jd => jd == jobDetail1 || jd == jobDetail2 || jd == jobDetail3),
A<ITrigger>.Ignored,
A<CancellationToken>.Ignored))
.MustHaveHappened(Repeated.Like(count => count == 3));
}
[Fact(DisplayName = "Запустили все зарегистрированые Job с указанными ITrigger")]
public async void IServiceCollectionExtensions_Register_RegisterJob_ITrigger()
{
// Зарегистрированные джобы
var scheduleJobc = new List<IScheduleJob>();
var jobDetail1 = A.Fake<IJobDetail>();
var trigger1 = A.Fake<ITrigger>();
var trigger2 = A.Fake<ITrigger>();
var trigger3 = A.Fake<ITrigger>();
scheduleJobc.Add(new ScheduleJob(jobDetail1, new List<ITrigger>() { trigger1, trigger2, trigger3 }));
IServiceProvider serviceProvider = A.Fake<IServiceProvider>();
A.CallTo(() => serviceProvider.GetService(typeof(IEnumerable<IScheduleJob>))).Returns(scheduleJobc);
ISchedulerFactory schedulerFactory = A.Fake<ISchedulerFactory>();
IScheduler scheduler = A.Fake<IScheduler>();
A.CallTo(() => schedulerFactory.GetScheduler(A<CancellationToken>.Ignored))
.Returns(Task.FromResult(scheduler));
IJobFactory jobFactory = A.Fake<IJobFactory>();
var testClass = new QuartzHostedService(serviceProvider, schedulerFactory, jobFactory);
await testClass.StartAsync(CancellationToken.None);
A.CallTo(
() => scheduler.ScheduleJob(
A<IJobDetail>.That.Matches(jd => jd == jobDetail1),
A<ITrigger>.That.Matches(t => t == trigger1),
A<CancellationToken>.Ignored))
.MustHaveHappened(Repeated.Exactly.Once);
A.CallTo(
() => scheduler.ScheduleJob(
A<ITrigger>.That.Matches(t => t == trigger2 || t == trigger3),
A<CancellationToken>.Ignored))
.MustHaveHappened(Repeated.Exactly.Twice);
}
}
}