summaryrefslogtreecommitdiff
path: root/installed-tests/js/testConsole.js
blob: 2e699fff281ec49aa3e3ffdf456d27edc90aac2b (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
// SPDX-License-Identifier: MIT OR LGPL-2.0-or-later
// SPDX-FileCopyrightText: 2021 Evan Welsh <contact@evanwelsh.com>

// eslint-disable-next-line
/// <reference types="jasmine" />

import GLib from 'gi://GLib';
import {DEFAULT_LOG_DOMAIN} from 'console';

import {decodedStringMatching} from './matchers.js';

function objectContainingLogMessage(
    message,
    domain = DEFAULT_LOG_DOMAIN,
    fields = {},
    messageMatcher = decodedStringMatching
) {
    return jasmine.objectContaining({
        MESSAGE: messageMatcher(message),
        GLIB_DOMAIN: decodedStringMatching(domain),
        ...fields,
    });
}

function matchStackTrace(log, sourceFile = null, encoding = 'utf-8') {
    const matcher = jasmine.stringMatching(log);
    const stackLineMatcher = jasmine.stringMatching(/^[\w./<]*@.*:\d+:\d+/);
    const sourceMatcher = sourceFile ? jasmine.stringMatching(RegExp(
        String.raw`^[\w]*@(file|resource):\/\/\/.*\/${sourceFile}\.js:\d+:\d+$`))
        : stackLineMatcher;

    return {
        asymmetricMatch(compareTo) {
            const decoder = new TextDecoder(encoding);
            const decoded = decoder.decode(new Uint8Array(Array.from(compareTo)));
            const lines = decoded.split('\n').filter(l => !!l.length);

            if (!matcher.asymmetricMatch(lines[0]))
                return false;

            if (!sourceMatcher.asymmetricMatch(lines[1]))
                return false;

            return lines.slice(2).every(l => stackLineMatcher.asymmetricMatch(l));
        },
        jasmineToString() {
            return `<decodedStringMatching(${log})>`;
        },
    };
}

describe('console', function () {
    /** @type {jasmine.Spy<(_level: any, _fields: any) => any>} */
    let writer_func;

    /**
     * @param {RegExp | string} message _
     * @param {*} [logLevel] _
     * @param {*} [domain] _
     * @param {*} [fields] _
     */
    function expectLog(
        message,
        logLevel = GLib.LogLevelFlags.LEVEL_MESSAGE,
        domain = DEFAULT_LOG_DOMAIN,
        fields = {}
    ) {
        if (logLevel < GLib.LogLevelFlags.LEVEL_WARNING) {
            const [_, currentFile] = new Error().stack.split('\n').at(0).match(
                /^[^@]*@(.*):\d+:\d+$/);

            fields = {
                ...fields,
                CODE_FILE: decodedStringMatching(currentFile),
            };
        }

        expect(writer_func).toHaveBeenCalledOnceWith(
            logLevel,
            objectContainingLogMessage(message, domain, fields)
        );

        // Always reset the calls, so that we can assert at the end that no
        // unexpected messages were logged
        writer_func.calls.reset();
    }

    beforeAll(function () {
        writer_func = jasmine.createSpy(
            'Console test writer func',
            function (level, _fields) {
                if (level === GLib.LogLevelFlags.ERROR)
                    return GLib.LogWriterOutput.UNHANDLED;

                return GLib.LogWriterOutput.HANDLED;
            }
        );

        writer_func.and.callThrough();

        // @ts-expect-error The existing binding doesn't accept any parameters because
        // it is a raw pointer.
        GLib.log_set_writer_func(writer_func);
    });

    beforeEach(function () {
        writer_func.calls.reset();
    });

    it('has correct object tag', function () {
        expect(console.toString()).toBe('[object console]');
    });

    it('logs a message', function () {
        console.log('a log');

        expect(writer_func).toHaveBeenCalledOnceWith(
            GLib.LogLevelFlags.LEVEL_MESSAGE,
            objectContainingLogMessage('a log')
        );
        writer_func.calls.reset();
    });

    it('logs a warning', function () {
        console.warn('a warning');

        expect(writer_func).toHaveBeenCalledOnceWith(
            GLib.LogLevelFlags.LEVEL_WARNING,
            objectContainingLogMessage('a warning')
        );
        writer_func.calls.reset();
    });

    it('logs an informative message', function () {
        console.info('an informative message');

        expect(writer_func).toHaveBeenCalledOnceWith(
            GLib.LogLevelFlags.LEVEL_INFO,
            objectContainingLogMessage('an informative message')
        );
        writer_func.calls.reset();
    });

    it('traces a line', function () {
        // eslint-disable-next-line max-statements-per-line
        console.trace('a trace'); const error = new Error();

        const [_, currentFile, errorLine] = error.stack.split('\n').at(0).match(
            /^[^@]*@(.*):(\d+):\d+$/);

        expect(writer_func).toHaveBeenCalledOnceWith(
            GLib.LogLevelFlags.LEVEL_MESSAGE,
            objectContainingLogMessage('a trace', DEFAULT_LOG_DOMAIN, {
                CODE_FILE: decodedStringMatching(currentFile),
                CODE_LINE: decodedStringMatching(errorLine),
            },
            message => matchStackTrace(message, 'testConsole'))
        );

        writer_func.calls.reset();
    });

    it('traces a empty message', function () {
        console.trace();

        const [_, currentFile] = new Error().stack.split('\n').at(0).match(
            /^[^@]*@(.*):\d+:\d+$/);

        expect(writer_func).toHaveBeenCalledOnceWith(
            GLib.LogLevelFlags.LEVEL_MESSAGE,
            objectContainingLogMessage('Trace', DEFAULT_LOG_DOMAIN, {
                CODE_FILE: decodedStringMatching(currentFile),
            },
            message => matchStackTrace(message, 'testConsole'))
        );

        writer_func.calls.reset();
    });

    describe('clear()', function () {
        it('can be called', function () {
            console.clear();
        });

        it('resets indentation', function () {
            console.group('a group');
            expectLog('a group');
            console.log('a log');
            expectLog('  a log');
            console.clear();
            console.log('a log');
            expectLog('a log');
        });
    });

    describe('table()', function () {
        it('logs at least something', function () {
            console.table(['title', 1, 2, 3]);
            expectLog(/title/);
        });
    });

    // %s - string
    // %d or %i - integer
    // %f - float
    // %o  - "optimal" object formatting
    // %O - "generic" object formatting
    // %c - "CSS" formatting (unimplemented by GJS)
    describe('string replacement', function () {
        const functions = {
            log: GLib.LogLevelFlags.LEVEL_MESSAGE,
            warn: GLib.LogLevelFlags.LEVEL_WARNING,
            info: GLib.LogLevelFlags.LEVEL_INFO,
            error: GLib.LogLevelFlags.LEVEL_CRITICAL,
            trace: GLib.LogLevelFlags.LEVEL_MESSAGE,
        };

        Object.entries(functions).forEach(([fn, level]) => {
            it(`console.${fn}() supports %s`, function () {
                console[fn]('Does this %s substitute correctly?', 'modifier');
                expectLog('Does this modifier substitute correctly?', level);
            });

            it(`console.${fn}() supports %d`, function () {
                console[fn]('Does this %d substitute correctly?', 10);
                expectLog('Does this 10 substitute correctly?', level);
            });

            it(`console.${fn}() supports %i`, function () {
                console[fn]('Does this %i substitute correctly?', 26);
                expectLog('Does this 26 substitute correctly?', level);
            });

            it(`console.${fn}() supports %f`, function () {
                console[fn]('Does this %f substitute correctly?', 27.56331);
                expectLog('Does this 27.56331 substitute correctly?', level);
            });

            it(`console.${fn}() supports %o`, function () {
                console[fn]('Does this %o substitute correctly?', new Error());
                expectLog(/Does this Error\n.*substitute correctly\?/s, level);
            });

            it(`console.${fn}() supports %O`, function () {
                console[fn]('Does this %O substitute correctly?', new Error());
                expectLog('Does this {} substitute correctly?', level);
            });

            it(`console.${fn}() ignores %c`, function () {
                console[fn]('Does this %c substitute correctly?', 'modifier');
                expectLog('Does this  substitute correctly?', level);
            });

            it(`console.${fn}() supports mixing substitutions`, function () {
                console[fn](
                    'Does this %s and the %f substitute correctly alongside %d?',
                    'string',
                    3.14,
                    14
                );
                expectLog(
                    'Does this string and the 3.14 substitute correctly alongside 14?',
                    level
                );
            });

            it(`console.${fn}() supports invalid numbers`, function () {
                console[fn](
                    'Does this support parsing %i incorrectly?',
                    'a string'
                );
                expectLog('Does this support parsing NaN incorrectly?', level);
            });

            it(`console.${fn}() supports missing substitutions`, function () {
                console[fn]('Does this support a missing %s substitution?');
                expectLog(
                    'Does this support a missing %s substitution?',
                    level
                );
            });
        });
    });

    describe('time()', function () {
        it('ends correctly', function (done) {
            console.time('testing time');

            // console.time logs nothing.
            expect(writer_func).not.toHaveBeenCalled();

            setTimeout(() => {
                console.timeLog('testing time');

                expectLog(/testing time: (.*)ms/);

                console.timeEnd('testing time');

                expectLog(/testing time: (.*)ms/);

                console.timeLog('testing time');

                expectLog(
                    "No time log found for label: 'testing time'.",
                    GLib.LogLevelFlags.LEVEL_WARNING
                );

                done();
            }, 10);
        });

        it("doesn't log initially", function (done) {
            console.time('testing time');

            // console.time logs nothing.
            expect(writer_func).not.toHaveBeenCalled();

            setTimeout(() => {
                console.timeEnd('testing time');
                expectLog(/testing time: (.*)ms/);

                done();
            }, 10);
        });

        afterEach(function () {
            // Ensure we only got the log lines that we expected
            expect(writer_func).not.toHaveBeenCalled();
        });
    });
});