Skip to content

Commit

Permalink
Merge pull request #7 from dtm-labs/feat/addmoretests
Browse files Browse the repository at this point in the history
test: add more tests
  • Loading branch information
catcherwong authored May 26, 2022
2 parents c4fab59 + 71bf9d9 commit aeec2f8
Show file tree
Hide file tree
Showing 10 changed files with 280 additions and 43 deletions.
23 changes: 22 additions & 1 deletion .github/workflows/build_and_ut.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,25 @@ jobs:
- name: Run tests on net6.0
run: |
dotnet test --framework=net6.0 tests/Dtmgrpc.Tests/Dtmgrpc.Tests.csproj
dotnet test --framework=net6.0 tests/Dtmgrpc.Tests/Dtmgrpc.Tests.csproj --collect:"XPlat Code Coverage"
- name: Prepare Codecov
if: ${{ matrix.os == 'ubuntu-latest' }}
run: |
dotnet tool install -g dotnet-reportgenerator-globaltool
reportgenerator -reports:"${{ github.workspace }}/tests/Dtmgrpc.Tests/TestResults/**/coverage.cobertura.xml" \
-targetdir:"${{ github.workspace }}/coverage" \
-classfilters:-*dtmgpb.* \
-reporttypes:Cobertura
ls ${{ github.workspace }}/coverage/
- name: Upload coverage to Codecov
if: ${{ matrix.os == 'ubuntu-latest' }}
uses: codecov/codecov-action@v2
with:
token: ${{ secrets.CODECOV_TOKEN }}
fail_ci_if_error: true
files: ${{ github.workspace }}/coverage/Cobertura.xml
name: codecov-umbrella
verbose: true
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ English | [简体中文](./README-cn.md)

It has supported distributed transaction patterns of Saga pattern, TCC pattern and 2-phase message pattern.

![Build_And_UnitTest](https://github.com/catcherwong/dtmgrpc-csharp/actions/workflows/build_and_ut.yml/badge.svg) ![Build_And_IntegrationTests](https://github.com/catcherwong/dtmgrpc-csharp/actions/workflows/build_and_it.yml/badge.svg)
![Build_And_UnitTest](https://github.com/catcherwong/dtmgrpc-csharp/actions/workflows/build_and_ut.yml/badge.svg) ![Build_And_IntegrationTests](https://github.com/catcherwong/dtmgrpc-csharp/actions/workflows/build_and_it.yml/badge.svg) [![codecov](https://codecov.io/gh/dtm-labs/dtmgrpc-csharp/branch/main/graph/badge.svg?token=BMVU39PSH4)](https://codecov.io/gh/dtm-labs/dtmgrpc-csharp)

![](https://img.shields.io/nuget/v/Dtmgrpc.svg) ![](https://img.shields.io/nuget/vpre/Dtmgrpc.svg) ![](https://img.shields.io/nuget/dt/Dtmgrpc) ![](https://img.shields.io/github/license/catcherwong/dtmgrpc-csharp)

Expand Down
39 changes: 0 additions & 39 deletions tests/Dtmgrpc.Tests/BranchBarrierTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -195,44 +195,5 @@ public void CreateBranchBarrier_FromContext_Should_ThrowException()

Assert.Throws<DtmException>(() => _factory.CreateBranchBarrier(context));
}

private class CusServerCallContext : Grpc.Core.ServerCallContext
{
private Grpc.Core.Metadata _reqMetadata;

public CusServerCallContext(Grpc.Core.Metadata reqMetadata)
{
this._reqMetadata = reqMetadata;
}

protected override string MethodCore => throw new NotImplementedException();

protected override string HostCore => throw new NotImplementedException();

protected override string PeerCore => throw new NotImplementedException();

protected override DateTime DeadlineCore => throw new NotImplementedException();

protected override Grpc.Core.Metadata RequestHeadersCore => _reqMetadata;

protected override CancellationToken CancellationTokenCore => throw new NotImplementedException();

protected override Grpc.Core.Metadata ResponseTrailersCore => throw new NotImplementedException();

protected override Grpc.Core.Status StatusCore { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
protected override Grpc.Core.WriteOptions WriteOptionsCore { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

protected override Grpc.Core.AuthContext AuthContextCore => throw new NotImplementedException();

protected override Grpc.Core.ContextPropagationToken CreatePropagationTokenCore(Grpc.Core.ContextPropagationOptions options)
{
throw new NotImplementedException();
}

protected override Task WriteResponseHeadersAsyncCore(Grpc.Core.Metadata responseHeaders)
{
return Task.CompletedTask;
}
}
}
}
45 changes: 45 additions & 0 deletions tests/Dtmgrpc.Tests/CusServerCallContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Dtmgrpc.Tests
{
internal class CusServerCallContext : Grpc.Core.ServerCallContext
{
private Grpc.Core.Metadata _reqMetadata;

public CusServerCallContext(Grpc.Core.Metadata reqMetadata)
{
this._reqMetadata = reqMetadata;
}

protected override string MethodCore => throw new NotImplementedException();

protected override string HostCore => throw new NotImplementedException();

protected override string PeerCore => throw new NotImplementedException();

protected override DateTime DeadlineCore => throw new NotImplementedException();

protected override Grpc.Core.Metadata RequestHeadersCore => _reqMetadata;

protected override CancellationToken CancellationTokenCore => throw new NotImplementedException();

protected override Grpc.Core.Metadata ResponseTrailersCore => throw new NotImplementedException();

protected override Grpc.Core.Status StatusCore { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
protected override Grpc.Core.WriteOptions WriteOptionsCore { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

protected override Grpc.Core.AuthContext AuthContextCore => throw new NotImplementedException();

protected override Grpc.Core.ContextPropagationToken CreatePropagationTokenCore(Grpc.Core.ContextPropagationOptions options)
{
throw new NotImplementedException();
}

protected override Task WriteResponseHeadersAsyncCore(Grpc.Core.Metadata responseHeaders)
{
return Task.CompletedTask;
}
}
}
3 changes: 3 additions & 0 deletions tests/Dtmgrpc.Tests/DbSpecialTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@ public void Test_PgSQL_DbSpecial()

Assert.IsType<PostgresDBSpecial>(special);
Assert.Equal("begin", special.GetXaSQL("start", "xa1"));
Assert.Equal(string.Empty, special.GetXaSQL("aa", "bb"));
Assert.Equal("insert into a(f) values(@f) on conflict ON CONSTRAINT c do nothing", special.GetInsertIgnoreTemplate("a(f) values(@f)", "c"));
Assert.Equal("insert into a(f) values(@f)", special.GetPlaceHoldSQL("insert into a(f) values(@f)"));
}

[Fact]
Expand All @@ -68,6 +70,7 @@ public void Test_MsSQL_DbSpecial()

Assert.IsType<SqlServerDBSpecial>(special);
Assert.Equal("insert into a(f) values(@f)", special.GetInsertIgnoreTemplate("a(f) values(@f)", "c"));
Assert.Equal("insert into a(f) values(@f)", special.GetPlaceHoldSQL("insert into a(f) values(@f)"));
Assert.Throws<DtmException>(() => special.GetXaSQL("", ""));
}

Expand Down
54 changes: 54 additions & 0 deletions tests/Dtmgrpc.Tests/DtmTransFactoryTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using Moq;
using Xunit;

namespace Dtmgrpc.Tests
{
public class DtmTransFactoryTests
{
[Fact]
public void NewMsg_Should_Succeed()
{
var tFactory = BuildFactory();

var gid = "TestMsgNormal";

var msg = tFactory.NewMsgGrpc(gid);

Assert.NotNull(msg);
}

[Fact]
public void NewSaga_Should_Succeed()
{
var tFactory = BuildFactory();

var gid = "TestSagaNormal";

var saga = tFactory.NewSagaGrpc(gid);

Assert.NotNull(saga);
}

[Fact]
public void NewTcc_Should_Succeed()
{
var tFactory = BuildFactory();

var gid = "TestTccNormal";

var saga = tFactory.NewTccGrpc(gid);

Assert.NotNull(saga);
}

private DtmTransFactory BuildFactory()
{
var dtmClient = new Mock<IDtmgRPCClient>();
var bbFactory = new Mock<IBranchBarrierFactory>();
var option = Microsoft.Extensions.Options.Options.Create(new DtmCommon.DtmOptions { });

return new DtmTransFactory(option, dtmClient.Object, bbFactory.Object);

}
}
}
20 changes: 19 additions & 1 deletion tests/Dtmgrpc.Tests/MsgTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,32 @@ public async void Submit_Should_Succeed()
{
{ "bh1", "123" },
{ "bh2", "456" },
});
})
.SetPassthroughHeaders(new List<string> { "bh1" });

await msg.Prepare(busi + "/query");
await msg.Submit();

Assert.True(true);
}

[Fact]
public async void DoAndSubmit_Should_Throw_Exception_When_Transbase_InValid()
{
var dtmClient = new Mock<IDtmgRPCClient>();
var bbFactory = new Mock<IBranchBarrierFactory>();

bbFactory.Setup(x => x.CreateBranchBarrier(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), null))
.Returns(new BranchBarrier("", "", "", "", null, null));

var gid = string.Empty;
var msg = new MsgGrpc(dtmClient.Object, bbFactory.Object, "", gid);

var req = new Empty();
msg.Add(busi + "/TransOut", req);
await Assert.ThrowsAsync<DtmException>(async () => await msg.DoAndSubmit(busi + "/query", x => Task.CompletedTask));
}

[Fact]
public async void DoAndSubmitDB_Should_Throw_Exception_When_Transbase_InValid()
{
Expand Down
10 changes: 9 additions & 1 deletion tests/Dtmgrpc.Tests/SagaTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,25 @@ public async void Submit_Should_Succeed()
.Add(string.Concat(busi, "/TransOut"), string.Concat(busi, "/TransOutRevert"), req)
.Add(string.Concat(busi, "/TransIn"), string.Concat(busi, "/TransInRevert"), req)
.Add(string.Concat(busi, "/TransIn"), string.Concat(busi, "/TransInRevert"), req)
.AddBranchOrder(3, new List<int> { 1, 2 })
.EnableWaitResult()
.EnableConcurrent()
.SetRetryInterval(10)
.SetTimeoutToFail(100)
.SetBranchHeaders(new Dictionary<string, string>
{
{ "bh1", "123" },
{ "bh2", "456" },
});
})
.SetPassthroughHeaders(new List<string> { "bh1" });

await saga.Submit();

var tb = saga.GetTransBase();
Assert.NotNull(tb.CustomData);
Assert.Equal(10, tb.RetryInterval);
Assert.Equal(100, tb.TimeoutToFail);

Assert.True(true);
}

Expand Down
1 change: 1 addition & 0 deletions tests/Dtmgrpc.Tests/TccTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ public async void Set_TransOptions_Should_Succeed()
{ "bh1", "123" },
{ "bh2", "456" },
});
tcc.SetPassthroughHeaders(new List<string> { "bh1" });
}, async (tcc) =>
{
await tcc.CallBranch<Empty, Empty>(new Empty(), "localhost:9999/svc/TransOutTry", "localhost:9999/svc/TransOutConfirm", "localhost:9999/svc/TransOutCancel");
Expand Down
126 changes: 126 additions & 0 deletions tests/Dtmgrpc.Tests/UtilsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
using DtmCommon;
using Grpc.Core;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

namespace Dtmgrpc.Tests
{
public class UtilsTests
{
private static DtmFailureException DtmFailure = new DtmFailureException();
private static DtmOngingException DtmOnging = new DtmOngingException();

[Fact]
public void DtmError2GrpcError_Should_Throw_Aborted_RpcException()
{
var ex = Assert.Throws<RpcException>(()=> DtmGImp.Utils.DtmError2GrpcError(DtmFailure));
Assert.Equal(StatusCode.Aborted, ex.StatusCode);
}

[Fact]
public void DtmError2GrpcError_Should_Throw_FailedPrecondition_RpcException()
{
var ex = Assert.Throws<RpcException>(() => DtmGImp.Utils.DtmError2GrpcError(DtmOnging));
Assert.Equal(StatusCode.FailedPrecondition, ex.StatusCode);
}

[Fact]
public void DtmError2GrpcError_Should_Throw_Unknown_RpcException()
{
var ex = Assert.Throws<RpcException>(() => DtmGImp.Utils.DtmError2GrpcError(new System.ArgumentNullException()));
Assert.Equal(StatusCode.Unknown, ex.StatusCode);
}

[Theory]
[InlineData(StatusCode.Aborted, "ONGOING")]
[InlineData(StatusCode.FailedPrecondition, "other")]
public void GrpcError2DtmError_Should_Be_DtmOngingException(StatusCode code, string msg)
{
var rpcEx = new RpcException(new Status(code, msg), msg);
var ex = DtmGImp.Utils.GrpcError2DtmError(rpcEx);
Assert.IsType<DtmOngingException>(ex);
}

[Fact]
public void GrpcError2DtmError_Should_Be_DtmFailureException()
{
var rpcEx = new RpcException(new Status(StatusCode.Aborted, "Other"));
var ex = DtmGImp.Utils.GrpcError2DtmError(rpcEx);
Assert.IsType<DtmFailureException>(ex);
}

[Fact]
public void GrpcError2DtmError_Should_Be_RawException()
{
var rpcEx = new System.ArgumentNullException();
var ex = DtmGImp.Utils.GrpcError2DtmError(rpcEx);
Assert.IsType<System.ArgumentNullException>(ex);
}

[Fact]
public void String2DtmError_Should_Succeed()
{
var fEx = DtmGImp.Utils.String2DtmError(Constant.ResultFailure);
Assert.IsType<DtmFailureException>(fEx);

var oEx = DtmGImp.Utils.String2DtmError(Constant.ResultOngoing);
Assert.IsType<DtmOngingException>(oEx);

var nullEx = DtmGImp.Utils.String2DtmError(Constant.ResultSuccess);
Assert.Null(nullEx);

nullEx = DtmGImp.Utils.String2DtmError(string.Empty);
Assert.Null(nullEx);

nullEx = DtmGImp.Utils.String2DtmError("other");
Assert.Null(nullEx);
}

[Theory]
[InlineData(null, "")]
[InlineData("http://a.b.com/", "a.b.com")]
[InlineData("https://a.b.com", "a.b.com")]
public void GetWithoutPrefixgRPCUrl_Should_Succeed(string url, string exp)
{
var res = DtmGImp.Utils.GetWithoutPrefixgRPCUrl(url);
Assert.Equal(exp, res);
}

[Fact]
public void TransInfo2Metadata_Should_Succeed()
{
var meta = DtmGImp.Utils.TransInfo2Metadata("1", "2", "3", "4", "5");

Assert.Equal("1", meta.Get(Constant.Md.Gid).Value);
Assert.Equal("2", meta.Get(Constant.Md.TransType).Value);
Assert.Equal("3", meta.Get(Constant.Md.BranchId).Value);
Assert.Equal("4", meta.Get(Constant.Md.Op).Value);
Assert.Equal("5", meta.Get(Constant.Md.Dtm).Value);
}

[Fact]
public void DtmGet_Should_Succeed()
{
var meta = new Metadata();
meta.Add("a", "b");
meta.Add("c", "d");
var context = new CusServerCallContext(meta);

var str1 = DtmGImp.Utils.DtmGet(context, "a");
Assert.Equal("b", str1);

var str2 = DtmGImp.Utils.DtmGet(context, "d");
Assert.Null(str2);
}

[Fact]
public void DtmGet_When_Header_IsNull_Should_Succeed()
{
var context = new CusServerCallContext(null);

var str = DtmGImp.Utils.DtmGet(context, "a");
Assert.Null(str);
}
}
}

0 comments on commit aeec2f8

Please sign in to comment.