diff --git a/CHANGELOG.md b/CHANGELOG.md index 3659cb1..d1c5c82 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,19 @@ ## [Не выпущено] +### Добавлено + +- `PilotUiTestBase.ClientAccount`: тесты класса под другим пользователем клиента (учётка из `accounts`, у учётки - необязательный `clientUser` для сверки подписи профиля). Работающий клиент закрывается, записывается вход учётки, после класса клиент закрывается и прежний сохранённый вход возвращается. +- `PilotApp.QuitRunning(config)` и `PilotClientLogin.SettingsPath(config)`. +- `PilotChat` (`PilotPage.Chat()`) и раздел каталога `PilotIds.Chat`: отправка сообщения, лента сообщений, щелчок по ссылке в сообщении. Разведано на Pilot-BIM 26.20. +- `PilotServerClient.GetCommonSetting` и `SetCommonSetting`: общие настройки базы для оргединицы, запись с ожиданием, что сервер её вернул. +- `PilotCommonSettingsWindow.FeatureRows(ключ)`: строки конфигураций одной настройки. + +### Исправлено + +- `SetAttributesAndWait` с пустым массивом (оргединицы, строки) ждал до таймаута: сервер хранит пустой массив как отсутствие значения. +- `PilotApp.StartOrAttach` изредка падал с `NullReferenceException` сразу после запуска клиента (FlaUI читает главный модуль процесса, которого ещё нет). Теперь подключение ждёт загрузки процесса, а если процесс сразу завершился, сообщает код выхода и путь к журналу клиента. + ## [0.4.0] - 2026-11-15 ### Изменено diff --git a/docs/pilot-ui-testing.md b/docs/pilot-ui-testing.md index b5d10f6..fdfdd45 100644 --- a/docs/pilot-ui-testing.md +++ b/docs/pilot-ui-testing.md @@ -78,15 +78,17 @@ public class MyModuleTests : PilotUiTestBase | `PilotToolbar` | панель команд | кнопка по id = имя из построителя (и у модулей), `IsEnabled/IsChecked/IsHidden` из ItemStatus, меню кнопки `ContextMenu`, скрытые кнопки через «…» | | `PilotMenu` | меню | контекстное (клавиша «Меню» или правый клик), кнопки панели, главное; `Click("id", "id подпункта")`, `ClickText(...)`, `Items()` | | `PilotCard` | карточка атрибутов | в любом окне и области: `Set`, `Choose`, `SetDate`, `PickReference`, `AddOrgUnit`, `ObligatoryAttributes` - с проверкой введённого; в справочнике уже отмеченная строка не нажимается повторно (клик снял бы отметку), выбор без изменений закрывается «Отменой» (`PilotReferenceBook.Submit`) | +| `PilotChat` | `page.Chat()` | панель чата Pilot в области страницы (вкладка «Чаты», чат объекта, чат в представлении модуля): `Send(текст)` с ожиданием сообщения в ленте, `Messages()`, `WaitMessage(текст)`, `ClickLink(адрес)` - щелчок мышью в первую строку ссылки в сообщении | | `UiGrid` | таблица | `RowCount`, `Columns()`, `Cell(строка, колонка)`, `FindRow`, `SelectRow` (FieldName или подпись колонки) | | `PilotMessageBox`, `PilotErrorWindow`, `WindowsFileDialog` | стандартные окна | `Answer(Yes/No/Cancel/Ok)` по фактическому набору кнопок; текст ошибки; открыть файл | | `By`, `Wait`, `UiActions` | ядро | селекторы; ожидания `Wait.Until(() => …)` без таймаута (описание - из текста условия), `Wait.Stays`; действия над найденным элементом для page object'ов модулей | -| `PilotServerClient` | `Server` | прежнее + `…AndWait` (подтверждение чтением и мгновенный отказ, если сервер отклонил изменение), `DeletePermanently`, `WaitDescendant`, `TaskAttachments`, `Errors` | +| `PilotServerClient` | `Server` | прежнее + `…AndWait` (подтверждение чтением и мгновенный отказ, если сервер отклонил изменение), `DeletePermanently`, `WaitDescendant`, `TaskAttachments`, `Errors`, общие настройки `GetCommonSetting/SetCommonSetting(ключ, значение, оргединица)` (нужен администратор базы) | | `PilotSandbox` | `TestData` | корень «{префикс} {класс} {время}» в корне базы, `CreateFolder/CreateDocument/Create`, `Unique(...)`, `Track(id)`; после класса удаляет окончательно и проверяет: поддерево корня, объекты из `Track` с их поддеревьями и объекты, которые тест удалил из песочницы в корзину (находятся по наборам изменений прогона и атрибуту `Delete_source`). Объект старше песочницы и его предки не удаляются (сервер удалил бы его вместе с родителем) - это отчёт об ошибке уборки. Удалённое в корзину через интерфейс под другим пользователем уборка видит, только если учётка Server API - администратор (иначе - предупреждение) | Базовый класс `PilotUiTestBase` дополнительно даёт `Step(...)` (журнал шагов), `RequireTypes(...)`, `OpenExplorer(...)`, `Track(...)` (вкладка или представление модуля закроется после теста/класса), `RestoreFileAfterTests(путь)`, `AssertNoPilotErrors()`, -`AssertNoPluginErrors()`, `NewOutputPath(имя)`. +`AssertNoPluginErrors()`, `NewOutputPath(имя)`, `ServerAs(учётка)` (Server API под другим пользователем) и `ClientAccount` +(клиент в тестах класса под другим пользователем, см. «Клиент под другим пользователем»). ## Каталог идентификаторов @@ -135,6 +137,24 @@ public class MyModuleTests : PilotUiTestBase PilotClientLogin.Save(PilotUiConfig.Load(), "bot", password); // exe, клиент и serverUrl - из конфигурации ``` +### Клиент под другим пользователем + +Класс тестов, которому нужен клиент под другим пользователем (например, без прав администратора), переопределяет `ClientAccount` - +имя учётки из ключа `accounts`: + +```csharp +protected override string ClientAccount => "worker"; +``` + +```json +"accounts": { "worker": { "login": "ui_worker", "password": "…", "clientUser": "ui_worker (Сотрудник)" } } +``` + +Перед запуском клиента работающий клиент закрывается (`PilotApp.QuitRunning`, «-quit»), в настройки записывается вход учётки, а подпись +кнопки профиля сверяется с её `clientUser` (вместо общего `clientUser`). После всех тестов класса клиент закрывается и прежний сохранённый +вход возвращается побайтно - следующий класс запускает клиент под своим пользователем. Учётки нет - тесты класса пропускаются. +Пароль учётки, как и другие, лучше держать в `pilot-ui-tests.local.json` или `PILOT_UI_ACCOUNT_<ИМЯ>_LOGIN/_PASSWORD`. + `StartOrAttach` не ждёт `clientStartTimeoutSeconds`, если клиент не войдёт: сразу бросает исключение с причиной, когда процесс клиента завершился, когда у клиента нет сохранённого входа (`ConnectionState:NoSettings`, «Необходимо настроить соединение») и когда в `client.log` записано исключение, после которого клиент перестаёт подключаться (неверный пароль, другая версия сервера). diff --git a/src/PilotUITesting/Client/Controls/PilotChat.cs b/src/PilotUITesting/Client/Controls/PilotChat.cs new file mode 100644 index 0000000..95c5208 --- /dev/null +++ b/src/PilotUITesting/Client/Controls/PilotChat.cs @@ -0,0 +1,125 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using FlaUI.Core.AutomationElements; +using FlaUI.Core.Definitions; +using PilotUITesting.Uia; + +namespace PilotUITesting.Client +{ + /// + /// Панель чата Pilot (): вкладка «Чаты», окно чата объекта, чат объекта в представлении модуля. + /// Сообщения - строки ленты (Name = текст сообщения), ссылки в тексте - Hyperlink с адресом в Name. + /// Берётся через . + /// + public sealed class PilotChat + { + private readonly Func _container; + private readonly string _description; + + internal PilotChat(Func container, string description) + { + _container = container; + _description = description; + } + + /// Панель чата (ChatView); нет за - исключение. + public AutomationElement Root => Wait.For(() => _container()?.TryById(PilotIds.Chat.Container), Wait.DefaultTimeout, "панель чата в " + _description); + + /// Тексты сообщений ленты, которые сейчас есть в дереве UI Automation, в порядке ленты (системные - тоже). + public IReadOnlyList Messages() + { + return MessageItems().Select(m => m.SafeName()).ToList(); + } + + /// Дождаться сообщения с точным текстом (Name строки ленты, без нормализации); timeout null - . + public AutomationElement WaitMessage(string text, TimeSpan? timeout = null) + { + if (text == null) + { + throw new ArgumentNullException(nameof(text)); + } + return Wait.ForStrict(() => MessageItems().LastOrDefault(m => m.SafeName() == text), timeout ?? Wait.DefaultTimeout, + $"сообщение «{text}» в чате ({_description})", () => "сообщения: " + string.Join(" | ", Messages().Select(m => "«" + m + "»"))); + } + + /// + /// Отправить сообщение: текст в поле нового сообщения (ValuePattern), «Отправить» после того, как она стала доступна, + /// и дождаться в ленте нового сообщения с этим текстом (прежние сообщения с тем же текстом не засчитываются). + /// Пустой чат объекта (ещё без сообщений) создаётся первым сообщением. Текст сравнивается точно - без пробелов по краям. + /// + public AutomationElement Send(string text, TimeSpan? timeout = null) + { + if (string.IsNullOrWhiteSpace(text) || text.Trim() != text) + { + throw new ArgumentException("Нужен текст сообщения без пробелов по краям (сообщение в ленте сравнивается точно)", nameof(text)); + } + AutomationElement root = Root; + List before = MessageItems().Where(m => m.SafeName() == text).ToList(); + UiActions.SetValue(root.ById(PilotIds.Chat.NewMessage, Wait.DefaultTimeout), text, "поле нового сообщения чата (" + _description + ")"); + AutomationElement send = root.ById(PilotIds.Chat.Send, Wait.DefaultTimeout); + Wait.Until(() => UiQuery.Read(() => send.IsEnabled, Wait.DefaultTimeout, "доступность «Отправить»"), Wait.DefaultTimeout, "«Отправить» доступна"); + UiActions.Click(send, "«Отправить» в чате (" + _description + ")"); + return Wait.ForStrict(() => MessageItems().LastOrDefault(m => m.SafeName() == text && !before.Any(m.Equals)), timeout ?? Wait.DefaultTimeout, + $"новое сообщение «{text}» в чате ({_description})", () => "сообщения: " + string.Join(" | ", Messages().Select(m => "«" + m + "»"))); + } + + /// + /// Щёлкнуть мышью по ссылке с адресом в тексте последнего сообщения, где она есть. + /// Мышью, а не Invoke: Invoke ссылки WPF через UI Automation выполняется синхронно и не возвращает управление, пока + /// обработчик перехода (модальное окно, долгая навигация) не завершится. Щелчок - в первую строку ссылки (TextPattern + /// текста сообщения): длинная ссылка переносится, и в центре её общего прямоугольника текста может не быть. + /// + public void ClickLink(string address, TimeSpan? timeout = null) + { + if (string.IsNullOrEmpty(address)) + { + throw new ArgumentException("Нужен адрес ссылки", nameof(address)); + } + (AutomationElement item, AutomationElement text, AutomationElement link) found = (null, null, null); + Wait.ForStrict(() => + { + found = MessageItems() + .Select(m => (m, m.TryById(PilotIds.Chat.MessageText))) + .Where(p => p.Item2 != null) + .Select(p => (p.m, p.Item2, p.Item2.FindDescendantBfs(e => e.SafeControlType() == ControlType.Hyperlink && e.SafeName() == address, 3))) + .LastOrDefault(p => p.Item3 != null); + return found.link; + }, + timeout ?? Wait.DefaultTimeout, $"ссылка «{address}» в сообщениях чата ({_description})", + () => "сообщения: " + string.Join(" | ", Messages().Select(m => "«" + m + "»"))); + string description = $"ссылка «{address}» в чате ({_description})"; + // сообщение за краем ленты: строки ссылки были бы вне видимой части, и щелчок попал бы в соседний элемент + UiQuery.Read(() => + { + found.item.Patterns.ScrollItem.PatternOrDefault?.ScrollIntoView(); + return true; + }, Wait.DefaultTimeout, "прокрутка к сообщению со ссылкой"); + Rectangle line = FirstLine(found.text, found.link); + if (line.IsEmpty) + { + UiActions.Click(found.link, description); + return; + } + UiAct.ClickAt(found.link, new Point(line.X + Math.Min(line.Width / 2, 20), line.Y + line.Height / 2), description); + } + + /// Прямоугольник первой строки ссылки на экране; пустой - текст сообщения не отдаёт строки (нет TextPattern). + private static Rectangle FirstLine(AutomationElement text, AutomationElement link) + { + Rectangle[] lines = UiQuery.Read(() => text.Patterns.Text.PatternOrDefault?.RangeFromChild(link)?.GetBoundingRectangles(), Wait.DefaultTimeout, + "строки ссылки в тексте сообщения") ?? new Rectangle[0]; + return lines.FirstOrDefault(r => r.Width > 0 && r.Height > 0); + } + + // без ожидания панели: вызывается в опросах с таймаутом вызывающего + private IEnumerable MessageItems() + { + AutomationElement list = _container()?.TryById(PilotIds.Chat.Container)?.TryById(PilotIds.Chat.Messages); + return list == null + ? Enumerable.Empty() + : list.SafeChildren().Where(c => c.SafeControlType() == ControlType.ListItem); + } + } +} diff --git a/src/PilotUITesting/Client/Ids/PilotIds.Chat.cs b/src/PilotUITesting/Client/Ids/PilotIds.Chat.cs new file mode 100644 index 0000000..6f174d6 --- /dev/null +++ b/src/PilotUITesting/Client/Ids/PilotIds.Chat.cs @@ -0,0 +1,36 @@ +namespace PilotUITesting.Client +{ + public static partial class PilotIds + { + /// + /// Панель чата (ChatView): вкладка «Чаты», окно чата объекта, чат объекта в представлении модуля (IChatControlsProvider.GetObjectChatsControl). + /// [Д] дамп Pilot-BIM 26.20, чат замечания в представлении модуля. + /// + public static class Chat + { + /// (Custom, класс ChatView) [Д] дамп. + public const string Container = "AUIDChatView"; + + /// Лента сообщений (List, ListView); сообщения - ListItem, Name = текст сообщения [Д] дамп. + public const string Messages = "messagesListControl"; + + /// Текст сообщения (Document, RichTextBox); ссылки в нём - Hyperlink, Name = адрес [Д] дамп. + public const string MessageText = "messageText"; + + /// Автор сообщения (Text) с Hyperlink имени пользователя [Д] дамп. + public const string MessageAuthor = "authorTextBlock"; + + /// Системное сообщение («… добавил(а) … в чат») (Text) [Д] дамп. + public const string SystemMessage = "chatSystemTextBlock"; + + /// Поле нового сообщения (Edit, ValuePattern) [Д] дамп. + public const string NewMessage = "newMessageTextBox"; + + /// «Отправить (Ctrl+Enter)» (Button); недоступна, пока поле сообщения пусто [Д] дамп. + public const string Send = "sendButton"; + + /// Добавить вложения (Button) [Д] дамп. + public const string AddAttachment = "addAttachmentButton"; + } + } +} diff --git a/src/PilotUITesting/Client/Pages/PilotPage.cs b/src/PilotUITesting/Client/Pages/PilotPage.cs index 3496b3b..e95e9dd 100644 --- a/src/PilotUITesting/Client/Pages/PilotPage.cs +++ b/src/PilotUITesting/Client/Pages/PilotPage.cs @@ -242,6 +242,12 @@ public PilotList ListBy(By selector, Func rowTitle = return new PilotList(App, () => TryFind(selector), "список " + selector + " в «" + Description + "»", rowTitle); } + /// Панель чата Pilot в этой области (вкладка «Чаты», чат объекта в окне или в представлении модуля). + public PilotChat Chat() + { + return new PilotChat(ResolveRoot, "«" + Description + "»"); + } + /// Таблица (GridPattern; проверено на DevExpress GridControl 20.1). public UiGrid GridById(string gridId) { diff --git a/src/PilotUITesting/Client/PilotApp.More.cs b/src/PilotUITesting/Client/PilotApp.More.cs index e85b3dc..b3dda93 100644 --- a/src/PilotUITesting/Client/PilotApp.More.cs +++ b/src/PilotUITesting/Client/PilotApp.More.cs @@ -177,6 +177,45 @@ public void Quit(TimeSpan? timeout = null) } } + /// + /// Закрыть клиент из конфигурации, если он запущен в текущем сеансе Windows (exe с аргументом «-quit»), и дождаться завершения + /// процесса; не запущен - ничего. Не завершился - исключение (без Kill). Нужен перед записью сохранённого входа (). + /// + public static void QuitRunning(PilotUiConfig config, TimeSpan? timeout = null) + { + if (config == null) + { + throw new ArgumentNullException(nameof(config)); + } + using (Process running = FindRunning(config)) + { + if (running == null) + { + return; + } + TimeSpan limit = timeout ?? config.ClientStartTimeout; + PilotLog.Action("закрытие запущенного клиента: -quit"); + RunClientCommand(config, "-quit", limit); + if (!running.WaitForExit((int)limit.TotalMilliseconds)) + { + throw new PilotWaitTimeoutException("завершение процесса клиента после «-quit» (открыто модальное окно?)", limit, limit, null, null); + } + } + } + + /// Запущен ли клиент из конфигурации в текущем сеансе Windows. + public static bool IsRunning(PilotUiConfig config) + { + if (config == null) + { + throw new ArgumentNullException(nameof(config)); + } + using (Process running = FindRunning(config)) + { + return running != null; + } + } + /// Закрыть клиент (), запустить заново и дождаться готовности. Этот объект освобождается. public PilotApp Restart() { @@ -205,12 +244,17 @@ public void SendKeys(string description, params VirtualKeyShort[] keys) private void RunClientCommand(string argument, TimeSpan timeout) { - ProcessStartInfo info = new ProcessStartInfo(_config.ResolvedExePath, "\"" + argument + "\"") { UseShellExecute = false }; + RunClientCommand(_config, argument, timeout); + } + + private static void RunClientCommand(PilotUiConfig config, string argument, TimeSpan timeout) + { + ProcessStartInfo info = new ProcessStartInfo(config.ResolvedExePath, "\"" + argument + "\"") { UseShellExecute = false }; using (Process second = Process.Start(info)) { if (second == null) { - throw new InvalidOperationException("Не удалось запустить " + _config.ResolvedExePath + " " + argument); + throw new InvalidOperationException("Не удалось запустить " + config.ResolvedExePath + " " + argument); } if (!second.WaitForExit((int)timeout.TotalMilliseconds)) { diff --git a/src/PilotUITesting/Client/PilotApp.cs b/src/PilotUITesting/Client/PilotApp.cs index 07f0c32..09e2a0a 100644 --- a/src/PilotUITesting/Client/PilotApp.cs +++ b/src/PilotUITesting/Client/PilotApp.cs @@ -1,7 +1,9 @@ using System; +using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; +using System.Threading; using FlaUI.Core; using FlaUI.Core.AutomationElements; using FlaUI.Core.Definitions; @@ -90,11 +92,45 @@ public static PilotApp StartOrAttach(PilotUiConfig config) // журнал - с текущего конца, до запуска: в нём ищется причина, по которой клиент не вошёл в базу ClientLogFile log = ClientLogFile.FromNow(ClientLogPath(config)); Process process = Process.Start(new ProcessStartInfo(config.ResolvedExePath) { UseShellExecute = true }); + WaitProcessLoaded(config, process); PilotApp app = new PilotApp(config, process, true, log); app.WaitMainWindow(); return app; } + /// + /// Дождаться, пока у только что запущенного процесса появится главный модуль: FlaUI Application.Attach читает + /// Process.MainModule, а сразу после запуска его ещё нет (NullReferenceException в ProcessModule.FileName). + /// + private static void WaitProcessLoaded(PilotUiConfig config, Process process) + { + Stopwatch sw = Stopwatch.StartNew(); + while (true) + { + if (process.HasExited) + { + throw new InvalidOperationException($"Процесс клиента завершился сразу после запуска (код {process.ExitCode}). Причина - в журнале клиента: {ClientLogPath(config)}"); + } + try + { + process.Refresh(); + if (!string.IsNullOrEmpty(process.MainModule?.FileName)) + { + return; + } + } + catch (Exception e) when (e is Win32Exception || e is InvalidOperationException || e is NullReferenceException) + { + // модули процесса ещё не загружены - читаем снова до таймаута + } + if (sw.Elapsed >= config.ClientStartTimeout) + { + throw new PilotWaitTimeoutException("загрузка процесса клиента (главный модуль)", config.ClientStartTimeout, sw.Elapsed, null, null); + } + Thread.Sleep(100); + } + } + private static string ClientLogPath(PilotUiConfig config) { return ClientLogFile.DefaultPath(config.ProductFolder); diff --git a/src/PilotUITesting/Client/PilotClientLogin.cs b/src/PilotUITesting/Client/PilotClientLogin.cs index 155694f..9cefbb8 100644 --- a/src/PilotUITesting/Client/PilotClientLogin.cs +++ b/src/PilotUITesting/Client/PilotClientLogin.cs @@ -22,5 +22,15 @@ public static void Save(PilotUiConfig config, string user, string password) ClientLoginFile.Save(config.ResolvedExePath, config.ProductFolder, config.ServerUrl, user, password); PilotLog.Action($"сохранён вход клиента {config.ProductFolder}: {user} в {config.ServerUrl}"); } + + /// Файл настроек клиента, в котором хранится сохранённый вход (для копии и возврата после тестов). + public static string SettingsPath(PilotUiConfig config) + { + if (config == null) + { + throw new ArgumentNullException(nameof(config)); + } + return ClientLoginFile.SettingsPath(config.ProductFolder); + } } } diff --git a/src/PilotUITesting/Client/Windows/PilotCommonSettingsWindow.cs b/src/PilotUITesting/Client/Windows/PilotCommonSettingsWindow.cs index 8935085..146ac20 100644 --- a/src/PilotUITesting/Client/Windows/PilotCommonSettingsWindow.cs +++ b/src/PilotUITesting/Client/Windows/PilotCommonSettingsWindow.cs @@ -104,6 +104,20 @@ public IReadOnlyList Rows() return Find(GridId).FindDescendantsBfs(element => element.SafeControlType() == ControlType.DataItem, 6); } + /// + /// Строки конфигураций одной настройки: у строки AutomationId - ключ настройки, Name - оргединица, для которой она задана + /// [Д] дамп Pilot-BIM 26.20. При виртуализации - только построенные. + /// + public IReadOnlyList FeatureRows(string featureKey) + { + if (string.IsNullOrEmpty(featureKey)) + { + throw new ArgumentException("Ключ настройки обязателен.", nameof(featureKey)); + } + + return Rows().Where(row => row.SafeAutomationId() == featureKey).ToList(); + } + /// Первая строка, в текстах которой есть подстрока; null - такой нет. public AutomationElement TryFindRow(string textPart) { diff --git a/src/PilotUITesting/Data/PilotServerClient.More.cs b/src/PilotUITesting/Data/PilotServerClient.More.cs index 2569c98..3e9cda6 100644 --- a/src/PilotUITesting/Data/PilotServerClient.More.cs +++ b/src/PilotUITesting/Data/PilotServerClient.More.cs @@ -211,7 +211,7 @@ public DObject SetAttributesAndWait(Guid id, IDictionary attribu foreach (KeyValuePair pair in expected) { obj.Attributes.TryGetValue(pair.Key, out DValue actual); - if (pair.Value == null ? actual != null && actual.Value != null : !pair.Value.Equals(actual)) + if (!SameAsStored(pair.Value, actual)) { return null; } @@ -332,6 +332,24 @@ internal static DValue AsSent(DValue value) return value; } + /// + /// Прочитанное с сервера значение совпадает с отправленным (). Пустой массив (int[] оргединиц, string[]) + /// сервер хранит как отсутствие значения, поэтому он совпадает с null; expected null (атрибут убран) - тоже. + /// + internal static bool SameAsStored(DValue expected, DValue actual) + { + bool expectedEmpty = expected?.Value == null + || (expected.Value is int[] ints && ints.Length == 0) + || (expected.Value is string[] strings && strings.Length == 0); + if (expectedEmpty) + { + return actual?.Value == null + || (actual.Value is int[] actualInts && actualInts.Length == 0) + || (actual.Value is string[] actualStrings && actualStrings.Length == 0); + } + return expected.Equals(actual); + } + /// Значение атрибута строкой; атрибута нет - null (в отличие от , который возвращает ""). public static string AttrOrNull(DObject obj, string name) { diff --git a/src/PilotUITesting/Data/PilotServerClient.Settings.cs b/src/PilotUITesting/Data/PilotServerClient.Settings.cs new file mode 100644 index 0000000..e10b9c3 --- /dev/null +++ b/src/PilotUITesting/Data/PilotServerClient.Settings.cs @@ -0,0 +1,62 @@ +using System; +using Ascon.Pilot.DataClasses; +using PilotUITesting.Uia; + +namespace PilotUITesting.Data +{ + /// Общие настройки базы («Управление общими настройками»): чтение и запись значения ключа для оргединицы. + public sealed partial class PilotServerClient + { + /// Оргединица общих настроек «для всей базы». + public const int WholeDatabase = 0; + + /// Значение общей настройки , заданное для оргединицы (не унаследованное); null - не задано. + public string GetCommonSetting(string key, int orgUnitId = WholeDatabase) + { + RequireKey(key); + DSettings settings = ServerApi.GetCommonSettings(); + return settings?.CommonSettings != null + && settings.CommonSettings.TryGetValue(orgUnitId, out DSettingsCollection collection) + && collection?.Values != null + && collection.Values.TryGetValue(key, out string value) + ? value + : null; + } + + /// + /// Записать общую настройку для оргединицы (подразделение - для всех его должностей) и дождаться, + /// что сервер её вернул. value null - убрать настройку. Нужны права администратора базы. + /// + public void SetCommonSetting(string key, string value, int orgUnitId = WholeDatabase, TimeSpan? timeout = null) + { + RequireKey(key); + PilotLog.Action($"общая настройка {key} для оргединицы {orgUnitId}: {(value == null ? "убрать" : "«" + value + "»")}"); + ServerApi.ChangeSettings(new DSettingsChange + { + Identity = Guid.NewGuid(), + OrgUnitId = orgUnitId, + PersonId = DSettingsChange.UNDEFINED, + Key = key, + Value = value, + }); + string actual = null; + if (!Wait.TryUntil(() => (actual = GetCommonSetting(key, orgUnitId)) == value, timeout ?? DefaultDataTimeout)) + { + throw new InvalidOperationException($"Сервер не вернул общую настройку {key} для оргединицы {orgUnitId}: ожидалось {Show(value)}, прочитано {Show(actual)}."); + } + } + + private static void RequireKey(string key) + { + if (string.IsNullOrWhiteSpace(key)) + { + throw new ArgumentException("Нужен ключ настройки", nameof(key)); + } + } + + private static string Show(string value) + { + return value == null ? "«не задана»" : "«" + value + "»"; + } + } +} diff --git a/src/PilotUITesting/NUnit/PilotUiTestBase.cs b/src/PilotUITesting/NUnit/PilotUiTestBase.cs index 8c41324..f0d7e1a 100644 --- a/src/PilotUITesting/NUnit/PilotUiTestBase.cs +++ b/src/PilotUITesting/NUnit/PilotUiTestBase.cs @@ -40,6 +40,7 @@ public abstract class PilotUiTestBase private readonly List<(string Description, Action Restore)> _afterTest = new List<(string, Action)>(); private readonly List<(string Description, Action Restore)> _afterTests = new List<(string, Action)>(); private string _clientRestartReason; + private LocalFileBackup _clientLogin; private PilotSandbox _testData; private PluginLogWatch _pluginLogs; private DateTime _testStartedUtc; @@ -62,6 +63,14 @@ public abstract class PilotUiTestBase /// Песочница тестовых данных класса (секция "sandbox" pilot-ui-tests.json): создаётся при первом обращении, убирается после всех тестов класса. protected PilotSandbox TestData => _testData ?? (_testData = PilotSandbox.Create(Server, Config.Sandbox, GetType().Name)); + /// + /// Учётка из конфигурации (ключ "accounts"), под которой работает клиент в тестах класса; null - сохранённый вход клиента как есть. + /// Задана - перед запуском клиента работающий клиент закрывается (-quit), в настройки клиента записывается вход этой учётки + /// (), подпись профиля сверяется с её clientUser; после всех тестов класса клиент закрывается + /// и прежний сохранённый вход возвращается. Учётки нет - тесты класса пропускаются (Assert.Ignore). + /// + protected virtual string ClientAccount => null; + /// Перед каждым тестом закрывать меню и окна, оставшиеся от упавшего теста (по умолчанию - ключ resetUiBeforeEachTest). protected virtual bool ResetUiBeforeEachTest => Config.ResetUiBeforeEachTest; @@ -82,6 +91,10 @@ public void PilotOneTimeSetUp() } Server = PilotServerClient.Connect(Config.ServerUrl, Config.ResolvedApiLogin, Config.ResolvedApiPassword); Server.DefaultDataTimeout = Config.DataTimeout; + if (!string.IsNullOrWhiteSpace(ClientAccount)) + { + LoginClientAs(ClientAccount); + } App = PilotApp.StartOrAttach(Config); _pluginLogs = new PluginLogWatch(PluginLogWatch.DefaultDirectory(Config.Client), Config.PluginLogs ?? new string[0]); TestArtifacts.Prune(Config); @@ -98,7 +111,21 @@ public void PilotOneTimeTearDown() Try(OnAfterTests, errors); } RunRestores(_afterTests, errors); - if (App != null) + if (_clientLogin != null) + { + // клиент под учёткой класса: закрыть (и не подключённый - запуск мог упасть после старта процесса), чтобы следующий + // класс не подключился к нему и клиент при выходе не перезаписал возвращаемый вход + if (App != null) + { + Try(() => CloseViews(TabLifetime.Fixture), errors); + Try(() => App.Quit(), errors); + } + else + { + Try(() => PilotApp.QuitRunning(Config), errors); + } + } + else if (App != null) { Try(() => CloseViews(TabLifetime.Fixture), errors); if (NeedsRestart(out string _)) @@ -115,6 +142,18 @@ public void PilotOneTimeTearDown() { Try(backup.Restore, errors); } + if (_clientLogin != null) + { + LocalFileBackup login = _clientLogin; + _clientLogin = null; + Try(login.Restore, errors); + if (PilotApp.IsRunning(Config)) + { + // клиент перезаписывает настройки при выходе - возвращённый вход пропадёт + errors.Add(new InvalidOperationException($"Клиент под учёткой «{ClientAccount}» не закрылся: прежний сохранённый вход возвращён, " + + "но при выходе клиент перезапишет его входом учётки. Закройте клиент и проверьте вход: " + PilotClientLogin.SettingsPath(Config))); + } + } if (_testData != null) { Try(_testData.Dispose, errors); @@ -284,10 +323,7 @@ protected PilotServerClient ServerAs(string accountName) { return existing; } - if (!Config.Accounts.TryGetValue(accountName, out PilotAccount account) || account == null || string.IsNullOrWhiteSpace(account.Login) || string.IsNullOrEmpty(account.Password)) - { - Assert.Ignore($"Нужна учётка «{accountName}»: ключ accounts в pilot-ui-tests.local.json или PILOT_UI_ACCOUNT_{accountName.ToUpperInvariant()}_LOGIN/_PASSWORD."); - } + PilotAccount account = RequireAccount(accountName); PilotServerClient client = PilotServerClient.Connect(Config.ServerUrl, account.Login, account.Password); client.DefaultDataTimeout = Config.DataTimeout; _accounts[accountName] = client; @@ -295,6 +331,26 @@ protected PilotServerClient ServerAs(string accountName) return client; } + private PilotAccount RequireAccount(string accountName) + { + if (!Config.Accounts.TryGetValue(accountName, out PilotAccount account) || account == null || string.IsNullOrWhiteSpace(account.Login) || string.IsNullOrEmpty(account.Password)) + { + Assert.Ignore($"Нужна учётка «{accountName}»: ключ accounts в pilot-ui-tests.local.json или PILOT_UI_ACCOUNT_{accountName.ToUpperInvariant()}_LOGIN/_PASSWORD."); + } + return account; + } + + /// Клиент под учёткой класса (): закрыть работающий, записать вход, сверять её подпись профиля. + private void LoginClientAs(string accountName) + { + PilotAccount account = RequireAccount(accountName); + PilotApp.QuitRunning(Config); + _clientLogin = LocalFileBackup.Take(PilotClientLogin.SettingsPath(Config)); + PilotClientLogin.Save(Config, account.Login, account.Password); + Config.ClientUser = string.IsNullOrWhiteSpace(account.ClientUser) ? null : account.ClientUser; + PilotLog.Action($"клиент в тестах класса - под учёткой «{accountName}» ({account.Login})"); + } + /// /// Вернуть состояние после теста (в том числе упавшего): действия выполняются в обратном порядке регистрации в TearDown, /// после закрытия вкладок теста; ошибки собираются и роняют TearDown. diff --git a/src/PilotUITesting/PilotUiConfig.cs b/src/PilotUITesting/PilotUiConfig.cs index c8c7b9a..09cd24d 100644 --- a/src/PilotUITesting/PilotUiConfig.cs +++ b/src/PilotUITesting/PilotUiConfig.cs @@ -29,12 +29,21 @@ public enum UnsentChangesPolicy Discard, } - /// Учётная запись базы Pilot (логин и пароль) - для подключения Server API под другим пользователем. + /// + /// Учётная запись базы Pilot (логин и пароль): для подключения Server API под другим пользователем (PilotUiTestBase.ServerAs) + /// и для клиента под другим пользователем (PilotUiTestBase.ClientAccount). + /// public sealed class PilotAccount { public string Login { get; set; } public string Password { get; set; } + + /// + /// Подпись кнопки профиля клиента под этой учёткой («отображаемое имя (должность)»), как . + /// Сверяется, когда клиент запущен под этой учёткой (PilotUiTestBase.ClientAccount); пусто - не сверяется. + /// + public string ClientUser { get; set; } } /// diff --git a/src/PilotUITesting/Uia/UiAct.cs b/src/PilotUITesting/Uia/UiAct.cs index b9351c9..bf633b4 100644 --- a/src/PilotUITesting/Uia/UiAct.cs +++ b/src/PilotUITesting/Uia/UiAct.cs @@ -132,6 +132,17 @@ internal static void Click(AutomationElement element, string description, MouseB } } + /// Клик мышью в заданную точку экрана внутри элемента (например, в строку переносимой ссылки, а не в центр её прямоугольника). + internal static void ClickAt(AutomationElement element, Point point, string description) + { + string action = "клик по " + description; + ProcessDpi.RequireForMouse(action); + int pid = UiQuery.Read(() => element.Properties.ProcessId.ValueOrDefault, Wait.DefaultTimeout, "процесс " + description); + EnsurePointBelongsTo(point, pid, element, action); + PilotLog.Action(action + $" ({point.X},{point.Y})"); + Mouse.Click(point, MouseButton.Left); + } + /// Нажать клавиши (одновременно) с фокусом на элементе; фокус должен оказаться в окне процесса клиента. internal static void Keys(AutomationElement focusTarget, string description, params VirtualKeyShort[] keys) { diff --git a/tests/PilotUITesting.Tests/PublicApi.approved.txt b/tests/PilotUITesting.Tests/PublicApi.approved.txt index 7ac3d93..8391a50 100644 --- a/tests/PilotUITesting.Tests/PublicApi.approved.txt +++ b/tests/PilotUITesting.Tests/PublicApi.approved.txt @@ -41,6 +41,8 @@ PilotUITesting.Client.PilotApp | method Dispose() : System.Void PilotUITesting.Client.PilotApp | static method EnableDpiAwareness() : PilotUITesting.Uia.DpiStatus PilotUITesting.Client.PilotApp | method ShowObject(System.Guid objectId, System.Guid? annotationId = null, System.TimeSpan? timeout = null) : System.Void PilotUITesting.Client.PilotApp | method Quit(System.TimeSpan? timeout = null) : System.Void +PilotUITesting.Client.PilotApp | static method QuitRunning(PilotUITesting.PilotUiConfig config, System.TimeSpan? timeout = null) : System.Void +PilotUITesting.Client.PilotApp | static method IsRunning(PilotUITesting.PilotUiConfig config) : System.Boolean PilotUITesting.Client.PilotApp | method Restart() : PilotUITesting.Client.PilotApp PilotUITesting.Client.PilotApp | method BringToFront() : System.Void PilotUITesting.Client.PilotApp | method SendKeys(System.String description, params FlaUI.Core.WindowsAPI.VirtualKeyShort[] keys) : System.Void @@ -84,8 +86,15 @@ PilotUITesting.Client.PilotCard | method AddOrgUnit(System.String stage, System. PilotUITesting.Client.PilotCard | method OrgUnits(System.String stage) : System.Collections.Generic.IReadOnlyList PilotUITesting.Client.PilotCard | method Describe() : System.String PilotUITesting.Client.PilotCard | method ToString() : System.String +PilotUITesting.Client.PilotChat | class +PilotUITesting.Client.PilotChat | method Messages() : System.Collections.Generic.IReadOnlyList +PilotUITesting.Client.PilotChat | method WaitMessage(System.String text, System.TimeSpan? timeout = null) : FlaUI.Core.AutomationElements.AutomationElement +PilotUITesting.Client.PilotChat | method Send(System.String text, System.TimeSpan? timeout = null) : FlaUI.Core.AutomationElements.AutomationElement +PilotUITesting.Client.PilotChat | method ClickLink(System.String address, System.TimeSpan? timeout = null) : System.Void +PilotUITesting.Client.PilotChat | property Root : FlaUI.Core.AutomationElements.AutomationElement { get; } PilotUITesting.Client.PilotClientLogin | static class PilotUITesting.Client.PilotClientLogin | static method Save(PilotUITesting.PilotUiConfig config, System.String user, System.String password) : System.Void +PilotUITesting.Client.PilotClientLogin | static method SettingsPath(PilotUITesting.PilotUiConfig config) : System.String PilotUITesting.Client.PilotCommonSettingsWindow | class : PilotUITesting.Client.PilotDialog PilotUITesting.Client.PilotCommonSettingsWindow | static method AddItemId(System.String featureKey) : System.String PilotUITesting.Client.PilotCommonSettingsWindow | static method Open(PilotUITesting.Client.PilotApp app, System.TimeSpan? timeout = null) : PilotUITesting.Client.PilotCommonSettingsWindow @@ -93,6 +102,7 @@ PilotUITesting.Client.PilotCommonSettingsWindow | static method Wait(PilotUITest PilotUITesting.Client.PilotCommonSettingsWindow | static method TryFind(PilotUITesting.Client.PilotApp app) : PilotUITesting.Client.PilotCommonSettingsWindow PilotUITesting.Client.PilotCommonSettingsWindow | method Groups() : System.Collections.Generic.IReadOnlyList PilotUITesting.Client.PilotCommonSettingsWindow | method Rows() : System.Collections.Generic.IReadOnlyList +PilotUITesting.Client.PilotCommonSettingsWindow | method FeatureRows(System.String featureKey) : System.Collections.Generic.IReadOnlyList PilotUITesting.Client.PilotCommonSettingsWindow | method TryFindRow(System.String textPart) : FlaUI.Core.AutomationElements.AutomationElement PilotUITesting.Client.PilotCommonSettingsWindow | method EditRow(FlaUI.Core.AutomationElements.AutomationElement row, System.TimeSpan? timeout = null) : PilotUITesting.Client.PilotNewSettingsItemWindow PilotUITesting.Client.PilotCommonSettingsWindow | method RemoveRow(System.String textPart, System.TimeSpan? timeout = null) : System.Void @@ -238,6 +248,15 @@ PilotUITesting.Client.PilotIds+Card+ReferenceBook | const field CheckBox : Syste PilotUITesting.Client.PilotIds+Card+ReferenceBook | const field ItemTitle : System.String = "titleTextBlock" PilotUITesting.Client.PilotIds+Card+ReferenceBook | const field Ok : System.String = "btnOk" PilotUITesting.Client.PilotIds+Card+ReferenceBook | const field Cancel : System.String = "btnCancel" +PilotUITesting.Client.PilotIds+Chat | static class +PilotUITesting.Client.PilotIds+Chat | const field Container : System.String = "AUIDChatView" +PilotUITesting.Client.PilotIds+Chat | const field Messages : System.String = "messagesListControl" +PilotUITesting.Client.PilotIds+Chat | const field MessageText : System.String = "messageText" +PilotUITesting.Client.PilotIds+Chat | const field MessageAuthor : System.String = "authorTextBlock" +PilotUITesting.Client.PilotIds+Chat | const field SystemMessage : System.String = "chatSystemTextBlock" +PilotUITesting.Client.PilotIds+Chat | const field NewMessage : System.String = "newMessageTextBox" +PilotUITesting.Client.PilotIds+Chat | const field Send : System.String = "sendButton" +PilotUITesting.Client.PilotIds+Chat | const field AddAttachment : System.String = "addAttachmentButton" PilotUITesting.Client.PilotIds+DialogWindow | static class PilotUITesting.Client.PilotIds+DialogWindow | const field Minimize : System.String = "btnMinimize" PilotUITesting.Client.PilotIds+DialogWindow | const field Restore : System.String = "btnRestore" @@ -1006,6 +1025,7 @@ PilotUITesting.Client.PilotPage | method ToolbarWith(System.String anyButtonId) PilotUITesting.Client.PilotPage | method CardIn(System.String containerId) : PilotUITesting.Client.PilotCard PilotUITesting.Client.PilotPage | method ListById(System.String listId, System.Func rowTitle = null) : PilotUITesting.Client.PilotList PilotUITesting.Client.PilotPage | method ListBy(PilotUITesting.Uia.By selector, System.Func rowTitle = null) : PilotUITesting.Client.PilotList +PilotUITesting.Client.PilotPage | method Chat() : PilotUITesting.Client.PilotChat PilotUITesting.Client.PilotPage | method GridById(System.String gridId) : PilotUITesting.Uia.UiGrid PilotUITesting.Client.PilotPage | method Dump(System.Int32 maxDepth = 40) : System.String PilotUITesting.Client.PilotPage | method ToString() : System.String @@ -1257,6 +1277,8 @@ PilotUITesting.Data.PilotServerClient | method ActualSnapshotCreated(System.Guid PilotUITesting.Data.PilotServerClient | method ReloadMetadata() : System.Void PilotUITesting.Data.PilotServerClient | static method AttrOrNull(Ascon.Pilot.DataClasses.DObject obj, System.String name) : System.String PilotUITesting.Data.PilotServerClient | method StateIdByName(System.String name) : System.Guid +PilotUITesting.Data.PilotServerClient | method GetCommonSetting(System.String key, System.Int32 orgUnitId = 0) : System.String +PilotUITesting.Data.PilotServerClient | method SetCommonSetting(System.String key, System.String value, System.Int32 orgUnitId = 0, System.TimeSpan? timeout = null) : System.Void PilotUITesting.Data.PilotServerClient | property ReconnectCount : System.Int32 { get; } PilotUITesting.Data.PilotServerClient | property Metadata : Ascon.Pilot.DataClasses.DMetadata { get; } PilotUITesting.Data.PilotServerClient | property DatabaseInfo : Ascon.Pilot.DataClasses.DDatabaseInfo { get; } @@ -1266,6 +1288,7 @@ PilotUITesting.Data.PilotServerClient | property DefaultDataTimeout : System.Tim PilotUITesting.Data.PilotServerClient | property Storage : Ascon.Pilot.DataModifier.FileSystemStorageProvider { get; } PilotUITesting.Data.PilotServerClient | property Errors : System.Collections.Generic.IReadOnlyList { get; } PilotUITesting.Data.PilotServerClient | static readonly field RootId : System.Guid +PilotUITesting.Data.PilotServerClient | const field WholeDatabase : System.Int32 = 0 PilotUITesting.Data.PilotTestFiles | static class PilotUITesting.Data.PilotTestFiles | static method Pdf(System.String text, System.String fileName = null) : System.String PilotUITesting.Data.PilotTestFiles | static method MinimalPdf(System.String text) : System.Byte[] @@ -1325,6 +1348,7 @@ PilotUITesting.NUnit.PilotUiTestBase | protected property ModuleButtonTitle : Sy PilotUITesting.NUnit.PilotUiTestBase | protected property Timeout : System.TimeSpan { get; } PilotUITesting.NUnit.PilotUiTestBase | protected property DataTimeout : System.TimeSpan { get; } PilotUITesting.NUnit.PilotUiTestBase | protected property TestData : PilotUITesting.Data.PilotSandbox { get; } +PilotUITesting.NUnit.PilotUiTestBase | protected property ClientAccount : System.String { get; } PilotUITesting.NUnit.PilotUiTestBase | protected property ResetUiBeforeEachTest : System.Boolean { get; } PilotUITesting.NUnit.PilotUiTestBase | protected property DialogCancelButtonIds : System.String[] { get; } PilotUITesting.NUnit.TabLifetime | enum @@ -1342,6 +1366,7 @@ PilotUITesting.PilotAccount | class PilotUITesting.PilotAccount | ctor() PilotUITesting.PilotAccount | property Login : System.String { get; set; } PilotUITesting.PilotAccount | property Password : System.String { get; set; } +PilotUITesting.PilotAccount | property ClientUser : System.String { get; set; } PilotUITesting.PilotClientKind | enum PilotUITesting.PilotClientKind | enum PilotIce = 0 PilotUITesting.PilotClientKind | enum PilotBim = 1 diff --git a/tests/PilotUITesting.Tests/Unit/ConfigTests.cs b/tests/PilotUITesting.Tests/Unit/ConfigTests.cs index 4a0dcfa..9e42f93 100644 --- a/tests/PilotUITesting.Tests/Unit/ConfigTests.cs +++ b/tests/PilotUITesting.Tests/Unit/ConfigTests.cs @@ -64,6 +64,20 @@ public void Accounts_are_read_case_insensitive_and_environment_overrides_them() Assert.That(config.Describe(), Does.Contain("expert").And.Contain("root")); } + [Test] + public void Account_client_user_is_read_for_client_under_account() + { + File.WriteAllText(Path.Combine(_dir, PilotUiConfig.FileName), @"{ + ""serverUrl"": ""http://host/db"", ""clientUser"": ""bot (Инженер)"", + ""accounts"": { ""worker"": { ""login"": ""w1"", ""password"": ""p1"", ""clientUser"": ""w1 (Сотрудник)"" }, ""plain"": { ""login"": ""x"", ""password"": ""y"" } } +}"); + PilotUiConfig config = PilotUiConfig.Load(_dir); + Assert.That(config.UnknownKeys, Is.Empty, "clientUser учётки - известный ключ"); + Assert.That(config.Accounts["worker"].ClientUser, Is.EqualTo("w1 (Сотрудник)")); + Assert.That(config.Accounts["plain"].ClientUser, Is.Null, "без clientUser подпись не сверяется"); + Assert.That(config.ClientUser, Is.EqualTo("bot (Инженер)"), "общая подпись клиента не меняется"); + } + [Test] public void Admin_login_without_password_is_a_problem() { diff --git a/tests/PilotUITesting.Tests/Unit/PureLogicTests.cs b/tests/PilotUITesting.Tests/Unit/PureLogicTests.cs index 9015efc..1d82403 100644 --- a/tests/PilotUITesting.Tests/Unit/PureLogicTests.cs +++ b/tests/PilotUITesting.Tests/Unit/PureLogicTests.cs @@ -86,6 +86,20 @@ public void Dates_are_compared_as_sent_to_server_in_utc() Assert.That(PilotServerClient.AsSent("текст").StrValue, Is.EqualTo("текст")); } + [Test] + public void Empty_arrays_match_missing_value_as_server_stores_them() + { + Assert.That(PilotServerClient.SameAsStored(new int[0], new DValue()), Is.True, "пустой список оргединиц сервер хранит как null"); + Assert.That(PilotServerClient.SameAsStored(new int[0], null), Is.True); + Assert.That(PilotServerClient.SameAsStored(new string[0], new DValue()), Is.True); + Assert.That(PilotServerClient.SameAsStored(null, new DValue()), Is.True, "атрибут убран"); + Assert.That(PilotServerClient.SameAsStored(null, new[] { 1 }), Is.False); + Assert.That(PilotServerClient.SameAsStored(new int[0], new[] { 1103 }), Is.False); + Assert.That(PilotServerClient.SameAsStored(new[] { 1103 }, new[] { 1103 }), Is.True, "массивы сравниваются по элементам"); + Assert.That(PilotServerClient.SameAsStored(new[] { 1103 }, new DValue()), Is.False); + Assert.That(PilotServerClient.SameAsStored("текст", "текст"), Is.True); + } + [Test] public void AttrOrNull_distinguishes_missing_from_empty() {