using SopHelper.Engine.Training; using SopHelper.Engine.Sop; using System.Text.Json.Nodes; var root = Path.Combine(Path.GetTempPath(), "parttrainer-test-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(root); try { var project = new TrainingProject { FilePath = Path.Combine(root, "project.json"), Name = "中文零件", Width = 640, Height = 480, Frames = [new FrameAnnotation { Image = "frames/000000.jpg", Box = [10, 20, 100, 200], Status = "reviewed", Prompt = true }] }; project.Save(); var loaded = TrainingProject.Load(project.FilePath); if (loaded.Name != project.Name || !loaded.Frames[0].Prompt || loaded.Frames[0].Box![2] != 100) throw new Exception("Project round trip failed"); foreach (var invalid in new double[][] { [-1,0,10,10], [0,0,0,10], [0,0,641,10], [double.NaN,0,1,1] }) { try { loaded.ValidateBox(invalid); throw new Exception("Invalid box accepted"); } catch (ArgumentException) { } } loaded.Frames[0].Image = "../outside.jpg"; loaded.Save(); try { TrainingProject.Load(loaded.FilePath); throw new Exception("Traversal accepted"); } catch (InvalidDataException) { } Console.WriteLine("PASS: project persistence, Unicode, invalid box rejection, path traversal rejection"); var storageRoot=Path.Combine(root,"layout"); var store=new RecipeWorkspace(storageRoot); var legacyConfigs=Path.Combine(storageRoot,"configs","sop");Directory.CreateDirectory(legacyConfigs); var legacyTraining=Path.Combine(storageRoot,"workspace","training","配方甲"); var part=Path.Combine(legacyTraining,"parts","part1");Directory.CreateDirectory(part); var video=Path.Combine(root,"source.avi");File.WriteAllText(video,"video"); File.WriteAllText(Path.Combine(part,"frame.jpg"),"image"); var oldProject=new TrainingProject {FilePath=Path.Combine(part,"project.json"),RecipeName="配方甲",RecipeDirectory=legacyTraining,Name="零件甲",Video=video,Width=100,Height=100, Frames=[new FrameAnnotation {Image="frame.jpg",Box=[0,0,30,30],Status="reviewed"}]};oldProject.Save(); var externalPart=Path.Combine(root,"external-part");Directory.CreateDirectory(externalPart); File.WriteAllText(Path.Combine(externalPart,"frame.jpg"),"image"); var externalProject=new TrainingProject {FilePath=Path.Combine(externalPart,"project.json"),Name="零件乙",Video=video,Width=100,Height=100, Frames=[new FrameAnnotation {Image="frame.jpg",Box=[0,0,30,30],Status="reviewed"}]};externalProject.Save(); var externalRun=Path.Combine(root,"external-run");Directory.CreateDirectory(externalRun); var weights=Path.Combine(externalRun,"配方甲.pt");File.WriteAllText(weights,"weights"); var onnx=Path.ChangeExtension(weights,".onnx");File.WriteAllText(onnx,"model"); File.WriteAllText(Path.Combine(legacyTraining,"latest-model.json"),System.Text.Json.JsonSerializer.Serialize(new {weights,onnx,runDirectory=externalRun,recipeName="配方甲",classes=new[]{"零件甲"},imageSize=640})); File.WriteAllText(Path.Combine(legacyTraining,"recipe-training.json"),new JsonObject { ["projects"]=new JsonArray(oldProject.FilePath,externalProject.FilePath),["labels"]=new JsonObject{[oldProject.FilePath]="零件甲",[externalProject.FilePath]="零件乙"},["classes"]=new JsonArray("零件甲","零件乙")}.ToJsonString()); var config=new SopConfig();config.Sop.Name="配方甲";config.Sop.Model=new ModelDef{Path=onnx}; SopConfigLoader.Save(config,Path.Combine(legacyConfigs,"配方甲.yaml")); store.Initialize(legacyConfigs); var recipe=store.DirectoryFor("配方甲"); var migratedProject=TrainingProject.Load(Path.Combine(recipe,"parts","part1","project.json")); if(migratedProject.RecipeDirectory!=recipe||!RecipeWorkspace.IsWithin(migratedProject.Video,recipe)||!File.Exists(migratedProject.Video))throw new Exception("Project/video migration failed"); var latest=JsonNode.Parse(File.ReadAllText(Path.Combine(recipe,"latest-model.json")))!; if(!RecipeWorkspace.IsWithin(latest["weights"]!.GetValue(),recipe)||!File.Exists(latest["onnx"]!.GetValue()))throw new Exception("External training output was not migrated"); var registry=JsonNode.Parse(File.ReadAllText(Path.Combine(recipe,"recipe-training.json")))!; if(registry["projects"]![0]!.GetValue()!=migratedProject.FilePath||registry["labels"]![migratedProject.FilePath]!.GetValue()!="零件甲")throw new Exception("Registry references were not rebased"); var relocatedExternal=registry["projects"]![1]!.GetValue(); if(!RecipeWorkspace.IsWithin(relocatedExternal,recipe)||TrainingProject.Load(relocatedExternal).RecipeDirectory!=recipe)throw new Exception("External annotation projects were not migrated"); var managedModel=SopConfigLoader.Load(store.ConfigPath("配方甲")).Sop.Model!.Path; if(Path.IsPathRooted(managedModel)||!File.Exists(Path.Combine(recipe,managedModel)))throw new Exception("Configured model was not localized"); File.WriteAllText(Path.Combine(legacyConfigs,"配方甲.yaml"),"obsolete");store.Initialize(legacyConfigs); if(SopConfigLoader.Load(store.ConfigPath("配方甲")).Sop.Name!="配方甲")throw new Exception("Migration overwrote managed settings"); if(!File.Exists(oldProject.FilePath)||!File.Exists(video))throw new Exception("Migration modified original data"); foreach(var bad in new[]{"..","../escape","a/b","a\\b","配方:甲","配方*甲","配方?","配方\"","配方<","配方>","配方|","末尾 ","末尾.","CON","nul.txt","COM1","LPT9","COM¹","换\n行",new string('长',100)}) try{store.DirectoryFor(bad);throw new Exception("Unsafe recipe name accepted");}catch(ArgumentException){} foreach(var good in new[]{"装配线A","配方.v1","配方 甲","COM10","普通配方(测试)"}) if(RecipeWorkspace.GetNameError(good) is not null)throw new Exception("Valid recipe name rejected: "+good); var renamedDisplay=SopConfigLoader.Load(store.ConfigPath("配方甲"));renamedDisplay.Sop.Name="另一个显示名称"; SopConfigLoader.Save(renamedDisplay,store.ConfigPath("配方甲"));store.Initialize(legacyConfigs); if(SopConfigLoader.Load(store.ConfigPath("配方甲")).Sop.Name!="配方甲")throw new Exception("Existing recipe name differs from filename"); Console.WriteLine("PASS: Unified recipe migration, model/video copies, registry rebasing, independent config and safe names"); if (args.Length > 0) { var script = Path.Combine(root, "worker.py"); File.WriteAllText(script, "import json,sys,time\nr=json.load(open(sys.argv[1]))\nprint('worker-ready',flush=True)\ntime.sleep(r.get('sleep',0))\nsys.exit(r.get('exit',0))\n"); var client = new WorkerClient(); var lines = new List(); await client.RunAsync(args[0], script, new { sleep = 0 }, line => { lock(lines) lines.Add(line); }, CancellationToken.None); if (!lines.Contains("worker-ready")) throw new Exception("Worker output was lost"); try { await client.RunAsync(args[0], script, new { exit = 2 }, _ => { }, CancellationToken.None); throw new Exception("Worker exit failure was ignored"); } catch (InvalidOperationException) { } using var cancel = new CancellationTokenSource(TimeSpan.FromSeconds(1)); try { await client.RunAsync(args[0], script, new { sleep = 60 }, _ => { }, cancel.Token); throw new Exception("Worker cancellation was ignored"); } catch (OperationCanceledException) { } Console.WriteLine("PASS: real Python process output, exit failure, cancellation"); } } finally { Directory.Delete(root, true); }