Files
open-wc/docs/TESTING.md

175 lines
8.8 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Стратегия тестирования OpenWC
## Принцип
Тесты являются частью функционала платформы: Godot Editor должен запускать проверки, показывать diagnostics, открывать проблемную сущность и формировать воспроизводимый playtest bundle. Один ручной запуск сцены не является достаточным доказательством.
## Пирамида тестов
### Unit
- parsers, codecs, bit/byte boundaries и malformed input;
- coordinate transforms и math;
- domain reducers, state machines, formulas и validators;
- schema migrations, ID allocation и semantic diff;
- quest/encounter graph rules;
- material mapping helpers без GPU там, где возможно.
### Contract
- packet fixtures для build 12340;
- golden update fields и packed GUID;
- TrinityCore/AzerothCore schema fingerprints;
- adapter round-trip `canonical → SQL → snapshot → canonical`;
- Content Project compatibility и migration fixtures;
- renderer/editor public API contracts.
- `recast-rs` navigation fixtures: geometry/profile → region/poly/detail counts и path queries.
- Lua VM contract: общий WoW-specific corpus выполняется на `rilua`, PUC-Rio 5.1.1 и, где возможно, оригинальном клиенте 3.3.5a.
- Wowser используется как дополнительный независимый источник auth/world packet cases; fixtures принимаются только после проверки build 12340 semantics и удаления credentials/proprietary payload data.
### Integration
- auth/realm/world session с disposable test core;
- character enum/login/update object/movement;
- asset import → cache → render attach;
- content build → SQL apply → server query;
- Godot Editor command → undo/redo → save/reload.
### End-to-end
- login → character → enter world;
- movement и server reconciliation;
- combat/cast/aura/death;
- quest accept/progress/complete/reward;
- loot/inventory/vendor;
- party/dungeon flow;
- editor NPC + quest → deploy → playtest.
### Visual и performance
- deterministic screenshot checkpoints по картам, времени и погоде;
- perceptual diff с approved baseline и tolerance;
- frame time, hitch percentiles, draw calls, memory, descriptor count и streaming queues;
- long traversal через ADT boundaries;
- dense WMO/M2, water, character equipment и UI scale matrices.
- navmesh overlay checkpoints и bake/query budgets для больших tiles/dungeons.
### Navigation compatibility
- Golden synthetic meshes проверяют slope, climb, radius erosion, holes, tiled seams и off-mesh connections.
- WoW fixtures проверяют canonical coordinates и ADT/WMO collision composition.
- `recast-rs` version и bake profile закрепляются в manifest; обновление требует baseline diff.
- OpenWC navigation cache сравнивается с C++ Recast reference на выбранных fixtures.
- Заявление о server mmap support требует отдельного сравнения с TrinityCore/AzerothCore generator: параметры, tile bounds, polygon queries и фактическое движение существ на disposable core.
- Editor reachability diagnostics должны различать `Reachable`, `Unreachable`, `Unknown` и `Not run`.
### Lua и addon compatibility
- Official Lua 5.1.1 suite запускается на pinned VM revision.
- Oracle tests сравнивают results, errors, byte strings, number formatting, coroutines, metatables, GC-visible behavior и bytecode expectations.
- WoW corpus проверяет restricted stdlib, global aliases, `bit`, BOM, GC defaults и запрещённые filesystem/native-module операции.
- TOC/load order, FrameXML inheritance, events, SavedVariables и addon errors проверяются отдельно от VM.
- Secure actions, combat lockdown и taint propagation имеют обязательные negative tests; без них addon compatibility не получает статус `Verified`.
- Performance suite измеряет `OnUpdate`, event fan-out, table churn, allocation и incremental GC frame budget.
### Exploratory и game design
- quest clarity и travel time;
- encounter readability и recovery;
- economy/reward impact;
- accessibility, localization и atypical input;
- latency/loss/reconnect behavior;
- authoring usability и error recovery.
## Test fixtures
Fixtures должны быть минимальными, обезличенными и легально распространяемыми. Не коммитятся credentials, proprietary bulk assets, account data или production dumps.
Типы fixtures:
- synthetic binary chunks;
- короткие redacted packet captures;
- schema-only/disposable DB seed;
- tiny custom content packs;
- known coordinate points;
- corrupt/truncated input corpus;
- screenshot metadata без обязательного включения proprietary textures.
## Test matrix
Минимальные оси:
- Godot/OS/rendering backend;
- TrinityCore и AzerothCore supported revisions;
- locale;
- quality preset;
- offline/online;
- clean cache/warm cache;
- latency, jitter, packet loss и reconnect;
- content schema current/previous version.
Полная матрица запускается периодически; pull request использует risk-based subset.
## Godot Editor Test Center
Editor dock должен предоставлять:
- Validate Selection, Map, Package и Project;
- список severity/code/location/fix suggestion;
- переход к объекту, полю или viewport position;
- фильтр и baseline известных diagnostics;
- запуск headless test suites;
- playtest checklist и запись результата;
- экспорт machine-readable report для CI.
Quick Fix допускается только как undoable command с preview diff.
## Network verification
- Каждый codec проверяет exact bytes и round-trip.
- Parser никогда не читает за packet boundary.
- Unknown opcode логируется rate-limited и не разрушает session без policy.
- Replay отделён от transport и детерминирован.
- Fuzz/property tests покрывают lengths, masks, packed values, compression и fragmentation.
- Secrets/session keys не появляются в обычных логах.
## Server data verification
Перед apply обязательны schema capability check, foreign references, ID collisions, dry-run и backup/checkpoint. После apply выполняются targeted queries и optional core startup smoke. Rollback тестируется на disposable DB.
## Content validation levels
- Error: сборка или применение запрещены.
- Warning: допустимо после осознанного подтверждения.
- Info: рекомендация или стоимость.
Примеры errors: broken reference, incompatible schema, duplicate allocation, invalid coordinate, unreachable mandatory quest step. Warnings: отсутствующий optional locale, высокая spawn density, превышение render budget.
## Observability
Логи структурированы по subsystem/category/correlation ID. Метрики включают network queues, entity counts, reconciliation errors, asset cache hit rate, editor job durations и validation counts. Пользовательские тексты, credentials и packet payload не логируются по умолчанию.
## CI gates
Изменение не сливается, если не проходят:
- headless project load;
- unit/contract tests затронутых модулей;
- content schema validation;
- deterministic generated artifact check;
- renderer material smoke при изменении renderer;
- adapter dry-run при изменении server mapping;
- documentation link check.
Nightly дополнительно запускает core integration, packet replay corpus, visual checkpoints, traversal performance и migration matrix.
## Definition of Done функции
- acceptance criteria наблюдаемы;
- happy path и минимум один failure/recovery path автоматизированы;
- boundary и malformed cases проверены для parser/network/data;
- diagnostics ведут к проблемному объекту;
- performance budget указан для frame-critical функции;
- manual playtest имеет сценарий и ожидаемый результат;
- regression test воспроизводит исправленный дефект.