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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using OpenTap.Cli;
 
namespace OpenTap.Engine.UnitTests.TestTestSteps
{
    [Display("user-input", "Used to verify user-input implementations", Group: "test")]
    public class UserInputTestAction : ICliAction
    {
        public class RequestObject
        {
            [Submit] public string Answer { get; set; }
        }
 
        [CommandLineArgument("answers", ShortName = "a", Description = "The answers that the caller is intending to give.")]
        public string[] ExpectedAnswers { get; set; }
 
        private static TraceSource log = Log.CreateSource(nameof(UserInputTestAction));
 
        public static string DescribeBytes(IEnumerable<char> i)
        {
            var s = i.ToArray();
            if (s.Length == 0) return "[]";
 
            var sb = new StringBuilder();
            sb.Append('[');
            foreach (var ch in s)
            {
                sb.Append(string.Format("0x{0:X}", (int)ch));
                sb.Append(", ");
            }
            sb.Remove(sb.Length - 2, 2);
            sb.Append(']');
            return sb.ToString();
        }
 
        public int Execute(CancellationToken cancellationToken)
        {
            try
            {
                for (int i = 0; i < ExpectedAnswers.Length; i++)
                {
                    var r = new RequestObject();
                    log.Info($"Checking input {i + 1} of {ExpectedAnswers.Length} ({ExpectedAnswers[i]})");
                    UserInput.Request(r);
                    var exp = DescribeBytes(ExpectedAnswers[i]);
                    var act = DescribeBytes(r.Answer);
                    log.Info($"Expected: {exp}");
                    log.Info($"  Actual: {act}");
                    if (r.Answer.Equals(ExpectedAnswers[i], StringComparison.InvariantCulture) == false)
                    {
                        log.Error($"Input {i + 1} did not match the expected input:");
                        log.Error($"Expected '{ExpectedAnswers[i]}', got '{r.Answer}'");
                        return 3;
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error($"Error while reading input: {ex.Message}");
                log.Debug(ex);
            }
 
            return 0;
        }
    }
 
    [Display("Piping Process Step", "A run process step with support for piping", "Tests")]
    public class PipingProcessStep : TestStep
    {
        [Display("Application", Order: -2.5,
            Description:
            "The path to the program. It should contain either a relative path to OpenTAP installation folder or an absolute path to the program.")]
        [FilePath(FilePathAttribute.BehaviorChoice.Open, "exe")]
        public string Application { get; set; } = "";
 
        [Display("Command Line Arguments", Order: -2.4, Description: "The arguments passed to the program.")]
        [DefaultValue("")]
        public string Arguments { get; set; } = "";
 
        [Display("Expected Exit Code", "The expected exit code of the process.")]
        public int ExpectedExitCode { get; set; } = 0;
 
        [Display("Write Speed", "How fast should the input be written to the process stream. Measured in number of milliseconds between writes")]
        [Unit("ms")]
        public int WriteSpeed { get; set; } = 100;
 
        [Layout(LayoutMode.Normal, 2, maxRowHeight: 5)]
        [Display("Pipe Data", "The data that should be written to the process' input stream.")]
        public string StdIn { get; set; } = "";
 
        public enum WriteMode
        {
            WriteLines,
            WriteChars,
            WriteAll,
        }
 
        [Display("Write Mode", "How should the data be written to the pipe?")]
        public WriteMode Mode { get; set; }
 
        public override void Run()
        {
            using var process = new Process
            {
                StartInfo =
                {
                    FileName = Application,
                    Arguments = Arguments,
                    WorkingDirectory = Directory.GetCurrentDirectory(),
                    UseShellExecute = false,
                    RedirectStandardError = true,
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true,
                    CreateNoWindow = true,
                }
            };
 
            Log.Info($"Starting process '{Application}' with arguments '{Arguments}'.");
 
            if (!process.Start())
            {
                Log.Error("Process failed to start.");
                UpgradeVerdict(Verdict.Error);
                return;
            }
            
            process.OutputDataReceived += (sender, args) =>
            {
                if (args.Data == null) return;
                Log.Info(args.Data);
            };
            process.ErrorDataReceived += (sender, args) =>
            {
                if (args.Data == null) return;
                Log.Error(args.Data);
            };
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            process.StandardInput.AutoFlush = true;
 
            Log.Info($"Writing payload to process: {UserInputTestAction.DescribeBytes(StdIn)}");
 
            try
            {
                var w = process.StandardInput;
                switch (Mode)
                {
                    case WriteMode.WriteAll:
                        w.Write(StdIn);
                        break;
                    case WriteMode.WriteLines:
                        foreach (var line in StdIn.Trim().Split('\n'))
                        {
                            if (WriteSpeed > 0)
                                TapThread.Sleep(WriteSpeed);
                            if (process.HasExited) break;
                            w.WriteLine(line);
                        }
 
                        break;
                    case WriteMode.WriteChars:
                        foreach (char ch in StdIn)
                        {
                            if (WriteSpeed > 0)
                                TapThread.Sleep(WriteSpeed);
                            if (process.HasExited) break;
                            w.Write(ch);
                        }
 
                        break;
                }
            }
            // Writing to the input pipe will fail if the process has already exited
            catch (Exception) when (process.HasExited)
            {
                // suppress
            }
            if (!process.HasExited)
                process.StandardInput.Close(); 
 
            if (!process.WaitForExit((int)TimeSpan.FromSeconds(10).TotalMilliseconds))
            {
                Log.Error("Process did not exit in a timely fashion.");
                UpgradeVerdict(Verdict.Error);
                return;
            }
 
            if (process.ExitCode == ExpectedExitCode)
                UpgradeVerdict(Verdict.Pass);
            else
            {
                Log.Error($"Expected exit code {ExpectedExitCode}, was {process.ExitCode}.");
                UpgradeVerdict(Verdict.Fail);
            }
        }
    }
}