summaryrefslogtreecommitdiff
path: root/libgweather/tests/test_libgweather.c
blob: 47f238900113ab2aa345ddf8895b48bdc103a696 (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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
/* test_libgweather.c: Test suite for libgweather
 *
 * SPDX-FileCopyrightText: 2017 Bastien Nocera <hadess@hadess.net>
 * SPDX-License-Identifier: LGPL-2.0-or-later
 */

#include "config.h"

#include <glib.h>
#include <glib/gstdio.h>
#include <libsoup/soup.h>
#include <locale.h>
#include <string.h>

#include <libgweather/gweather.h>

#include "gweather-test-utils.h"

#include "gweather-private.h"

/* For test_metar_weather_stations */
#define METAR_SOURCES "https://www.aviationweather.gov/docs/metar/stations.txt"

/* Maximum for test_airport_distance_sanity() */
#define TOO_FAR 100.0
static double max_distance = 0.0;

static void
test_no_code_serialize (void)
{
    GVariant *variant;
    g_autoptr (GWeatherLocation) world = NULL;
    g_autoptr (GWeatherLocation) loc = NULL;
    g_autoptr (GWeatherLocation) new_loc = NULL;
    GString *str;

    world = gweather_location_get_world ();
    g_assert_nonnull (world);

    loc = gweather_location_find_nearest_city (world, 56.833333, 53.183333);
    g_assert_nonnull (loc);
    g_assert_cmpstr (gweather_location_get_name (loc), ==, "Izhevsk");
    g_assert_null (gweather_location_get_code (loc));

    variant = gweather_location_serialize (loc);
    g_assert_nonnull (variant);
    str = g_variant_print_string (variant, NULL, TRUE);
    g_test_message ("variant: %s", str->str);
    g_string_free (str, TRUE);

    new_loc = gweather_location_deserialize (world, variant);
    g_variant_unref (variant);
    g_assert_nonnull (new_loc);
    g_assert_cmpstr (gweather_location_get_name (loc), ==, gweather_location_get_name (new_loc));
    g_assert_true (gweather_location_equal (loc, new_loc));

    g_clear_object (&world);
    g_clear_object (&loc);
    g_clear_pointer (&new_loc, g_object_unref);

    gweather_test_reset_world ();
}

static void
test_distance (GWeatherLocation *location)
{
    g_autoptr (GWeatherLocation) parent = NULL;
    double distance;

    parent = gweather_location_get_parent (location);
    if (gweather_location_get_level (parent) < GWEATHER_LOCATION_CITY)
        return;
    distance = gweather_location_get_distance (location, parent);

    if (distance > TOO_FAR) {
        g_test_message ("Airport '%s' is too far from city '%s' (%.1lf km)\n",
                        gweather_location_get_name (location),
                        gweather_location_get_name (parent),
                        distance);
        max_distance = MAX (max_distance, distance);
        g_test_fail ();
    }
}

static void
test_airport_distance_children (GWeatherLocation *location)
{
    g_autoptr (GWeatherLocation) child = NULL;

    while ((child = gweather_location_next_child (location, child)) != NULL) {
        if (gweather_location_get_level (child) == GWEATHER_LOCATION_WEATHER_STATION)
            test_distance (child);
        else
            test_airport_distance_children (child);
    }
}

static void
test_airport_distance_sanity (void)
{
    g_autoptr (GWeatherLocation) world = NULL;

    world = gweather_location_get_world ();
    g_assert_nonnull (world);

    test_airport_distance_children (world);

    if (g_test_failed ())
        g_warning ("Maximum city to airport distance is %.1f km", max_distance);

    g_clear_object (&world);

    gweather_test_reset_world ();
}

static GHashTable *
parse_metar_stations (const char *contents)
{
    GHashTable *stations_ht;
    char **lines;
    guint i, num_stations;

    stations_ht = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
    num_stations = 0;
    lines = g_strsplit (contents, "\n", -1);

    for (i = 0; lines[i] != NULL; i++) {
        char *line = lines[i];
        char *station;

        if (line[0] == '!')
            continue;

        if (strlen (line) != 83)
            continue;

        station = g_strndup (line + 20, 4);
        /* Skip stations with no ICAO code */
        if (g_str_equal (station, "    ")) {
            g_free (station);
            continue;
        }

        if (g_hash_table_lookup (stations_ht, station)) {
            const char * const known_duplicates[] = {
                "VOGO",
                "KHQG",
                "KOEL",
                "KTQK",
                "KX26",
                NULL
            };
            if (g_strv_contains (known_duplicates, station)) {
                g_free (station);
                continue;
            }
            g_test_message ("Weather station '%s' already defined\n", station);
        }

        g_hash_table_insert (stations_ht, station, g_strdup (line));
        num_stations++;
    }

    g_strfreev (lines);

    /* Duplicates? */
    g_assert_cmpuint (num_stations, ==, g_hash_table_size (stations_ht));

    g_test_message ("Parsed %u weather stations", num_stations);

    return stations_ht;
}

static void
test_metar_weather_station (GWeatherLocation *location,
                            GHashTable *stations_ht)
{
    const char *code, *line;

    code = gweather_location_get_code (location);
    g_assert_nonnull (code);

    line = g_hash_table_lookup (stations_ht, code);
    if (!line) {
        g_test_message ("Could not find airport for '%s' in " METAR_SOURCES "\n", code);
        g_test_fail ();
    } else {
        char *has_metar;

        has_metar = g_strndup (line + 62, 1);
        if (*has_metar == 'Z') {
            g_test_message ("Airport weather station '%s' is obsolete\n", code);
            g_test_fail ();
        } else if (*has_metar == ' ') {
            g_test_message ("Could not find weather station for '%s' in " METAR_SOURCES "\n", code);
            g_test_fail ();
        }
        g_free (has_metar);
    }
}

static void
test_metar_weather_stations_children (GWeatherLocation *location,
                                      GHashTable *stations_ht)
{
    g_autoptr (GWeatherLocation) child = NULL;

    while ((child = gweather_location_next_child (location, child)) != NULL) {
        if (gweather_location_get_level (child) == GWEATHER_LOCATION_WEATHER_STATION)
            test_metar_weather_station (child, stations_ht);
        else
            test_metar_weather_stations_children (child, stations_ht);
    }
}

static void
test_metar_weather_stations (void)
{
    g_autoptr (GWeatherLocation) world = NULL;
    SoupMessage *msg;
    SoupSession *session;
    GHashTable *stations_ht;
    char *contents;
#if SOUP_CHECK_VERSION(2, 99, 2)
    GBytes *body;
    GError *error = NULL;
    gsize bsize;
#endif

    world = gweather_location_get_world ();
    g_assert_nonnull (world);

    msg = soup_message_new ("GET", METAR_SOURCES);
    session = soup_session_new ();
#if SOUP_CHECK_VERSION(2, 99, 2)
    body = soup_session_send_and_read (session, msg, NULL, &error);
    if (error && error->domain == G_TLS_ERROR) {
#else
    soup_session_send_message (session, msg);
    if (msg->status_code == SOUP_STATUS_SSL_FAILED) {
#endif
        g_test_message ("SSL/TLS failure, please check your glib-networking installation");
        g_test_failed ();
        return;
    }
#if SOUP_CHECK_VERSION(2, 99, 2)
    g_assert_no_error (error);
    g_assert_cmpint (soup_message_get_status (msg), >=, 200);
    g_assert_cmpint (soup_message_get_status (msg), <, 300);
    g_assert_nonnull (body);
    contents = g_bytes_unref_to_data (body, &bsize);
#else
    g_assert_cmpint (msg->status_code, >=, 200);
    g_assert_cmpint (msg->status_code, <, 300);
    g_assert_nonnull (msg->response_body);
    contents = g_strndup (msg->response_body->data, msg->response_body->length);
#endif
    g_object_unref (session);
    g_object_unref (msg);

    stations_ht = parse_metar_stations (contents);
    g_assert_nonnull (stations_ht);
    g_free (contents);

    test_metar_weather_stations_children (world, stations_ht);

    g_hash_table_unref (stations_ht);

    g_clear_object (&world);

    gweather_test_reset_world ();
}

static void
test_utc_sunset (void)
{
    g_autoptr (GWeatherLocation) world = NULL;
    g_autoptr (GWeatherLocation) utc = NULL;
    GWeatherInfo *info;
    char *sunset;
    GWeatherMoonPhase phase;
    GWeatherMoonLatitude lat;
    gboolean ret;

    world = gweather_location_get_world ();
    g_assert_nonnull (world);
    utc = gweather_location_find_by_station_code (world, "@UTC");
    g_assert_nonnull (utc);

    info = gweather_info_new (utc);
    gweather_info_set_enabled_providers (info, GWEATHER_PROVIDER_NONE);
    gweather_info_update (info);

    sunset = gweather_info_get_sunset (info);
    g_assert_nonnull (sunset);
    g_free (sunset);

    ret = gweather_info_get_value_moonphase (info, &phase, &lat);
    g_assert_false (ret);

    g_object_unref (info);

    g_clear_object (&world);
    g_clear_object (&utc);

    gweather_test_reset_world ();
}

static void
test_location_names (void)
{
    g_autoptr (GWeatherLocation) world = NULL;
    g_autoptr (GWeatherLocation) brussels = NULL;
    char *old_locale;

    world = gweather_location_get_world ();
    g_assert_nonnull (world);

    brussels = gweather_location_find_nearest_city (world, 50.833333, 4.333333);
    g_assert_nonnull (brussels);
    g_assert_cmpstr (gweather_location_get_name (brussels), ==, "Brussels");
    g_assert_cmpstr (gweather_location_get_sort_name (brussels), ==, "brussels");
    g_assert_cmpstr (gweather_location_get_english_name (brussels), ==, "Brussels");

    old_locale = setlocale (LC_ALL, "fr_FR.UTF-8");
    if (old_locale == NULL) {
        g_test_skip ("Locale fr_FR.UTF-8 is not available");
        return;
    }

    g_clear_object (&world);
    g_clear_object (&brussels);
    gweather_test_reset_world ();

    world = gweather_location_get_world ();
    g_assert_nonnull (world);

    brussels = gweather_location_find_nearest_city (world, 50.833333, 4.333333);
    g_assert_nonnull (brussels);
    g_assert_cmpstr (gweather_location_get_name (brussels), ==, "Bruxelles");
    g_assert_cmpstr (gweather_location_get_sort_name (brussels), ==, "bruxelles");
    g_assert_cmpstr (gweather_location_get_english_name (brussels), ==, "Brussels");
    g_clear_object (&brussels);

    g_clear_object (&world);

    setlocale (LC_ALL, old_locale);
    gweather_test_reset_world ();
}

static gboolean
find_loc_children (GWeatherLocation *location,
                   const char *search_str,
                   GWeatherLocation **ret)
{
    g_autoptr (GWeatherLocation) child = NULL;
    while ((child = gweather_location_next_child (location, child)) != NULL) {
        if (gweather_location_get_level (child) == GWEATHER_LOCATION_WEATHER_STATION) {
            const char *code;

            code = gweather_location_get_code (child);
            if (g_strcmp0 (search_str, code) == 0) {
                *ret = g_object_ref (child);
                return TRUE;
            }
        } else {
            if (find_loc_children (child, search_str, ret))
                return TRUE;
        }
    }

    return FALSE;
}

static GWeatherLocation *
find_loc (GWeatherLocation *world,
          const char *search_str)
{
    GWeatherLocation *loc = NULL;

    find_loc_children (world, search_str, &loc);
    return loc;
}

static void
weather_updated (GWeatherInfo *info,
                 GMainLoop *loop)
{
    g_assert_not_reached ();
}

static gboolean
stop_loop_cb (gpointer user_data)
{
    g_main_loop_quit (user_data);
    return G_SOURCE_REMOVE;
}

static void
test_weather_loop_use_after_free (void)
{
    GMainLoop *loop;
    g_autoptr (GWeatherLocation) world = NULL;
    GWeatherLocation *loc;
    GWeatherInfo *info;
    const char *search_str = "LFLL";

    world = gweather_location_get_world ();
    loc = find_loc (world, search_str);

    if (!loc) {
        g_test_message ("Could not find station for %s", search_str);
        g_test_failed ();
        return;
    }

    g_test_message ("Found station %s for '%s'", gweather_location_get_name (loc), search_str);

    loop = g_main_loop_new (NULL, TRUE);
    info = gweather_info_new (NULL);
    gweather_info_set_application_id (info, "org.gnome.LibGWeather");
    gweather_info_set_contact_info (info, "https://gitlab.gnome.org/GNOME/libgweather/");
    gweather_info_set_enabled_providers (info,
                                         GWEATHER_PROVIDER_METAR |
                                             GWEATHER_PROVIDER_IWIN |
                                             GWEATHER_PROVIDER_MET_NO |
                                             GWEATHER_PROVIDER_OWM);
    gweather_info_set_location (info, loc);
    g_signal_connect (G_OBJECT (info), "updated", G_CALLBACK (weather_updated), loop);
    gweather_info_update (info);
    g_object_unref (info);

    g_object_unref (loc);

    g_timeout_add_seconds (5, stop_loop_cb, loop);
    g_main_loop_run (loop);
    g_main_loop_unref (loop);
}

static void
test_walk_world (void)
{
    g_autoptr (GWeatherLocation) cur = NULL, next = NULL;
    gint visited = 0;

    next = gweather_location_get_world ();
    while (next) {
        /* Update cur pointer. */
        g_clear_object (&cur);

        cur = g_steal_pointer (&next);
        visited += 1;

        /* Select next item, which is in this order:
	     *  1. The first child
	     *  2. Walk up the parent tree and try to find a sibbling
	     * Note that cur remains valid after the loop and points to the world
	     * again.
	     */
        if ((next = gweather_location_next_child (cur, NULL)))
            continue;

        while (TRUE) {
            g_autoptr (GWeatherLocation) child = NULL;

            /* Move cur to the parent, keeping the child as reference. */
            child = g_steal_pointer (&cur);
            cur = gweather_location_get_parent (child);
            if (!cur)
                break;

            if ((next = gweather_location_next_child (cur, g_object_ref (child))))
                break;
        }
    }

    /* cur must be NULL at this point */
    g_assert_null (cur);

    /* Check that we visited a reasonable number of nodes.
     * Due to implicit nearest nodes, this needs to be more than the number
     * of DB entries. */
    cur = gweather_location_get_world ();
    g_assert_cmpint (visited, >, cur->db->locations->len);
    g_clear_object (&cur);

    /* noop, but asserts we did not leak */
    gweather_test_reset_world ();
}

static void
test_radians_to_degrees_str (void)
{
    char long_version[G_ASCII_DTOSTR_BUF_SIZE];
    g_autofree char *short_version = NULL;
    double coord = 1.260765526077;

    g_ascii_dtostr (long_version, G_ASCII_DTOSTR_BUF_SIZE, RADIANS_TO_DEGREES (coord));
    short_version = _radians_to_degrees_str (coord);

    g_assert_cmpint (strlen (long_version), >, strlen (short_version));
    g_assert_cmpstr (short_version, ==, "72.2365");
}

int
main (int argc, char *argv[])
{
    setlocale (LC_ALL, "");

    g_test_init (&argc, &argv, NULL);
    g_test_bug_base ("http://gitlab.gnome.org/GNOME/libgweather/issues/");

    g_autofree char *schemas_dir = gweather_test_setup_gsettings ();

    g_test_add_func ("/weather/radians-to-degrees_str", test_radians_to_degrees_str);
    g_test_add_func ("/weather/no-code-serialize", test_no_code_serialize);
    g_test_add_func ("/weather/airport_distance_sanity", test_airport_distance_sanity);
    g_test_add_func ("/weather/metar_weather_stations", test_metar_weather_stations);
    g_test_add_func ("/weather/utc_sunset", test_utc_sunset);
    g_test_add_func ("/weather/weather-loop-use-after-free", test_weather_loop_use_after_free);
    g_test_add_func ("/weather/location-names", test_location_names);
    g_test_add_func ("/weather/walk_world", test_walk_world);

    int res = g_test_run ();

    gweather_test_teardown_gsettings (schemas_dir);

    return res;
}