alielie
2026-09-10 9ec80cafc23f5ee3278cacce3c9f86f4087b435a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//            Copyright Keysight Technologies 2012-2019
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, you can obtain one at http://mozilla.org/MPL/2.0/.
using OpenTap.Addin;
using OpenTap.Addin.Annotation;
using OpenTap.Addin.Listener;
using OpenTap.Addin.Reader;
using OpenTap.Addin.Util;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml.Serialization;
 
namespace OpenTap.Plugins.BasicSteps
{
    [Display("Sequence Call", Description: "µ÷ÓÃ×ÓÐòÁÐ")]
    public class SequenceCallStep : TestStep
    {
        protected override void OnRootChanged(TestPlan old, TestPlan plan)
        {
            LoadPlan();
        }
 
 
        //public List<>
 
        ITestStepParent parent;
        // The PlanDir of 'this' should be ignored when calculating Filepath, so the MacroString context is set to the parent.
        [XmlIgnore]
        public override ITestStepParent Parent { get => parent; set { parent = value; } }
 
        string currentlyLoaded;
 
        public bool CanOpenFile => File.Exists(Filepath);
 
 
        private string filePath;
        [Display("Îļþ", Order: 0, Description: "A file path pointing to a test plan which will be loaded as read-only test steps.")]
        [Browsable(true)]
        [FilePath(FilePathAttribute.BehaviorChoice.Open, "TapPlan | *.TapPlan", 1)]
        [DeserializeOrder(1.0)]
        [Unsweepable]
        public string Filepath
        {
            get => filePath;
            set
            {
                filePath = value;
                OnPropertyChanged(nameof(Filepath));
                try
                {
                    LoadPlan();
                }
                catch
                {
 
                }
            }
        }
 
        [Obsolete]
        public bool ShareGlobals { get; set; }
 
        private string realPath;
 
        private bool currentFile;
        [Display("µ±Ç°Îļþ")]
        public bool CurrentFile
        {
            get => currentFile;
            set
            {
                currentFile = value;
                OnPropertyChanged(nameof(CurrentFile));
                try
                {
                    LoadPlan();
                }
                catch
                {
 
                }
            }
        }
 
        private string sequenceName;
 
        [Display("ÐòÁÐÃû")]
        [DynamicSelect("SequenceNames")]
        public string SequenceName
        {
            get => sequenceName;
            set
            {
                sequenceName = value;
                var seq = Sequences?.FirstOrDefault(e => e.SequenceName == value);
                if (seq != null)
                {
                    var list = new ObservableCollection<TestVariable>();
                    foreach (var tv in seq.Parameters)
                    {
                        var newone = new TestVariable
                        {
                            Name = tv.Name,
                            IsArray = tv.IsArray,
                            Type = tv.Type
                        };
                        var old = Parameters.FirstOrDefault(e => e.Name == tv.Name);
                        if (old != null)
                        {
                            newone.Value = old.Value;
                        }
                        list.Add(newone);
                    }
                    Parameters = list;// seq.Parameters;
                }
                OnPropertyChanged(nameof(SequenceName));
            }
        }
 
        [XmlIgnore]
        public List<string> SequenceNames
        {
            get => plan?.Sequences.Select(s => s.SequenceName).ToList();
        }
 
 
        [XmlIgnore]
        public ObservableCollection<TestStepList> Sequences
        {
            get => plan?.Sequences;
        }
 
        [Browsable(false)]
        public string Hash { get; set; }
 
        [AnnotationIgnore]
        public string Path => Filepath;
 
        private ObservableCollection<TestVariable> parameters = new ObservableCollection<TestVariable>();
        [Display("²ÎÊý")]
        [BindingList(nameof(Parameters), false)]
        //[TreeData]
        public ObservableCollection<TestVariable> Parameters
        {
            get => parameters;
            set
            {
                parameters = value;
                OnPropertyChanged(nameof(Parameters));
            }
        }
 
        public SequenceCallStep()
        {
 
        }
 
        private void RefreshPlan(string path)
        {
            if (CurrentFile)
            {
                plan = this.Root;
            }
            else
            {
                var newSerializer = new TapSerializer();
                var timer = Stopwatch.StartNew();
                var doc = ReadCachedXmlFile(path);
                Log.Debug(timer, $"Read Sequence Xml {path}");
 
                //plan = (TestPlan)newSerializer.Deserialize(doc, TypeData.FromType(typeof(TestPlan)), true, path);
                plan = TestPlanReader.ReadTestPlanFromDocument(doc, path);
                OnPropertyChanged(nameof(SequenceNames));
 
                using (var algo = System.Security.Cryptography.SHA1.Create())
                {
                    using (var ms = new MemoryStream())
                    {
                        doc.Save(ms, SaveOptions.DisableFormatting);
                        Hash = BitConverter.ToString(algo.ComputeHash(ms.ToArray()), 0, 8)
                            .Replace("-", string.Empty);
                    }
                }
            }
        }
 
        private string GetPlanPath()
        {
            if (CurrentFile)
            {
                return this.plan?.VisualPath;
            }
            if (PlanRun == null)
            {
                // ¼æÈÝδÔËÐеÄÇé¿ö£¬ÕâÀﻹҪÓÅ»¯
                realPath = VariableResolverFactory.DEFAULT.Resolve<string>(null, this, Filepath);
            }
            else
            {
                realPath = PlanRun.Resolve<string>(this, Filepath);
            }
 
            if (!string.IsNullOrEmpty(realPath))
            {
                var refPlanPath = realPath;
                return refPlanPath.Replace('\\', '/');
            }
            return realPath;
        }
 
        private void LoadPlan()
        {
            if (this.Root == null)
            {
                return;
            }
            if (CurrentFile)
            {
                plan = this.Root;
                OnPropertyChanged(nameof(SequenceNames));
            }
            else
            {
                string path = GetPlanPath();
                if (string.IsNullOrEmpty(path))
                {
                    return;
                }
 
                string p1 = System.IO.Path.GetFullPath(path);
                string p2 = System.IO.Path.GetFullPath(this.Root.VisualPath);
                if (string.Equals(p1, p2, StringComparison.OrdinalIgnoreCase))
                {
                    plan = this.Root;
                    OnPropertyChanged(nameof(SequenceNames));
                    return;
                }
 
                if (!File.Exists(path))
                {
                    Log.Warning("File does not exist: \"{0}\"", path);
                    return;
                }
 
                try
                {
                    RefreshPlan(path);
                }
                catch (Exception ex)
                {
                    Log.Error("Unable to read '{0}'.", realPath);
                    Log.Error(ex);
                }
            }
        }
 
        public override void PrePlanRun()
        {
            string path = GetPlanPath();
 
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentException("Path Can't be empty!");
            }
 
            if (!File.Exists(path))
            {
                throw new ArgumentException($"File does not exist: \"{path}\"");
            }
            RefreshPlan(path);
 
 
            var xml = plan.SerializeToString();
            using (var reader = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
            {
                runningPlan = TestPlanReader.ReadTestPlanFromStream(reader, plan.Path);
            }
            //runningPlan = Utils.DeserializeFromString<TestPlan>(xml);
            runningPlan.PrintTestPlanRunSummary = false;
            runningPlan.VisualPath = plan.VisualPath;
        }
 
        private RuntimeVariable Convert(TestVariable tv)
        {
            if (tv.Type == TestVariableType.String)
            {
                return new RuntimeVariable(PlanRun, tv.Name, PlanRun.Resolve<string>(this, tv.Value));
            }
 
            if (tv.Type == TestVariableType.Int)
            {
                return new RuntimeVariable(PlanRun, tv.Name, PlanRun.Resolve<int>(this, tv.Value));
            }
 
            if (tv.Type == TestVariableType.Double)
            {
                return new RuntimeVariable(PlanRun, tv.Name, PlanRun.Resolve<double>(this, tv.Value));
            }
 
            if (tv.Type == TestVariableType.Bool)
            {
                return new RuntimeVariable(PlanRun, tv.Name, PlanRun.Resolve<bool>(this, tv.Value));
            }
            return new RuntimeVariable(PlanRun, tv.Name, PlanRun.Resolve(this, tv.Value));
        }
 
        private RuntimeVariable GetMergeContainer()
        {
            ConcurrentDictionary<string, RuntimeVariable> pool = new ConcurrentDictionary<string, RuntimeVariable>();
            foreach (var tv in Parameters)
            {
                pool[tv.Name] = Convert(tv);
            }
            return new RuntimeVariable(PlanRun, ConstNames.ParametersName, pool);
        }
 
        protected override void RunDetail()
        {
            try
            {
                var loglisteners = OpenTap.Log.GetListeners();
 
                var resultSetting = ResultSettings.Current;
                var fileGlobalsContext = PlanRun.fileGlobalsContext;
 
                List<object> childrenListeners = new List<object>();
                using (Session.Create())
                {
                    var sb = ResultSettings.Current;
                    foreach (var listener in loglisteners)
                    {
                        OpenTap.Log.AddListener(listener);
                    }
 
                    // Ìí¼Ó×Ó±¨¸æ
                    foreach (var listener in resultSetting)
                    {
                        if (listener is RootListener rl)
                        {
                            var child = rl.CreateChild();
                            childrenListeners.Add(child);
                            ResultSettings.Current.Add(child);
                        }
                    }
                    TestPlanRun subRun;
                    subRun = runningPlan.Execute(SequenceName, sb, null, null,
                           new VariableContainer(GetMergeContainer(), fileGlobalsContext, this.PlanRun.StationGlobalsRuntime));
 
                    UpgradeVerdict(subRun.Verdict);
 
                    foreach (var listener in loglisteners)
                    {
                        OpenTap.Log.RemoveListener(listener);
                    }
 
                    foreach (var listener in childrenListeners)
                    {
                        ResultSettings.Current.Remove(listener);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("Sequence Call Error. {0}", ex);
                this.Verdict = Verdict.Error;
            }
        }
 
        static readonly Memorizer<string, XDocument> dict = new Memorizer<string, XDocument>(p =>
        {
            return XDocument.Load(p, LoadOptions.SetLineInfo);
        })
        {
            // Validator is to reload the file if it has been changed.
            // Assuming it is much faster to check file write time than to read and parse it. Testing has verified this.
            Validator = str =>
            {
                var file = new FileInfo(str);
                return $"{file.LastWriteTime} {file.Length}";
            },
            MaxNumberOfElements = 100
        };
 
 
 
        static XDocument ReadCachedXmlFile(string path)
        {
            var cached = dict.Invoke(path);
            // The deserializer may modify the XDocument class so it must be cloned by constructing a new XDocument (this causes a deep clone to be made).
            return new XDocument(cached);
        }
 
        [XmlIgnore]
        internal TestPlan plan;
 
        [XmlIgnore]
        public TestPlan runningPlan { get; private set; }
        string loadedPlanPath;
 
        void UpdateStep()
        {
            if (CurrentFile)
            {
                plan = this.Root;
                OnPropertyChanged(nameof(SequenceNames));
                // Sequences = plan?.Sequences;
            }
            else
            {
                object testplandir = null;
                var currentSerializer = TapSerializer.GetObjectDeserializer(this);
                if (currentSerializer != null && currentSerializer.ReadPath != null)
                    testplandir = System.IO.Path.GetDirectoryName(currentSerializer.ReadPath);
 
                var refPlanPath = realPath;
                refPlanPath = refPlanPath.Replace('\\', '/');
                if (!File.Exists(refPlanPath))
                {
                    Log.Warning("File does not exist: \"{0}\"", refPlanPath);
                    return;
                }
                try
                {
                    try
                    {
                        var newSerializer = new TapSerializer();
                        if (currentSerializer != null)
                            newSerializer.GetSerializer<ExternalParameterSerializer>().PreloadedValues.MergeInto(currentSerializer.GetSerializer<ExternalParameterSerializer>().PreloadedValues);
                        var ext = newSerializer.GetSerializer<ExternalParameterSerializer>();
 
                        loadedPlanPath = realPath;
 
                        var doc = ReadCachedXmlFile(refPlanPath);
                        TestPlan tp = (TestPlan)newSerializer.Deserialize(doc, TypeData.FromType(typeof(TestPlan)), true, refPlanPath);
                        plan = tp;
                        OnPropertyChanged(nameof(SequenceNames));
                        //Sequences = tp.Sequences;
 
                        using (var algo = System.Security.Cryptography.SHA1.Create())
                        {
                            using (var ms = new MemoryStream())
                            {
                                doc.Save(ms, SaveOptions.DisableFormatting);
                                Hash = BitConverter.ToString(algo.ComputeHash(ms.ToArray()), 0, 8)
                                    .Replace("-", string.Empty);
                            }
                        }
 
                        if (currentSerializer == null)
                        {
                            // if currentSerializer is set, it means that we are loading a previously saved test plan reference.
                            // Hence these things will be automatically set up.
                            // otherwise we need to trasfer mixins and dynamic member values.
 
                            // transfer mixins
                            var thisType = TypeData.GetTypeData(this);
                            var s = TypeData.GetTypeData(tp).GetMembers();
 
                            foreach (var member in TypeData.GetTypeData(tp).GetMembers())
                            {
                                if (member is MixinMemberData mixinMember)
                                {
                                    if (thisType.GetMember(member.Name) != null) continue;
                                    var mixin = mixinMember.Source;
                                    var mem = mixin.ToDynamicMember(thisType);
                                    if (mem == null)
                                    {
                                        if (mixin is IValidatingObject validating && validating.Error is string err && string.IsNullOrEmpty(err) == false)
                                        {
                                            Log.Error($"Unable to load mixin: {err}");
                                        }
                                        else
                                        {
                                            Log.Error($"Unable to load mixin: {TypeData.GetTypeData(mixin)?.GetDisplayAttribute()?.Name ?? mixin.ToString()}");
                                        }
                                        continue;
                                    }
                                    // transfer  the value from the test plan instance to this instance.
                                    var value = member.GetValue(tp);
                                    DynamicMember.AddDynamicMember(this, mem);
                                    mem.SetValue(this, value);
                                }
                            }
 
                            // transfer dynamic member values.
                            foreach (var member in TypeData.GetTypeData(tp).GetMembers().Where(mem => mem is DynamicMember))
                            {
                                if (member.HasAttribute<XmlIgnoreAttribute>())
                                    continue;
                                member.SetValue(this, member.GetValue(tp));
                            }
                        }
 
 
                    }
                    finally
                    {
 
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("Unable to read '{0}'.", realPath);
                    Log.Error(ex);
                }
            }
        }
 
        /// <summary> Used to determine if a step ID has changed from the time it was loaded to the time it is saved. </summary>
        Dictionary<ITestStep, Guid> StepIdMapping { get; set; }
 
        [Browsable(true)]
        //[Display("Load Test Plan", Order: 1, Description: "Load the selected test plan.")]
        [EnabledIf(nameof(CanOpenFile))]
        public void LoadTestPlan() => loadTestPlan();
 
        public void loadTestPlan()
        {
            if (!CurrentFile && string.IsNullOrWhiteSpace(realPath))
            {
                return;
            }
            UpdateStep();
        }
 
        string GetPath()
        {
            object testplandir = null;
            var currentSerializer = TapSerializer.GetObjectDeserializer(this);
            if (currentSerializer != null && currentSerializer.ReadPath != null)
                testplandir = System.IO.Path.GetDirectoryName(currentSerializer.ReadPath);
 
            var refPlanPath = realPath;
            refPlanPath = refPlanPath.Replace('\\', '/');
 
            return refPlanPath;
        }
 
        public bool anyStepsLoaded => ChildTestSteps.Any() && GetPath() is string path && File.Exists(path);
 
 
 
        
    }
}