Files
AndroidDeviceStreaming/desktop/Ads.Desktop.Smoke/Program.cs
T

174 lines
10 KiB
C#

using Ads.Desktop;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless;
using Avalonia.Threading;
internal static class Program
{
[STAThread]
public static int Main(string[] args)
{
if (args.Length == 2 && args[0] == "--port-child")
{
var listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, int.Parse(args[1]));
listener.Start();
Console.WriteLine("READY");
Console.Out.Flush();
Thread.Sleep(Timeout.Infinite);
return 0;
}
AppBuilder.Configure<App>().UseSkia().UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false }).SetupWithoutStarting();
using var finished = new CancellationTokenSource();
Exception? failure = null;
Dispatcher.UIThread.Post(async () =>
{
try { await RunAsync(args.Contains("--live"), args.Contains("--screen"), args.Contains("--usb")); }
catch (Exception error) { failure = error; }
finally { finished.Cancel(); }
});
Dispatcher.UIThread.MainLoop(finished.Token);
if (failure != null) { Console.Error.WriteLine(failure); return 1; }
return 0;
}
private static void Require(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
private static async Task UntilAsync(Func<bool> condition, string message)
{
var deadline = DateTime.UtcNow.AddSeconds(35);
while (!condition())
{
if (DateTime.UtcNow > deadline) throw new InvalidOperationException(message);
await Task.Delay(150);
}
}
private static async Task RunAsync(bool live, bool screen, bool usb)
{
var root = DesktopPaths.ProjectRoot() ?? throw new InvalidOperationException("Project root not found");
var folder = Path.Combine(root, "work", "desktop-smoke", Guid.NewGuid().ToString("N"));
using var vm = new MainViewModel(folder, backgroundMonitoring: true, loadLocalCredentials: live);
// Avoid collisions with the interactive application or another local ADB device.
var temporary = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
temporary.Start(); vm.Port = ((System.Net.IPEndPoint)temporary.LocalEndpoint).Port; temporary.Stop();
vm.UsbMode = usb;
if (usb) {
var usbProbe = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
usbProbe.Start(); vm.UsbPort = ((System.Net.IPEndPoint)usbProbe.LocalEndpoint).Port; usbProbe.Stop();
}
var window = new MainWindow { DataContext = vm };
window.Show();
await Task.Delay(60);
try
{
Require(window.FindControl<TextBox>("ServerBox")?.Text == RelayOptions.DefaultServer, "Server binding is wrong");
Require(window.FindControl<TextBox>("OriginBox")?.Text == RelayOptions.DefaultOrigin, "Origin binding is wrong");
Require(window.FindControl<CheckBox>("RelayOnlyCheck")?.IsChecked == vm.RelayOnly, "Transport preference binding is wrong");
if (!live)
{
Require(window.FindControl<Button>("ConnectButton")?.IsEffectivelyEnabled == false, "Connect should be disabled before device selection");
vm.Devices.Add(new DeviceItem("busy-phone", true, false));
vm.SelectedDevice = vm.Devices[0];
vm.RelayOnline = true;
Require(!vm.ConnectCommand.CanExecute(null), "Busy device was connectable");
vm.Devices.Add(new DeviceItem("free-phone", false, false));
vm.SelectedDevice = vm.Devices[1];
Require(vm.ConnectCommand.CanExecute(null), "Available device was not connectable");
var occupied = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
occupied.Start();
try
{
vm.Port = ((System.Net.IPEndPoint)occupied.LocalEndpoint).Port;
await vm.ConnectCommand.ExecuteAsync(null);
Require(!vm.HasConnection && vm.Notice.Contains("已被占用"), "Occupied port was not rejected safely");
}
finally { occupied.Stop(); }
var childInfo = ProcessTools.CreateStartInfo("dotnet", [typeof(Program).Assembly.Location, "--port-child", vm.Port.ToString()]);
using var child = System.Diagnostics.Process.Start(childInfo)!;
try
{
Require(await child.StandardOutput.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(10)) == "READY", "Listener child did not start");
await vm.ClearPortCommand.ExecuteAsync(null);
Require(child.HasExited && vm.PortCleanupStatus.Contains("已释放"), "GUI clear-port action did not terminate listener");
Require(window.FindControl<Button>("ClearPortButton") != null, "Clear-port button is missing");
Console.WriteLine("PASS: GUI cleanup terminates the exact port owner and frees the port");
}
finally { if (!child.HasExited) { child.Kill(); child.WaitForExit(5000); } }
Console.WriteLine("PASS: Avalonia bindings and device action availability");
return;
}
await vm.InitializeAsync();
await UntilAsync(() => vm.RelayOnline && vm.Devices.Any(d => d.Id == "home-phone"), "Public gateway was not discovered: " + vm.Notice);
Require(vm.RelayNodes.Count == 2 && vm.RelayNodes.All(n => n.Healthy), "Both relay nodes should be healthy");
vm.SelectedDevice = vm.Devices.Single(d => d.Id == "home-phone");
Require(!vm.SelectedDevice.Busy, "The gateway is in use; smoke test will not steal its lease");
await vm.ConnectCommand.ExecuteAsync(null);
await UntilAsync(() => vm.Ready && vm.Model != "—", "Device did not become ready: " + vm.Notice);
await UntilAsync(() => vm.TransportStatus.Contains("P2P") || vm.TransportStatus.Contains("中继连接"), "Transport status was not updated");
Require(window.FindControl<TextBlock>("TransportStatusText")?.Text == vm.TransportStatus, "Actual route binding failed");
if (usb) Require(vm.Endpoint?.StartsWith("ADS-") == true, "USB mode did not select the USB serial");
Console.WriteLine("PASS: two healthy nodes and actual transport shown: " + vm.TransportStatus);
Require(window.FindControl<TextBlock>("ModelText")?.Text == vm.Model, "Model UI binding failed");
Require(window.FindControl<Button>("ReconnectButton")?.IsEffectivelyEnabled == true, "Reconnect button not enabled");
Console.WriteLine("PASS: public device list, GUI connect, local ADB ready and model information: " + vm.Model);
Require(vm.Devices.Single(d => d.Id == "home-phone").IsLocal, "Current device ownership label is wrong");
using (var frame = window.CaptureRenderedFrame()) frame?.Save(Path.Combine(root, "work", "desktop-live.png"));
window.Width = 980; window.Height = 700;
await Task.Delay(60);
using (var frame = window.CaptureRenderedFrame()) frame?.Save(Path.Combine(root, "work", "desktop-minimum.png"));
window.Width = 1240; window.Height = 880;
if (screen)
{
await vm.CheckToolsCommand.ExecuteAsync(null);
Require(!vm.ToolsStatus.Contains("未就绪"), "Missing tool: " + vm.ToolsStatus);
await vm.StartScrcpyCommand.ExecuteAsync(null);
Require(vm.ScreenRunning, "scrcpy did not start: " + vm.Notice);
try
{
await UntilAsync(() => vm.Logs.Any(line => line.Contains("INFO: Texture")),
"scrcpy did not report a video texture");
}
catch (Exception error)
{
throw new InvalidOperationException(error.Message + "; state=" + vm.ScreenRunning + "; notice=" + vm.Notice + "; logs=" + string.Join(" | ", vm.Logs.TakeLast(25)));
}
Require(vm.ScreenRunning, "scrcpy process exited unexpectedly");
await vm.StopScrcpyCommand.ExecuteAsync(null);
Require(!vm.ScreenRunning, "scrcpy did not stop");
Console.WriteLine("PASS: GUI starts real scrcpy video stream and stops its process");
}
await vm.ReconnectCommand.ExecuteAsync(null);
await UntilAsync(() => vm.Ready && vm.Model != "—", "Reconnect did not recover device: " + vm.Notice);
Console.WriteLine("PASS: GUI reconnect and information recovery");
await vm.DisconnectCommand.ExecuteAsync(null);
Require(!vm.HasConnection && !vm.Ready && vm.Endpoint == null, "Disconnect did not clean up local connection");
await vm.RefreshCommand.ExecuteAsync(null);
Require(vm.Devices.Single(d => d.Id == "home-phone").Busy == false, "Device lease was not released");
Console.WriteLine("PASS: GUI disconnect releases lease; remote gateway remains online");
vm.SelectedDevice = vm.Devices.Single(d => d.Id == "home-phone");
await vm.ConnectCommand.ExecuteAsync(null);
await UntilAsync(() => vm.Ready, "Device did not recover before own-port cleanup");
await vm.ClearPortCommand.ExecuteAsync(null);
Require(!vm.HasConnection && !vm.Ready && vm.PortCleanupStatus.Contains("已释放"), "Own connection was not cleared");
await vm.RefreshCommand.ExecuteAsync(null);
Require(!vm.Devices.Single(d => d.Id == "home-phone").Busy, "Own-port cleanup did not release lease");
Console.WriteLine("PASS: cleanup of the workbench's own port releases ADB and device lease");
vm.SaveCommand.Execute(null);
Require(!File.ReadAllText(Path.Combine(folder, "settings.json")).Contains(vm.Token), "Saved settings leaked the token");
Require(!vm.Logs.Any(line => line.Contains(vm.Token)), "UI log leaked token");
Console.WriteLine("PASS: settings and UI logs do not contain client token");
}
finally
{
await vm.ShutdownAsync();
File.WriteAllLines(Path.Combine(root, "work", "desktop-smoke.log"), vm.Logs);
window.Close();
}
}
}