增加商铺列表
This commit is contained in:
1 parent
d5232c581c
commit
440510aa8c
19 files changed
+734
-77
No files matched your search
@@ -0,0 +1,182 @@
|
||||
using Autofac;
|
||||
using Store.Management;
|
||||
using Store.Management.Api;
|
||||
using Store.Management.Api.Shops;
|
||||
using Store.Management.Framework.Controls;
|
||||
using Store.Management.Framework.Services;
|
||||
using Store.Management.ViewModels;
|
||||
using Store.Management.Views;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Threading;
|
||||
|
||||
internal static class ShopManagementChecks
|
||||
{
|
||||
public static int Run()
|
||||
{
|
||||
using ShopHandler handler = new();
|
||||
using HttpClient http = new(handler);
|
||||
using StoreApiClient client = new(new ApiClientOptions { BaseUrl = new Uri("https://test.invalid/api/v1/") }, http);
|
||||
client.Auth.LoginAsync(new Store.Management.Api.Authentication.LoginRequest { UserName = "tester", Password = "password" }).GetAwaiter().GetResult();
|
||||
Prism.Autofac.AutofacContainerExtension extension = new();
|
||||
extension.RegisterInstance(typeof(StoreApiClient), client);
|
||||
extension.FinalizeExtension();
|
||||
using IContainer container = extension.Instance;
|
||||
IShopService service = container.Resolve<IShopService>();
|
||||
ShopManagementViewModel vm = new(service, new TestStatusBar())
|
||||
{
|
||||
Account = " account ", ShopId = " shop-1 ", ShopName = " shop name ", Notes = " note "
|
||||
};
|
||||
vm.SearchCommand.Execute().GetAwaiter().GetResult();
|
||||
Check(handler.Path == "/api/v1/shop/GetAllShops" && handler.Authorization == "Bearer shop-test-token", "route and authentication");
|
||||
Check(handler.Query!.SearchUserName == "account" && handler.Query.SearchId == "shop-1" &&
|
||||
handler.Query.SearchName == "shop name" && handler.Query.SearchNotes == "note", "trimmed search fields");
|
||||
Check(vm.Total == 101 && vm.Shops.Single().ShopAccount == "sample shop" && vm.Shops[0].GroupName == "group" && vm.Shops[0].LoginStatus == "状态:未登录" && vm.Shops[0].IsLoggedOut, "mapping and total");
|
||||
vm.Account = "not submitted";
|
||||
vm.PageCommand.Execute(new DataGridPageRequest(2, 50)).GetAwaiter().GetResult();
|
||||
Check(handler.Query!.SearchUserName == "account" && vm.Page == 2, "paging preserves submitted filters");
|
||||
vm.SearchCommand.Execute().GetAwaiter().GetResult();
|
||||
Check(vm.Page == 1 && handler.Query!.SearchUserName == "not submitted", "search resets page");
|
||||
vm.ResetCommand.Execute().GetAwaiter().GetResult();
|
||||
Check(vm.Account == "" && vm.ShopId == "" && vm.ShopName == "" && vm.Notes == "" && handler.Query!.SearchNotes == "", "reset");
|
||||
handler.Total = 1;
|
||||
vm.PageCommand.Execute(new DataGridPageRequest(3, 50)).GetAwaiter().GetResult();
|
||||
Check(vm.Page == 1 && handler.Query!.Page == 1, "shrinking results return to valid page");
|
||||
handler.Fail = true;
|
||||
vm.SearchCommand.Execute().GetAwaiter().GetResult();
|
||||
Check(vm.Shops.Count == 0 && vm.Total == 0 && !vm.LoadingStatus.IsLoading && vm.LoadingStatus.ErrorMessage == "query failed", "failure clears stale rows and loading");
|
||||
handler.Fail = false;
|
||||
vm.SearchCommand.Execute().GetAwaiter().GetResult();
|
||||
Check(vm.Shops.Count == 1 && vm.LoadingStatus.ErrorMessage == "", "retry recovers");
|
||||
handler.Total = 0;
|
||||
vm.SearchCommand.Execute().GetAwaiter().GetResult();
|
||||
Check(vm.Total == 0 && vm.Shops.Count == 0, "empty result");
|
||||
int count = handler.Count;
|
||||
try
|
||||
{
|
||||
client.Shops.SearchAsync(new ShopQueryRequest { Page = 0 }).GetAwaiter().GetResult();
|
||||
throw new Exception("Missing page validation");
|
||||
}
|
||||
catch (System.ComponentModel.DataAnnotations.ValidationException)
|
||||
{
|
||||
Check(handler.Count == count, "invalid page never sent");
|
||||
}
|
||||
|
||||
Check(!new Store.Management.Framework.ViewModels.ShopItemViewModel { LoginStatus = "已登录" }.IsLoggedOut &&
|
||||
!new Store.Management.Framework.ViewModels.ShopItemViewModel().IsLoggedOut, "normal and null login status");
|
||||
var cookies = service.GetCookiesAsync("shop-1").GetAwaiter().GetResult();
|
||||
Check(cookies.Single().Cookies == "test-cookie" && cookies[0].ShopId == "shop-1", "cookie response");
|
||||
Check(!vm.CopyCookieCommand.CanExecute(new Store.Management.Framework.ViewModels.ShopItemViewModel()), "missing shop ID disables copy");
|
||||
handler.Total = 1;
|
||||
vm.SearchCommand.Execute().GetAwaiter().GetResult();
|
||||
App app = new();
|
||||
app.InitializeComponent();
|
||||
app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
|
||||
ShopManagementView view = new() { DataContext = vm };
|
||||
Window window = new() { Content = view, Width = 1000, Height = 650, ShowInTaskbar = false };
|
||||
try
|
||||
{
|
||||
window.Show();
|
||||
app.Dispatcher.Invoke(() => { }, DispatcherPriority.ApplicationIdle);
|
||||
view.UpdateLayout();
|
||||
Check(view.IsLoaded && view.ActualWidth > 0, "page resources and layout");
|
||||
TextBox[] searchInputs = Descendants<TextBox>(view).Where(input => input.GetBindingExpression(TextBox.TextProperty)?.ParentBinding.Path.Path is "Account" or "ShopId" or "ShopName" or "Notes").ToArray();
|
||||
Check(searchInputs.Length == 4 && searchInputs.All(input => input.Width == 180 && input.Height == 32 && input.ReadLocalValue(FrameworkElement.StyleProperty) == DependencyProperty.UnsetValue), "search inputs inherit scoped styles");
|
||||
Button searchButton = Descendants<Button>(view).Single(button => Equals(button.Content, "查询"));
|
||||
Check(searchButton.Width == 80 && searchButton.Height == 32 && searchButton.ReadLocalValue(FrameworkElement.StyleProperty) == DependencyProperty.UnsetValue, "search button inherits scoped style");
|
||||
DataGridEx grid = Descendants<DataGridEx>(view).Single();
|
||||
DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(0);
|
||||
Check(ReferenceEquals(row.Background, app.FindResource("DangerBrush")), "logged-out row color");
|
||||
row.IsSelected = true;
|
||||
view.UpdateLayout();
|
||||
Check(ReferenceEquals(row.Foreground, app.FindResource("SelectedForegroundBrush")), "selected warning row contrast");
|
||||
DataGridTemplateColumn actions = grid.Columns.OfType<DataGridTemplateColumn>().Single();
|
||||
FrameworkElement content = actions.GetCellContent(row);
|
||||
Button[] buttons = Descendants<Button>(content).ToArray();
|
||||
Check(buttons.Length == 3 && ReferenceEquals(buttons[0].Command, vm.CopyCookieCommand) &&
|
||||
ReferenceEquals(buttons[0].CommandParameter, vm.Shops[0]) && !buttons[1].IsEnabled && !buttons[2].IsEnabled,
|
||||
"row commands and pending action buttons");
|
||||
}
|
||||
finally
|
||||
{
|
||||
window.Close();
|
||||
app.Shutdown();
|
||||
}
|
||||
Console.WriteLine("PASS: shop API, DI, filters, paging, reset, errors, retry, empty results and WPF page load.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static IEnumerable<T> Descendants<T>(DependencyObject parent) where T : DependencyObject
|
||||
{
|
||||
for (int index = 0; index < System.Windows.Media.VisualTreeHelper.GetChildrenCount(parent); index++)
|
||||
{
|
||||
DependencyObject child = System.Windows.Media.VisualTreeHelper.GetChild(parent, index);
|
||||
if (child is T match)
|
||||
{
|
||||
yield return match;
|
||||
}
|
||||
foreach (T descendant in Descendants<T>(child))
|
||||
{
|
||||
yield return descendant;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void Check(bool condition, string message)
|
||||
{
|
||||
if (!condition)
|
||||
{
|
||||
throw new Exception(message);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class TestStatusBar : IStatusBarService
|
||||
{
|
||||
public StatusBarMessage Current { get; private set; } = new("", StatusLevel.Info, null);
|
||||
public void Report(string text, StatusLevel level = StatusLevel.Info, int? progress = null)
|
||||
=> Current = new(text, level, progress);
|
||||
}
|
||||
|
||||
private sealed class ShopHandler : HttpMessageHandler
|
||||
{
|
||||
public string? Path { get; private set; }
|
||||
public string? Authorization { get; private set; }
|
||||
public ShopQueryRequest? Query { get; private set; }
|
||||
public bool Fail { get; set; }
|
||||
public int Total { get; set; } = 101;
|
||||
public int Count { get; private set; }
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (request.RequestUri!.AbsolutePath.EndsWith("/Auth/Login"))
|
||||
{
|
||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent("""{"code":200,"data":{"token":"shop-test-token"}}""", Encoding.UTF8, "application/json")
|
||||
};
|
||||
}
|
||||
Count++;
|
||||
Check(request.Method == HttpMethod.Post, "POST required");
|
||||
Path = request.RequestUri!.AbsolutePath;
|
||||
Authorization = request.Headers.Authorization?.ToString();
|
||||
if (Path.EndsWith("/shop/GetShopCookies"))
|
||||
{
|
||||
using JsonDocument body = JsonDocument.Parse(await request.Content!.ReadAsStringAsync(cancellationToken));
|
||||
Check(body.RootElement.GetProperty("shopIds").GetArrayLength() == 1 &&
|
||||
body.RootElement.GetProperty("shopIds")[0].GetString() == "shop-1", "cookie request shop ID");
|
||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent("""{"code":200,"data":[{"shopId":"shop-1","cookies":"test-cookie"}]}""", Encoding.UTF8, "application/json")
|
||||
};
|
||||
}
|
||||
Query = JsonSerializer.Deserialize<ShopQueryRequest>(await request.Content!.ReadAsStringAsync(cancellationToken), new JsonSerializerOptions(JsonSerializerDefaults.Web));
|
||||
string items = Total == 0 ? "[]" : """[{"id":1,"userName":"account","shopId":"shop-1","shopAccount":"sample shop","loginStatus":"状态:未登录","notes":null,"groupName":"group"}]""";
|
||||
string json = Fail ? """{"code":400,"msg":"query failed"}""" : $$$"""{"code":200,"data":{"total":{{{Total}}},"items":{{{items}}}}}""";
|
||||
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user