QA

Testing

Test cases from three projects: a Unity game, a WordPress site and this portfolio site. Each case has preconditions, steps, an expected result and the test code. When a case found a defect, you also see what happened before the fix and the code of the fix itself.

test cases
26
automated
22
defects found and fixed
21
cases passed
26

Test cases · 10

The Hidden Library

A 2D point-and-click game in Unity: story, dialogues, mini-games, saves in three slots and four languages. I tested quest logic, saves, the inventory and scene data integrity.

  • Unity 6
  • C#
  • NUnit
  • Unity Test Framework
  • FMOD
Project page

The “before the fix” status of the game tests comes from reading the code and scene data: a licence issue blocked running Unity from the command line before the changes. After the fixes all 24 tests were run in the Test Runner.

TC-THL-01 Passed

The password hint unlocks after the trade with the cat

  • Automated
  • Integration, EditMode
  • Priority: high
  • BUG-01
Preconditions
  • The cat quest is completed up to trading catnip for the note
  • The shed table requires the cat trade
Steps
  1. Set the flag the cat quest writes after the trade
  2. Put the password note in the inventory
  3. Ask the table whether dialogue D26 may start
  4. Repeat without the flag and without the note
Expected result
With the flag and the note, D26 is unlocked. Without either one, it stays locked.
Actual result before the fix Failed before the fix
PaperDialogUnlocksAfterCatExchange failed. The cat wrote cat_exchange_done while the table waited for cat_catnip_given, which nothing ever set. The password hint never played.
Fix
One shared constant in ProgressFlags for both scripts, the old key removed. The flag value is unchanged, so old saves still work.
Test code CatTradeTableDialogTests.cs
public class CatTradeTableDialogTests
{
    [SetUp]
    public void SetUp()
    {
        _saveHost = new GameObject("SaveManager");
        _saveManager = _saveHost.AddComponent<SaveManager>();
        SetSaveManagerInstance(_saveManager);

        _playerHost = new GameObject("Player");
        _inventory = _playerHost.AddComponent<PlayerInventory>();
        PlayerBrain brain = _playerHost.AddComponent<PlayerBrain>();
        ReflectionTestHelper.SetField(brain, "_playerInventory", _inventory);

        _paperPassword = ScriptableObject.CreateInstance<T_Item>();

        _tableHost = new GameObject("Table");
        _table = _tableHost.AddComponent<CircleTableMiniGameWorld>();
        ReflectionTestHelper.SetField(_table, "_playerBrain", brain);
        ReflectionTestHelper.SetField(_table, "_paperPasswordItem", _paperPassword);
        ReflectionTestHelper.SetField(_table, "_requireCatTrade", true);
    }

    // Флаг берётся у того, кто его пишет (квест кота), а не у того, кто читает (стол).
    // Так тест ловит расхождение ключей между двумя скриптами.
    private static string FlagWrittenByCatQuest()
    {
        FieldInfo field = typeof(CatQuestProgress).GetField("F_EXCHANGE_DONE", BindingFlags.NonPublic | BindingFlags.Static);
        Assert.IsNotNull(field);
        return (string)field.GetValue(null);
    }

    private bool TableUnlocksPaperDialog()
    {
        return (bool)ReflectionTestHelper.Invoke(_table, "HasPaperPasswordAfterCatTrade");
    }

    [Test]
    public void PaperDialogStaysLockedBeforeCatExchange()
    {
        _inventory.AddItem(_paperPassword);
        Assert.IsFalse(TableUnlocksPaperDialog());
    }

    [Test]
    public void PaperDialogNeedsPaperInInventory()
    {
        _saveManager.SetFlag(FlagWrittenByCatQuest(), true);
        Assert.IsFalse(TableUnlocksPaperDialog());
    }

    [Test]
    public void PaperDialogUnlocksAfterCatExchange()
    {
        _saveManager.SetFlag(FlagWrittenByCatQuest(), true);
        _inventory.AddItem(_paperPassword);

        Assert.IsTrue(TableUnlocksPaperDialog());
    }
}
Fix code ProgressFlags.cs, CatQuestProgress.cs, CircleTableMiniGameWorld.cs
// ProgressFlags.cs: один ключ на два скрипта
public const string CatExchangeDone = "cat_exchange_done";

// CatQuestProgress.cs: квест кота пишет флаг
private const string F_EXCHANGE_DONE = ProgressFlags.CatExchangeDone;

// CircleTableMiniGameWorld.cs: стол читает тот же флаг
bool tradeCompleted = ProgressFlags.Get(ProgressFlags.CatExchangeDone, false);
TC-THL-02 Passed

Every scene item is in the database and survives loading

  • Automated
  • Data integrity, EditMode
  • Priority: high
  • BUG-02
Preconditions
  • GameScene is open
  • The save stores inventory items by Id
Steps
  1. Collect every item reference in every scene component, dialogue lines included
  2. Compare them with the _allItems list in the item database
  3. Separately load the inventory from a list with a known and an unknown Id
Expected result
No item is missing from the database. The known item is restored, the unknown Id is skipped without an error.
Actual result before the fix Failed before the fix
ItemDatabaseCoversItemsUsedInGameScene failed: the umbrella was listed twice instead of the password note. After saving and Continue the note vanished, with “Skip unknown item id” in the log. A regression: this bug had been closed before.
Fix
The second umbrella in _allItems was replaced with the note. One line of the scene changed, and the test now guards against this coming back.
Test code ProjectIntegrityTests.cs, PlayerInventoryTests.cs
// ProjectIntegrityTests.cs
[Test]
public void ItemDatabaseCoversItemsUsedInGameScene()
{
    LogAssert.ignoreFailingMessages = true;
    Scene scene = EditorSceneManager.OpenScene(GameScenePath, OpenSceneMode.Additive);

    try
    {
        MonoBehaviour[] behaviours = scene.GetRootGameObjects()
            .SelectMany(root => root.GetComponentsInChildren<MonoBehaviour>(true))
            .Where(behaviour => behaviour != null)
            .ToArray();

        BaseGameInformation database = behaviours.OfType<BaseGameInformation>().Single();
        HashSet<T_Item> known = CollectItems(database);
        var used = new HashSet<T_Item>();

        foreach (MonoBehaviour behaviour in behaviours)
        {
            if (behaviour != database)
                used.UnionWith(CollectItems(behaviour));
        }

        // Любой предмет, который сцена может положить в инвентарь,
        // обязан быть в базе, иначе после загрузки он пропадёт.
        CollectionAssert.IsEmpty(used.Where(item => !known.Contains(item)).Select(item => item.name));
    }
    finally
    {
        EditorSceneManager.CloseScene(scene, true);
    }
}

// Обходит все сериализованные ссылки компонента, включая реплики диалогов.
private static HashSet<T_Item> CollectItems(Object source)
{
    var items = new HashSet<T_Item>();
    SerializedProperty property = new SerializedObject(source).GetIterator();

    while (property.Next(true))
    {
        if (property.propertyType != SerializedPropertyType.ObjectReference)
            continue;

        if (property.objectReferenceValue is T_Item item)
            items.Add(item);
        else if (property.objectReferenceValue is DialogSettingConfig line)
            items.UnionWith(CollectItems(line));
    }

    return items;
}

// PlayerInventoryTests.cs
[Test]
public void LoadRestoresKnownItemsAndSkipsUnknown()
{
    T_Item pruner = CreateItem("Pruner");
    BaseGameInformation database = Track(new GameObject("Database")).AddComponent<BaseGameInformation>();
    ReflectionTestHelper.SetField(database, "_allItems", new List<T_Item> { pruner });
    database.InitAwake();

    _inventory.SetItemsByIds(new List<string> { pruner.Id, "unknown_id" });

    CollectionAssert.AreEqual(new[] { pruner.Id }, _inventory.GetItemIds());
}
TC-THL-03 Passed

The world ignores clicks during a dialogue

  • Manual
  • System, manual
  • Priority: high
  • BUG-04
Preconditions
  • A game build or Play Mode
  • The heroine is next to a character or object with a dialogue
Steps
  1. Start any dialogue
  2. Press I, then I again
  3. Click the floor
  4. Click a door
Expected result
The inventory does not open, the heroine stays put, a click only advances the dialogue.
Actual result before the fix Failed before the fix
Closing the inventory lifted the input lock. The heroine walked with a dialogue open, and a new dialogue overwrote the current callback. At a door with a dialogue this caused a soft lock until the scene was restarted.
Fix
An IsDialogActive property on DialogController. While a dialogue runs, I does not open the inventory, and an already open one can only be closed.
Fix code DialogController.cs, InputController.cs
// DialogController.cs
public bool IsDialogActive => _isWork;

// InputController.cs
private bool CanToggleInventory()
{
    if (DialogController.Instance == null || !DialogController.Instance.IsDialogActive) return true;

    // Во время диалога инвентарь можно только закрыть, если он уже открыт.
    PlayerInventory inventory = _playerBrain.GetPlayerInventory();
    return inventory != null && inventory.IsInventoryOpen();
}

private void Update()
{
    if (Input.GetKeyDown(KeyCode.I))
    {
        if (_playerBrain == null) _playerBrain = PlayerBrain.Instance;
        if (_playerBrain != null && CanToggleInventory()) _playerBrain.ToggleInventory();
        return;
    }
    // ...
}
TC-THL-04 Passed

Quitting during the intro cutscene does not corrupt the slot

  • Manual
  • System, manual
  • Priority: medium
  • BUG-05
Preconditions
  • An empty save slot
Steps
  1. Start a new game in an empty slot from the main menu
  2. Close the window during the cutscene (Alt+F4)
  3. Launch the game again
Expected result
The slot stays empty, Continue loads nothing, a new game starts from the spawn point.
Actual result before the fix Failed before the fix
A save file appeared in the slot. The player spawned at (0, 0, 0) instead of (37.85, -28.81), and the location camera was not saved.
Fix
On quit the save is skipped if the slot has never been saved and there is no player in the scene. Normal saves and autosaves are unaffected.
Fix code SaveManager.cs
// SaveManager.cs
private void OnApplicationQuit()
{
    if (SceneManager.GetActiveScene().buildIndex == 0)
        return;

    // Слот ещё ни разу не сохранялся, а игрока в сцене нет (идёт ролик):
    // писать нечего, иначе в файл попадёт позиция (0, 0, 0).
    if (_current != null && _current.lastSavedUtcTicks == 0 && FindPlayerForSave() == null)
        return;

    SaveNow();
}
TC-THL-05 Passed

Rapid floor clicks do not pile up footstep sounds

  • Manual
  • System, manual, FMOD Profiler
  • Priority: medium
  • BUG-03
Preconditions
  • Play Mode
  • FMOD Profiler is open
Steps
  1. Click the floor far from the heroine
  2. While she walks, click 10 different points
  3. Watch the Instances counter of the footsteps event
Expected result
Only one footsteps instance is alive at a time, sounds do not overlap.
Actual result before the fix Failed before the fix
Every click created a new EventInstance while the old one was never stopped or released. Instances piled up in FMOD.
Fix
The existing StopFootsteps() is called before a new instance is created: it fades the sound out and releases the instance.
Fix code PlayerMoveController.cs
// PlayerMoveController.cs
private void SetStartMove(Action moveDone)
{
    _moving = true;
    _callBackMoveDone = moveDone;
    _transformTarget.position = new Vector3(_target.x, _target.y, _transformTarget.position.z);

    TurnPlayer(_target);
    _playerAnimController.SetMove();

    // Гасит и освобождает прошлый экземпляр, прежде чем создать новый.
    StopFootsteps();

    footstepsInstance = RuntimeManager.CreateInstance(footstepsEvent);
    footstepsInstance.start();

    _footstepCoroutine = StartCoroutine(PlayFootstepsLoop());
}
TC-THL-06 Passed

Build scenes contain no missing scripts

  • Automated
  • Scene integrity, EditMode
  • Priority: medium
  • BUG-06
Preconditions
  • Scenes are listed in Build Settings
Steps
  1. Open each scene from Build Settings in turn
  2. Walk every object and its children
  3. Count components that reference a missing script
Expected result
Not a single object with a missing script.
Actual result before the fix Failed before the fix
Failed: the Default Sound object in GameScene had a component pointing to a script GUID that exists neither in the project nor in git history.
Fix
Only the empty component was removed; Transform and AudioSource stayed.
Test code ProjectIntegrityTests.cs
[Test]
public void BuildScenesHaveNoMissingScripts()
{
    LogAssert.ignoreFailingMessages = true;
    var broken = new List<string>();

    foreach (EditorBuildSettingsScene buildScene in EditorBuildSettings.scenes)
    {
        Scene scene = EditorSceneManager.OpenScene(buildScene.path, OpenSceneMode.Additive);

        try
        {
            foreach (GameObject root in scene.GetRootGameObjects())
                CollectMissingScripts(root, buildScene.path, broken);
        }
        finally
        {
            EditorSceneManager.CloseScene(scene, true);
        }
    }

    CollectionAssert.IsEmpty(broken);
}

private static void CollectMissingScripts(GameObject gameObject, string scenePath, List<string> broken)
{
    if (GameObjectUtility.GetMonoBehavioursWithMissingScriptCount(gameObject) > 0)
        broken.Add($"{scenePath}: {gameObject.name}");

    foreach (Transform child in gameObject.transform)
        CollectMissingScripts(child.gameObject, scenePath, broken);
}
TC-THL-07 Passed

All source files are UTF-8

  • Automated
  • Static check, EditMode
  • Priority: medium
  • BUG-07
Preconditions
  • Scripts live in Assets/Scripts, Assets/Editor and Assets/Tests
Steps
  1. Read the bytes of every .cs file
  2. Decode them with a strict UTF-8 decoder that throws on a bad byte
Expected result
No file fails to decode.
Actual result before the fix Failed before the fix
Failed: 67 of 127 scripts were in Windows-1251. On GitHub and in editors Russian text turned into “�”, and string literals could compile wrong.
Fix
All 67 files were converted to UTF-8. Converting back gave identical bytes, and the text was compared with HEAD line by line.
Test code ProjectIntegrityTests.cs
private static readonly string[] SourceFolders = { "Assets/Scripts", "Assets/Editor", "Assets/Tests" };

[Test]
public void SourceFilesAreUtf8()
{
    // Строгий декодер бросает исключение на любом байте, который не является UTF-8.
    var strictUtf8 = new UTF8Encoding(false, true);
    var broken = new List<string>();

    foreach (string folder in SourceFolders.Where(Directory.Exists))
    {
        foreach (string path in Directory.GetFiles(folder, "*.cs", SearchOption.AllDirectories))
        {
            try
            {
                strictUtf8.GetString(File.ReadAllBytes(path));
            }
            catch (DecoderFallbackException)
            {
                broken.Add(path);
            }
        }
    }

    CollectionAssert.IsEmpty(broken);
}
TC-THL-08 Passed

A save survives a JSON round trip intact

  • Automated
  • Unit, EditMode
  • Priority: high
Preconditions
  • SaveManager is created on an empty object
Steps
  1. Check the default value of a missing flag
  2. Mark the same object as collected twice
  3. Fill SaveData: scene, location, time, position, inventory, flags
  4. Serialise to JSON and parse it back
Expected result
A missing flag returns its default, a collected object is stored once, every field of the copy equals the original.
Test code SaveManagerTests.cs
public class SaveManagerTests
{
    [Test]
    public void MissingFlagReturnsDefault()
    {
        Assert.IsTrue(_saveManager.GetFlag("missing_flag", true));
        Assert.IsFalse(_saveManager.GetFlag("missing_flag"));
    }

    [Test]
    public void CollectedIdIsStoredOnce()
    {
        _saveManager.MarkCollected("item_1");
        _saveManager.MarkCollected("item_1");

        Assert.IsTrue(_saveManager.WasCollected("item_1"));
        Assert.IsFalse(_saveManager.WasCollected("item_2"));

        SaveData data = ReflectionTestHelper.GetField<SaveData>(_saveManager, "_current");
        Assert.AreEqual(1, data.collectedPersistentIds.Count);
    }

    [Test]
    public void SaveDataSurvivesJsonRoundTrip()
    {
        var data = new SaveData
        {
            sceneBuildIndex = 2,
            activeLocationName = "Kitchen",
            totalPlaySeconds = 125.5,
            lastSavedUtcTicks = 638000000000000000,
            playerPos = new SerializableVector3(new Vector3(37.85f, -28.81f, 0f)),
            inventoryItemIds = { "key", "pruner" },
            collectedPersistentIds = { "hairpin_on_floor" },
            boolFlags = { new StringBoolPair { key = "vines_cut", value = true } }
        };

        SaveData copy = JsonUtility.FromJson<SaveData>(JsonUtility.ToJson(data));

        Assert.AreEqual(data.sceneBuildIndex, copy.sceneBuildIndex);
        Assert.AreEqual(data.activeLocationName, copy.activeLocationName);
        Assert.AreEqual(data.totalPlaySeconds, copy.totalPlaySeconds);
        Assert.AreEqual(data.lastSavedUtcTicks, copy.lastSavedUtcTicks);
        Assert.AreEqual(data.playerPos.ToVector3(), copy.playerPos.ToVector3());
        CollectionAssert.AreEqual(data.inventoryItemIds, copy.inventoryItemIds);
        CollectionAssert.AreEqual(data.collectedPersistentIds, copy.collectedPersistentIds);
        Assert.AreEqual("vines_cut", copy.boolFlags[0].key);
        Assert.IsTrue(copy.boolFlags[0].value);
    }
}
TC-THL-09 Passed

A dialogue line waits for the required item and takes it

  • Automated
  • Unit, EditMode
  • Priority: medium
Preconditions
  • A dialogue of two lines
  • The second line requires catnip
Steps
  1. Ask whether the next line is available with an empty inventory
  2. Add catnip and ask again
  3. Mark the line as consuming the item and check the inventory
  4. Step forward five times in a two-line dialogue
Expected result
Without catnip the line is locked, with it unlocked. A consuming line removes the catnip. The line counter stops at the end.
Test code DialogConteynerTests.cs
public class DialogConteynerTests
{
    private DialogSettingConfig CreateLine(params T_Item[] requiredItems)
    {
        DialogSettingConfig line = Track(ScriptableObject.CreateInstance<DialogSettingConfig>());
        line._itemsNeedsForTalk = new List<T_Item>(requiredItems);
        return line;
    }

    [Test]
    public void NextLineWaitsForRequiredItem()
    {
        T_Item catnip = Track(ScriptableObject.CreateInstance<T_Item>());
        DialogConteyner dialog = CreateDialog(CreateLine(), CreateLine(catnip));

        Assert.IsFalse(dialog.CheckIsCanTalkNextSentence(_inventory));

        _inventory.AddItem(catnip);

        Assert.IsTrue(dialog.CheckIsCanTalkNextSentence(_inventory));
        Assert.IsTrue(_inventory.HasItem(catnip));
    }

    [Test]
    public void RequiredItemIsTakenWhenLineConsumesIt()
    {
        T_Item catnip = Track(ScriptableObject.CreateInstance<T_Item>());
        DialogSettingConfig giveCatnip = CreateLine(catnip);
        giveCatnip._itemsMustBeenDelete = true;

        DialogConteyner dialog = CreateDialog(CreateLine(), giveCatnip);
        _inventory.AddItem(catnip);

        Assert.IsTrue(dialog.CheckIsCanTalkNextSentence(_inventory));
        Assert.IsFalse(_inventory.HasItem(catnip));
    }

    [Test]
    public void StepDoesNotRunPastEnd()
    {
        DialogConteyner dialog = CreateDialog(CreateLine(), CreateLine());

        for (int i = 0; i < 5; i++)
            dialog.SetNextOfSentence();

        Assert.AreEqual(2, dialog.GetStepOfDialog());

        dialog.ResetStep();
        Assert.AreEqual(0, dialog.GetStepOfDialog());
    }
}
TC-THL-10 Passed

The inventory adds and removes items one at a time

  • Automated
  • Unit, EditMode
  • Priority: medium
Preconditions
  • PlayerInventory is created on an empty object
Steps
  1. Add null
  2. Add a key and its copy, remove three times
  3. Add three catnips, remove two by name
  4. Add two items and get the Id list
Expected result
null is rejected. One copy is removed at a time, the third removal returns false. One catnip remains. Id order matches insertion order.
Test code PlayerInventoryTests.cs
public class PlayerInventoryTests
{
    [Test]
    public void NullItemIsRejected()
    {
        Assert.IsFalse(_inventory.AddItem(null).Result);
    }

    [Test]
    public void RemoveItemTakesOneCopyAtATime()
    {
        T_Item key = CreateItem("Key");
        T_Item copy = Track(Object.Instantiate(key));

        _inventory.AddItem(key);
        _inventory.AddItem(copy);

        Assert.IsTrue(_inventory.RemoveItem(key).Result);
        Assert.IsTrue(_inventory.HasItem(key));
        Assert.IsTrue(_inventory.RemoveItem(key).Result);
        Assert.IsFalse(_inventory.HasItem(key));
        Assert.IsFalse(_inventory.RemoveItem(key).Result);
    }

    [Test]
    public void RemoveByNameRespectsCount()
    {
        _inventory.AddItem(CreateItem("Catnip"));
        _inventory.AddItem(CreateItem("Catnip"));
        _inventory.AddItem(CreateItem("Catnip"));

        Assert.AreEqual(2, _inventory.RemoveItemsByName("Catnip", 2));
        Assert.AreEqual(1, _inventory.CountItemsByName("Catnip"));
    }

    [Test]
    public void ItemIdsKeepInventoryOrder()
    {
        T_Item first = CreateItem("First");
        T_Item second = CreateItem("Second");

        _inventory.AddItem(first);
        _inventory.AddItem(second);

        CollectionAssert.AreEqual(new[] { first.Id, second.Id }, _inventory.GetItemIds());
    }
}

Test cases · 5

BrandGallery Home

A WordPress and WooCommerce site for an Italian furniture showroom: catalogue, request form, price sync with a partner, staff admin. I tested entry points, form protection, permissions and pricing logic.

  • PHP 8.2
  • WordPress
  • WooCommerce
  • Node.js
Project page
TC-BGH-01 Passed

Another selection from the same customer becomes a new request

  • Automated
  • Integration, WordPress stubs
  • Priority: high
  • BUG-01
Preconditions
  • Duplicate merging: an identical request within 30 minutes does not create a new card
  • The same phone number
Steps
  1. Submit a selection of items 11 and 12
  2. Submit the same selection again
  3. Submit a selection of items 40 and 41
  4. Compare the fingerprints of the two selections
Expected result
Repeating the same selection is merged: one card, repeat counter 1. A different selection makes a second card and a second email to the showroom. No PHP warnings.
Actual result before the fix Failed before the fix
4 failures. The visitor saw “Request sent” but no new card or email appeared. implode() joined the item arrays into “Array,Array”, so the fingerprint ignored what was selected.
Fix
The fingerprint now uses item ids via array_column().
Test code tools/request-test.php
<?php
// tools/request-test.php, раздел «Повторная отправка».
// send() вызывает настоящий обработчик формы на заглушках WordPress,
// $store держит в памяти заявки и письма вместо базы и почты.

reset_store();
$first = send(form());
check('заявка записана и ушла письмом', true === $first->ok && 1 === count($store['posts']) && 1 === count($store['mail']));

$again = send(form());
check('та же заявка второй раз не заводит карточку и письмо',
    true === $again->ok && 1 === count($store['posts']) && 1 === count($store['mail']));
check('у первой заявки растёт счётчик повторов', 1 === (int) get_post_meta(1, '_bgh_repeats', true));

reset_store();
send(form(array('items' => '11,12')));
$other = send(form(array('items' => '40,41')));
check('другая подборка того же человека становится новой заявкой',
    true === $other->ok && 2 === count($store['posts']), 'записей: ' . count($store['posts']));
check('письмо о второй подборке ушло в салон', 2 === count($store['mail']), 'писем: ' . count($store['mail']));

$base = array('phone' => array('e164' => '+79180001122'), 'kind' => 'podborka', 'note' => '', 'goals' => array());
check('отпечаток различает состав подборки',
    bgh_request_fingerprint($base + array('items' => bgh_request_items('11,12')))
    !== bgh_request_fingerprint($base + array('items' => bgh_request_items('40,41'))));

echo "\nПредупреждения PHP\n";
check('за прогон ни одного предупреждения', !$warnings, implode('; ', array_slice(array_unique($warnings), 0, 2)));
Fix code includes/request-submit.php
<?php
// includes/request-submit.php
function bgh_request_fingerprint($data)
{
    return md5(implode('|', array(
        $data['phone']['e164'],
        $data['kind'],
        $data['note'],
        implode(',', $data['goals']),
        // Было: implode(',', $data['items']). Позиции приходят массивами,
        // и любая подборка из двух товаров превращалась в «Array,Array».
        implode(',', array_map('intval', array_column((array) $data['items'], 'id'))),
    )));
}
TC-BGH-02 Passed

A made-to-order item gets no price unless the partner has stock

  • Automated
  • Unit, state transition table
  • Priority: medium
  • BUG-02
Preconditions
  • Per the docs a made-to-order item has no price
  • Partner price 120,000
Steps
  1. Run the price write for every combination: site state (Moscow, to order, Krasnodar) × partner stock (in, out, unknown)
  2. Check the state and price afterwards
Expected result
To order + out or unknown: no price. To order + in: “In stock in Moscow” with a price. Moscow + out: to order with no price. Krasnodar is left alone.
Actual result before the fix Failed before the fix
2 failures. The storefront showed “To order” with a price. Saving the card wiped it, and 12 hours later the sync put it back.
Fix
An early return in bgh_price_write() when the item is to order and the partner has no stock.
Test code tools/price-sync-test.php
<?php
// tools/price-sync-test.php, раздел «Запись цены и наличия».
// Товар и его метаполя живут в памяти, WooCommerce не нужен.

function sync_case($state, $price, $partner, $stock)
{
    static $id = 100;

    $id++;
    $GLOBALS['bgh_meta'][$id] = array('_bgh_stock_state' => $state);

    $product = new BghTestProduct($id, $price);
    bgh_price_write($product, $partner, $stock);

    return array(bgh_get_stock_state($id), $product->get_regular_price());
}

// Шесть переходов: состояние на сайте × наличие у партнёра.
same('Москва, у партнёра есть: новая цена', sync_case('moscow', '100000', 120000.0, 'in'), array('moscow', '120000'));
same('Москва, у партнёра кончилось: под заказ без цены', sync_case('moscow', '100000', 120000.0, 'out'), array('order', ''));
same('под заказ, у партнёра появилось: Москва с ценой', sync_case('order', '', 120000.0, 'in'), array('moscow', '120000'));
same('под заказ, у партнёра нет: цена не появляется', sync_case('order', '', 120000.0, 'out'), array('order', ''));
same('под заказ, наличие у партнёра не размечено: цена не появляется', sync_case('order', '', 120000.0, ''), array('order', ''));
same('Краснодар не трогается, цена обновляется', sync_case('krasnodar', '100000', 120000.0, 'out'), array('krasnodar', '120000'));
Fix code includes/price-sync.php
<?php
// includes/price-sync.php, bgh_price_write()
if ('out' === $stock && 'moscow' === $state) {
    // ... перевод в «Под заказ» и очистка цены
    return true;
}

// Позиция под заказ получает цену только вместе с наличием у партнёра.
// Раньше сочетания «под заказ + нет» и «под заказ + неизвестно»
// проваливались в общую ветку записи цены.
if ('order' === $state && 'in' !== $stock) {
    return false;
}

if (abs($value - $current) >= 0.5) {
    $price = wc_format_decimal($value);
    $product->set_regular_price($price);
    // ...
}
TC-BGH-03 Passed

Bulk edit without a nonce changes nothing (CSRF)

  • Automated
  • Security, integration
  • Priority: high
  • BUG-03
Preconditions
  • A staff member is logged into the admin
  • The bulk edit handler is hooked to load-edit.php
Steps
  1. Open the product list with bulk edit parameters but no nonce
  2. Repeat with the nonce the real form sends
  3. Repeat for a product the user has no permission to edit
Expected result
Without a nonce the request stops and stock and prices stay. The real form works. A product without permission is untouched.
Actual result before the fix Failed before the fix
2 failures. A link opened by a logged-in staff member switched products to “To order” and wiped their prices. The hook fires before WordPress core checks the nonce, and a permission check does not stop CSRF.
Fix
The handler starts with the same check_admin_referer('bulk-posts') call that core makes.
Test code tools/bulk-edit-test.php
<?php
// tools/bulk-edit-test.php
// Обработчик висит на load-edit.php, здесь его вызывают напрямую.

// Настоящая check_admin_referer при неудаче обрывает запрос.
function check_admin_referer($action)
{
    if (!isset($_REQUEST['_wpnonce']) || 'nonce:' . $action !== $_REQUEST['_wpnonce']) {
        throw new Stop($action);
    }

    return 1;
}

function run_list_screen($query)
{
    $_GET     = $query;
    $_REQUEST = $query;

    try {
        foreach ($GLOBALS['hooks']['load-edit.php'] as $callback) {
            $callback();
        }
    } catch (Stop $stop) {
        return 'остановлен';
    }

    return 'выполнен';
}

$forged = array(
    'post_type'       => 'product',
    'bulk_edit'       => '1',
    'post'            => array('11', '12'),
    'bgh_stock_state' => 'order',
);

echo "Подделанная ссылка\n";
catalog();
$result = run_list_screen($forged);
check('без nonce списка запрос обрывается', 'остановлен' === $result, $result);
check('наличие у товаров не поменялось',
    'krasnodar' === get_post_meta(11, '_bgh_stock_state', true) && 'moscow' === get_post_meta(12, '_bgh_stock_state', true));

echo "\nНастоящая групповая правка\n";
catalog();
$result = run_list_screen($forged + array('bgh_lead' => '10–12 недель', '_wpnonce' => 'nonce:bulk-posts'));
check('с nonce списка правка проходит', 'выполнен' === $result, $result);
check('наличие поменялось у отмеченных',
    'order' === get_post_meta(11, '_bgh_stock_state', true) && 'order' === get_post_meta(12, '_bgh_stock_state', true));

echo "\nПрава\n";
catalog();
run_list_screen(array('post' => array('13')) + $forged + array('_wpnonce' => 'nonce:bulk-posts'));
check('товар без права на правку не меняется', 'moscow' === get_post_meta(13, '_bgh_stock_state', true));
Fix code includes/admin/product-ui.php
<?php
// includes/admin/product-ui.php
add_action('load-edit.php', function () {
    if (empty($_GET['bulk_edit']) || empty($_GET['post'])) {
        return;
    }

    // Хук срабатывает раньше, чем ядро проверит nonce списка.
    // Без своей проверки чужая ссылка, открытая сотрудником,
    // переводила товары в «Под заказ» и стирала им цены.
    check_admin_referer('bulk-posts');

    $state = sanitize_key(wp_unslash($_GET['bgh_stock_state'] ?? ''));
    // ...
});
TC-BGH-04 Passed

Spam protection layers of the request form

  • Automated
  • Integration, automated checklist
  • Priority: high
Preconditions
  • The form handler runs on stubs, with database and mail in memory
Steps
  1. Fill in the hidden honeypot field
  2. Submit with a foreign nonce
  3. Submit right after the page loads
  4. Put a link in the comment
  5. Untick the consent box
  6. Send four requests from one address within an hour
Expected result
The honeypot replies as if successful but stores nothing and is logged. Other rejections store nothing and highlight the right field. The fourth request gets a polite refusal with the showroom phone.
Test code tools/request-test.php
<?php
// tools/request-test.php, раздел «Слои защиты формы».

reset_store();
$reply = send(form(array('email' => 'bot@example.com')));
check('ловушка: ответ такой же, как при успехе', true === $reply->ok);
check('ловушка: заявки нет и письмо не ушло', !$store['posts'] && !$store['mail']);
check('ловушка: попытка записана в журнал', 'заполнено скрытое поле' === last_reject(), last_reject());

reset_store();
$reply = send(form(array('nonce' => 'bad')));
check('чужой nonce отклоняется', false === $reply->ok && !$store['posts']);

reset_store();
$reply = send(form(array('stamp' => bgh_form_stamp())));
check('отправка сразу после загрузки отклоняется', false === $reply->ok && !$store['posts']);

reset_store();
$reply = send(form(array('note' => 'подробности на https://spam.example')));
check('ссылка в комментарии: отказ с подсветкой поля', false === $reply->ok && 'note' === $reply->data['field']);

reset_store();
$reply = send(form(array('agree' => '')));
check('без согласия заявка не уходит', false === $reply->ok && 'agree' === $reply->data['field']);

reset_store();
foreach (array('+7 918 000-11-01', '+7 918 000-11-02', '+7 918 000-11-03') as $number) {
    send(form(array('phone' => $number)));
}
$reply = send(form(array('phone' => '+7 918 000-11-04')));
check('первые три заявки с одного адреса дошли', 3 === count($store['posts']), 'записей: ' . count($store['posts']));
check('четвёртая за час: вежливый отказ с телефоном салона',
    false === $reply->ok && false !== strpos($reply->data['message'], '+7 918 657-50-27'));
TC-BGH-05 Passed

Phone, name, comment and timestamp validation

  • Automated
  • Unit, equivalence classes and boundary values
  • Priority: medium
Preconditions
  • The form accepts Russian numbers only
Steps
  1. A number starting with 8, ten digits with no code, a Kazakh number, another country, a non-existent code, one digit ten times
  2. A one-letter name, a link in the name, a bare domain in the comment, room sizes with dots
  3. A one-minute-old stamp, one under three seconds, one over a day, one with a forged signature
Expected result
A Russian number is normalised to +7, the rest are rejected. Links are rejected, sizes with dots pass. Only a fresh stamp with a valid HMAC signature passes.
Test code tools/request-test.php
<?php
// tools/request-test.php, разделы «Телефон», «Имя и комментарий», «Метка времени».

echo "Телефон\n";
$phone = bgh_normalize_phone('8 (918) 000-11-22');
check('восьмёрка в начале становится +7', $phone['ok'] && '+79180001122' === $phone['e164']);
check('десять цифр без кода страны', '+79180001122' === bgh_normalize_phone('9180001122')['e164']);
check('номер Казахстана отклоняется', !bgh_normalize_phone('+7 701 000-11-22')['ok']);
check('номер другой страны отклоняется', !bgh_normalize_phone('+995 599 20 93 47')['ok']);
check('несуществующий код отклоняется', !bgh_normalize_phone('+7 118 000-11-22')['ok']);
check('одна цифра десять раз отклоняется', !bgh_normalize_phone('+7 999 999-99-99')['ok']);

echo "\nИмя и комментарий\n";
check('имя из одной буквы отклоняется', !bgh_clean_name('А')['ok']);
check('ссылка в имени отклоняется', !bgh_clean_name('www.spam.ru')['ok']);
check('домен без http тоже считается ссылкой', !bgh_clean_note('пишите на sale.ru')['ok']);
check('размеры комнаты с точками проходят', bgh_clean_note('Гостиная 4.5 на 6 м, диван 2.8')['ok']);

echo "\nМетка времени\n";
// Метка подписана HMAC: время отправки нельзя подделать в браузере.
function fresh_stamp($age = 60)
{
    $time = time() - $age;

    return $time . '.' . hash_hmac('sha256', (string) $time, bgh_form_salt());
}

check('метка минутной давности проходит', true === bgh_form_stamp_check(fresh_stamp(60)));
check('отправка быстрее трёх секунд отклоняется', true !== bgh_form_stamp_check(bgh_form_stamp()));
check('метка старше суток отклоняется', true !== bgh_form_stamp_check(fresh_stamp(DAY_IN_SECONDS + 60)));
check('подделанная подпись отклоняется', true !== bgh_form_stamp_check((time() - 60) . '.' . str_repeat('0', 64)));

Test cases · 11

WebPortfolioBakla83

This site: a static Astro portfolio in two languages, with dark and light themes and runnable copies of my work. I tested the markup of every page, the sitemap, narrow screens, the keyboard, project data and this section.

  • Astro
  • TypeScript
  • Playwright
  • Node.js
  • Cloudflare Pages
Home page

The 154 checks are 50 in the new tools/site-test.mjs and 104 in the existing tools/audit.mjs. The first run of the new suite gave 10 failures. Nine of them traced back to 6 defects: three failures on the site root shared one cause, a utility page listed in the sitemap. The tenth was a mistake in the test itself: after a click the code block stopped matching the selector, so the next block was checked instead. The test was fixed; the page behaviour stayed the same.

TC-WEB-01 Passed

The sitemap lists every page and only indexable ones

  • Automated
  • SEO, build check
  • Priority: medium
  • WEB-07
Preconditions
  • The site is built into dist
  • The root / only picks a language and is closed to search (noindex)
Steps
  1. List every .html page in dist/ru and dist/en
  2. Compare the list with the addresses in sitemap-0.xml
  3. Check that “Work in progress” and the root are not in the sitemap
Expected result
Every open page is in the sitemap. No noindex page is in it.
Actual result before the fix Failed before the fix
The noindex root / was listed in the sitemap. A search engine gets a contradiction: the page is submitted for indexing and forbidden at once, and Search Console flags it as an error. In the first run this caused three failures: the root’s language, title and canonical broke the rules for normal pages.
Fix
The sitemap filter in astro.config.mjs skips the root the same way it skips “Work in progress”.
Test code tools/site-test.mjs
// tools/site-test.mjs, раздел «Карта сайта».
const built = [];
const walk = async (dir, prefix) => {
  for (const entry of await readdir(dir, { withFileTypes: true })) {
    if (entry.isDirectory()) await walk(join(dir, entry.name), `${prefix}/${entry.name}`);
    else if (entry.name.endsWith('.html')) built.push(`${prefix}/${entry.name.replace(/\.html$/, '')}`);
  }
};
await walk(join(DIST, 'ru'), '/ru');
await walk(join(DIST, 'en'), '/en');
built.push('/ru', '/en');

const notListed = built.filter((p) => !p.endsWith('/in-progress') && !sitemap.includes(p));
check('в карте сайта все собранные страницы', !notListed.length, list(notListed));
check('страница «В процессе создания» не попала в карту сайта', !sitemap.some((p) => p.endsWith('/in-progress')));

// Страница с noindex в карте сайта — противоречие, на которое ругается Search Console.
const rootHtml = await readFile(join(DIST, 'index.html'), 'utf8');
const rootNoindex = /<meta name="robots" content="noindex/.test(rootHtml);
check('корень закрыт от поиска и поэтому не стоит в карте сайта', rootNoindex && !sitemap.includes('/'),
  `noindex: ${rootNoindex}, в карте: ${sitemap.includes('/')}`);
Fix code astro.config.mjs
// astro.config.mjs
sitemap({
  // Корень только выбирает язык и закрыт от поиска (noindex),
  // поэтому в карте сайта ему не место.
  filter: (page) => !page.includes('/in-progress') && new URL(page).pathname !== '/',
}),
TC-WEB-02 Passed

Markup of every page: language, headings, description, canonical, hreflang

  • Automated
  • Accessibility and SEO, all 66 pages
  • Priority: medium
  • WEB-08, WEB-09
Preconditions
  • The site is built; pages come from the sitemap plus “Work in progress”
Steps
  1. Open every page
  2. Compare the document lang with the language in the URL
  3. Count h1 elements and check heading levels never skip
  4. Measure the meta description length
  5. Compare canonical with the page URL and hreflang with existing pages
Expected result
Exactly one h1, and an h2 follows it, not an h3. A description of 50 to 200 characters. canonical points to the page itself, hreflang ru, en and x-default to existing pages.
Actual result before the fix Failed before the fix
On 12 section pages (6 sections in two languages) the card h3 came right after h1, leaving a gap in a screen reader’s outline. The “About” description was 201 and 216 characters and “Work in progress” 324 and 360, so search results and messenger previews cut it mid-word.
Fix
The card heading level is now set by the page: h2 on a section page, still h3 on the home page under an h2. “About” and “Work in progress” got their own short descriptions instead of the first paragraph.
Test code tools/site-test.mjs
// tools/site-test.mjs, раздел «Разметка страниц». Обходит каждую страницу из карты сайта.
for (const path of pages) {
  await page.goto(base + path, { waitUntil: 'domcontentloaded' });

  const info = await page.evaluate(() => {
    const $ = (s) => document.querySelector(s);
    const all = (s) => [...document.querySelectorAll(s)];

    // h1 → h3 без h2 между ними ломает оглавление у программ чтения с экрана.
    const levels = all('main h1, main h2, main h3, main h4').map((h) => Number(h.tagName[1]));
    const skipped = levels.some((level, i) => i > 0 && level - levels[i - 1] > 1);

    return {
      lang: document.documentElement.lang,
      h1: all('h1').length,
      skipped: skipped ? levels.join('') : '',
      title: document.title.trim(),
      description: $('meta[name="description"]')?.content.trim() ?? '',
      canonical: $('link[rel="canonical"]')?.href ?? '',
      hreflang: all('link[rel="alternate"][hreflang]').map((l) => [l.hreflang, new URL(l.href).pathname]),
    };
  });

  if (info.lang !== path.split('/')[1]) problems.lang.push(`${path}: ${info.lang}`);
  if (info.h1 !== 1) problems.h1.push(`${path}: ${info.h1}`);
  if (info.skipped) problems.headings.push(`${path}: ${info.skipped}`);
  // Длиннее ~200 знаков поисковик обрезает описание на полуслове.
  if (info.description.length < 50 || info.description.length > 200) {
    problems.description.push(`${path}: ${info.description.length} знаков`);
  }
  if (info.canonical !== SITE + path) problems.canonical.push(`${path}: ${info.canonical}`);

  const langs = info.hreflang.map(([lang]) => lang).sort().join(',');
  if (langs !== 'en,ru,x-default') problems.hreflang.push(`${path}: ${langs}`);
}

check('язык документа совпадает с языком адреса', !problems.lang.length, list(problems.lang));
check('на каждой странице ровно один h1', !problems.h1.length, list(problems.h1));
check('уровни заголовков не перескакивают', !problems.headings.length, list(problems.headings));
check('описание для поиска от 50 до 200 знаков', !problems.description.length, list(problems.description));
check('canonical указывает на саму страницу', !problems.canonical.length, list(problems.canonical));
check('hreflang ru, en и x-default ведут на существующие страницы', !problems.hreflang.length, list(problems.hreflang));
Fix code ProjectCard.astro, work/[section]/index.astro
---
// components/ProjectCard.astro
interface Props {
  project: Project;
  lang: EnabledLocale;
  showSection?: boolean;
  headingLevel?: 2 | 3;
}

const { project, lang, showSection = false, headingLevel = 3 } = Astro.props;
const Heading = `h${headingLevel}` as const;
---

<Heading class="card__title">{title}</Heading>

<!-- pages/[lang]/work/[section]/index.astro: на странице раздела карточки
     стоят сразу под h1, поэтому их заголовок второго уровня. -->
<ProjectCard project={project} lang={lang} headingLevel={2} />
Fix code i18n/ui.ts, about.astro
---
// i18n/ui.ts: короткое описание вместо первого абзаца текста «Обо мне»
about: {
  description:
    'Владислав Баклан — разработчик полного цикла: сайты на JavaScript и TypeScript, Android-приложения на Kotlin, игры на Unity и 3D-модели в Blender.',
},
---

<!-- pages/[lang]/about.astro. Было: description={pick(ABOUT_TEXT, lang)[0]}, 201 и 216 знаков -->
<Base lang={lang} path="about" title={strings.about.title} description={strings.about.description}>
TC-WEB-03 Passed

Buttons and links are at least 24×24 on a phone

  • Automated
  • Accessibility, WCAG 2.2 criterion 2.5.8
  • Priority: medium
  • WEB-10
Preconditions
  • A 390×844 screen with touch input
Steps
  1. Open the home, About, Contact, Testing, a section and a project page
  2. Measure every link, button, summary and field
  3. Skip links inside running text: they are an exception to the criterion
Expected result
No target is smaller than 24 pixels wide or tall.
Actual result before the fix Failed before the fix
The footer “Back to top” link was 69×23.8 on every page. The section link above a project title was 61×19.8. The test case number in this section was 74×21.
Fix
The links got a minimum height: 44 pixels for “Back to top” and the section link, 32 for the case number. They look the same; only the tap area grew.
Test code tools/site-test.mjs
// tools/site-test.mjs, раздел «Размер целей касания (WCAG 2.5.8)».
const ctx = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true });
const page = await ctx.newPage();
const small = [];

for (const path of ['/ru', '/ru/about', '/ru/contacts', '/ru/testing', '/ru/work/landings', '/ru/work/pc-games/the-hidden-library']) {
  await page.goto(base + path, { waitUntil: 'domcontentloaded' });
  const found = await page.evaluate(() =>
    [...document.querySelectorAll('a, button, summary, input, select')]
      .filter((el) => {
        const box = el.getBoundingClientRect();
        if (!box.width || !box.height) return false;
        // Ссылки внутри текста — исключение из критерия, их не считаем.
        if (getComputedStyle(el).display === 'inline' && el.closest('p, li, dd')) return false;
        return box.width < 24 || box.height < 24;
      })
      .map((el) => {
        const box = el.getBoundingClientRect();
        return `${el.tagName.toLowerCase()} «${(el.textContent || el.getAttribute('aria-label') || '').trim().slice(0, 20)}» ${Math.round(box.width)}×${Math.round(box.height)}`;
      }),
  );
  for (const item of found) small.push(`${path}: ${item}`);
}

check('кнопки и ссылки вне текста не меньше 24×24', !small.length, list(small));
Fix code Footer.astro, [slug].astro, TestCaseCard.astro
/* components/Footer.astro: «Наверх» была 69×23.8 */
.site-footer__top {
  display: inline-flex;
  align-items: center;
  min-height: 44px;
  gap: 0.4rem;
}

/* pages/[lang]/work/[section]/[slug].astro: ссылка на раздел была 61×19.8 */
.proj-hero__back {
  display: inline-flex;
  align-items: center;
  min-height: 44px;
}

/* components/TestCaseCard.astro: номер кейса был 74×21 */
.tc__id {
  display: inline-flex;
  align-items: center;
  min-height: 32px;
}
TC-WEB-04 Passed

Pages do not scroll sideways at 320, 360 and 390 pixels

  • Automated
  • Responsive layout, WCAG 1.4.10
  • Priority: high
Preconditions
  • Mobile browser mode with touch input
Steps
  1. For each width, open every page of the site
  2. Compare the document width with the screen width
  3. If the document is wider, find the element that sticks out
Expected result
No page scrolls sideways at any width.
Test code tools/site-test.mjs
// tools/site-test.mjs, раздел «Узкие экраны (WCAG 1.4.10)».
// Аудит смотрит сайт на ширине ноутбука, поэтому вылет на телефоне он не видит.
for (const width of [320, 360, 390]) {
  const ctx = await browser.newContext({ viewport: { width, height: 800 }, isMobile: true, hasTouch: true });
  const page = await ctx.newPage();
  const wide = [];

  for (const path of pages) {
    await page.goto(base + path, { waitUntil: 'domcontentloaded' });
    const overflow = await page.evaluate(() => {
      const extra = document.documentElement.scrollWidth - window.innerWidth;
      if (extra <= 0) return null;

      // Называем виновника, чтобы не искать его руками в DevTools.
      const culprit = [...document.querySelectorAll('body *')].find((el) => el.getBoundingClientRect().right > window.innerWidth + 1);
      return `${extra}px, ${culprit ? culprit.tagName.toLowerCase() + '.' + [...culprit.classList].join('.') : '?'}`;
    });
    if (overflow) wide.push(`${path}: ${overflow}`);
  }

  check(`${width}px: страницы без горизонтальной прокрутки`, !wide.length, list(wide));
  await ctx.close();
}
TC-WEB-11 Passed

The name in the header does not run over the buttons on a phone

  • Automated
  • Responsive layout, visual
  • Priority: high
  • WEB-13
Preconditions
  • Mobile mode at 320, 360 and 390 pixels
Steps
  1. Open the home page
  2. For each header element compare the text width with the width of its box
  3. Compare the right edge of the brand with the left edge of the language, theme and menu buttons
Expected result
Text fits its boxes and the brand ends before the buttons.
Actual result before the fix Failed before the fix
The name “Vladislav Baklan” sat on one line and at 320 pixels overflowed its box by 75 pixels, right over the language switcher. By 37 at 360 and 8 at 390. The page did not get wider than the screen, so TC-WEB-04 missed it. I spotted it on a screenshot while replacing the header mark, and wrote the test first.
Fix
Below 560 pixels the name wraps onto two lines. Below 360 the mark is 32 pixels, gaps are tighter and the name font slightly smaller. Buttons stay 40 pixels.
Test code tools/site-test.mjs
// tools/site-test.mjs, раздел «Узкие экраны», для каждой ширины 320, 360 и 390.
// Текст может вылезти из своего блока поверх соседей, а страница шире экрана
// при этом не станет. Проверка на горизонтальную прокрутку такое пропускает.
await page.goto(base + '/ru', { waitUntil: 'domcontentloaded' });
const overlap = await page.evaluate(() => {
  const found = [];
  for (const el of document.querySelectorAll('.site-header *')) {
    if (el.scrollWidth > el.clientWidth + 1 && getComputedStyle(el).overflowX === 'visible' && el.clientWidth > 0) {
      found.push(`${el.className}: текст ${el.scrollWidth}px в блоке ${el.clientWidth}px`);
    }
  }
  const brand = document.querySelector('.brand')?.getBoundingClientRect();
  const tools = document.querySelector('.site-header__tools')?.getBoundingClientRect();
  if (brand && tools && brand.right > tools.left) found.push(`бренд заходит на кнопки на ${Math.round(brand.right - tools.left)}px`);
  return found;
});
check(`${width}px: в шапке ничего не налезает друг на друга`, !overlap.length, list(overlap));
Fix code Header.astro
/* components/Header.astro */
@media (max-width: 560px) {
  /* В одну строку имя налезало на переключатель языка уже на 390px. */
  .brand__name {
    white-space: normal;
  }
}

/* На 320px даже «Владислав» не помещался рядом с кнопками:
   ужимаем значок и промежутки, кнопки остаются 40px. */
@media (max-width: 360px) {
  .site-header__inner {
    gap: var(--space-1);
  }

  .brand {
    gap: 0.5rem;
  }

  .brand__mark {
    width: 32px;
    height: 32px;
  }

  .brand__name {
    font-size: 0.92rem;
  }

  .site-header__tools {
    gap: 0.25rem;
  }
}
TC-WEB-05 Passed

The site works from the keyboard

  • Automated
  • Accessibility, E2E
  • Priority: medium
Preconditions
  • A laptop, no mouse
Steps
  1. Open About and press Tab
  2. Press Enter on the skip link, then Tab again
  3. On the home page press Tab twice and look at the focus ring
Expected result
The first Tab lands on a visible “Skip to content” link, and after it focus goes straight into main. The focused element shows a ring.
Test code tools/site-test.mjs
// tools/site-test.mjs, раздел «Клавиатура».
await page.goto(base + '/ru/about', { waitUntil: 'networkidle' });

await page.keyboard.press('Tab');
const first = await page.evaluate(() => document.activeElement?.className ?? '');
check('первый Tab попадает на ссылку «Перейти к содержимому»', first.includes('skip-link'), first);

const skipVisible = await page.evaluate(() => document.activeElement.getBoundingClientRect().top >= 0);
check('ссылка пропуска видна в фокусе', skipVisible);

await page.keyboard.press('Enter');
await page.keyboard.press('Tab');
const inMain = await page.evaluate(() => Boolean(document.activeElement?.closest('main')));
check('после пропуска следующий Tab уже внутри main', inMain);

await page.goto(base + '/ru', { waitUntil: 'networkidle' });
await page.keyboard.press('Tab');
await page.keyboard.press('Tab');
const outline = await page.evaluate(() => getComputedStyle(document.activeElement).outlineStyle);
check('у элемента в фокусе видна рамка', outline !== 'none', outline);
TC-WEB-06 Passed

The filters in this section hide the other cards

  • Automated
  • Functional, E2E
  • Priority: high
  • WEB-11
Preconditions
  • The Testing page is open
Steps
  1. Pick The Hidden Library and the Manual type
  2. Compare the number of visible cards with the counter
  3. Pick BrandGallery Home, which has no manual cases
  4. Reset both filters
  5. Open the page with JavaScript turned off
Expected result
Only the game’s manual cases are visible, as many as the counter says. An empty combination shows 0 and a hint. Reset brings every card back. Without JavaScript there are no filters and every card is visible.
Actual result before the fix Failed before the fix
The counter said 3 while all 10 game cards stayed on screen. The script set the hidden attribute, but the card’s display: grid rule overrides that attribute.
Fix
A dedicated .tc[hidden] { display: none } rule. Caught before the section went live.
Test code tools/site-test.mjs
// tools/site-test.mjs, раздел «Тестирование».
await page.goto(base + '/ru/testing', { waitUntil: 'networkidle' });

const total = await page.locator('[data-test-case]').count();
const shown = () => page.textContent('[data-qa-shown]').then(Number);
const visibleCards = () => page.locator('[data-test-case]:visible').count();

await page.click('[data-filter="project"][data-value="thl"]');
await page.click('[data-filter="kind"][data-value="manual"]');
const thlManual = await visibleCards();
// Сверяем то, что видно глазу, со счётчиком: счётчик считал верно, а карточки не прятались.
check('фильтр «игра + ручные» оставляет только ручные кейсы игры',
  thlManual > 0 && thlManual === (await shown()) && (await page.locator('[data-qa-project="bgh"]').isHidden()),
  `видно ${thlManual}`);
check('у ручных кейсов нет пометки «Автотест»',
  (await page.locator('[data-test-case]:visible[data-kind="auto"]').count()) === 0);

await page.click('[data-filter="project"][data-value="bgh"]');
check('пустой фильтр показывает подсказку и счётчик 0',
  (await shown()) === 0 && (await page.isVisible('[data-qa-project="bgh"] [data-qa-empty]')));

await page.click('[data-filter="project"][data-value="all"]');
await page.click('[data-filter="kind"][data-value="all"]');
check('сброс фильтров возвращает все карточки', (await visibleCards()) === total && (await shown()) === total);

// Без JavaScript фильтры бесполезны: их нет, а карточки видны все.
const noJs = await browser.newContext({ javaScriptEnabled: false });
const plain = await noJs.newPage();
await plain.goto(base + '/en/testing');
check('без JavaScript видны все карточки, а фильтры спрятаны',
  (await plain.locator('[data-test-case]:visible').count()) === total && (await plain.isHidden('[data-qa-filters]')));
Fix code TestCaseCard.astro
/* components/TestCaseCard.astro */
.tc {
  display: grid;
  /* Шапка 80px и липкая панель фильтров под ней. Было 90px,
     и карточка по ссылке-якорю пряталась под панелью. */
  scroll-margin-top: 162px;
}

/* display: grid сильнее атрибута hidden, без этого фильтр не прятал карточки. */
.tc[hidden] {
  display: none;
}

/* На телефоне панель фильтров не липкая, хватает отступа под шапку. */
@media (max-width: 520px) {
  .tc {
    scroll-margin-top: 102px;
  }
}
TC-WEB-07 Passed

A link to a test case does not hide it under the filter bar

  • Automated
  • Functional, E2E
  • Priority: low
  • WEB-12
Preconditions
  • A 1366×900 laptop
  • “Reduce motion” on, so scrolling is instant
Steps
  1. Open /ru/testing#tc-bgh-03
  2. Find the bottom edge of everything sticky at the top: header and filter bar
  3. Compare it with the top of the card
Expected result
The top of the card sits below the filter bar, in the upper half of the screen.
Actual result before the fix Failed before the fix
The card stopped at 90 pixels while the filter bar ends at 129, so the case number and title slid under the bar.
Fix
A 162-pixel scroll-margin-top for the header and bar. On a phone the bar is not sticky, so 102 is enough.
Test code tools/site-test.mjs
// tools/site-test.mjs, раздел «Тестирование».
// На сайте плавная прокрутка, по длинной странице она идёт секунду и больше.
// С «уменьшением движения» сайт прыгает к якорю сразу, это заодно проверяет и его.
const still = await browser.newContext({ viewport: { width: 1366, height: 900 }, reducedMotion: 'reduce' });
const anchorPage = await still.newPage();
await anchorPage.goto(base + '/ru/testing#tc-bgh-03', { waitUntil: 'load' });
await anchorPage.waitForTimeout(300);

const anchored = await anchorPage.evaluate(() => {
  const card = document.getElementById('tc-bgh-03').getBoundingClientRect();
  // Всё липкое сверху: шапка сайта и панель фильтров.
  const covers = [...document.querySelectorAll('.site-header, [data-qa-filters]')]
    .filter((el) => getComputedStyle(el).position === 'sticky')
    .map((el) => el.getBoundingClientRect().bottom);
  return { top: Math.round(card.top), covered: Math.round(Math.max(0, ...covers)) };
});
check('ссылка на кейс прокручивает к нему, а не под шапку и фильтры',
  anchored.top >= anchored.covered && anchored.top < 450, `карточка на ${anchored.top}px, закрыто до ${anchored.covered}px`);
Fix code TestCaseCard.astro
/* components/TestCaseCard.astro */
.tc {
  display: grid;
  /* Шапка 80px и липкая панель фильтров под ней. Было 90px,
     и карточка по ссылке-якорю пряталась под панелью. */
  scroll-margin-top: 162px;
}

/* display: grid сильнее атрибута hidden, без этого фильтр не прятал карточки. */
.tc[hidden] {
  display: none;
}

/* На телефоне панель фильтров не липкая, хватает отступа под шапку. */
@media (max-width: 520px) {
  .tc {
    scroll-margin-top: 102px;
  }
}
TC-WEB-08 Passed

Project data and dictionaries are intact before the build

  • Automated
  • Data integrity
  • Priority: medium
Preconditions
  • Node 22: TypeScript data files are read directly
Steps
  1. Check project addresses are unique and every project sits in an existing section
  2. Check all 86 images, models and work copies exist in public
  3. Compare the keys of the Russian and English dictionaries
Expected result
No duplicates or lost sections, every file in place, every Russian key has an English one.
Test code tools/site-test.mjs
// tools/site-test.mjs, разделы «Данные проектов» и «Словари интерфейса».
// Node 22 читает TypeScript напрямую, поэтому данные проверяются до сборки.
const { PROJECTS } = await import('../src/data/projects.ts');
const { SECTIONS } = await import('../src/data/sections.ts');
const { t } = await import('../src/i18n/ui.ts');

const slugs = PROJECTS.map((p) => p.slug);
const twins = slugs.filter((slug, i) => slugs.indexOf(slug) !== i);
check('адреса проектов не повторяются', twins.length === 0, list(twins));

const sectionSlugs = new Set(SECTIONS.map((s) => s.slug));
const lost = PROJECTS.filter((p) => !sectionSlugs.has(p.section)).map((p) => `${p.slug} → ${p.section}`);
check('каждый проект лежит в существующем разделе', lost.length === 0, list(lost));

const missing = [];
for (const [slug, src] of files) {
  if (/^https?:/.test(src)) continue;
  if (!(await exists(join(PUBLIC, src)))) missing.push(`${slug}: ${src}`);
}
check(`все ${files.length} файлов картинок, моделей и копий на месте`, missing.length === 0, list(missing));

const keys = (obj, prefix = '') =>
  Object.entries(obj).flatMap(([key, value]) =>
    value && typeof value === 'object' && !Array.isArray(value) ? keys(value, `${prefix}${key}.`) : [`${prefix}${key}`],
  );

const ru = keys(t('ru'));
const en = keys(t('en'));
const onlyRu = ru.filter((k) => !en.includes(k));
const onlyEn = en.filter((k) => !ru.includes(k));
check('в английском словаре те же ключи, что в русском', !onlyRu.length && !onlyEn.length, list([...onlyRu, ...onlyEn]));
TC-WEB-09 Passed

The mobile menu opens, closes and gives scrolling back

  • Automated
  • Functional, E2E, regression
  • Priority: high
Preconditions
  • A 390×844 screen with touch input
Steps
  1. Open the home page
  2. Tap the menu button
  3. Press Esc
  4. Open the menu again and follow a link
Expected result
The menu starts hidden and opens on tap, aria-expanded becomes true and the background stops scrolling. Esc and following a link close it and give scrolling back.
Test code tools/audit.mjs
// tools/audit.mjs, мобильное меню.
const ctx = await browser.newContext({
  viewport: { width: 390, height: 844 },
  isMobile: true,
  hasTouch: true,
});
const page = await ctx.newPage();
await page.goto(base + '/ru', { waitUntil: 'networkidle' });

ok('меню изначально скрыто', await page.isHidden('[data-menu-panel]'));

await page.click('[data-menu-open]');
await page.waitForTimeout(200);
const opened = await page.isVisible('[data-menu-panel]');
ok('меню открывается', opened);
ok('aria-expanded становится true', (await page.getAttribute('[data-menu-open]', 'aria-expanded')) === 'true');
ok('фон заблокирован от прокрутки', (await page.evaluate(() => document.body.style.overflow)) === 'hidden');

await page.keyboard.press('Escape');
await page.waitForTimeout(200);
ok('Esc закрывает меню', await page.isHidden('[data-menu-panel]'));
ok('прокрутка возвращается', (await page.evaluate(() => document.body.style.overflow)) === '');

if (opened) {
  await page.click('[data-menu-open]');
  await page.waitForTimeout(200);
  await page.click('.mobile-menu__list a');
  await page.waitForLoadState('networkidle');
  ok('переход по ссылке закрывает меню', await page.isHidden('[data-menu-panel]'));
}
TC-WEB-10 Passed

Work copy sync finds every source and reports a miss

  • Manual
  • Build tooling, manual
  • Priority: medium
  • WEB-05, WEB-06
Preconditions
  • The work sources sit next to the site in D:\MyPortfolioProjects
Steps
  1. Run node tools/sync-demos.mjs --check
  2. See whether all 11 sources are found
  3. Check the exit code: echo $?
Expected result
All 11 sources are found and the exit code is 0. If a source goes missing, the exit code is 1 with a clear message.
Actual result before the fix Failed before the fix
The BrandGallery Home mock-ups moved to another folder while the path in the work list stayed old. The script printed a warning but exited with 0, so the copy the client opens by link went un-updated for a month.
Fix
The new path to the mock-ups and exit code 1 for any missing source or file.
Fix code tools/sync-demos.mjs
// tools/sync-demos.mjs
const DEMOS = [
  {
    slug: 'brandgalleryhome',
    // Было 'brandgalleryhome/design': 16.08 макеты переехали в отдельную папку,
    // и копия, которую заказчица открывает по ссылке, месяц не обновлялась.
    from: 'brandgalleryhomeDesign/design',
    // ...
  },
];

// Конец файла. Раньше пропущенный источник давал только предупреждение
// и код выхода 0, поэтому проверка перед выкладкой его не замечала.
if (missing) {
  console.error(`\nПропущено работ: ${missing}. Их копии на сайте остались от прошлой синхронизации и больше не обновляются.`);
}
if (failed) {
  console.error(`\nНе найдено файлов: ${failed}`);
}
if (missing || failed) process.exit(1);