Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
39 changes: 14 additions & 25 deletions tests/Neo.Plugins.StateService.Tests/UT_StatePlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
using Neo.Extensions;
using Neo.Json;
using Neo.Network.P2P.Payloads;
using Neo.Persistence.Providers;
using Neo.Plugins.RpcServer;
using Neo.Plugins.StateService.Network;
using Neo.Plugins.StateService.Storage;
Expand All @@ -23,7 +22,6 @@
using Neo.SmartContract.Native;
using Neo.UnitTests;
using Neo.VM;
using System.Reflection;

namespace Neo.Plugins.StateService.Tests
{
Expand All @@ -38,22 +36,11 @@ public class UT_StatePlugin

private StatePlugin? _statePlugin;
private TestBlockchain.TestNeoSystem? _system;
private MemoryStore? _memoryStore;

[TestInitialize]
public void Setup()
{
_memoryStore = new MemoryStore();
_system = new TestBlockchain.TestNeoSystem(s_protocol);
_statePlugin = new StatePlugin();

// Use reflection to call the protected OnSystemLoaded method
var bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
var onSystemLoaded = typeof(StatePlugin).GetMethod("OnSystemLoaded", bindingFlags);
Assert.IsNotNull(onSystemLoaded, "OnSystemLoaded method not found via reflection.");

onSystemLoaded.Invoke(_statePlugin, [_system]);

var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
Expand All @@ -64,13 +51,16 @@ public void Setup()
.GetSection("PluginConfiguration");
StateServiceSettings.Load(config);
Assert.IsTrue(StateServiceSettings.Default.FullState);

// StatePlugin.OnSystemLoaded it's called during the NeoSystem constructor
_system = new TestBlockchain.TestNeoSystem(s_protocol);
}

[TestCleanup]
public void Cleanup()
{
_statePlugin?.Dispose();
_memoryStore?.Dispose();
_system?.Dispose();
}

[TestMethod]
Expand All @@ -79,10 +69,9 @@ public void TestGetStateHeight_Basic()
var result = _statePlugin!.GetStateHeight();

Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(JObject));
Assert.IsInstanceOfType<JObject>(result);

Assert.IsNull(result!["localrootindex"]);
Assert.IsNull(result!["validatedrootindex"]);
Assert.AreEqual("{\"localrootindex\":0,\"validatedrootindex\":null}", result.ToString());
}

[TestMethod]
Expand Down Expand Up @@ -120,7 +109,7 @@ public void TestGetStateRoot_WithMockData_ShouldReturnStateRoot()
var result = _statePlugin!.GetStateRoot(1);

Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(JObject));
Assert.IsInstanceOfType<JObject>(result);

var json = (JObject)result;
Assert.AreEqual(0x00, json["version"]?.AsNumber());
Expand All @@ -141,7 +130,7 @@ public void TestGetProof_WithMockData_ShouldReturnProof()
var result = _statePlugin!.GetProof(rootHash, scriptHash, Convert.ToBase64String([0x01, 0x02]));

Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(JString));
Assert.IsInstanceOfType<JString>(result);

var proof = ((JString)result).Value; // long string
Assert.IsFalse(string.IsNullOrEmpty(proof));
Expand All @@ -157,7 +146,7 @@ public void TestGetState_WithMockData_ShouldReturnValue()

var result = _statePlugin!.GetState(rootHash, scriptHash, [0x01, 0x02]);
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(JString));
Assert.IsInstanceOfType<JString>(result);
Assert.AreEqual("aabb", Convert.FromBase64String(result.AsString() ?? "").ToHexString());
}

Expand All @@ -170,14 +159,14 @@ public void TestFindStates_WithMockData_ShouldReturnResults()

var result = _statePlugin!.FindStates(rootHash, scriptHash, []);
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(JObject));
Assert.IsInstanceOfType<JObject>(result);

var jsonResult = (JObject)result;
Assert.IsNotNull(jsonResult["results"]);
Assert.IsInstanceOfType(jsonResult["results"], typeof(JArray));
Assert.IsInstanceOfType<JArray>(jsonResult["results"]);

var results = (JArray)jsonResult["results"]!;
Assert.AreEqual(2, results.Count);
Assert.HasCount(2, results);

Assert.AreEqual("0102", Convert.FromBase64String(results[0]?["key"]?.AsString() ?? "").ToHexString());
Assert.AreEqual("0304", Convert.FromBase64String(results[1]?["key"]?.AsString() ?? "").ToHexString());
Expand All @@ -186,15 +175,15 @@ public void TestFindStates_WithMockData_ShouldReturnResults()
Assert.IsFalse(jsonResult["truncated"]?.AsBoolean());
}

private void SetupMockStateRoot(uint index, UInt256 rootHash)
private static void SetupMockStateRoot(uint index, UInt256 rootHash)
{
var stateRoot = new StateRoot { Index = index, RootHash = rootHash, Witness = Witness.Empty };
using var store = StateStore.Singleton.GetSnapshot();
store.AddLocalStateRoot(stateRoot);
store.Commit();
}

private UInt256 SetupMockContractAndStorage(UInt160 scriptHash)
private static UInt256 SetupMockContractAndStorage(UInt160 scriptHash)
{
var nef = new NefFile { Compiler = "mock", Source = "mock", Tokens = [], Script = new byte[] { 0x01 } };
nef.CheckSum = NefFile.ComputeChecksum(nef);
Expand Down
8 changes: 4 additions & 4 deletions tests/Neo.UnitTests/SmartContract/Native/UT_NativeContract.cs
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ public void TestGenerateNativeContractApi()

var docsDirectory = LocateDocsDirectory(new DirectoryInfo(Directory.GetCurrentDirectory()));
var outputPath = Path.Combine(docsDirectory.FullName, "native-contracts-api.md");
using (var writer = new StreamWriter(outputPath))
using (var writer = new StreamWriter(outputPath) { NewLine = "\n" })
{
writer.WriteLine("""
# Native Contracts API
Expand Down Expand Up @@ -348,8 +348,8 @@ private static DirectoryInfo LocateDocsDirectory(DirectoryInfo start)
private static string GenMarkdownTable(string contractName, List<ContractMethodMetadata> methods)
{
var table = new System.Text.StringBuilder();
table.AppendLine("| Method | Summary | Parameters | Return Value | CPU fee | Storage fee | Call Flags | Hardfork |");
table.AppendLine("|--------|---------|------------|--------------|---------|-------------|------------|----------|");
table.Append("| Method | Summary | Parameters | Return Value | CPU fee | Storage fee | Call Flags | Hardfork |\n");
table.Append("|--------|---------|------------|--------------|---------|-------------|------------|----------|\n");

foreach (var method in methods)
{
Expand All @@ -363,7 +363,7 @@ private static string GenMarkdownTable(string contractName, List<ContractMethodM
var storageFee = FormatPowerOfTwo(method.StorageFee);
var callFlags = FormatCallFlags(method.RequiredCallFlags);
var hardfork = FormatHardfork(method.ActiveIn, method.DeprecatedIn);
table.AppendLine($"| {methodName} | {summary} | {parameters} | {returnType} | {cpuFee} | {storageFee} | {callFlags} | {hardfork} |");
table.Append($"| {methodName} | {summary} | {parameters} | {returnType} | {cpuFee} | {storageFee} | {callFlags} | {hardfork} |\n");
}

return table.ToString();
Expand Down
28 changes: 24 additions & 4 deletions tests/Neo.UnitTests/TestBlockchain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,43 @@
using Neo.Ledger;
using Neo.Persistence;
using Neo.Persistence.Providers;
using System.Collections.Generic;

#nullable enable

namespace Neo.UnitTests
{
public static class TestBlockchain
{
private class TestStoreProvider : IStoreProvider
{
public readonly MemoryStore Store = new();
public readonly Dictionary<string, MemoryStore> Stores = [];

public string Name => "TestProvider";

public IStore GetStore(string path) => Store;
public IStore GetStore(string? path)
{
path ??= "";

lock (Stores)
{
if (Stores.TryGetValue(path, out var store))
return store;

return Stores[path] = new MemoryStore();
}
}
}

public class TestNeoSystem(ProtocolSettings settings) : NeoSystem(settings, new TestStoreProvider())
{
public void ResetStore()
{
(StorageProvider as TestStoreProvider).Store.Reset();
if (StorageProvider is TestStoreProvider testStore)
{
foreach (var store in testStore.Stores)
store.Value.Reset();
}
Blockchain.Ask(new Blockchain.Initialize()).ConfigureAwait(false).GetAwaiter().GetResult();
}

Expand All @@ -43,9 +61,11 @@ public StoreCache GetTestSnapshotCache(bool reset = true)
}
}

public static readonly UInt160[] DefaultExtensibleWitnessWhiteList;
public static readonly UInt160[]? DefaultExtensibleWitnessWhiteList;

public static TestNeoSystem GetSystem() => new(TestProtocolSettings.Default);
public static StoreCache GetTestSnapshotCache() => GetSystem().GetSnapshotCache();
}
}

#nullable disable