File: test-server.vala

package info (click to toggle)
geary 46.0-12
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 15,092 kB
  • sloc: javascript: 972; ansic: 722; sql: 247; xml: 183; python: 30; makefile: 28; sh: 24
file content (226 lines) | stat: -rw-r--r-- 6,768 bytes parent folder | download | duplicates (5)
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
/*
 * Copyright 2019 Michael Gratton <mike@vee.net>
 *
 * This software is licensed under the GNU Lesser General Public License
 * (version 2.1 or later). See the COPYING file in this distribution.
 */

/**
 * A simple mock server for testing network connections.
 *
 * To use it, unit tests should construct an instance as a fixture in
 * set up, specify a test script by adding lines and then check the
 * result, before stopping the server in tear down.
 */
public class TestServer : GLib.Object {


    /** Possible actions a script may take. */
    public enum Action {
        /**
         * The implicit first action.
         *
         * This does not need to be specified as a script action, it
         * will always be taken when a client connects.
         */
        CONNECTED,

        /** Send a line to the client. */
        SEND_LINE,

        /** Receive a line from the client. */
        RECEIVE_LINE,

        /** Wait for the client to disconnect. */
        WAIT_FOR_DISCONNECT,

        /** Disconnect immediately. */
        DISCONNECT;
    }


    /** A line of the server's script. */
    public struct Line {

        /** The action to take for this line. */
        public Action action;

        /**
         * The value for the action.
         *
         * If sending, this string will be sent. If receiving, the
         * expected line.
         */
        public string value;

    }

    /** The result of executing a script line. */
    public struct Result {

        /** The expected action. */
        public Line line;

        /** Was the expected action successful. */
        public bool succeeded;

        /** The actual string sent by a client when not as expected. */
        public string? actual;

        /** In case of an error being thrown, the error itself. */
        public GLib.Error? error;

    }


    private GLib.DataStreamNewlineType line_ending;
    private uint16 port;
    private GLib.ThreadedSocketService service =
        new GLib.ThreadedSocketService(10);
    private GLib.Cancellable running = new GLib.Cancellable();
    private Gee.List<Line?> script = new Gee.ArrayList<Line?>();
    private GLib.AsyncQueue<Result?> completion_queue =
        new GLib.AsyncQueue<Result?>();


    public TestServer(GLib.DataStreamNewlineType line_ending = CR_LF)
        throws GLib.Error {
        this.line_ending = line_ending;
        this.port = this.service.add_any_inet_port(null);
        this.service.run.connect((conn) => {
                handle_connection(conn);
                return true;
            });
        this.service.start();
    }

    public GLib.SocketConnectable get_client_address() {
        return new GLib.NetworkAddress("localhost", this.port);
    }

    public void add_script_line(Action action, string value) {
        this.script.add({ action, value });
    }

    public Result wait_for_script(GLib.MainContext loop) {
        Result? result = null;
        while (result == null) {
            loop.iteration(false);
            result = this.completion_queue.try_pop();
        }
        return result;
    }

    public void stop() {
        this.service.stop();
        this.running.cancel();
    }

    private void handle_connection(GLib.SocketConnection connection) {
        debug("Connected");
        var input = new GLib.DataInputStream(
            connection.input_stream
        );
        input.set_newline_type(this.line_ending);

        var output = new GLib.DataOutputStream(
            connection.output_stream
        );

        Line connected_line = { CONNECTED, "" };
        Result result = { connected_line, true, null, null };
        foreach (var line in this.script) {
            result.line = line;
            switch (line.action) {
            case CONNECTED:
                // no-op
                break;

            case SEND_LINE:
                debug("Sending: %s", line.value);
                try {
                    output.put_string(line.value);
                    switch (this.line_ending) {
                    case CR:
                        output.put_byte('\r');
                        break;
                    case LF:
                        output.put_byte('\n');
                        break;
                    default:
                        output.put_byte('\r');
                        output.put_byte('\n');
                        break;
                    }
                } catch (GLib.Error err) {
                    result.succeeded = false;
                    result.error = err;
                }
                break;

            case RECEIVE_LINE:
                debug("Waiting for: %s", line.value);
                try {
                    size_t len;
                    string? received = input.read_line(out len, this.running);
                    if (received == null || received != line.value) {
                        result.succeeded = false;
                        result.actual = received;
                    }
                } catch (GLib.Error err) {
                    result.succeeded = false;
                    result.error = err;
                }
                break;

            case WAIT_FOR_DISCONNECT:
                debug("Waiting for disconnect");
                var socket = connection.get_socket();
                try {
                    uint8 buffer[4096];
                    while (socket.receive_with_blocking(buffer, true) > 0) { }
                } catch (GLib.Error err) {
                    result.succeeded = false;
                    result.error = err;
                }
                break;

            case DISCONNECT:
                debug("Disconnecting");
                try {
                    connection.close(this.running);
                } catch (GLib.Error err) {
                    result.succeeded = false;
                    result.error = err;
                }
                break;
            }

            if (!result.succeeded) {
                break;
            }
        }
        if (result.succeeded) {
            debug("Done");
        } else if (result.error != null) {
            warning("Error: %s", result.error.message);
        } else if (result.line.action == RECEIVE_LINE) {
            warning("Received unexpected line: %s", result.actual ?? "(null)");
        } else {
            warning("Failed for unknown reason");
        }

        if (connection.is_connected()) {
            try {
                connection.close(this.running);
            } catch (GLib.Error err) {
                warning(
                    "Error closing test server connection: %s", err.message
                );
            }
        }

        this.completion_queue.push(result);
    }

}