Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
C
CAP
Project
Project
Details
Activity
Releases
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
tsai
CAP
Commits
3c2f51e8
Commit
3c2f51e8
authored
Jun 28, 2017
by
yangxiaodong
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Add unit test
parent
d477e602
Changes
14
Hide whitespace changes
Inline
Side-by-side
Showing
14 changed files
with
734 additions
and
306 deletions
+734
-306
ConnectionUtil.cs
...DotNetCore.CAP.EntityFrameworkCore.Test/ConnectionUtil.cs
+46
-0
DatabaseTestHost.cs
...tNetCore.CAP.EntityFrameworkCore.Test/DatabaseTestHost.cs
+61
-0
DbUtil.cs
test/DotNetCore.CAP.EntityFrameworkCore.Test/DbUtil.cs
+1
-1
DefaultPocoTest.cs
...otNetCore.CAP.EntityFrameworkCore.Test/DefaultPocoTest.cs
+57
-55
DotNetCore.CAP.EntityFrameworkCore.Test.csproj
...kCore.Test/DotNetCore.CAP.EntityFrameworkCore.Test.csproj
+1
-0
EnsuranceTest.cs
.../DotNetCore.CAP.EntityFrameworkCore.Test/EnsuranceTest.cs
+12
-0
MessageStoreTest.cs
...tNetCore.CAP.EntityFrameworkCore.Test/MessageStoreTest.cs
+104
-89
MessageStoreWithGenericsTest.cs
....EntityFrameworkCore.Test/MessageStoreWithGenericsTest.cs
+0
-62
TestHost.cs
test/DotNetCore.CAP.EntityFrameworkCore.Test/TestHost.cs
+97
-0
config.json
test/DotNetCore.CAP.EntityFrameworkCore.Test/config.json
+1
-1
DotNetCore.CAP.Test.csproj
test/DotNetCore.CAP.Test/DotNetCore.CAP.Test.csproj
+0
-4
ComputedJobTest.cs
test/DotNetCore.CAP.Test/Job/ComputedJobTest.cs
+56
-0
JobProcessingServerTest.cs
test/DotNetCore.CAP.Test/Job/JobProcessingServerTest.cs
+185
-0
MessageManagerTestBase.cs
test/Shared/MessageManagerTestBase.cs
+113
-94
No files found.
test/DotNetCore.CAP.EntityFrameworkCore.Test/ConnectionUtil.cs
0 → 100644
View file @
3c2f51e8
using
System
;
using
System.Data.SqlClient
;
namespace
DotNetCore.CAP.EntityFrameworkCore.Test
{
public
static
class
ConnectionUtil
{
private
const
string
DatabaseVariable
=
"Cap_SqlServer_DatabaseName"
;
private
const
string
ConnectionStringTemplateVariable
=
"Cap_SqlServer_ConnectionStringTemplate"
;
private
const
string
MasterDatabaseName
=
"master"
;
private
const
string
DefaultDatabaseName
=
@"DotNetCore.CAP.EntityFrameworkCore.Test"
;
private
const
string
DefaultConnectionStringTemplate
=
@"Server=.\sqlexpress;Database={0};Trusted_Connection=True;"
;
public
static
string
GetDatabaseName
()
{
return
Environment
.
GetEnvironmentVariable
(
DatabaseVariable
)
??
DefaultDatabaseName
;
}
public
static
string
GetMasterConnectionString
()
{
return
string
.
Format
(
GetConnectionStringTemplate
(),
MasterDatabaseName
);
}
public
static
string
GetConnectionString
()
{
return
string
.
Format
(
GetConnectionStringTemplate
(),
GetDatabaseName
());
}
private
static
string
GetConnectionStringTemplate
()
{
return
Environment
.
GetEnvironmentVariable
(
ConnectionStringTemplateVariable
)
??
DefaultConnectionStringTemplate
;
}
public
static
SqlConnection
CreateConnection
(
string
connectionString
=
null
)
{
connectionString
=
connectionString
??
GetConnectionString
();
var
connection
=
new
SqlConnection
(
connectionString
);
connection
.
Open
();
return
connection
;
}
}
}
test/DotNetCore.CAP.EntityFrameworkCore.Test/DatabaseTestHost.cs
0 → 100644
View file @
3c2f51e8
using
System.Data
;
using
Dapper
;
using
Microsoft.EntityFrameworkCore
;
namespace
DotNetCore.CAP.EntityFrameworkCore.Test
{
public
abstract
class
DatabaseTestHost
:
TestHost
{
private
static
bool
_sqlObjectInstalled
;
protected
override
void
PostBuildServices
()
{
base
.
PostBuildServices
();
InitializeDatabase
();
}
public
override
void
Dispose
()
{
DeleteAllData
();
base
.
Dispose
();
}
private
void
InitializeDatabase
()
{
if
(!
_sqlObjectInstalled
)
{
using
(
CreateScope
())
{
var
context
=
GetService
<
CapDbContext
>();
context
.
Database
.
EnsureDeleted
();
context
.
Database
.
Migrate
();
_sqlObjectInstalled
=
true
;
}
}
}
private
void
DeleteAllData
()
{
using
(
CreateScope
())
{
var
context
=
GetService
<
CapDbContext
>();
var
commands
=
new
[]
{
"DISABLE TRIGGER ALL ON ?"
,
"ALTER TABLE ? NOCHECK CONSTRAINT ALL"
,
"DELETE FROM ?"
,
"ALTER TABLE ? CHECK CONSTRAINT ALL"
,
"ENABLE TRIGGER ALL ON ?"
};
foreach
(
var
command
in
commands
)
{
context
.
Database
.
GetDbConnection
().
Execute
(
"sp_MSforeachtable"
,
new
{
command1
=
command
},
commandType
:
CommandType
.
StoredProcedure
);
}
}
}
}
}
test/DotNetCore.CAP.EntityFrameworkCore.Test/DbUtil.cs
View file @
3c2f51e8
...
...
@@ -7,7 +7,7 @@ namespace DotNetCore.CAP.EntityFrameworkCore.Test
public
static
class
DbUtil
{
public
static
IServiceCollection
ConfigureDbServices
(
string
connectionString
,
IServiceCollection
services
=
null
)
{
return
ConfigureDbServices
<
C
onsistency
DbContext
>(
connectionString
,
services
);
return
ConfigureDbServices
<
C
ap
DbContext
>(
connectionString
,
services
);
}
public
static
IServiceCollection
ConfigureDbServices
<
TContext
>(
string
connectionString
,
IServiceCollection
services
=
null
)
where
TContext
:
DbContext
{
...
...
test/DotNetCore.CAP.EntityFrameworkCore.Test/DefaultPocoTest.cs
View file @
3c2f51e8
//using System.Threading.Tasks;
//using DotNetCore.CAP.Infrastructure;
//using DotNetCore.CAP.Store;
//using Microsoft.AspNetCore.Builder.Internal;
//using Microsoft.AspNetCore.Testing.xunit;
//using Microsoft.EntityFrameworkCore;
//using Microsoft.Extensions.DependencyInjection;
//using Xunit;
//namespace DotNetCore.CAP.EntityFrameworkCore.Test
//{
// public class DefaultPocoTest : IClassFixture<ScratchDatabaseFixture>
// {
// private readonly ApplicationBuilder _builder;
// public DefaultPocoTest(ScratchDatabaseFixture fixture) {
// var services = new ServiceCollection();
// services
// .AddDbContext<ConsistencyDbContext>(o => o.UseSqlServer(fixture.ConnectionString))
// .AddConsistency()
// .AddEntityFrameworkStores<ConsistencyDbContext>();
// services.AddLogging();
// var provider = services.BuildServiceProvider();
// _builder = new ApplicationBuilder(provider);
// using (var scoped = provider.GetRequiredService<IServiceScopeFactory>().CreateScope())
// using (var db = scoped.ServiceProvider.GetRequiredService<ConsistencyDbContext>()) {
// db.Database.EnsureCreated();
// }
// }
// [ConditionalFact]
// [FrameworkSkipCondition(RuntimeFrameworks.Mono)]
// [OSSkipCondition(OperatingSystems.Linux)]
// [OSSkipCondition(OperatingSystems.MacOSX)]
// public async Task EnsureStartupUsageWorks() {
// var messageStore = _builder.ApplicationServices.GetRequiredService<IConsistencyMessageStore>();
// var messageManager = _builder.ApplicationServices.GetRequiredService<IConsistencyMessageStore >();
// Assert.NotNull(messageStore);
// Assert.NotNull(messageManager);
// var user = new ConsistencyMessage();
// var operateResult = await messageManager.CreateAsync(user);
// Assert.True(operateResult.Succeeded);
// operateResult = await messageManager.DeleteAsync(user);
// Assert.True(operateResult.Succeeded);
// }
// }
//}
\ No newline at end of file
using
System.Threading.Tasks
;
using
DotNetCore.CAP.Infrastructure
;
using
Microsoft.AspNetCore.Builder.Internal
;
using
Microsoft.AspNetCore.Testing.xunit
;
using
Microsoft.EntityFrameworkCore
;
using
Microsoft.Extensions.DependencyInjection
;
using
Xunit
;
namespace
DotNetCore.CAP.EntityFrameworkCore.Test
{
public
class
DefaultPocoTest
:
IClassFixture
<
ScratchDatabaseFixture
>
{
private
readonly
ApplicationBuilder
_builder
;
public
DefaultPocoTest
(
ScratchDatabaseFixture
fixture
)
{
var
services
=
new
ServiceCollection
();
services
.
AddDbContext
<
CapDbContext
>(
o
=>
o
.
UseSqlServer
(
fixture
.
ConnectionString
))
.
AddConsistency
()
.
AddEntityFrameworkStores
<
CapDbContext
>();
services
.
AddLogging
();
var
provider
=
services
.
BuildServiceProvider
();
_builder
=
new
ApplicationBuilder
(
provider
);
using
(
var
scoped
=
provider
.
GetRequiredService
<
IServiceScopeFactory
>().
CreateScope
())
using
(
var
db
=
scoped
.
ServiceProvider
.
GetRequiredService
<
CapDbContext
>())
{
db
.
Database
.
EnsureCreated
();
}
}
[
ConditionalFact
]
[
FrameworkSkipCondition
(
RuntimeFrameworks
.
Mono
)]
[
OSSkipCondition
(
OperatingSystems
.
Linux
)]
[
OSSkipCondition
(
OperatingSystems
.
MacOSX
)]
public
async
Task
EnsureStartupUsageWorks
()
{
var
messageStore
=
_builder
.
ApplicationServices
.
GetRequiredService
<
ICapMessageStore
>();
var
messageManager
=
_builder
.
ApplicationServices
.
GetRequiredService
<
ICapMessageStore
>();
Assert
.
NotNull
(
messageStore
);
Assert
.
NotNull
(
messageManager
);
var
message
=
new
CapSentMessage
();
var
operateResult
=
await
messageManager
.
StoreSentMessageAsync
(
message
);
Assert
.
True
(
operateResult
.
Succeeded
);
operateResult
=
await
messageManager
.
RemoveSentMessageAsync
(
message
);
Assert
.
True
(
operateResult
.
Succeeded
);
}
}
}
\ No newline at end of file
test/DotNetCore.CAP.EntityFrameworkCore.Test/DotNetCore.CAP.EntityFrameworkCore.Test.csproj
View file @
3c2f51e8
...
...
@@ -23,6 +23,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="1.50.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" />
<PackageReference Include="xunit" Version="2.2.0" />
...
...
test/DotNetCore.CAP.EntityFrameworkCore.Test/EnsuranceTest.cs
0 → 100644
View file @
3c2f51e8
using
Xunit
;
namespace
DotNetCore.CAP.EntityFrameworkCore.Test
{
public
class
EnsuranceTest
:
DatabaseTestHost
{
[
Fact
]
public
void
Ensure
()
{
}
}
}
test/DotNetCore.CAP.EntityFrameworkCore.Test/MessageStoreTest.cs
View file @
3c2f51e8
//using System;
//using System.Linq;
//using System.Threading.Tasks;
//using DotNetCore.CAP.Infrastructure;
//using DotNetCore.CAP.Store;
//using DotNetCore.CAP.Test;
//using Microsoft.AspNetCore.Testing;
//using Microsoft.AspNetCore.Testing.xunit;
//using Microsoft.EntityFrameworkCore;
//using Microsoft.Extensions.DependencyInjection;
//using Xunit;
using
System
;
using
System.Linq
;
using
System.Threading.Tasks
;
using
DotNetCore.CAP.Infrastructure
;
using
DotNetCore.CAP.Test
;
using
Microsoft.AspNetCore.Testing
;
using
Microsoft.AspNetCore.Testing.xunit
;
using
Microsoft.EntityFrameworkCore
;
using
Microsoft.Extensions.DependencyInjection
;
using
Xunit
;
//
namespace DotNetCore.CAP.EntityFrameworkCore.Test
//
{
// public class MessageStoreTest : MessageManagerTestBase<ConsistencyMessage>
, IClassFixture<ScratchDatabaseFixture>
//
{
//
private readonly ScratchDatabaseFixture _fixture;
namespace
DotNetCore.CAP.EntityFrameworkCore.Test
{
public
class
MessageStoreTest
:
MessageManagerTestBase
,
IClassFixture
<
ScratchDatabaseFixture
>
{
private
readonly
ScratchDatabaseFixture
_fixture
;
// public MessageStoreTest(ScratchDatabaseFixture fixture) {
// _fixture = fixture;
// }
public
MessageStoreTest
(
ScratchDatabaseFixture
fixture
)
{
_fixture
=
fixture
;
}
// protected override bool ShouldSkipDbTests() {
// return TestPlatformHelper.IsMono || !TestPlatformHelper.IsWindows;
// }
protected
override
bool
ShouldSkipDbTests
()
{
return
TestPlatformHelper
.
IsMono
||
!
TestPlatformHelper
.
IsWindows
;
}
// public class ApplicationDbContext : ConsistencyDbContext
// {
// public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) {
// }
// }
public
class
ApplicationDbContext
:
CapDbContext
{
public
ApplicationDbContext
(
DbContextOptions
<
ApplicationDbContext
>
options
)
:
base
(
options
)
{
}
}
// [ConditionalFact]
// [FrameworkSkipCondition(RuntimeFrameworks.Mono)]
// [OSSkipCondition(OperatingSystems.Linux)]
// [OSSkipCondition(OperatingSystems.MacOSX)]
// public void CanCreateMessageUsingEF() {
// using (var db = CreateContext()) {
// var guid = Guid.NewGuid().ToString();
// db.Messages.Add(new ConsistencyMessage {
// Id = guid,
// Payload = "this is message body",
// Status = MessageStatus.WaitForSend,
// SendTime = DateTime.Now,
// UpdateTime = DateTime.Now
// });
[
ConditionalFact
]
[
FrameworkSkipCondition
(
RuntimeFrameworks
.
Mono
)]
[
OSSkipCondition
(
OperatingSystems
.
Linux
)]
[
OSSkipCondition
(
OperatingSystems
.
MacOSX
)]
public
void
CanCreateSentMessageUsingEF
()
{
using
(
var
db
=
CreateContext
())
{
var
guid
=
Guid
.
NewGuid
().
ToString
();
db
.
CapSentMessages
.
Add
(
new
CapSentMessage
{
Id
=
guid
,
Content
=
"this is message body"
,
StateName
=
StateName
.
Enqueued
});
//
db.SaveChanges();
// Assert.True(db.
Messages.Any(u => u.Id == guid));
// Assert.NotNull(db.Messages.FirstOrDefault(u => u.Status == MessageStatus.WaitForSen
d));
//
}
//
}
db
.
SaveChanges
();
Assert
.
True
(
db
.
CapSent
Messages
.
Any
(
u
=>
u
.
Id
==
guid
));
Assert
.
NotNull
(
db
.
CapSentMessages
.
FirstOrDefault
(
u
=>
u
.
StateName
==
StateName
.
Enqueue
d
));
}
}
//
[ConditionalFact]
//
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
//
[OSSkipCondition(OperatingSystems.Linux)]
//
[OSSkipCondition(OperatingSystems.MacOSX)]
// public async Task CanCreateUsingManager() {
// var manager = CreateManager();
// var guid = Guid.NewGuid().ToString
();
// var message = new ConsistencyMessage {
// Id = guid,
// Payload = "this is message body",
// Status = MessageStatus.WaitForSen
d,
// SendTime = DateTime.Now
,
// UpdateTime = DateTime.Now
//
};
[
ConditionalFact
]
[
FrameworkSkipCondition
(
RuntimeFrameworks
.
Mono
)]
[
OSSkipCondition
(
OperatingSystems
.
Linux
)]
[
OSSkipCondition
(
OperatingSystems
.
MacOSX
)]
public
async
Task
CanCreateUsingManager
()
{
var
manager
=
CreateManager
();
var
guid
=
Guid
.
NewGuid
().
ToString
();
var
message
=
new
CapSentMessage
{
Id
=
gui
d
,
Content
=
"this is message body"
,
StateName
=
StateName
.
Enqueued
,
};
// var result = await manager.Creat
eAsync(message);
//
Assert.NotNull(result);
//
Assert.True(result.Succeeded);
var
result
=
await
manager
.
StoreSentMessag
eAsync
(
message
);
Assert
.
NotNull
(
result
);
Assert
.
True
(
result
.
Succeeded
);
// result = await manager.Delet
eAsync(message);
//
Assert.NotNull(result);
//
Assert.True(result.Succeeded);
//
}
result
=
await
manager
.
RemoveSentMessag
eAsync
(
message
);
Assert
.
NotNull
(
result
);
Assert
.
True
(
result
.
Succeeded
);
}
// public ConsistencyDbContext CreateContext(bool delete = false) {
// var db = DbUtil.Create<ConsistencyDbContext>(_fixture.ConnectionString);
// if (delete) {
// db.Database.EnsureDeleted();
// }
// db.Database.EnsureCreated();
// return db;
// }
public
CapDbContext
CreateContext
(
bool
delete
=
false
)
{
var
db
=
DbUtil
.
Create
<
CapDbContext
>(
_fixture
.
ConnectionString
);
if
(
delete
)
{
db
.
Database
.
EnsureDeleted
();
}
db
.
Database
.
EnsureCreated
();
return
db
;
}
// protected override object CreateTestContext() {
// return CreateContext();
// }
protected
override
object
CreateTestContext
()
{
return
CreateContext
();
}
// protected override ConsistencyMessage CreateTestMessage(string payload = "") {
// return new ConsistencyMessage {
// Payload = payload
// };
// }
protected
override
void
AddMessageStore
(
IServiceCollection
services
,
object
context
=
null
)
{
services
.
AddSingleton
<
ICapMessageStore
>(
new
CapMessageStore
<
CapDbContext
>((
CapDbContext
)
context
));
}
// protected override void AddMessageStore(IServiceCollection services, object context = null) {
// services.AddSingleton<IConsistencyMessageStore>(new ConsistencyMessageStore<ConsistencyDbContext>((ConsistencyDbContext)context));
// }
// }
protected
override
CapSentMessage
CreateTestSentMessage
(
string
content
=
""
)
{
return
new
CapSentMessage
{
Content
=
content
};
}
// public class ApplicationMessage : ConsistencyMessage { }
//}
\ No newline at end of file
protected
override
CapReceivedMessage
CreateTestReceivedMessage
(
string
content
=
""
)
{
return
new
CapReceivedMessage
()
{
Content
=
content
};
}
}
}
\ No newline at end of file
test/DotNetCore.CAP.EntityFrameworkCore.Test/MessageStoreWithGenericsTest.cs
deleted
100644 → 0
View file @
d477e602
//using System;
//using DotNetCore.CAP.Infrastructure;
//using DotNetCore.CAP.Store;
//using DotNetCore.CAP.Test;
//using Microsoft.AspNetCore.Testing;
//using Microsoft.Extensions.DependencyInjection;
//using Xunit;
//namespace DotNetCore.CAP.EntityFrameworkCore.Test
//{
// public class MessageStoreWithGenericsTest : MessageManagerTestBase<MessageWithGenerics, string>, IClassFixture<ScratchDatabaseFixture>
// {
// private readonly ScratchDatabaseFixture _fixture;
// public MessageStoreWithGenericsTest(ScratchDatabaseFixture fixture) {
// _fixture = fixture;
// }
// protected override void AddMessageStore(IServiceCollection services, object context = null) {
// services.AddSingleton<IConsistencyMessageStore>(new MessageStoreWithGenerics((ContextWithGenerics)context));
// }
// protected override object CreateTestContext() {
// return CreateContext();
// }
// public ContextWithGenerics CreateContext() {
// var db = DbUtil.Create<ContextWithGenerics>(_fixture.ConnectionString);
// db.Database.EnsureCreated();
// return db;
// }
// protected override MessageWithGenerics CreateTestMessage(string payload = "") {
// return new MessageWithGenerics() {
// Payload = payload,
// SendTime = DateTime.Now,
// Status = MessageStatus.WaitForSend,
// UpdateTime = DateTime.Now
// };
// }
// protected override bool ShouldSkipDbTests() {
// return TestPlatformHelper.IsMono || !TestPlatformHelper.IsWindows;
// }
// }
// public class MessageWithGenerics : ConsistencyMessage
// {
// }
// public class MessageStoreWithGenerics : ConsistencyMessageStore<ContextWithGenerics>
// {
// public MessageStoreWithGenerics(ContextWithGenerics context) : base(context) {
// }
// }
// public class ContextWithGenerics : ConsistencyDbContext
// {
// public ContextWithGenerics() {
// }
// }
//}
\ No newline at end of file
test/DotNetCore.CAP.EntityFrameworkCore.Test/TestHost.cs
0 → 100644
View file @
3c2f51e8
using
System
;
using
Microsoft.EntityFrameworkCore
;
using
Microsoft.Extensions.DependencyInjection
;
namespace
DotNetCore.CAP.EntityFrameworkCore.Test
{
public
abstract
class
TestHost
:
IDisposable
{
protected
IServiceCollection
_services
;
private
IServiceProvider
_provider
;
private
IServiceProvider
_scopedProvider
;
public
TestHost
()
{
CreateServiceCollection
();
PreBuildServices
();
BuildServices
();
PostBuildServices
();
}
protected
IServiceProvider
Provider
=>
_scopedProvider
??
_provider
;
private
void
CreateServiceCollection
()
{
var
services
=
new
ServiceCollection
();
services
.
AddOptions
();
services
.
AddLogging
();
var
connectionString
=
ConnectionUtil
.
GetConnectionString
();
//services.AddSingleton(new SqlServerOptions { ConnectionString = connectionString });
services
.
AddDbContext
<
CapDbContext
>(
options
=>
options
.
UseSqlServer
(
connectionString
));
_services
=
services
;
}
protected
virtual
void
PreBuildServices
()
{
}
private
void
BuildServices
()
{
_provider
=
_services
.
BuildServiceProvider
();
}
protected
virtual
void
PostBuildServices
()
{
}
public
IDisposable
CreateScope
()
{
var
scope
=
CreateScope
(
_provider
);
var
loc
=
scope
.
ServiceProvider
;
_scopedProvider
=
loc
;
return
new
DelegateDisposable
(()
=>
{
if
(
_scopedProvider
==
loc
)
{
_scopedProvider
=
null
;
}
scope
.
Dispose
();
});
}
public
IServiceScope
CreateScope
(
IServiceProvider
provider
)
{
var
scope
=
provider
.
GetService
<
IServiceScopeFactory
>().
CreateScope
();
return
scope
;
}
public
T
GetService
<
T
>()
=>
Provider
.
GetService
<
T
>();
public
T
Ensure
<
T
>(
ref
T
service
)
where
T
:
class
=>
service
??
(
service
=
GetService
<
T
>());
public
virtual
void
Dispose
()
{
(
_provider
as
IDisposable
)?.
Dispose
();
}
private
class
DelegateDisposable
:
IDisposable
{
private
Action
_dispose
;
public
DelegateDisposable
(
Action
dispose
)
{
_dispose
=
dispose
;
}
public
void
Dispose
()
{
_dispose
();
}
}
}
}
test/DotNetCore.CAP.EntityFrameworkCore.Test/config.json
View file @
3c2f51e8
{
"Test"
:
{
"SqlServer"
:
{
"DefaultConnectionString"
:
"Server=
(localdb)
\\
MSSqlLocaldb;Integrated Security=true;MultipleActiveResultSets=true;Connect Timeout=30
"
"DefaultConnectionString"
:
"Server=
192.168.2.206;Initial Catalog=Test;User Id=cmswuliu;Password=h7xY81agBn*Veiu3;MultipleActiveResultSets=True
"
}
}
}
\ No newline at end of file
test/DotNetCore.CAP.Test/DotNetCore.CAP.Test.csproj
View file @
3c2f51e8
...
...
@@ -32,8 +32,4 @@
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
</ItemGroup>
<ItemGroup>
<Folder Include="Job\" />
</ItemGroup>
</Project>
test/DotNetCore.CAP.Test/Job/ComputedJobTest.cs
0 → 100644
View file @
3c2f51e8
using
System
;
using
System.Collections.Generic
;
using
System.Text
;
using
DotNetCore.CAP.Job
;
using
Xunit
;
namespace
DotNetCore.CAP.Test.Job
{
public
class
ComputedJobTest
{
[
Fact
]
public
void
UpdateNext_LastRunNever_SchedulesNow
()
{
// Arrange
var
now
=
new
DateTime
(
2000
,
1
,
1
,
8
,
0
,
0
);
var
cronJob
=
new
CronJob
(
Cron
.
Daily
());
var
computed
=
new
ComputedCronJob
(
cronJob
);
// Act
computed
.
UpdateNext
(
now
);
// Assert
Assert
.
Equal
(
computed
.
Next
,
now
);
}
[
Fact
]
public
void
UpdateNext_LastRun_BeforePrev_SchedulesNow
()
{
// Arrange
var
now
=
new
DateTime
(
2000
,
1
,
1
,
8
,
0
,
0
);
var
cronJob
=
new
CronJob
(
Cron
.
Daily
(),
now
.
Subtract
(
TimeSpan
.
FromDays
(
2
)));
var
computed
=
new
ComputedCronJob
(
cronJob
);
// Act
computed
.
UpdateNext
(
now
);
// Assert
Assert
.
Equal
(
computed
.
Next
,
now
);
}
[
Fact
]
public
void
UpdateNext_LastRun_AfterPrev_SchedulesNormal
()
{
// Arrange
var
now
=
new
DateTime
(
2000
,
1
,
1
,
8
,
0
,
0
);
var
cronJob
=
new
CronJob
(
Cron
.
Daily
(),
now
.
Subtract
(
TimeSpan
.
FromSeconds
(
5
)));
var
computed
=
new
ComputedCronJob
(
cronJob
);
// Act
computed
.
UpdateNext
(
now
);
// Assert
Assert
.
True
(
computed
.
Next
>
now
);
}
}
}
test/DotNetCore.CAP.Test/Job/JobProcessingServerTest.cs
0 → 100644
View file @
3c2f51e8
using
System
;
using
System.Collections.Generic
;
using
System.Text
;
using
System.Threading
;
using
System.Threading.Tasks
;
using
DotNetCore.CAP.Infrastructure
;
using
DotNetCore.CAP.Job
;
using
Microsoft.Extensions.DependencyInjection
;
using
Moq
;
using
Xunit
;
namespace
DotNetCore.CAP.Test.Job
{
public
class
JobProcessingServerTest
{
private
CancellationTokenSource
_cancellationTokenSource
;
private
ProcessingContext
_context
;
private
CapOptions
_options
;
private
IServiceProvider
_provider
;
private
Mock
<
ICapMessageStore
>
_mockStorage
;
public
JobProcessingServerTest
()
{
_options
=
new
CapOptions
()
{
PollingDelay
=
0
};
_mockStorage
=
new
Mock
<
ICapMessageStore
>();
_cancellationTokenSource
=
new
CancellationTokenSource
();
var
services
=
new
ServiceCollection
();
services
.
AddTransient
<
JobProcessingServer
>();
services
.
AddTransient
<
DefaultCronJobRegistry
>();
services
.
AddLogging
();
services
.
AddSingleton
(
_options
);
services
.
AddSingleton
(
_mockStorage
.
Object
);
_provider
=
services
.
BuildServiceProvider
();
_context
=
new
ProcessingContext
(
_provider
,
null
,
_cancellationTokenSource
.
Token
);
}
//[Fact]
//public async Task ProcessAsync_CancellationTokenCancelled_ThrowsImmediately()
//{
// // Arrange
// _cancellationTokenSource.Cancel();
// var fixture = Create();
// // Act
// await Assert.ThrowsAsync<OperationCanceledException>(() => fixture.s(_context));
//}
//[Fact]
//public async Task ProcessAsync()
//{
// // Arrange
// var job = new CronJob(
// InvocationData.Serialize(
// MethodInvocation.FromExpression(() => Method())).Serialize());
// var mockFetchedJob = Mock.Get(Mock.Of<IFetchedJob>(fj => fj.JobId == 42));
// _mockStorageConnection
// .Setup(m => m.FetchNextJobAsync())
// .ReturnsAsync(mockFetchedJob.Object).Verifiable();
// _mockStorageConnection
// .Setup(m => m.GetJobAsync(42))
// .ReturnsAsync(job).Verifiable();
// var fixture = Create();
// // Act
// fixture.Start();
// // Assert
// _mockStorageConnection.VerifyAll();
// _mockStateChanger.Verify(m => m.ChangeState(job, It.IsAny<SucceededState>(), It.IsAny<IStorageTransaction>()));
// mockFetchedJob.Verify(m => m.Requeue(), Times.Never);
// mockFetchedJob.Verify(m => m.RemoveFromQueue());
//}
//[Fact]
//public async Task ProcessAsync_Exception()
//{
// // Arrange
// var job = new Job(
// InvocationData.Serialize(
// MethodInvocation.FromExpression(() => Throw())).Serialize());
// var mockFetchedJob = Mock.Get(Mock.Of<IFetchedJob>(fj => fj.JobId == 42));
// _mockStorageConnection
// .Setup(m => m.FetchNextJobAsync())
// .ReturnsAsync(mockFetchedJob.Object);
// _mockStorageConnection
// .Setup(m => m.GetJobAsync(42))
// .ReturnsAsync(job);
// _mockStateChanger.Setup(m => m.ChangeState(job, It.IsAny<IState>(), It.IsAny<IStorageTransaction>()))
// .Throws<Exception>();
// var fixture = Create();
// // Act
// await fixture.ProcessAsync(_context);
// // Assert
// job.Retries.Should().Be(0);
// mockFetchedJob.Verify(m => m.Requeue());
//}
//[Fact]
//public async Task ProcessAsync_JobThrows()
//{
// // Arrange
// var job = new Job(
// InvocationData.Serialize(
// MethodInvocation.FromExpression(() => Throw())).Serialize());
// var mockFetchedJob = Mock.Get(Mock.Of<IFetchedJob>(fj => fj.JobId == 42));
// _mockStorageConnection
// .Setup(m => m.FetchNextJobAsync())
// .ReturnsAsync(mockFetchedJob.Object).Verifiable();
// _mockStorageConnection
// .Setup(m => m.GetJobAsync(42))
// .ReturnsAsync(job).Verifiable();
// var fixture = Create();
// // Act
// await fixture.ProcessAsync(_context);
// // Assert
// job.Retries.Should().Be(1);
// _mockStorageTransaction.Verify(m => m.UpdateJob(job));
// _mockStorageConnection.VerifyAll();
// _mockStateChanger.Verify(m => m.ChangeState(job, It.IsAny<ScheduledState>(), It.IsAny<IStorageTransaction>()));
// mockFetchedJob.Verify(m => m.RemoveFromQueue());
//}
//[Fact]
//public async Task ProcessAsync_JobThrows_WithNoRetry()
//{
// // Arrange
// var job = new Job(
// InvocationData.Serialize(
// MethodInvocation.FromExpression<NoRetryJob>(j => j.Throw())).Serialize());
// var mockFetchedJob = Mock.Get(Mock.Of<IFetchedJob>(fj => fj.JobId == 42));
// _mockStorageConnection
// .Setup(m => m.FetchNextJobAsync())
// .ReturnsAsync(mockFetchedJob.Object);
// _mockStorageConnection
// .Setup(m => m.GetJobAsync(42))
// .ReturnsAsync(job);
// var fixture = Create();
// // Act
// await fixture.ProcessAsync(_context);
// // Assert
// _mockStateChanger.Verify(m => m.ChangeState(job, It.IsAny<FailedState>(), It.IsAny<IStorageTransaction>()));
//}
private
JobProcessingServer
Create
()
=>
_provider
.
GetService
<
JobProcessingServer
>();
//public static void Method() { }
//public static void Throw() { throw new Exception(); }
//private class NoRetryJob : IRetryable
//{
// public RetryBehavior RetryBehavior => new RetryBehavior(false);
// public void Throw() { throw new Exception(); }
//}
}
}
test/Shared/MessageManagerTestBase.cs
View file @
3c2f51e8
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Linq.Expressions;
//using System.Security.Claims;
//using System.Threading.Tasks;
//using DotNetCore.CAP.Infrastructure;
//using DotNetCore.CAP.Store;
//using Microsoft.AspNetCore.Builder;
//using Microsoft.AspNetCore.Http;
//using Microsoft.Extensions.DependencyInjection;
//using Microsoft.Extensions.Logging;
//using Xunit;
//namespace DotNetCore.CAP.Test
//{
// public abstract class MessageManagerTestBase<TMessage> : MessageManagerTestBase<TMessage, string>
// where TMessage : ConsistencyMessage
// {
// }
// public abstract class MessageManagerTestBase<TMessage, TKey>
// where TMessage : ConsistencyMessage
// where TKey : IEquatable<TKey>
// {
// private const string NullValue = "(null)";
// protected virtual bool ShouldSkipDbTests() {
// return false;
// }
// protected virtual void SetupMessageServices(IServiceCollection services, object context = null) {
// services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// services.AddConsistency();
// AddMessageStore(services, context);
// services.AddSingleton<ILogger<IConsistencyMessageStore >>(new TestLogger<IConsistencyMessageStore >());
// }
// protected virtual IConsistencyMessageStore CreateManager(object context = null, IServiceCollection services = null, Action<IServiceCollection> configureServices = null) {
// if (services == null) {
// services = new ServiceCollection();
// }
// if (context == null) {
// context = CreateTestContext();
// }
// SetupMessageServices(services, context);
// configureServices?.Invoke(services);
// return services.BuildServiceProvider().GetService<IConsistencyMessageStore >();
// }
// protected abstract object CreateTestContext();
// protected abstract TMessage CreateTestMessage(string payload = "");
// protected abstract void AddMessageStore(IServiceCollection services, object context = null);
// [Fact]
// public async Task CanDeleteMessage() {
// if (ShouldSkipDbTests()) {
// return;
// }
// var manager = CreateManager();
// var message = CreateTestMessage();
// var operateResult = await manager.CreateAsync(message);
// Assert.NotNull(operateResult);
// Assert.True(operateResult.Succeeded);
// var messageId = await manager.GeConsistencyMessageIdAsync(message);
// operateResult = await manager.DeleteAsync(message);
// Assert.Null(await manager.FindByIdAsync(messageId));
// }
// [Fact]
// public async Task CanFindById() {
// if (ShouldSkipDbTests()) {
// return;
// }
// var manager = CreateManager();
// var message = CreateTestMessage();
// var operateResult = await manager.CreateAsync(message);
// Assert.NotNull(operateResult);
// Assert.True(operateResult.Succeeded);
// var messageId = await manager.GeConsistencyMessageIdAsync(message);
// Assert.NotNull(await manager.FindByIdAsync(messageId));
// }
// }
//}
\ No newline at end of file
using
System
;
using
System.Threading.Tasks
;
using
DotNetCore.CAP.Infrastructure
;
using
Microsoft.AspNetCore.Http
;
using
Microsoft.Extensions.DependencyInjection
;
using
Microsoft.Extensions.Logging
;
using
Xunit
;
namespace
DotNetCore.CAP.Test
{
public
abstract
class
MessageManagerTestBase
{
private
const
string
NullValue
=
"(null)"
;
protected
virtual
bool
ShouldSkipDbTests
()
{
return
false
;
}
protected
virtual
void
SetupMessageServices
(
IServiceCollection
services
,
object
context
=
null
)
{
services
.
AddSingleton
<
IHttpContextAccessor
,
HttpContextAccessor
>();
services
.
AddConsistency
();
AddMessageStore
(
services
,
context
);
services
.
AddSingleton
<
ILogger
<
ICapMessageStore
>>(
new
TestLogger
<
ICapMessageStore
>());
}
protected
virtual
ICapMessageStore
CreateManager
(
object
context
=
null
,
IServiceCollection
services
=
null
,
Action
<
IServiceCollection
>
configureServices
=
null
)
{
if
(
services
==
null
)
{
services
=
new
ServiceCollection
();
}
if
(
context
==
null
)
{
context
=
CreateTestContext
();
}
SetupMessageServices
(
services
,
context
);
configureServices
?.
Invoke
(
services
);
return
services
.
BuildServiceProvider
().
GetService
<
ICapMessageStore
>();
}
protected
abstract
object
CreateTestContext
();
protected
abstract
CapSentMessage
CreateTestSentMessage
(
string
content
=
""
);
protected
abstract
CapReceivedMessage
CreateTestReceivedMessage
(
string
content
=
""
);
protected
abstract
void
AddMessageStore
(
IServiceCollection
services
,
object
context
=
null
);
[
Fact
]
public
async
Task
CanDeleteSentMessage
()
{
if
(
ShouldSkipDbTests
())
{
return
;
}
var
manager
=
CreateManager
();
var
message
=
CreateTestSentMessage
();
var
operateResult
=
await
manager
.
StoreSentMessageAsync
(
message
);
Assert
.
NotNull
(
operateResult
);
Assert
.
True
(
operateResult
.
Succeeded
);
operateResult
=
await
manager
.
RemoveSentMessageAsync
(
message
);
Assert
.
NotNull
(
operateResult
);
Assert
.
True
(
operateResult
.
Succeeded
);
}
[
Fact
]
public
async
Task
CanUpdateReceivedMessage
()
{
if
(
ShouldSkipDbTests
())
{
return
;
}
var
manager
=
CreateManager
();
var
message
=
CreateTestReceivedMessage
();
var
operateResult
=
await
manager
.
StoreReceivedMessageAsync
(
message
);
Assert
.
NotNull
(
operateResult
);
Assert
.
True
(
operateResult
.
Succeeded
);
message
.
StateName
=
StateName
.
Processing
;
operateResult
=
await
manager
.
UpdateReceivedMessageAsync
(
message
);
Assert
.
NotNull
(
operateResult
);
Assert
.
True
(
operateResult
.
Succeeded
);
}
[
Fact
]
public
async
Task
CanGetNextSendMessage
()
{
if
(
ShouldSkipDbTests
())
{
return
;
}
var
manager
=
CreateManager
();
var
message
=
CreateTestSentMessage
();
var
operateResult
=
await
manager
.
StoreSentMessageAsync
(
message
);
Assert
.
NotNull
(
operateResult
);
Assert
.
True
(
operateResult
.
Succeeded
);
var
storeMessage
=
await
manager
.
GetNextSentMessageToBeEnqueuedAsync
();
Assert
.
Equal
(
message
,
storeMessage
);
}
}
}
\ No newline at end of file
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment