ModernUO/Projects/UOContent.Tests/Tests/Utilities/TryParseTests.cs
Kamron Batman 1e97ed50f6
fix: Harden Advanced Search: crash-safety, autosave, correct results & worker fixes (#2543)
## Summary

Hardens the **Advanced Search** engine (`Projects/UOContent/Engines/Advanced Search/`) — the GM entity finder that fans searches across background worker threads. A code review surfaced 14 defects (A–N), including a shard-crasher reachable from a single admin typo and a path that silently disables autosave for the rest of the shard's uptime. Each behavioral fix ships with a test.

Full `UOContent.Tests` suite: **530/530 green** (21 new AdvancedSearch tests).

## Fixes

### Crash / data-loss
- **A — Shard crash on a malformed Property Test.** `AdvancedSearchThreadWorker.Execute` had no `try/catch` and the worker `Thread` is foreground, so a parse throw (`Hits>abc`, `Layer=onehanded` — `Enum.Parse` was case-sensitive, `Hits>1@` — empty sub-expression indexing) terminated the process. Now: `ParseValue`/`CompareValues` use `TryParse`/`Enum.TryParse(ignoreCase)` and return no-match instead of throwing; the per-entity filter is wrapped in `try/catch` (logs + skips); empty expressions are guarded.
- **C — Overlapping searches corrupt state + brick autosave.** `_threadWorkers`/`_threadId` were `static` but `DoSearch` is an instance method; a second search (double-click / two admins) stomped shared worker state and could leave a drain waiting forever on the shared `AutoResetEvent`, so `AutoSave.SavesEnabled` was never restored. Now: an `Interlocked` re-entrancy guard rejects concurrent searches.
- **G — Autosave restore not guaranteed.** The restore lived only in the success callback. Now it's in a `finally` (plus an outer `catch` covering the synchronous setup and a `catch` on the drain body), so autosave + the guard are always released.

### Wrong results
- **D — `@`/`|` operator precedence.** `a@b|c` evaluated as `a && (b || c)` instead of `(a && b) || c`. OR now binds looser than AND (`AdvancedSearchUtilities.EvaluateBoolean`, unit-tested).
- **E — Descending sort, partial last page rendered blank** (the index decreased in descending mode and the `break` early-out killed the loop). Now a bounded `VisibleCount`-driven loop renders the last page in both directions.
- **F — Deleted entities** were not skipped (ghost rows). Now `DoEntitySearch` skips `entity.Deleted`.
- **N — Reference-type comparisons** threw (`Comparer<T>.Default.Compare` on non-`IComparable`) and compared references to a string. Now equality is by value and ordering is guarded to `IComparable` (no throw).

### Worker perf / hardening
- **H** busy-spin → `Thread.Yield()` in the drain; **I** `GetProperties()` cached per `Type`; **J** `HandleValidInternal` moved behind the cheap map/range/region filters; **K** worker threads are `IsBackground` + `Exit()` tolerates an already-terminated worker; **L** `_filter == null` guard; **M** consistent `Volatile` access on `_pause`/`_exit`.

### Documented
- **B** — the residual worker/event-loop read race is documented on `AdvancedSearchThreadWorker`: workers read live entity state concurrently with the loop, so value-type reads may be stale-but-safe and getter exceptions are swallowed; fully eliminating it would require snapshotting entity fields on the main thread (deferred).

## Notes
- New test-only seams (`TryBeginSearch`/`EndSearch`/`IsSearchInProgress`/`VisibleCount`/`TryParseValue`/`EvaluateBoolean`) are `internal` via the existing `InternalsVisibleTo("UOContent.Tests")`.
- Dead `public ParseValue<T>` removed.
- `ConcurrentDictionary` for the reflection cache is intentional — these workers are genuinely parallel.
2026-07-21 07:51:06 -07:00

47 lines
1.6 KiB
C#

using System;
using Xunit;
namespace Server.Tests.Utility;
public class TryParseTests
{
[Theory]
[InlineData("True", null, true)]
[InlineData("False", null, false)]
[InlineData("Alakazam", "Not a valid boolean string.", true)]
public void TestTryParseBool(string value, string returned, bool parsedAs)
{
var actualReturned = Server.Types.TryParse(typeof(bool), value, out var constructed);
Assert.Equal(returned, actualReturned);
if (returned == null)
{
Assert.Equal(parsedAs, constructed);
}
}
[Theory]
// Parsed directly into the target type (INumber<T>.TryParse), not via ulong + Convert.ChangeType.
[InlineData(typeof(int), "42", true, 42)]
[InlineData(typeof(int), "-5", true, -5)] // signed values parse directly now
[InlineData(typeof(int), "0xFF", true, 255)] // hex
[InlineData(typeof(int), "notanumber", false, null)]
[InlineData(typeof(byte), "255", true, (byte)255)]
[InlineData(typeof(byte), "256", false, null)] // out of the byte range
[InlineData(typeof(uint), "4294967295", true, 4294967295u)]
[InlineData(typeof(long), "-9000000000", true, -9000000000L)]
public void TestTryParseNumeric(Type type, string value, bool success, object expected)
{
var error = Server.Types.TryParse(type, value, out var constructed);
if (success)
{
Assert.Null(error);
Assert.Equal(expected, constructed);
}
else
{
Assert.NotNull(error);
}
}
}