Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor/actionbase #3917

Draft
wants to merge 15 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions Libplanet.SDK.Action.Tests/Libplanet.SDK.Action.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>

<RootNamespace>Libplanet.SDK.Tests</RootNamespace>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0"/>
<PackageReference Include="Moq.AutoMock" Version="3.5.0" />
<PackageReference Include="xunit" Version="2.4.1"/>
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.1.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Libplanet.SDK.Action\Libplanet.SDK.Action.csproj" />
<ProjectReference Include="..\test\Libplanet.Mocks\Libplanet.Mocks.csproj" />
</ItemGroup>

</Project>
60 changes: 60 additions & 0 deletions Libplanet.SDK.Action.Tests/MockActionContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using Libplanet.Action;
using Libplanet.Action.State;
using Libplanet.Crypto;
using Libplanet.Types.Evidence;
using Libplanet.Types.Tx;

namespace Libplanet.SDK.Action.Tests
{
public class MockActionContext : IActionContext
{
public MockActionContext(
Address signer,
Address miner,
IWorld previousState)
{
Signer = signer;
Miner = miner;
PreviousState = previousState;
}

public Address Signer { get; }

public TxId? TxId =>
throw new NotSupportedException();

public Address Miner { get; }

public long BlockIndex =>
throw new NotSupportedException();

public int BlockProtocolVersion =>
throw new NotSupportedException();

public IWorld PreviousState { get; }

public int RandomSeed =>
throw new NotSupportedException();

public bool IsPolicyAction =>
throw new NotSupportedException();

public IReadOnlyList<ITransaction> Txs =>
throw new NotSupportedException();

public IReadOnlyList<EvidenceBase> Evidence =>
throw new NotSupportedException();

public void UseGas(long gas) =>
throw new NotSupportedException();

public IRandom GetRandom() =>
throw new NotSupportedException();

public long GasUsed() =>
throw new NotSupportedException();

public long GasLimit() =>
throw new NotSupportedException();
}
}
47 changes: 47 additions & 0 deletions Libplanet.SDK.Action.Tests/Sample/Actions/NumberAction.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using Bencodex.Types;
using Libplanet.Action;
using Libplanet.Crypto;
using Libplanet.SDK.Action.Attributes;

namespace Libplanet.SDK.Action.Tests.Sample.Actions
{
[ActionType("Number")]
public class NumberAction : ActionBase
{
public override Address StorageAddress =>
new Address("0x1000000000000000000000000000000000000001");

[Executable]
public void Add(IValue args)
{
Integer operand = (Integer)args;
Integer stored = GetState(Signer) is IValue value
? (Integer)value
: new Integer(0);
Call<NumberLogAction>(nameof(NumberLogAction.Add), new object?[] { operand });
SetState(Signer, new Integer(stored.Value + operand.Value));
}

[Executable]
public void Subtract(IValue args)
{
Integer operand = (Integer)args;
Integer stored = GetState(Signer) is IValue value
? (Integer)value
: new Integer(0);
Call<NumberLogAction>(nameof(NumberLogAction.Subtract), new object?[] { operand });
SetState(Signer, new Integer(stored.Value - operand.Value));
}

[Executable]
public void Multiply(IValue args)
{
Integer operand = (Integer)args;
Integer stored = GetState(Signer) is IValue value
? (Integer)value
: new Integer(1);
Call<NumberLogAction>(nameof(NumberLogAction.Multiply), new object?[] { operand });
SetState(Signer, new Integer(stored.Value * operand.Value));
}
}
}
57 changes: 57 additions & 0 deletions Libplanet.SDK.Action.Tests/Sample/Actions/NumberLogAction.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using Bencodex.Types;
using Libplanet.Crypto;
using Libplanet.SDK.Action.Attributes;

namespace Libplanet.SDK.Action.Tests.Sample.Actions
{
public class NumberLogAction : ActionBase
{
public override Address StorageAddress =>
new Address("0x1000000000000000000000000000000000000002");

[Callable]
public void Add(Integer operand)
{
Text stored = GetState(Signer) is IValue value
? (Text)value
: new Text(string.Empty);
Text formatted = operand.Value >= 0
? new Text($"{operand.Value}")
: new Text($"({operand.Value})");
formatted = stored.Value.Length == 0
? new Text(stored.Value + $"{formatted.Value}")
: new Text(stored.Value + $" + {formatted.Value}");
SetState(Signer, formatted);
}

[Callable]
public void Subtract(Integer operand)
{
Text stored = GetState(Signer) is IValue value
? (Text)value
: new Text(string.Empty);
Text formatted = operand.Value >= 0
? new Text($"{operand.Value}")
: new Text($"({operand.Value})");
formatted = stored.Value.Length == 0
? new Text(stored.Value + $"{formatted.Value}")
: new Text(stored.Value + $" - {formatted.Value}");
SetState(Signer, formatted);
}

// This is without Callable attribute on purpose for testing.
public void Multiply(Integer operand)
{
Text stored = GetState(Signer) is IValue value
? (Text)value
: new Text(string.Empty);
Text formatted = operand.Value >= 0
? new Text($"{operand.Value}")
: new Text($"({operand.Value})");
formatted = stored.Value.Length == 0
? new Text($"{formatted.Value}")
: new Text(stored.Value + $" * {formatted.Value}");
SetState(Signer, formatted);
}
}
}
24 changes: 24 additions & 0 deletions Libplanet.SDK.Action.Tests/Sample/Actions/TextAction.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using Bencodex.Types;
using Libplanet.Action;
using Libplanet.Crypto;
using Libplanet.SDK.Action.Attributes;

namespace Libplanet.SDK.Action.Tests
{
[ActionType("Text")]
public class TextAction : ActionBase
{
public override Address StorageAddress =>
new Address("0x1000000000000000000000000000000000000003");

[Executable]
public void Append(IValue args)
{
Text operand = (Text)args;
Text stored = GetState(Signer) is IValue value
? (Text)value
: new Text(string.Empty);
SetState(Signer, new Text(stored.Value + operand.Value));
}
}
}
174 changes: 174 additions & 0 deletions Libplanet.SDK.Action.Tests/Sample/SampleActionsTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
using System.Collections.Immutable;
using System.Reflection;
using Bencodex.Types;
using Libplanet.Action;
using Libplanet.Action.Loader;
using Libplanet.Action.State;
using Libplanet.Crypto;
using Libplanet.SDK.Action.Tests.Sample.Actions;
using Libplanet.Store;
using Libplanet.Store.Trie;
using Libplanet.Types.Blocks;
using Xunit;

namespace Libplanet.SDK.Action.Tests.Sample
{
public class SampleActionsTest
{
private TypedActionLoader _loader;
private IStateStore _stateStore;
private IWorld _world;

public SampleActionsTest()
{
_loader = new TypedActionLoader(
ImmutableDictionary<IValue, Type>.Empty
.Add(new Text("Number"), typeof(NumberAction))
.Add(new Text("Text"), typeof(TextAction)));

_stateStore = new TrieStateStore(new MemoryKeyValueStore());

ITrie trie = _stateStore.GetStateRoot(null);
trie = trie.SetMetadata(new TrieMetadata(Block.CurrentProtocolVersion));
trie = _stateStore.Commit(trie);
_world = new World(new WorldBaseState(trie, _stateStore));
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public void NumberAddAndSubtract(bool commit)
{
IValue plainValue = Dictionary.Empty
.Add("type_id", "Number")
.Add("call", "Add")
.Add("args", 5);
NumberAction action = Assert.IsType<NumberAction>(_loader.LoadAction(0, plainValue));
Address signer = new PrivateKey().Address;
IWorld world = _world;

world = action.Execute(new MockActionContext(signer, signer, world));
world = commit ? _stateStore.CommitWorld(world) : world;
Assert.Equal(
new Integer(5),
world.GetAccountState(action.StorageAddress).GetState(signer));
Assert.Equal(
new Text("5"),
world
.GetAccountState(new Address("0x1000000000000000000000000000000000000002"))
.GetState(signer));

plainValue = Dictionary.Empty
.Add("type_id", "Number")
.Add("call", "Subtract")
.Add("args", 8);
action = Assert.IsType<NumberAction>(_loader.LoadAction(0, plainValue));
world = action.Execute(new MockActionContext(signer, signer, world));
world = commit ? _stateStore.CommitWorld(world) : world;
Assert.Equal(
new Integer(-3),
world.GetAccountState(action.StorageAddress).GetState(signer));
Assert.Equal(
new Text("5 - 8"),
world
.GetAccountState(new Address("0x1000000000000000000000000000000000000002"))
.GetState(signer));
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public void TextAppend(bool commit)
{
IValue plainValue = Dictionary.Empty
.Add("type_id", "Text")
.Add("call", "Append")
.Add("args", "Hello");
TextAction action = Assert.IsType<TextAction>(_loader.LoadAction(0, plainValue));
Address signer = new PrivateKey().Address;
IWorld world = _world;

world = action.Execute(new MockActionContext(signer, signer, world));
world = commit ? _stateStore.CommitWorld(world) : world;
Assert.Equal(
new Text("Hello"),
world.GetAccountState(action.StorageAddress).GetState(signer));

plainValue = Dictionary.Empty
.Add("type_id", "Text")
.Add("call", "Append")
.Add("args", " world");
action = Assert.IsType<TextAction>(_loader.LoadAction(0, plainValue));
world = action.Execute(new MockActionContext(signer, signer, world));
world = commit ? _stateStore.CommitWorld(world) : world;
Assert.Equal(
new Text("Hello world"),
world.GetAccountState(action.StorageAddress).GetState(signer));
}

[Fact]
public void InvalidPlainValueForLoading()
{
IValue plainValue = Dictionary.Empty // Invalid type_id
.Add("type_id", "Run")
.Add("call", "Append")
.Add("args", "Hello");
Assert.Throws<InvalidActionException>(() => _loader.LoadAction(0, plainValue));

plainValue = Dictionary.Empty // Missing type_id
.Add("call", "Append")
.Add("args", "Hello");
Assert.Throws<InvalidActionException>(() => _loader.LoadAction(0, plainValue));

plainValue = Dictionary.Empty // Missing call
.Add("type_id", "Number")
.Add("args", 5);
Assert.Throws<InvalidActionException>(() => _loader.LoadAction(0, plainValue));

plainValue = Dictionary.Empty // Missing args
.Add("type_id", "Number")
.Add("call", "Add");
Assert.Throws<InvalidActionException>(() => _loader.LoadAction(0, plainValue));
}

[Fact]
public void InvalidPlainValueForExecution()
{
IValue plainValue = Dictionary.Empty // Invalid call
.Add("type_id", "Number")
.Add("call", "Divide")
.Add("args", 5);
IAction action = Assert.IsType<NumberAction>(_loader.LoadAction(0, plainValue));
Address address = new PrivateKey().Address;
Assert.Throws<InvalidOperationException>(() =>
action.Execute(new MockActionContext(address, address, _world)));

plainValue = Dictionary.Empty // Invalid args
.Add("type_id", "Number")
.Add("call", "Add")
.Add("args", "Hello");
action = Assert.IsType<NumberAction>(_loader.LoadAction(0, plainValue));
Assert.IsType<InvalidCastException>(
Assert.Throws<TargetInvocationException>(() =>
action.Execute(new MockActionContext(address, address, _world)))
.InnerException);
}

[Fact]
public void CallableAttributeIsRequired()
{
IValue plainValue = Dictionary.Empty
.Add("type_id", "Number")
.Add("call", "Multiply")
.Add("args", 5);
NumberAction action = Assert.IsType<NumberAction>(_loader.LoadAction(0, plainValue));
Address signer = new PrivateKey().Address;
IWorld world = _world;

Assert.IsType<Exception>(
Assert.Throws<TargetInvocationException>(() =>
action.Execute(new MockActionContext(signer, signer, world)))
.InnerException);
}
}
}
Loading