chr
2026-04-05 fe750b791d5b517cc4e9bc8e99a9a75139a0cfba
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using NUnit.Framework;
 
namespace OpenTap.Engine.UnitTests
{
    [TestFixture]
    public class ListSerialization 
    {
        public class StringTemp
        {
            public string Test { get; set; }
        }
 
        public class StringTempListStep : TestStep
        {
            public List<StringTemp> TestProp { get; set; }
            public System.Collections.ObjectModel.ReadOnlyCollection<string> NullList { get; set; }
 
 
            public StringTempListStep()
            {
                TestProp = new List<StringTemp>();
            }
 
            public override void Run()
            {
            }
        }
        public enum TestEnum
        {
            A, B, C
        }
        public class StringListStep : TestStep
        {
 
            public List<String> TestProp { get; set; }
 
            public IList List { get; set; }
 
            public HashSet<int> Set { get; set; }
 
            public HashSet<TestEnum> EnumSet { get; set; }
 
            public Dictionary<string, int> Dict { get; set; }
 
            public StringListStep()
            {
                TestProp = new List<String>();
                List = new List<double> { 1, 2, 3 };
                Set = new HashSet<int>();
                EnumSet = new HashSet<TestEnum>();
                Dict = new Dictionary<string, int>();
            }
 
            public override void Run()
            {
            }
        }
 
        [Test]
        public void StringTempListSerialization()
        {
            TestPlan target = new TestPlan();
            var targetStep = new StringTempListStep { TestProp = new List<StringTemp> { new StringTemp { Test = "123" }, new StringTemp { Test = "abc" } } };
 
            target.Steps.Add(targetStep);
 
            using (var ms = new MemoryStream())
            {
                target.Save(ms);
 
                ms.Seek(0, SeekOrigin.Begin);
 
                TestPlan deserialized = TestPlan.Load(ms, target.Path);
                var step = deserialized.ChildTestSteps.First() as StringTempListStep;
 
                Assert.IsNotNull(step.TestProp);
                Assert.AreEqual(targetStep.TestProp.Count, step.TestProp.Count);
 
                for (int i = 0; i < targetStep.TestProp.Count; i++)
                    Assert.AreEqual(targetStep.TestProp[i].Test, step.TestProp[i].Test);
            }
        }
 
        [Test]
        public void StringListSerialization()
        {
            TestPlan target = new TestPlan();
 
            var specList = new List<double> { 5, 6, 7 };
            var hashSet = new HashSet<TestEnum>(new TestEnum[] { TestEnum.C });
            var targetStep = new StringListStep
            {
                TestProp = new List<String> { "123", "abc" },
                List = specList,
                EnumSet = hashSet,
                Set = new HashSet<int>(Enumerable.Range(100, 10)),
                Dict = new Dictionary<string, int>() { }
            };
            targetStep.Dict["asd"] = 5;
            targetStep.Dict[""] = 15;
 
            target.Steps.Add(targetStep);
 
            TestPlan deserialized;
 
            using (var ms = new MemoryStream())
            {
                target.Save(ms);
                ms.Seek(0, SeekOrigin.Begin);
                deserialized = TestPlan.Load(ms, target.Path);
            }
            var step = deserialized.ChildTestSteps.First() as StringListStep;
 
            Assert.IsNotNull(step.TestProp);
            Assert.AreEqual(targetStep.TestProp.Count, step.TestProp.Count);
 
            for (int i = 0; i < targetStep.TestProp.Count; i++)
                Assert.AreEqual(targetStep.TestProp[i], step.TestProp[i]);
            Assert.IsTrue(specList.SequenceEqual(step.List.Cast<double>()));
            Assert.IsTrue(step.EnumSet.Except(hashSet).Count() == 0);
            Assert.IsTrue(step.Set.OrderBy(x => x).SequenceEqual(targetStep.Set.OrderBy(x => x)));
            Assert.AreEqual(5, step.Dict["asd"]);
            Assert.AreEqual(15, step.Dict[""]);
        }
 
        public class InstStep : TestStep
        {
            public List<IInstrument> Instrs { get; set; }
 
            public override void Run()
            {
            }
        }
 
        public class SomeotherInstrument : Instrument
        {
 
        }
 
        void loadDummyInstruments(int count)
        {
            for (int i = 0; i < count; i++)
            {
                InstrumentSettings.Current.Add(new ScpiDummyInstrument() { Tag = (i + 1).ToString() });
                InstrumentSettings.Current.Add(new SomeotherInstrument());
            }
        }
 
        void unloadDummyInstruments()
        {
            InstrumentSettings.Current.RemoveIf<IInstrument>(instr => instr is ScpiDummyInstrument && ((ScpiDummyInstrument)instr).Tag != null);
            InstrumentSettings.Current.RemoveIf<IInstrument>(instr => instr is SomeotherInstrument);
        }
 
        /// <summary>
        /// Tests deserialization/serialzation of a list of instruments.
        /// </summary>
        [Test]
        public void ListInstrumentSerialization()
        {
            try
            {
                loadDummyInstruments(10);
                TestPlan target = new TestPlan();
                Random rnd = new Random(0);
                var targetStep = new InstStep { Instrs = InstrumentSettings.Current.OrderBy(item => rnd.Next()).ToList() };
 
                target.Steps.Add(targetStep);
 
                using (var ms = new MemoryStream())
                {
                    target.Save(ms);
 
                    ms.Seek(0, SeekOrigin.Begin);
 
                    TestPlan deserialized = TestPlan.Load(ms, target.Path);
                    var step = deserialized.ChildTestSteps.First() as InstStep;
 
                    Assert.IsNotNull(step.Instrs);
                    Assert.AreEqual(targetStep.Instrs.Count, step.Instrs.Count);
 
                    for (int i = 0; i < targetStep.Instrs.Count; i++)
                        Assert.AreEqual(targetStep.Instrs[i], step.Instrs[i]);
                }
            }
            finally
            {
                unloadDummyInstruments();
            }
        }
 
        public class NestedInstStep : TestStep
        {
            public List<List<IInstrument>> Instrs { get; set; }
 
            public NestedInstStep()
            {
                Instrs = new List<List<IInstrument>>();
            }
 
            public override void Run()
            {
            }
        }
 
        /// <summary>
        /// This test step tests serializing/deserializing a list of lists of instruments.
        /// Since Instruments are from ComponentSettingsLists, they should all convert to indexes.
        /// </summary>
        [Test]
        public void ListListInstrumentSerialization()
        {
            loadDummyInstruments(10);
            try
            {
                TestPlan target = new TestPlan();
                Random rnd = new Random(0);
                var randomSeq = InstrumentSettings.Current.OrderBy(item => rnd.Next());
                var targetStep = new NestedInstStep { Instrs = new List<List<IInstrument>> { randomSeq.ToList(), randomSeq.ToList(), randomSeq.ToList() } };
 
                target.Steps.Add(targetStep);
 
                using (var ms = new MemoryStream())
                {
                    target.Save(ms);
                    ms.Seek(0, SeekOrigin.Begin);
 
                    TestPlan deserialized = TestPlan.Load(ms, target.Path);
                    var step = deserialized.ChildTestSteps.First() as NestedInstStep;
 
                    Assert.IsNotNull(step.Instrs);
                    Assert.AreEqual(targetStep.Instrs.Count, step.Instrs.Count);
 
                    for (int i = 0; i < targetStep.Instrs.Count; i++)
                    {
                        Assert.AreEqual(targetStep.Instrs[i].Count, step.Instrs[i].Count);
 
                        for (int i2 = 0; i2 < targetStep.Instrs[i].Count; i2++)
                        {
                            Assert.AreEqual(targetStep.Instrs[i][i2], step.Instrs[i][i2]);
                        }
                    }
                }
 
            }
            finally
            {
                unloadDummyInstruments();
            }
        }
 
        public class DualNestedInstStep : TestStep
        {
            public List<List<List<IInstrument>>> Instrs { get; set; }
 
            public DualNestedInstStep()
            {
                Instrs = new List<List<List<IInstrument>>>();
            }
 
            public override void Run()
            {
            }
        }
 
        /// <summary>
        /// This test tests serializing / deserializing of lists of lists of lists of instrments.
        /// </summary>
        [Test]
        public void ListListListInstrumentSerialization()
        {
            loadDummyInstruments(10);
            try
            {
                TestPlan target = new TestPlan();
                Random rnd = new Random(0);
                var randomSeq = InstrumentSettings.Current.OrderBy(item => rnd.Next());
                var targetStep = new DualNestedInstStep { Instrs = new List<List<List<IInstrument>>> { new List<List<IInstrument>> { randomSeq.ToList(), randomSeq.ToList() }, new List<List<IInstrument>> { randomSeq.ToList(), randomSeq.ToList(), randomSeq.ToList(), randomSeq.ToList() } } };
 
                target.Steps.Add(targetStep);
 
                using (var ms = new MemoryStream())
                {
                    target.Save(ms);
 
                    ms.Seek(0, SeekOrigin.Begin);
 
                    TestPlan deserialized = TestPlan.Load(ms, target.Path);
                    var step = deserialized.ChildTestSteps.First() as DualNestedInstStep;
 
                    Assert.IsNotNull(step.Instrs);
                    Assert.AreEqual(targetStep.Instrs.Count, step.Instrs.Count);
 
                    for (int i = 0; i < targetStep.Instrs.Count; i++)
                    {
                        Assert.AreEqual(targetStep.Instrs[i].Count, step.Instrs[i].Count);
 
                        for (int i2 = 0; i2 < targetStep.Instrs[i].Count; i2++)
                        {
                            Assert.AreEqual(targetStep.Instrs[i][i2].Count, step.Instrs[i][i2].Count);
 
                            for (int i3 = 0; i3 < targetStep.Instrs[i][i2].Count; i3++)
                            {
                                Assert.AreEqual(targetStep.Instrs[i][i2][i3], step.Instrs[i][i2][i3]);
                            }
                        }
                    }
                }
 
            }
            finally
            {
                unloadDummyInstruments();
            }
        }
 
        public class DeserializedCallbackTestStep : TestStep, IDeserializedCallback
        {
            public bool WasDeserialized = false;
            public void OnDeserialized()
            {
                WasDeserialized = true;
            }
 
            public override void Run()
            {
 
            }
        }
 
        public class DeserializedCallbackInstrument : Instrument, IDeserializedCallback
        {
            public bool WasDeserialized = false;
            public void OnDeserialized()
            {
                WasDeserialized = true;
            }
        }
 
        [Browsable(false)]
        public class DeserializedCallbackSettings : ComponentSettings, IDeserializedCallback
        {
            public bool WasDeserialized = false;
            public void OnDeserialized()
            {
                WasDeserialized = true;
            }
        }
 
        [Test]
        public void TestIDeserializedCallback()
        {
            {// test deserializing plan
                TestPlan plan = new TestPlan();
                DeserializedCallbackTestStep step = new DeserializedCallbackTestStep();
                plan.ChildTestSteps.Add(step);
                using (var tmpFile = new MemoryStream())
                {
                    plan.Save(tmpFile);
                    tmpFile.Position = 0;
                    plan = TestPlan.Load(tmpFile, plan.Path);
                }
                Assert.IsFalse(step.WasDeserialized);
                step = (DeserializedCallbackTestStep)plan.ChildTestSteps[0];
                Assert.IsTrue(step.WasDeserialized);
            }
 
            bool testSerializeStandaloneInstrument = false;
            if (testSerializeStandaloneInstrument)
            {
                // This cannot work, because there is no ComponentSettings referencing inst.
                // Previously this worked because of an error.
 
                // test deserializing instrument
                DeserializedCallbackInstrument inst = new DeserializedCallbackInstrument();
                string xml = new TapSerializer().SerializeToString(inst);
                var inst2 = (DeserializedCallbackInstrument)new TapSerializer().DeserializeFromString(xml, TypeData.GetTypeData(inst));
                Assert.IsTrue(inst2.WasDeserialized);
                Assert.IsFalse(inst.WasDeserialized);
            }
 
            { // test deserializing settings
                DeserializedCallbackSettings settings = new DeserializedCallbackSettings();
                string xml = new TapSerializer().SerializeToString(settings);
                var settings2 = (DeserializedCallbackSettings)new TapSerializer().DeserializeFromString(xml, TypeData.GetTypeData(settings));
                Assert.IsTrue(settings2.WasDeserialized);
                Assert.IsFalse(settings.WasDeserialized);
            }
        }
 
        class PrivateComponentSettingsList : ComponentSettingsList<PrivateComponentSettingsList, IInstrument>
        {
 
        }
 
        [Test]
        public void SerializeDeserializePrivateType()
        {
            var settings = new PrivateComponentSettingsList();
            settings.Add(new ScpiDummyInstrument() { VisaAddress = "test" });
            var xml = new TapSerializer().SerializeToString(settings);
 
            var settings2 = (PrivateComponentSettingsList)(new TapSerializer().DeserializeFromString(xml, TypeData.FromType(typeof(PrivateComponentSettingsList))));
            var inst = (ScpiDummyInstrument)settings2[0];
            Assert.AreEqual("test", inst.VisaAddress);
        }
 
        [Test]
        public void SerializeDeserializeNullResource()
        {
            IInstrument instr = new ScpiDummyInstrument();
            InstrumentSettings.Current.Add(instr);
            try
            {
                ScpiTestStep step = new ScpiTestStep();
                step.Instrument = null;
                var xml = new TapSerializer().SerializeToString(step);
                Assert.IsTrue(xml.Contains($"<Instrument />"));
                var deserializedStep = new TapSerializer().DeserializeFromString(xml) as ScpiTestStep;
                Assert.AreEqual(step.Instrument, deserializedStep.Instrument);
            }
            finally
            {
                InstrumentSettings.Current.Remove(instr);
            }
        }
 
        public class StringObject
        {
            public string TheString { get; set; }
        }
 
        [Test]
        public void SerializeDeserializeProblematicString()
        {
            {
                StringBuilder sb = new StringBuilder("test:");
                var ser = new TapSerializer();
                for (int i = 0; i < 512; i++)
                    sb.Append((char) i);
 
                var st = new StringObject() {TheString = sb.ToString()};
                var stt = ser.SerializeToString(st);
                var rev = (StringObject) ser.DeserializeFromString(stt);
                Assert.IsTrue(string.Compare(st.TheString, rev.TheString) == 0);
                
            }
            {
                StringBuilder sb = new StringBuilder("test::::");
                var ser = new TapSerializer();
                for (int i = 0; i < 512; i++)
                    sb.Append((char) i);
                var st = new StringObject() { TheString = sb.ToString() };
                var stt = ser.SerializeToString(st);
                var rev = (StringObject)ser.DeserializeFromString(stt);
                Assert.IsTrue(string.Compare(st.TheString, rev.TheString) == 0);
                
            }
 
        }
 
        public class SimpleClass
        {
            public SimpleClass(object obj)
            {
                
            }
        }
        public class UnbalancedListStep : TestStep
        {
            [Display("Tx Command Sequences", "A predefined list of TX command sequences to control the DUT.",
                Order: 10.2)]
            public IReadOnlyList<SimpleClass> ReadOnlyList { get; set; } = new List<SimpleClass> {new SimpleClass(default), new SimpleClass(default)}.AsReadOnly();
 
            public override void Run()
            {
                throw new NotImplementedException();
            }
        }
        
        [Test]
        public void DeserializeUnbalancedList()
        {
            using (Session.Create())
            {
                var trace = new EngineUnitTestUtils.TestTraceListener();
                Log.AddListener(trace);
 
                var plan = new TestPlan();
                plan.ChildTestSteps.Add(new UnbalancedListStep());
 
                var ser = new TapSerializer();
                var planXml = ser.SerializeToString(plan);
                CollectionAssert.IsEmpty(ser.Errors);
 
                var currentLength = planXml.Length;
 
                var itemElem = $"<{nameof(SimpleClass)}></{nameof(SimpleClass)}>";
                // Remove one of the two items from the xml
                planXml = planXml.Remove(planXml.IndexOf(itemElem, StringComparison.Ordinal), itemElem.Length);
                
                // Ensure an element was actually removed
                Assert.AreEqual(currentLength - itemElem.Length, planXml.Length);
                
                var deserializedPlan = ser.DeserializeFromString(planXml) as TestPlan;
 
                CollectionAssert.IsEmpty(ser.Errors);
 
                // Deserialization should succeed even though we expect an element which was missing
                Assert.IsTrue(
                    deserializedPlan.ChildTestSteps.First() is UnbalancedListStep s && s.ReadOnlyList.Count == 2,
                    "Expected list to contain 2 element.");
                
                Assert.AreEqual(1, trace.WarningMessage.Count);
                CollectionAssert.Contains(trace.WarningMessage, "Deserialized unbalanced list.");
            }
        }
    }
}