chr
2026-04-08 53e656200368a983e563550e2cc1acbc6d86b729
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
//            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 System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Serialization;
 
namespace OpenTap
{
    partial class TestPlan
    {
        bool runPrePlanRunMethods(IList<ITestStep> steps, TestPlanRun planRun)
        {
            Stopwatch preTimer = Stopwatch.StartNew(); // try to avoid calling Stopwatch.StartNew too often.
            TimeSpan elaps = preTimer.Elapsed;
            foreach (ITestStep step in steps)
            {
                if (step.Enabled == false)
                    continue;
                bool runPre = true;
                if (step is TestStep s)
                {
                    runPre = s.PrePostPlanRunUsed;
                }
                planRun.StepsWithPrePlanRun.Add(step);
                try
                {
                    if (runPre)
                    {
                        planRun.AddTestStepStateUpdate(step.Id, null, StepState.PrePlanRun);
                        try
                        {
                            step.PlanRun = planRun;
                            planRun.ResourceManager.BeginStep(planRun, step, TestPlanExecutionStage.PrePlanRun, TapThread.Current.AbortToken);
                            try
                            {
                                step.PrePlanRun();
                            }
                            finally
                            {
                                planRun.ResourceManager.EndStep(step, TestPlanExecutionStage.PrePlanRun);
                                step.PlanRun = null;
                            }
                        }
                        finally
                        {
                            planRun.AddTestStepStateUpdate(step.Id, null, StepState.Idle);
                        }
                    }
 
                    if (!runPrePlanRunMethods(step.ChildTestSteps, planRun))
                    {
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(String.Format("PrePlanRun of '{0}' failed with message '{1}'.",
                        step.Name, ex.Message));
                    Log.Debug(ex);
                    Log.Error("Aborting TestPlan.");
                    return false;
                }
                finally
                {
                    if (runPre)
                    {
                        var newelaps = preTimer.Elapsed;
 
                        Log.Debug(newelaps - elaps, "{0} PrePlanRun completed.", step.GetStepPath());
                        elaps = newelaps;
 
                    }
                }
            }
            return true;
        }
        #region Nested Types
 
        enum failState
        {
            Ok,
            StartFail,
            ExecFail
        }
 
        #endregion
 
        internal static void PrintWaitingMessage(IEnumerable<IResource> resources)
        {
            // Save disconnected ressources to avoid race conditions.
            var waitingRessources = resources.Where(r => !r.IsConnected).ToArray();
            if (waitingRessources.Length == 0)
            {
                return;
            }
 
            Log.Info("Waiting for resources to open:");
            foreach (var resource in waitingRessources)
            {
                Log.Info(" - {0}", resource);
            }
        }
 
        failState execTestPlan(TestPlanRun execStage, IList<ITestStep> steps)
        {
            WaitHandle.WaitAny(new[] { execStage.PromptWaitHandle, TapThread.Current.AbortToken.WaitHandle });
            bool resultListenerError = false;
            execStage.ScheduleInResultProcessingThread<IResultListener>(resultListener =>
            {
                try
                {
                    using (TimeoutOperation.Create(() => PrintWaitingMessage(new List<IResource>() { resultListener })))
                        execStage.ResourceManager.WaitUntilResourcesOpened(TapThread.Current.AbortToken, resultListener);
                    try
                    {
                        // some resources might set metadata in the Open methods.
                        // this information needs to be propagated to result listeners as well.
                        // this returns quickly if its a lazy resource manager.
                        using (TimeoutOperation.Create(
                            () => PrintWaitingMessage(new List<IResource>() { resultListener })))
                            execStage.ResourceManager.WaitUntilAllResourcesOpened(TapThread.Current.AbortToken);
                    }
                    catch
                    {
                        // this error will also be handled somewhere else.
                    }
 
                    execStage.WaitForSerialization();
                    foreach (var res in execStage.PromptedResources)
                        execStage.Parameters.AddRange(ResultParameters.GetMetadataFromObject(res));
                    resultListener.OnTestPlanRunStart(execStage);
                }
                catch (OperationCanceledException) when (execStage.MainThread.AbortToken.IsCancellationRequested)
                {
                    // test plan thread was aborted, this is OK.
                }
                catch (Exception ex)
                {
                    Log.Error("Error in OnTestPlanRunStart for '{0}': '{1}'", resultListener, ex.Message);
                    Log.Debug(ex);
                    resultListenerError = true;
                }
 
            }, true);
 
            if (resultListenerError)
                return failState.StartFail;
 
            var sw = Stopwatch.StartNew();
            try
            {
                execStage.StepsWithPrePlanRun.Clear();
 
                // Invoke test plan pre run event mixins.
                TestPlanPreRunEvent.Invoke(this);
 
                if (!runPrePlanRunMethods(steps, execStage))
                {
                    return failState.StartFail;
                }
            }
            catch (Exception e)
            {
                Log.Error(e.GetInnerMostExceptionMessage());
                Log.Debug(e);
                return failState.StartFail;
            }
            finally
            {
                {
                    Log.Debug(sw, "PrePlanRun Methods completed");
                }
            }
 
            Stopwatch planRunOnlyTimer = Stopwatch.StartNew();
            var runs = new List<TestStepRun>();
 
            bool didBreak = false;
            void addBreakResult(TestStepRun run)
            {
                if (didBreak) return;
                didBreak = true;
                execStage.Parameters.Add(new ResultParameter(TestPlanRun.SpecialParameterNames.BreakIssuedFrom, run.Id.ToString()));
            }
 
            TestStepRun getBreakingRun(TestStepRun first)
            {
                while ((first.Exception as TestStepBreakException)?.Run is { } inner)
                    first = inner;
                return first;
            }
 
            try
            {
                for (int i = 0; i < steps.Count; i++)
                {
                    var step = steps[i];
                    if (step.Enabled == false) continue;
                    var run = step.DoRun(execStage, execStage);
                    if (!run.Skipped)
                        runs.Add(run);
                    if (run.BreakConditionsSatisfied())
                    {
                        var breakingRun = getBreakingRun(run);
                        addBreakResult(breakingRun);
                        run.LogBreakCondition();
                        break;
                    }
 
                    // note: The following is copied inside TestStep.cs
                    if (run.SuggestedNextStep is Guid id)
                    {
                        int nextindex = steps.IndexWhen(x => x.Id == id);
                        if (nextindex >= 0)
                            i = nextindex - 1;
                        // if skip to next step, dont add it to the wait queue.
                    }
                }
            }
            catch (TestStepBreakException breakEx)
            {
                var breakingRun = getBreakingRun(breakEx.Run);
                addBreakResult(breakingRun);
                Log.Info("{0}", breakEx.Message);
            }
            finally
            {
                // Now wait for them to actually complete. They might defer internally.
                foreach (var run in runs)
                {
                    run.WaitForCompletion();
                    execStage.UpgradeVerdict(run.Verdict);
                }
            }
 
            Log.Debug(planRunOnlyTimer, "Test step runs finished.");
 
            return failState.Ok;
        }
 
        void finishTestPlanRun(TestPlanRun run, Stopwatch testPlanTimer, failState runWentOk, TraceListener Logger, HybridStream logStream)
        {
            try
            {
                if (run != null)
                {
                    if (runWentOk == failState.StartFail)
                    {
                        if (PrintTestPlanRunSummary)
                            summaryListener.OnTestPlanRunStart(run); // Call this to ensure that the correct planrun is being summarized
 
                        if (run.Verdict < Verdict.Aborted)
                            run.Verdict = Verdict.Error;
                    }
 
                    for (int i = run.StepsWithPrePlanRun.Count - 1; i >= 0; i--)
                    {
                        Stopwatch postTimer = Stopwatch.StartNew();
                        String stepPath = string.Empty;
                        try
                        {
                            ITestStep step = run.StepsWithPrePlanRun[i];
 
                            if ((step as TestStep)?.PrePostPlanRunUsed ?? true)
                            {
                                stepPath = step.GetStepPath();
                                run.AddTestStepStateUpdate(step.Id, null, StepState.PostPlanRun);
                                try
                                {
                                    run.ResourceManager.BeginStep(run, step, TestPlanExecutionStage.PostPlanRun, TapThread.Current.AbortToken);
                                    step.PlanRun = run;
                                    try
                                    {
                                        step.PostPlanRun();
                                    }
                                    finally
                                    {
                                        run.ResourceManager.EndStep(step, TestPlanExecutionStage.PostPlanRun);
                                        step.PlanRun = null;
                                    }
                                }
                                finally
                                {
                                    run.AddTestStepStateUpdate(step.Id, null, StepState.Idle);
                                }
                                Log.Debug(postTimer, "{0} PostPlanRun completed.", stepPath);
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Warning("Error during post plan run of {0}.", stepPath);
                            Log.Debug(ex);
                        }
                    }
                    run.Duration = testPlanTimer.Elapsed;
                }
 
                if (run != null)
                {
 
                    try
                    {
                        // The open resource threads might throw exceptions. If they do we must
                        // Wait() for them to catch the exception.
                        // If the run was aborted after the open resource threads were started but 
                        // before we wait for them (e.g. by an error in PrePlanRun), then we do it
                        // here.
                        run.ResourceManager.WaitUntilAllResourcesOpened(TapThread.Current.AbortToken);
                    }
                    catch (OperationCanceledException)
                    {
                        // Ignore this because this typically means that the wait was cancelled before.
                        // Just to be sure also upgrade verdict to aborted.
                        run.UpgradeVerdict(Verdict.Aborted);
                    }
                    catch (Exception e)
                    {
                        Log.Error("Failed to open resource ({0})", e.GetInnerMostExceptionMessage());
                        Log.Debug(e);
                    }
 
                    if (PrintTestPlanRunSummary)
                    {
                        // wait for the summaryListener so the summary appears in the log file.
                        run.WaitForResultListener(summaryListener);
                        summaryListener.PrintSummary();
                    }
 
                    OpenTap.Log.Flush();
                    Logger.Flush();
                    logStream.Flush();
 
                    run.AddTestPlanCompleted(logStream, runWentOk != failState.StartFail);
 
                    if (PrintTestPlanRunSummary)
                        summaryListener.PrintArtifactsSummary();
                    run.ResourceManager.EndStep(this, TestPlanExecutionStage.Execute);
 
                    if (!run.IsCompositeRun)
                        run.ResourceManager.EndStep(this, TestPlanExecutionStage.Open);
                }
            }
            finally
            {
                if (monitors != null)
                    foreach (var item in monitors)
                        item.ExitTestPlanRun(run);
            }
        }
        /// <summary> When true, prints the test plan run summary at the end of a run. </summary>
        [XmlIgnore]
        [AnnotationIgnore]
        public bool PrintTestPlanRunSummary { get; set; }
 
        /// <summary>
        /// FileGlobals±äÁ¿
        /// </summary>
        public ObservableCollection<TestVariable> ParameterVariables { get; set; } = new ObservableCollection<TestVariable>();
        public ObservableCollection<TestVariable> Variables { get; set; } = new ObservableCollection<TestVariable>();
 
        /// <summary>
        /// Calls the PromptForDutMetadata delegate for all referenced DUTs.
        /// </summary>
        internal void StartResourcePromptAsync(TestPlanRun planRun, IEnumerable<IResource> _resources)
        {
            var resources = _resources.Where(x => x != null).ToArray();
 
            var componentSettingsWithMetaData = new List<ITypeData>();
            var componentSettings = TypeData.GetDerivedTypes<ComponentSettings>()
                .Where(type => type.CanCreateInstance);
            bool anyMetaData = false;
            planRun.PromptWaitHandle.Reset();
 
            try
            {
                foreach (var setting in componentSettings)
                {
                    foreach (var member in setting.GetMembers())
                    {
                        var attr = member.GetAttribute<MetaDataAttribute>();
                        if (attr != null && attr.PromptUser)
                        {
                            anyMetaData = true;
                            componentSettingsWithMetaData.Add(setting);
                            break; // avoid adding this multiple times.
                        }
                    }
                }
 
                foreach (var resource in resources)
                {
                    if (anyMetaData) break;
                    var type = TypeData.GetTypeData(resource);
                    foreach (var prop in type.GetMembers())
                    {
                        var attr = prop.GetAttribute<MetaDataAttribute>();
                        if (attr != null && attr.PromptUser)
                        {
                            anyMetaData = true;
                            break;
                        }
                    }
                }
            }
            catch
            {
                // this is just a defensive catch to make sure that the WaitHandle is not left unset (and we risk waiting for it indefinitely)
                planRun.PromptWaitHandle.Set();
                throw;
            }
 
            if (anyMetaData && EngineSettings.Current.PromptForMetaData)
            {
                TapThread.Start(() =>
                    {
                        try
                        {
                            List<object> objects = new List<object>();
                            objects.AddRange(componentSettingsWithMetaData.Select(ComponentSettings.GetCurrent));
                            objects.AddRange(resources);
                            objects.RemoveIf<object>(x => x == null); //ComponentSettings.GetCurrent can return null for abstract types.
 
                            planRun.PromptedResources = resources;
                            var obj = new MetadataPromptObject { Resources = objects };
                            UserInput.Request(obj, false);
                            if (obj.Response == MetadataPromptObject.PromptResponse.Abort)
                                planRun.MainThread.Abort();
                        }
                        catch (Exception e)
                        {
                            Log.Debug(e);
                            planRun.MainThread.Abort("Error occured while executing platform requests. Metadata prompt can be disabled from the Engine settings menu.");
                        }
                        finally
                        {
                            planRun.PromptWaitHandle.Set();
                        }
                    }, name: "Request Metadata");
            }
            else
            {
                planRun.PromptWaitHandle.Set();
            }
        }
 
        /// <summary>
        /// Blocking Execute TestPlan. Uses ResultListeners from ResultSettings.Current.
        /// </summary>
        /// <returns>Result of test plan run as a TestPlanRun object.</returns>
        public TestPlanRun Execute()
        {
            return Execute(ResultSettings.Current, null);
        }
 
        /// <summary>Executes the test plan asynchronously </summary>
        /// <returns>A task returning the test plan run.</returns>
        public Task<TestPlanRun> ExecuteAsync()
        {
            return ExecuteAsync(ResultSettings.Current, null, null, TapThread.Current.AbortToken);
        }
 
        /// <summary>
        /// Executes the test plan asynchronously.
        /// </summary>
        /// <param name="abortToken">This abort token can be used to abort the operation.</param>
        /// <returns>A task returning the test plan run.</returns>
        public Task<TestPlanRun> ExecuteAsync(CancellationToken abortToken)
        {
            return ExecuteAsync(ResultSettings.Current, null, null, abortToken);
        }
 
        readonly TestPlanRunSummaryListener summaryListener = new TestPlanRunSummaryListener();
        /// <summary>
        /// Execute the TestPlan as specified.
        /// </summary>
        /// <param name="resultListeners">ResultListeners for result outputs.</param>
        /// <param name="metaDataParameters">Optional metadata parameters.</param>
        /// <param name="stepsOverride">Sub-section of test plan to be executed. Note this might include child steps of disabled parent steps.</param>
        /// <param name="cancellationToken">Cancellation token to abort the testplan</param>
        /// <returns>TestPlanRun results, no StepResults.</returns>
        public Task<TestPlanRun> ExecuteAsync(IEnumerable<IResultListener> resultListeners, IEnumerable<ResultParameter> metaDataParameters, HashSet<ITestStep> stepsOverride, CancellationToken cancellationToken)
        {
            var tcs = new TaskCompletionSource<TestPlanRun>();
            TapThread.Start(() =>
            {
                try
                {
                    cancellationToken.Register(TapThread.Current.Abort);
                    var testPlanRun = Execute(resultListeners, metaDataParameters, stepsOverride);
                    tcs.SetResult(testPlanRun);
                }
                catch (Exception e)
                {
                    tcs.SetException(e);
                }
            }, "Plan Thread");
            return tcs.Task;
        }
 
        internal static ThreadHierarchyLocal<TestPlanRun> executingPlanRun = new ThreadHierarchyLocal<TestPlanRun>();
 
        /// <summary>
        /// Execute the TestPlan as specified. Blocking.
        /// </summary>
        /// <param name="resultListeners">ResultListeners for result outputs.</param>
        /// <param name="metaDataParameters">Optional metadata parameters.</param>
        /// <param name="stepsOverride">Sub-section of test plan to be executed. Note this might include child steps of disabled parent steps.</param>
        /// <param name="variableContainer"></param>
        /// <returns>TestPlanRun results, no StepResults.</returns>
        public TestPlanRun Execute(IEnumerable<IResultListener> resultListeners,
            IEnumerable<ResultParameter> metaDataParameters = null,
            HashSet<ITestStep> stepsOverride = null,
            VariableContainer variableContainer = null)
        {
            return executeInContext(resultListeners, metaDataParameters, stepsOverride,
                variableContainer, MAIN_SEQ_NAME);
        }
 
        public TestPlanRun Execute(string sequenceName, IEnumerable<IResultListener> resultListeners,
            IEnumerable<ResultParameter> metaDataParameters = null,
            HashSet<ITestStep> stepsOverride = null,
            VariableContainer variableContainer = null)
        {
            return executeInContext(resultListeners, metaDataParameters, stepsOverride,
                variableContainer, sequenceName);
        }
 
        TestPlanRun executeInContext(IEnumerable<IResultListener> resultListeners,
            IEnumerable<ResultParameter> metaDataParameters, HashSet<ITestStep> stepsOverride,
            VariableContainer variableContainer, 
            string sequenceName)
        {
            using (TapThread.UsingThreadContext())
            {
                return ExecuteByName(resultListeners, metaDataParameters, stepsOverride, sequenceName, variableContainer);
            }
        }
 
        /// <summary>
        /// °´Ãû³ÆÖ´ÐвâÊԼƻ®
        /// </summary>
        /// <param name="resultListeners"></param>
        /// <param name="metaDataParameters"></param>
        /// <param name="stepsOverride"></param>
        /// <param name="variableContainer"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentException"></exception>
        private TestPlanRun ExecuteByName(IEnumerable<IResultListener> resultListeners, 
            IEnumerable<ResultParameter> metaDataParameters, 
            HashSet<ITestStep> stepsOverride, string sequenceName, VariableContainer variableContainer = null)
        {
            if (resultListeners == null)
                throw new ArgumentNullException(nameof(resultListeners));
 
            ResultParameters.ParameterCache.LoadCache();
 
            if (PrintTestPlanRunSummary && !resultListeners.Contains(summaryListener))
                resultListeners = resultListeners.Concat(new IResultListener[] { summaryListener });
            resultListeners = resultListeners.Where(r => r is IEnabledResource ? ((IEnabledResource)r).IsEnabled : true);
            IList<ITestStep> steps;
            TestStepList list;
 
            if (stepsOverride == null)
            {
                list = GetStepsByName(sequenceName);
                steps = list;
            }
            else
            {
                var tempStep = GetStepsByName(sequenceName);
                if (tempStep == null)
                {
                    throw new ArgumentException("No Name");
                }
                list = tempStep;
 
                // Remove steps that are already included via their parent steps.
                foreach (var step in stepsOverride)
                {
                    if (step == null)
                        throw new ArgumentException("stepsOverride may not contain null", nameof(stepsOverride));
 
                    var p = step.GetParent<ITestStep>();
                    while (p != null)
                    {
                        if (stepsOverride.Contains(p))
                            throw new ArgumentException("stepsOverride may not contain steps and their parents.", nameof(stepsOverride));
                        p = p.GetParent<ITestStep>();
                    }
                }
                steps = Utils.FlattenHeirarchy(tempStep, step => step.ChildTestSteps).Where(stepsOverride.Contains).ToList();
            }
 
            long initTimeStamp = Stopwatch.GetTimestamp();
            var initTime = DateTime.Now;
 
            Log.Info("-----------------------------------------------------------------");
 
 
            var logStream = new HybridStream();
 
            var planRunLog = new FileTraceListener(logStream) { IsRelative = true };
            OpenTap.Log.AddListener(planRunLog);
 
            var allSteps = Utils.FlattenHeirarchy(steps, step => step.ChildTestSteps);
            var allEnabledSteps = Utils.FlattenHeirarchy(steps.Where(x => x.Enabled), step => step.GetEnabledChildSteps());
 
            var enabledSinks = new HashSet<IResultSink>();
            TestStepExtensions.GetObjectSettings<IResultSink, ITestStep, IResultSink>(allEnabledSteps, true, null, enabledSinks);
            if (enabledSinks.Count > 0)
            {
                var sinkListener = new ResultSinkListener(enabledSinks);
                resultListeners = resultListeners.Append(sinkListener);
            }
 
            Log.Info("Starting TestPlan '{0}' on {1}, {2} of {3} TestSteps enabled.", Name, initTime, allEnabledSteps.Count, allSteps.Count);
 
            // Reset step verdict.
            foreach (var step in allSteps)
            {
                if (step.Verdict != Verdict.NotSet)
                {
                    step.Verdict = Verdict.NotSet;
                    step.OnPropertyChanged("Verdict");
                }
            }
 
            if (currentExecutionState != null)
            {
                currentExecutionState.ResultListenersSealed = false;
                // load result listeners that are _not_ used in the previous runs.
                // otherwise they wont get opened later.
                foreach (var rl in resultListeners)
                {
                    currentExecutionState.AddResultListener(rl);
                }
            }
 
            TestPlanRun execStage;
            bool continuedExecutionState = false;
            if (currentExecutionState != null)
            {
                execStage = new TestPlanRun(currentExecutionState, initTime, initTimeStamp, variableContainer);
                continuedExecutionState = true;
            }
            else
            {
                execStage = new TestPlanRun(this, resultListeners.ToList(), initTime, initTimeStamp, variableContainer);
                if (stepsOverride != null)
                {
                    var overrides = stepsOverride.Select(o => o.Id.ToString()).ToArray();
                    // The order of the guids does not really matter. 
                    // Only that the order is the same across runs
                    Array.Sort(overrides);
                    execStage.Parameters.Add(new ResultParameter(TestPlanRun.SpecialParameterNames.StepOverrideList, string.Join(",", overrides)));
                }
 
                execStage.Start();
 
                execStage.Parameters.AddRange(PluginManager.GetPluginVersions(allEnabledSteps));
                execStage.ResourceManager.ResourceOpened += r =>
                {
                    execStage.Parameters.AddRange(PluginManager.GetPluginVersions(new List<object> { r }));
                };
            }
            execStage.LocalsRuntime = VariableContext.FromTestVariables(list.Variables);
 
 
            if (metaDataParameters != null)
                execStage.Parameters.AddRange(metaDataParameters);
 
            var prevExecutingPlanRun = executingPlanRun.LocalValue;
            executingPlanRun.LocalValue = execStage;
            CurrentRun = execStage;
 
            failState runWentOk = failState.StartFail;
            // Ã»É¶ÓúÃÏñ
            // ³õʼ»¯ÔËÐÐʱ±äÁ¿³Ø
            //FileGlobalContext.Add(execStage, execStage.runtimeVariablePool);
 
            // ReSharper disable once InconsistentNaming
            var preRun_Run_PostRunTimer = Stopwatch.StartNew();
            try
            {
                execStage.FailedToStart = true; // Set it here in case OpenInternal throws an exception. Could happen if a step is missing an instrument
 
                OpenInternal(execStage, continuedExecutionState, allEnabledSteps, Array.Empty<IResource>());
 
                execStage.WaitForSerialization();
                execStage.ResourceManager.BeginStep(execStage, this, TestPlanExecutionStage.Execute, TapThread.Current.AbortToken);
 
                if (continuedExecutionState)
                {  // Since resources are not opened, getting metadata cannot be done in the wait for resources continuation
                   // like shown in TestPlanRun. Instead we do it here.
                    foreach (var res in execStage.ResourceManager.Resources)
                        execStage.Parameters.AddRange(ResultParameters.GetMetadataFromObject(res));
                }
 
                runWentOk = failState.ExecFail; //important if test plan is aborted and runWentOk is never returned.
                runWentOk = execTestPlan(execStage, steps);
            }
            catch (Exception e)
            {
                if (e is OperationCanceledException && execStage.MainThread.AbortToken.IsCancellationRequested)
                {
 
                    Log.Warning(String.Format("TestPlan aborted. ({0})", e.Message));
                    execStage.UpgradeVerdict(Verdict.Aborted);
                }
                else if (e is ThreadAbortException)
                {
                    // It seems this actually never happens.
                    Log.Warning("TestPlan aborted.");
                    execStage.UpgradeVerdict(Verdict.Aborted);
                    //Avoid entering the finally clause.
                    Thread.Sleep(500);
                }
                else if (e is System.ComponentModel.LicenseException)
                {
                    execStage.Exception = e;
                    Log.Error(e.Message);
                    execStage.UpgradeVerdict(Verdict.Error);
                }
                else
                {
                    execStage.Exception = e;
                    Log.Warning("TestPlan aborted.");
                    Log.Error(e.Message);
                    Log.Debug(e);
                    execStage.UpgradeVerdict(Verdict.Error);
                }
            }
            finally
            {
                execStage.FailedToStart = (runWentOk == failState.StartFail);
 
                try
                {
                    finishTestPlanRun(execStage, preRun_Run_PostRunTimer, runWentOk, planRunLog, logStream);
                }
                catch (Exception ex)
                {
                    Log.Error("Error while finishing TestPlan.");
                    Log.Debug(ex);
                }
 
                OpenTap.Log.RemoveListener(planRunLog);
                planRunLog.Dispose();
 
                logStream.Dispose();
 
                // Clean all test steps StepRun, otherwise the next test plan execution will be stuck at TestStep.DoRun at steps that does not have a cleared StepRun.
                foreach (var step in allSteps)
                    step.StepRun = null;
 
                executingPlanRun.LocalValue = prevExecutingPlanRun;
                CurrentRun = prevExecutingPlanRun;
            }
            return execStage;
        }
 
        private TestPlanRun DoExecute(IEnumerable<IResultListener> resultListeners, IEnumerable<ResultParameter> metaDataParameters, HashSet<ITestStep> stepsOverride, VariableContainer variableContainer = null)
        {
            return ExecuteByName(resultListeners, metaDataParameters, stepsOverride, MAIN_SEQ_NAME, variableContainer);
        }
 
        /// <summary>
        /// Execute the TestPlan as specified. Blocking.
        /// </summary>
        /// <param name="resultListeners">ResultListeners for result outputs.</param>
        /// <param name="metaDataParameters">Metadata parameters.</param>
        /// <returns>TestPlanRun results, no StepResults.</returns>
        public TestPlanRun Execute(IEnumerable<IResultListener> resultListeners, IEnumerable<ResultParameter> metaDataParameters)
        {
            return Execute(resultListeners, metaDataParameters, null);
        }
 
        TestPlanRun currentExecutionState = null;
 
        /// <summary> true if the plan is in its open state. </summary>
        [AnnotationIgnore]
        public bool IsOpen { get { return currentExecutionState != null; } }
 
        /// <summary>
        /// Opens all resources referenced in this TestPlan (Instruments/DUTs/ResultListeners). 
        /// This can be called before <see cref="TestPlan.Execute()"/> to manually control the opening/closing of the resources.
        /// </summary>
        public void Open()
        {
            Open(ResultSettings.Current);
        }
 
        /// <summary>
        /// Opens all resources referenced in this TestPlan (Instruments/DUTs/ResultListeners). 
        /// This can be called before <see cref="TestPlan.Execute()"/> to manually control the opening/closing of the resources.
        /// </summary>
        /// <param name="listeners">Result listeners used in connection with the test plan.</param>
        public void Open(IEnumerable<IResultListener> listeners)
        {
            Open(listeners, Array.Empty<IResource>());
        }
 
        /// <summary>
        /// Opens all resources referenced in this TestPlan (Instruments/DUTs/ResultListeners). 
        /// This can be called before <see cref="TestPlan.Execute()"/> to manually control the opening/closing of the resources.
        /// It can also be called multiple times to add more resources.
        /// </summary>
        /// <param name="additionalResources">Additional resources added as 'static' resources.</param>
        public void Open(IEnumerable<IResource> additionalResources)
        {
            Open(ResultSettings.Current, additionalResources);
        }
 
        /// <summary>
        /// Opens all resources referenced in this TestPlan (Instruments/DUTs/ResultListeners). 
        /// This can be called before <see cref="TestPlan.Execute()"/> to manually control the opening/closing of the resources.
        /// It can also be called multiple times to add more resources.
        /// </summary>
        /// <param name="listeners">Result listeners used in connection with the test plan.</param>
        /// <param name="additionalResources">Additional resources added as 'static' resources.</param>
        public void Open(IEnumerable<IResultListener> listeners, IEnumerable<IResource> additionalResources)
        {
            if (listeners == null)
                throw new ArgumentNullException(nameof(listeners));
            if (PrintTestPlanRunSummary)
                listeners = listeners.Concat(new IResultListener[] { summaryListener });
 
            if (IsRunning)
                throw new InvalidOperationException("This TestPlan is already running.");
 
            try
            {
                var allSteps = Utils.FlattenHeirarchy(Steps.Where(x => x.Enabled), step => step.GetEnabledChildSteps()).ToList();
 
                Stopwatch timer = Stopwatch.StartNew();
                if (currentExecutionState == null)
                {
                    currentExecutionState = new TestPlanRun(this, listeners.ToList(), DateTime.Now, Stopwatch.GetTimestamp(), null, true);
                    currentExecutionState.Start();
                }
                OpenInternal(currentExecutionState, false, allSteps, additionalResources);
 
                try
                {
                    currentExecutionState.ResourceManager.WaitUntilAllResourcesOpened(TapThread.Current.AbortToken);
                }
                catch (Exception ex)
                {
                    Log.Warning("Caught error while opening resources! See error message for details.");
                    ex.RethrowInner();
                }
 
                Log.Debug(timer, "TestPlan opened.");
            }
            catch
            {
                // If there is an error, reset the state to allow calling open again later 
                // when the user has fixed the error.
                if (currentExecutionState != null)
                    currentExecutionState.ResourceManager.EndStep(this, TestPlanExecutionStage.Open);
 
                if (monitors != null)
                    foreach (var item in monitors)
                        item.ExitTestPlanRun(currentExecutionState);
 
                currentExecutionState = null;
                throw;
            }
        }
 
        private void OpenInternal(TestPlanRun run, bool isOpen, List<ITestStep> steps, IEnumerable<IResource> additionalResources)
        {
            monitors = TestPlanRunMonitors.GetCurrent();
 
            // Enter monitors
            foreach (var item in monitors)
                item.EnterTestPlanRun(run);
 
            run.ResourceManager.EnabledSteps = steps;
            run.ResourceManager.StaticResources = run.ResultListeners.Concat(additionalResources).ToArray();
            run.ResultListenersSealed = true;
            if (!isOpen)
                run.ResourceManager.BeginStep(run, this, TestPlanExecutionStage.Open, TapThread.Current.AbortToken);
        }
 
        /// <summary>
        /// Closes all resources referenced in this TestPlan (Instruments/DUTs/ResultListeners). 
        /// This should be called if <see cref="TestPlan.Open()"/> was called earlier to manually close the resources again.
        /// </summary>
        public void Close()
        {
            if (IsRunning)
                throw new InvalidOperationException("Cannot close TestPlan while it is running.");
            if (currentExecutionState == null)
                throw new InvalidOperationException("Call open first.");
 
            Stopwatch timer = Stopwatch.StartNew();
            currentExecutionState.ResourceManager.EndStep(this, TestPlanExecutionStage.Open);
 
            // If we locked the setup earlier, unlock it now that all recourses has been closed:
            foreach (var item in monitors)
                item.ExitTestPlanRun(currentExecutionState);
 
            currentExecutionState = null;
            Log.Debug(timer, "TestPlan closed.");
 
        }
    }
 
    // This object has a special data annotator that embeds metadata properties
    // from Resources into it.
    class MetadataPromptObject
    {
        public string Name { get; private set; } = "Please enter test plan metadata.";
        [Browsable(false)]
        public IEnumerable<object> Resources { get; set; }
 
        public enum PromptResponse
        {
            OK,
            Abort
        }
 
        [Layout(LayoutMode.FloatBottom | LayoutMode.FullRow)]
        [Submit]
        public PromptResponse Response { get; set; }
 
    }
}