Debian Codegraph @

src/testlib/cockpittest.c

raw
1 /*
2 * Copyright (C) 2014 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 #include "config.h"
7
8 #include "cockpittest.h"
9
10 #include "common/cockpitconf.h"
11
12 #include <glib-object.h>
13 #include <json-glib/json-glib.h>
14
15 #include <net/if.h>
16 #include <netinet/in.h>
17 #include <netinet/ip6.h>
18 #include <ifaddrs.h>
19
20 /*
21 * HACK: We can't yet use g_test_expect_message() and friends.
22 * They were pretty broken until GLib 2.40 if you have any debug
23 * or info messages ... which we do.
24 *
25 * https://bugzilla.gnome.org/show_bug.cgi?id=661926
26 */
27
28 static gboolean cockpit_test_init_was_called = FALSE;
29 static const gchar *orig_g_debug;
30
31 /* In cockpitconf.c */
32 extern const gchar *cockpit_config_file;
33
34 G_LOCK_DEFINE (expected);
35
36 typedef struct {
37 gchar *log_domain;
38 GLogLevelFlags log_level;
39 gchar *pattern;
40 const gchar *file;
41 int line;
42 const gchar *func;
43 gboolean skipable;
44 gboolean optional;
45 } ExpectedMessage;
46
47 static void
48 expected_message_free (gpointer data)
49 {
50 ExpectedMessage *expected = data;
51 g_free (expected->log_domain);
52 g_free (expected->pattern);
53 g_free (expected);
54 }
55
56 static gint ignore_fatal_count = 0;
57 static GSList *expected_messages = NULL;
58 static GLogFunc gtest_default_log_handler = NULL;
59
60 static const gchar *
61 calc_prefix (gint level)
62 {
63 switch (level)
64 {
65 case G_LOG_LEVEL_ERROR:
66 return "ERROR";
67 case G_LOG_LEVEL_CRITICAL:
68 return "CRITICAL";
69 case G_LOG_LEVEL_WARNING:
70 return "WARNING";
71 case G_LOG_LEVEL_MESSAGE:
72 return "Message";
73 case G_LOG_LEVEL_INFO:
74 return "INFO";
75 case G_LOG_LEVEL_DEBUG:
76 return "DEBUG";
77 default:
78 return "Unknown";
79 }
80 }
81
82 static gboolean
83 expected_fatal_handler (const gchar *log_domain,
84 GLogLevelFlags log_level,
85 const gchar *message,
86 gpointer user_data)
87 {
88 gboolean ret = TRUE;
89
90 if (log_level & G_LOG_FLAG_FATAL)
91 {
92 G_LOCK (expected);
93
94 if (ignore_fatal_count > 0)
95 {
96 ignore_fatal_count--;
97 ret = FALSE;
98 }
99
100 G_UNLOCK (expected);
101 }
102
103 return ret;
104 }
105
106 static void
107 expected_message_handler (const gchar *log_domain,
108 GLogLevelFlags log_level,
109 const gchar *message,
110 gpointer user_data)
111 {
112 gint level = log_level & G_LOG_LEVEL_MASK;
113 ExpectedMessage *expected = NULL;
114 GSList *l = NULL;
115 gchar *expected_message;
116 gboolean skip = FALSE;
117
118 G_LOCK (expected);
119
120 if (level && expected_messages &&
121 (level & G_LOG_LEVEL_DEBUG) == 0)
122 {
123 if (log_level & G_LOG_FLAG_FATAL)
124 {
125 ignore_fatal_count = 1;
126
127 /* This handler is reset for each test, so set it right before we need it */
128 g_test_log_set_fatal_handler (expected_fatal_handler, NULL);
129 }
130
131 /* Loop until we find a non-skipable message or have a match */
132 for (l = expected_messages; l != NULL; l = l->next)
133 {
134 expected = l->data;
135 if (g_strcmp0 (expected->log_domain, log_domain) == 0 &&
136 ((log_level & expected->log_level) == expected->log_level) &&
137 g_pattern_match_simple (expected->pattern, message))
138 {
139 expected_messages = g_slist_delete_link (expected_messages, l);
140 expected_message_free (expected);
141 skip = TRUE;
142 break;
143 }
144 else if (!expected->skipable)
145 {
146 break;
147 }
148 }
149 }
150
151 G_UNLOCK (expected);
152
153 if (skip)
154 return;
155
156 gtest_default_log_handler (log_domain, log_level, message, NULL);
157
158 if (expected)
159 {
160 expected_message = g_strdup_printf ("Got unexpected message: %s instead of %s-%s: %s",
161 message,
162 expected->log_domain,
163 calc_prefix (expected->log_level),
164 expected->pattern);
165 g_assertion_message (expected->log_domain, expected->file, expected->line,
166 expected->func, expected_message);
167 g_free (expected_message);
168 }
169 }
170
171 /**
172 * cockpit_test_init:
173 *
174 * Call this instead of g_test_init() to setup a cocpit test.
175 * Enables use of cockpit_expect_xxx() functions.
176 *
177 * Sets up cleaner logging during testing.
178 *
179 * Also calls g_test_init() for you.
180 */
181 void
182 cockpit_test_init (int *argc,
183 char ***argv)
184 {
185 static gchar path[4096];
186 gchar *basename;
187
188 signal (SIGPIPE, SIG_IGN);
189
190 cockpit_test_setenv ("GIO_USE_VFS", "local");
191 cockpit_test_setenv ("GSETTINGS_BACKEND", "memory");
192 cockpit_test_setenv ("GIO_USE_PROXY_RESOLVER", "dummy");
193
194 g_assert (g_snprintf (path, sizeof (path), "%s:%s", BUILDDIR, g_getenv ("PATH")) < sizeof (path));
195 cockpit_test_setenv ("PATH", path);
196
197 /* For our process (children are handled through $G_DEBUG) */
198 g_log_set_always_fatal (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING);
199
200 // System cockpit configuration file should not be loaded
201 cockpit_config_file = NULL;
202
203 if (*argc > 0)
204 {
205 basename = g_path_get_basename ((*argv)[0]);
206 g_set_prgname (basename);
207 g_free (basename);
208 }
209
210 g_test_init (argc, argv, NULL);
211
212 /* Chain to the gtest log handler */
213 gtest_default_log_handler = g_log_set_default_handler (expected_message_handler, NULL);
214 g_assert (gtest_default_log_handler != NULL);
215
216 cockpit_test_init_was_called = TRUE;
217 }
218
219 void
220 _cockpit_expect_logged_msg (const char *domain,
221 const gchar *file,
222 int line,
223 const gchar *func,
224 GLogLevelFlags log_level,
225 const gchar *pattern,
226 gboolean skipable,
227 gboolean optional)
228 {
229 ExpectedMessage *expected;
230
231 g_assert (cockpit_test_init_was_called);
232
233 g_return_if_fail (log_level != 0);
234 g_return_if_fail (pattern != NULL);
235 g_return_if_fail (~log_level & G_LOG_LEVEL_ERROR);
236 g_return_if_fail (log_level & G_LOG_LEVEL_MASK);
237
238 expected = g_new (ExpectedMessage, 1);
239 expected->log_domain = g_strdup (domain);
240 expected->log_level = log_level & G_LOG_LEVEL_MASK;
241 expected->pattern = g_strdup (pattern);
242 expected->file = file;
243 expected->line = line;
244 expected->func = func;
245 expected->skipable = optional ? TRUE : skipable;
246 expected->optional = optional;
247
248 G_LOCK (expected);
249 expected_messages = g_slist_append (expected_messages, expected);
250 G_UNLOCK (expected);
251 }
252
253 /**
254 * cockpit_assert_expected:
255 *
256 * Assert that all the things we were expecting in a test
257 * happened. This should be called in a teardown() function
258 * or after a cockpit_expect_xxx() function.
259 */
260 void
261 cockpit_assert_expected (void)
262 {
263 ExpectedMessage *expected = NULL;
264 gchar *message = NULL;
265 GSList *l = NULL;
266 g_assert (cockpit_test_init_was_called);
267
268 G_LOCK (expected);
269
270 if (expected_messages)
271 {
272 for (l = expected_messages; l != NULL; l = l->next)
273 {
274 expected = l->data;
275 if (!expected->optional)
276 {
277 message = g_strdup_printf ("Did not see expected %s-%s: %s",
278 expected->log_domain,
279 calc_prefix (expected->log_level),
280 expected->pattern);
281 break;
282 }
283 }
284 }
285
286 G_UNLOCK (expected);
287
288 if (message)
289 {
290 g_assertion_message (expected->log_domain, expected->file, expected->line,
291 expected->func, message);
292 g_free (message);
293 }
294
295 g_slist_free_full (expected_messages, expected_message_free);
296 expected_messages = NULL;
297 ignore_fatal_count = 0;
298 }
299
300 /**
301 * cockpit_assert_strmatch:
302 * @str: the string
303 * @pattern: to match
304 *
305 * Checks that @str matches the wildcard style @pattern
306 */
307 void
308 _cockpit_assert_strmatch_msg (const char *domain,
309 const char *file,
310 int line,
311 const char *func,
312 const gchar *string,
313 const gchar *pattern)
314 {
315 const gchar *suffix;
316 gchar *escaped;
317 gchar *msg;
318 int len;
319
320 if (!string || !g_pattern_match_simple (pattern, string))
321 {
322 escaped = g_strescape (pattern, "");
323 if (!string)
324 {
325 msg = g_strdup_printf ("'%s' does not match: (null)", escaped);
326 }
327 else
328 {
329 suffix = "";
330 len = strlen (string);
331
332 /* To avoid insane output */
333 if (len > 8192)
334 {
335 len = 8192;
336 suffix = "\n...\n";
337 }
338
339 msg = g_strdup_printf ("'%s' does not match: %.*s%s", escaped, len, string, suffix);
340 }
341 g_assertion_message (domain, file, line, func, msg);
342 g_free (escaped);
343 g_free (msg);
344 }
345 }
346
347 void
348 _cockpit_assert_json_eq_msg (const char *domain,
349 const char *file,
350 int line,
351 const char *func,
352 gpointer object_or_array,
353 const gchar *expect)
354 {
355 GError *error = NULL;
356 JsonParser *parser;
357 JsonNode *node;
358 JsonNode *exnode;
359
360 if (expect[0] == '[')
361 {
362 node = json_node_new (JSON_NODE_ARRAY);
363 json_node_set_array (node, object_or_array);
364 }
365 else
366 {
367 node = json_node_new (JSON_NODE_OBJECT);
368 json_node_set_object (node, object_or_array);
369 }
370
371 parser = json_parser_new ();
372 if (!json_parser_load_from_data (parser, expect, -1, &error))
373 {
374 g_assertion_message_error (domain, file, line, func, "error", error, 0, 0);
375 g_object_unref (parser);
376 json_node_free (node);
377 return;
378 }
379
380 exnode = json_parser_get_root (parser);
381 g_assert (exnode);
382
383 if (!json_node_equal (exnode, node))
384 {
385 JsonGenerator *generator = json_generator_new ();
386 json_generator_set_root (generator, node);
387 gchar *escaped = json_generator_to_data (generator, NULL);
388 g_object_unref (generator);
389
390 gchar *msg = g_strdup_printf ("%s != %s", escaped, expect);
391 g_assertion_message (domain, file, line, func, msg);
392 g_free (escaped);
393 g_free (msg);
394 }
395 g_object_unref (parser);
396 json_node_free (node);
397 }
398
399 void
400 _cockpit_assert_gvariant_eq_msg (const char *domain,
401 const char *file,
402 int line,
403 const char *func,
404 GVariant *actual,
405 const gchar *expected)
406 {
407 GVariant *expected_variant = g_variant_parse (NULL, expected, NULL, NULL, NULL);
408 if (!g_variant_equal (actual, expected_variant))
409 {
410 gchar *actual_string = g_variant_print (actual, TRUE);
411 gchar *msg = g_strdup_printf ("%s != %s", actual_string, expected);
412 g_assertion_message (domain, file, line, func, msg);
413 g_free (msg);
414 g_free (actual_string);
415 }
416 g_variant_unref (expected_variant);
417 }
418
419 static gchar *
420 test_escape_data (const guchar *data,
421 gssize n_data)
422 {
423 static const char HEXC[] = "0123456789ABCDEF";
424 GString *result;
425 gchar c;
426 gsize i;
427 guchar j;
428
429 if (!data)
430 return g_strdup ("NULL");
431
432 result = g_string_sized_new (n_data * 2 + 1);
433 for (i = 0; i < n_data; ++i)
434 {
435 c = data[i];
436 if (g_ascii_isprint (c) && !strchr ("\n\r\v", c))
437 {
438 g_string_append_c (result, c);
439 }
440 else
441 {
442 g_string_append (result, "\\x");
443 j = c >> 4 & 0xf;
444 g_string_append_c (result, HEXC[j]);
445 j = c & 0xf;
446 g_string_append_c (result, HEXC[j]);
447 }
448 }
449
450 return g_string_free (result, FALSE);
451 }
452
453 void
454 _cockpit_assert_data_eq_msg (const char *domain,
455 const char *file,
456 int line,
457 const char *func,
458 gconstpointer data,
459 gssize len,
460 gconstpointer expect,
461 gssize exp_len)
462 {
463 char *a1, *a2, *s;
464 if (!data && !expect)
465 return;
466 if (len < 0)
467 len = strlen (data ?: "");
468 if (exp_len < 0)
469 exp_len = strlen (expect ?: "");
470
471 if (len == exp_len)
472 {
473 if (len == 0)
474 return;
475 else if (data && expect && memcmp (data, expect, len) == 0)
476 return;
477 }
478
479 a1 = test_escape_data (data, len);
480 a2 = test_escape_data (expect, exp_len);
481 s = g_strdup_printf ("data is not the same (%s != %s)", a1, a2);
482 g_free (a1);
483 g_free (a2);
484 g_assertion_message (domain, file, line, func, s);
485 g_free (s);
486 }
487
488 void
489 _cockpit_assert_bytes_eq_msg (const char *domain,
490 const char *file,
491 int line,
492 const char *func,
493 GBytes *data,
494 gconstpointer expect,
495 gssize exp_len)
496 {
497 _cockpit_assert_data_eq_msg (domain, file, line, func,
498 g_bytes_get_data (data, NULL),
499 g_bytes_get_size (data),
500 expect, exp_len);
501 }
502
503 GInetAddress *
504 cockpit_test_find_non_loopback_address (void)
505 {
506 GInetAddress *inet = NULL;
507 struct ifaddrs *ifas, *ifa;
508 gpointer bytes;
509
510 g_assert_cmpint (getifaddrs (&ifas), ==, 0);
511 for (ifa = ifas; ifa != NULL; ifa = ifa->ifa_next)
512 {
513 if (!(ifa->ifa_flags & IFF_UP))
514 continue;
515 if (ifa->ifa_addr == NULL)
516 continue;
517 if (ifa->ifa_addr->sa_family == AF_INET)
518 {
519 bytes = &(((struct sockaddr_in *)ifa->ifa_addr)->sin_addr);
520 inet = g_inet_address_new_from_bytes (bytes, G_SOCKET_FAMILY_IPV4);
521 }
522 else if (ifa->ifa_addr->sa_family == AF_INET6)
523 {
524 bytes = &(((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr);
525 inet = g_inet_address_new_from_bytes (bytes, G_SOCKET_FAMILY_IPV6);
526 }
527 if (inet)
528 {
529 if (!g_inet_address_get_is_loopback (inet))
530 break;
531 g_object_unref (inet);
532 inet = NULL;
533 }
534 }
535
536 freeifaddrs (ifas);
537 return inet;
538 }
539
540 void
541 cockpit_test_allow_warnings (void)
542 {
543 /* make some noise if this gets called twice */
544 g_return_if_fail (orig_g_debug == NULL);
545 orig_g_debug = g_getenv ("G_DEBUG");
546 cockpit_test_setenv ("G_DEBUG", "fatal-criticals");
547 }
548
549 void
550 cockpit_test_reset_warnings (void)
551 {
552 if (orig_g_debug != NULL)
553 {
554 cockpit_test_setenv ("G_DEBUG", orig_g_debug);
555 orig_g_debug = NULL;
556 }
557 }
558
559 void
560 cockpit_test_setenv (const char *variable,
561 const char *value)
562 {
563 if (!g_setenv (variable, value, TRUE))
564 g_error ("couldn't set $%s", variable);
565 }
566
567 gboolean
568 cockpit_test_skip_slow (void)
569 {
570 if (g_getenv ("COCKPIT_SKIP_SLOW_TESTS"))
571 {
572 g_test_skip ("Skipping slow tests");
573 return TRUE;
574 }
575
576 return FALSE;
577 }
578
579 void
580 cockpit_assertion_message_error_matches (const char *domain,
581 const char *file,
582 int line,
583 const char *func,
584 const char *expr,
585 const GError *error,
586 GQuark error_domain,
587 int error_code,
588 const char *message_pattern)
589 {
590 /* loosely based on g_assertion_message_error() */
591 g_autoptr(GString) gstring = g_string_new ("assertion failed ");
592
593 g_string_append_printf (gstring, "%s =~ GError(", expr);
594
595 if (error_domain)
596 g_string_append_printf (gstring, "domain=%s", g_quark_to_string (error_domain));
597 else
598 g_string_append (gstring, "domain=any");
599
600 g_string_append (gstring, ", ");
601
602 if (error_code != -1)
603 g_string_append_printf (gstring, "code=%d", error_code);
604 else
605 g_string_append (gstring, "code=any");
606
607 g_string_append (gstring, ", ");
608
609 if (message_pattern)
610 g_string_append_printf (gstring, "message=~'%s'", message_pattern);
611 else
612 g_string_append (gstring, "message=any");
613
614 g_string_append (gstring, ")): ");
615
616 if (error)
617 g_string_append_printf (gstring, "%s (%s, %d)", error->message,
618 g_quark_to_string (error->domain), error->code);
619 else
620 g_string_append_printf (gstring, "%s is NULL", expr);
621
622 g_assertion_message (domain, file, line, func, gstring->str);
623 }