|
| 1 | +#if REGORUS_FFI_TEST_HOOKS |
| 2 | +// Copyright (c) Microsoft Corporation. |
| 3 | +// Licensed under the MIT License. |
| 4 | + |
| 5 | +using System; |
| 6 | +using System.Runtime.InteropServices; |
| 7 | +using Microsoft.VisualStudio.TestTools.UnitTesting; |
| 8 | +using Regorus.Internal; |
| 9 | + |
| 10 | +namespace Regorus.Tests; |
| 11 | + |
| 12 | +[TestClass] |
| 13 | +public sealed class PanicGuardTests |
| 14 | +{ |
| 15 | + [TestInitialize] |
| 16 | + public void Initialize() |
| 17 | + { |
| 18 | + API.regorus_engine_test_reset_poison(); |
| 19 | + } |
| 20 | + |
| 21 | + [TestCleanup] |
| 22 | + public void Cleanup() |
| 23 | + { |
| 24 | + API.regorus_engine_test_reset_poison(); |
| 25 | + } |
| 26 | + |
| 27 | + [TestMethod] |
| 28 | + public void Panic_produces_invalid_operation_exception() |
| 29 | + { |
| 30 | + var panic = Assert.ThrowsException<InvalidOperationException>(TriggerPanic); |
| 31 | + StringAssert.Contains(panic.Message, "panicked", "panic message should capture payload"); |
| 32 | + } |
| 33 | + |
| 34 | + [TestMethod] |
| 35 | + public void Poison_flag_blocks_subsequent_calls() |
| 36 | + { |
| 37 | + _ = Assert.ThrowsException<InvalidOperationException>(TriggerPanic); |
| 38 | + var poisoned = Assert.ThrowsException<InvalidOperationException>(TriggerPanic); |
| 39 | + StringAssert.Contains(poisoned.Message, "poisoned", "poisoned message should explain guard state"); |
| 40 | + } |
| 41 | + |
| 42 | + private static unsafe void TriggerPanic() |
| 43 | + { |
| 44 | + var result = API.regorus_engine_test_trigger_panic(); |
| 45 | + try |
| 46 | + { |
| 47 | + if (result.status == RegorusStatus.Ok) |
| 48 | + { |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + var message = PtrToStringUtf8((IntPtr)result.error_message); |
| 53 | + throw result.status.CreateException(message); |
| 54 | + } |
| 55 | + finally |
| 56 | + { |
| 57 | + API.regorus_result_drop(result); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + private static string? PtrToStringUtf8(IntPtr ptr) |
| 62 | + { |
| 63 | +#if NETSTANDARD2_1 |
| 64 | + return Marshal.PtrToStringUTF8(ptr); |
| 65 | +#else |
| 66 | + if (ptr == IntPtr.Zero) |
| 67 | + { |
| 68 | + return null; |
| 69 | + } |
| 70 | + |
| 71 | + var len = 0; |
| 72 | + while (Marshal.ReadByte(ptr, len) != 0) |
| 73 | + { |
| 74 | + len++; |
| 75 | + } |
| 76 | + |
| 77 | + var buffer = new byte[len]; |
| 78 | + Marshal.Copy(ptr, buffer, 0, buffer.Length); |
| 79 | + return System.Text.Encoding.UTF8.GetString(buffer); |
| 80 | +#endif |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +#endif |
0 commit comments