aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/FSE/Modules/Tango.FSE.Stubs/TestContext.cs
blob: 9761a937843c5b12395069ea459d91aadbafccc4 (plain)
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Google.Protobuf;
using Tango.Core.DI;
using Tango.Core.ExtensionMethods;
using Tango.FSE.Common.Connection;
using Tango.FSE.Common.Notifications;
using Tango.FSE.Common.Threading;
using Tango.FSE.Stubs.Dialogs;
using Tango.Integration.Operation;
using Tango.PMR;
using Tango.Scripting.Basic;

namespace Tango.FSE.Stubs
{
    public class TestContext : ITestContext
    {
        private ITestLogger _logger;
        private TestProject _project;
        private Dictionary<String, TestInput> _inputs;

        [TangoInject]
        private IMachineProvider MachineProvider { get; set; }

        [TangoInject]
        private INotificationProvider NotificationProvider { get; set; }

        [TangoInject]
        private IDispatcherProvider DispatcherProvider { get; set; }

        public ReadOnlyCollection<Result> Results { get; private set; }

        public TestContext(TestProject project, ITestLogger logger)
        {
            _project = project;
            _inputs = new Dictionary<string, TestInput>();

            foreach (var input in _project.Inputs)
            {
                _inputs.Add(input.Key, input);
            }

            _logger = logger;
            Results = new ReadOnlyCollection<Result>(new List<Result>());
            TangoIOC.Default.Inject(this);
        }

        public IMessage Run(string messageName, int? timeout = null, params object[] args)
        {
            var stubType = MessageFactory.GetAvailableRequestStubs().SingleOrDefault(x => x.Name.ToLower() == messageName.ToLower() || x.Name.Replace("Request", "").ToLower() == messageName.ToLower());
            if (stubType == null)
            {
                throw new ArgumentException("Invalid stub '" + messageName + "'.");
            }

            var stubProps = stubType.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            if (stubProps.Length > args.Length)
            {
                throw new ArgumentOutOfRangeException("Not enough arguments for " + stubType.Name + ".");
            }

            Object request = Activator.CreateInstance(stubType);

            int argIndex = 0;
            foreach (var prop in stubProps)
            {
                Object arg = args[argIndex++];

                if (prop.PropertyType == typeof(UInt32))
                {
                    prop.SetValue(request, UInt32.Parse(arg.ToString()));
                }
                else if (prop.PropertyType == typeof(bool))
                {
                    prop.SetValue(request, bool.Parse(arg.ToString()));
                }
                else if (prop.PropertyType.IsPrimitive)
                {
                    object converted = Convert.ChangeType(arg, prop.PropertyType);
                    prop.SetValue(request, converted);
                }
                else
                {
                    prop.SetValue(request, arg);
                }
            }

            return Run(request as IMessage, timeout);
        }

        public T Run<T>(string messageName, int? timeout = null, params object[] args) where T : class, IMessage
        {
            return Run(messageName, timeout, args) as T;
        }

        public IMessage Run(IMessage message, int? timeout = null)
        {
            TimeSpan? timespan = null;

            if (timeout != null)
            {
                timespan = TimeSpan.FromMilliseconds(timeout.Value);
            }

            return MachineProvider.MachineOperator.SendRequest(message, new Transport.TransportRequestConfig()
            {
                Timeout = timespan,
            }).Result;
        }

        public T Run<T>(IMessage messageName, int? timeout = null) where T : class, IMessage
        {
            return Run(messageName, timeout) as T;
        }

        public void RunContinuous<T>(IMessage messageName, Action<T> callback, int? timeout = null) where T : class, IMessage
        {
            TaskCompletionSource<object> completion = new TaskCompletionSource<object>();

            TimeSpan? timespan = null;

            if (timeout != null)
            {
                timespan = TimeSpan.FromMilliseconds(timeout.Value);
            }

            MachineProvider.MachineOperator.SendContinuousRequest(messageName, new Transport.TransportContinuousRequestConfig()
            {
                Timeout = timespan,
                ContinuousTimeout = timespan
            }).ObserveOn(new NewThreadScheduler()).Subscribe((msg) =>
            {
                try
                {
                    callback?.Invoke(msg as T);
                }
                catch { }
            }, (ex) =>
            {
                completion.SetException(ex);
            }, () =>
            {
                completion.SetResult(true);
            });

            completion.Task.GetAwaiter().GetResult();
        }

        public void RunContinuous<T>(string messageName, Action<T> callback, int? timeout = null, params object[] args) where T : class, IMessage
        {
            var stubType = MessageFactory.GetAvailableRequestStubs().SingleOrDefault(x => x.Name.ToLower() == messageName.ToLower() || x.Name.Replace("Request", "").ToLower() == messageName.ToLower());
            if (stubType == null)
            {
                throw new ArgumentException("Invalid stub '" + messageName + "'.");
            }

            var stubProps = stubType.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            if (stubProps.Length > args.Length)
            {
                throw new ArgumentOutOfRangeException("Not enough arguments for " + stubType.Name + ".");
            }

            IMessage request = Activator.CreateInstance(stubType) as IMessage;

            int argIndex = 0;
            foreach (var prop in stubProps)
            {
                Object arg = args[argIndex++];

                if (prop.PropertyType == typeof(UInt32))
                {
                    prop.SetValue(request, UInt32.Parse(arg.ToString()));
                }
                else if (prop.PropertyType == typeof(bool))
                {
                    prop.SetValue(request, bool.Parse(arg.ToString()));
                }
                else if (prop.PropertyType.IsPrimitive)
                {
                    object converted = Convert.ChangeType(arg, prop.PropertyType);
                    prop.SetValue(request, converted);
                }
                else
                {
                    prop.SetValue(request, arg);
                }
            }

            RunContinuous<IMessage>(request, callback as Action<IMessage>, timeout);
        }

        public void WriteLine(object obj)
        {
            String line = "null";

            if (obj != null)
            {
                if (!obj.GetType().IsValueTypeOrString())
                {
                    line = obj.ToJsonString();
                }
                else
                {
                    line = obj.ToString();
                }
            }

            _logger?.WriteLine(line);
        }

        public void Write(object obj)
        {
            String line = "null";

            if (obj != null)
            {
                if (obj.GetType().IsClass)
                {
                    line = obj.ToJsonString();
                }
                else
                {
                    line = obj.ToString();
                }
            }

            _logger?.WriteLine(line);
        }

        public void WriteLineHex(object number, int digits)
        {
            _logger?.WriteLine("#" + Convert.ToInt32(number).ToString("X" + digits.ToString()));
        }

        public void WriteHex(object number, int digits)
        {
            _logger?.Write("#" + Convert.ToInt32(number).ToString("X" + digits.ToString()));
        }

        public void Clear()
        {
            _logger?.Clear();
        }

        public void WriteToFile(string filePath, string content)
        {
            File.WriteAllText(filePath, content);
        }

        public void AppendToFile(string filePath, string content)
        {
            File.AppendAllText(filePath, content);
        }

        public Result AddResult(ResultType type, string name, object value)
        {
            var result = new Result(type, name, value);
            return AddResult(result);
        }

        public Result AddResult(Result result)
        {
            List<Result> results = new List<Result>(Results);
            results.Add(result);
            Results = new ReadOnlyCollection<Result>(results);
            return result;
        }

        public void RemoveResult(Result result)
        {
            List<Result> results = new List<Result>(Results);
            results.Remove(result);
            Results = new ReadOnlyCollection<Result>(results);
        }

        public void ClearResults()
        {
            Results = new ReadOnlyCollection<Result>(new List<Result>());
        }

        public T GetInput<T>(string key)
        {
            var value = GetInput(key);

            try
            {
                return (T)Convert.ChangeType(value, typeof(T));
            }
            catch
            {
                throw new InvalidCastException($"Error converting the specified input '{value}' to type '{typeof(T).Name}'.");
            }
        }

        public List<T> GetInputArray<T>(String key)
        {
            var value = GetInput(key);

            String[] arr = value.ToStringSafe().Split(',');
            var list = new List<T>(arr.Select(x => (T)Convert.ChangeType(x, typeof(T))));

            return list;
        }

        public object GetInput(string key)
        {
            TestInput input = null;

            if (_inputs.TryGetValue(key, out input))
            {
                return input.Value;
            }
            else
            {
                throw new KeyNotFoundException($"Could no find input with key '{key}'.");
            }
        }

        public void Fail(string message)
        {
            throw new TestFailedException(message);
        }

        public void ShowInfo(string message)
        {
            TaskCompletionSource<object> completion = new TaskCompletionSource<object>();

            DispatcherProvider.Invoke(async () =>
            {
                await NotificationProvider.ShowInfo(message);
                completion.SetResult(true);
            });

            completion.Task.GetAwaiter().GetResult();
        }

        public void ShowWarning(string message)
        {
            TaskCompletionSource<object> completion = new TaskCompletionSource<object>();

            DispatcherProvider.Invoke(async () =>
            {
                await NotificationProvider.ShowWarning(message);
                completion.SetResult(true);
            });

            completion.Task.GetAwaiter().GetResult();
        }

        public void ShowError(string message)
        {
            TaskCompletionSource<object> completion = new TaskCompletionSource<object>();

            DispatcherProvider.Invoke(async () =>
            {
                await NotificationProvider.ShowError(message);
                completion.SetResult(true);
            });

            completion.Task.GetAwaiter().GetResult();
        }

        public bool ShowQuestion(string message)
        {
            TaskCompletionSource<bool> completion = new TaskCompletionSource<bool>();

            DispatcherProvider.Invoke(async () =>
            {
                var result = await NotificationProvider.ShowQuestion(message);
                completion.SetResult(result);
            });

            return completion.Task.GetAwaiter().GetResult();
        }

        public bool ShowWarningQuestion(string message)
        {
            TaskCompletionSource<bool> completion = new TaskCompletionSource<bool>();

            DispatcherProvider.Invoke(async () =>
            {
                var result = await NotificationProvider.ShowWarningQuestion(message);
                completion.SetResult(result);
            });

            return completion.Task.GetAwaiter().GetResult();
        }

        public T RequestUserInputFor<T>(string title, string message)
        {
            return RequestUserInputFor<T>(Activator.CreateInstance<T>(), title, message);
        }

        public T RequestUserInputFor<T>(T model, string title, string message)
        {
            UserInputDialogViewVM vm = new UserInputDialogViewVM(title, message, model);
            vm.Init();

            TaskCompletionSource<T> completion = new TaskCompletionSource<T>();

            DispatcherProvider.Invoke(async () =>
            {
                await NotificationProvider.ShowDialog(vm);
                completion.SetResult(model);
            });

            var result = completion.Task.GetAwaiter().GetResult();
            vm.FinalizeModel();
            return model;
        }

        public void WriteLineArray(IEnumerable array, ArrayParsingStyle style)
        {
            String line = String.Empty;

            List<Object> list = new List<object>();

            foreach (var item in array)
            {
                list.Add(item);
            }

            if (style == ArrayParsingStyle.Comma)
            {
                line = String.Join(", ", list.Select(x => x.ToStringSafe()));
            }
            else
            {
                foreach (var item in list)
                {
                    line += $"[{item.ToStringSafe()}] ";
                }
            }

            WriteLine(line);
        }
    }
}