Imported Upstream version 2.66.8
[platform/upstream/glib.git] / gio / tests / file.c
1 #include <string.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <gio/gio.h>
5 #include <gio/gfiledescriptorbased.h>
6 #ifdef G_OS_UNIX
7 #include <sys/stat.h>
8 #endif
9
10 static void
11 test_basic_for_file (GFile       *file,
12                      const gchar *suffix)
13 {
14   gchar *s;
15
16   s = g_file_get_basename (file);
17   g_assert_cmpstr (s, ==, "testfile");
18   g_free (s);
19
20   s = g_file_get_uri (file);
21   g_assert_true (g_str_has_prefix (s, "file://"));
22   g_assert_true (g_str_has_suffix (s, suffix));
23   g_free (s);
24
25   g_assert_true (g_file_has_uri_scheme (file, "file"));
26   s = g_file_get_uri_scheme (file);
27   g_assert_cmpstr (s, ==, "file");
28   g_free (s);
29 }
30
31 static void
32 test_basic (void)
33 {
34   GFile *file;
35
36   file = g_file_new_for_path ("./some/directory/testfile");
37   test_basic_for_file (file, "/some/directory/testfile");
38   g_object_unref (file);
39 }
40
41 static void
42 test_build_filename (void)
43 {
44   GFile *file;
45
46   file = g_file_new_build_filename (".", "some", "directory", "testfile", NULL);
47   test_basic_for_file (file, "/some/directory/testfile");
48   g_object_unref (file);
49
50   file = g_file_new_build_filename ("testfile", NULL);
51   test_basic_for_file (file, "/testfile");
52   g_object_unref (file);
53 }
54
55 static void
56 test_parent (void)
57 {
58   GFile *file;
59   GFile *file2;
60   GFile *parent;
61   GFile *root;
62
63   file = g_file_new_for_path ("./some/directory/testfile");
64   file2 = g_file_new_for_path ("./some/directory");
65   root = g_file_new_for_path ("/");
66
67   g_assert_true (g_file_has_parent (file, file2));
68
69   parent = g_file_get_parent (file);
70   g_assert_true (g_file_equal (parent, file2));
71   g_object_unref (parent);
72
73   g_assert_null (g_file_get_parent (root));
74
75   g_object_unref (file);
76   g_object_unref (file2);
77   g_object_unref (root);
78 }
79
80 static void
81 test_child (void)
82 {
83   GFile *file;
84   GFile *child;
85   GFile *child2;
86
87   file = g_file_new_for_path ("./some/directory");
88   child = g_file_get_child (file, "child");
89   g_assert_true (g_file_has_parent (child, file));
90
91   child2 = g_file_get_child_for_display_name (file, "child2", NULL);
92   g_assert_true (g_file_has_parent (child2, file));
93
94   g_object_unref (child);
95   g_object_unref (child2);
96   g_object_unref (file);
97 }
98
99 static void
100 test_type (void)
101 {
102   GFile *datapath_f;
103   GFile *file;
104   GFileType type;
105   GError *error = NULL;
106
107   datapath_f = g_file_new_for_path (g_test_get_dir (G_TEST_DIST));
108
109   file = g_file_get_child (datapath_f, "g-icon.c");
110   type = g_file_query_file_type (file, 0, NULL);
111   g_assert_cmpint (type, ==, G_FILE_TYPE_REGULAR);
112   g_object_unref (file);
113
114   file = g_file_get_child (datapath_f, "cert-tests");
115   type = g_file_query_file_type (file, 0, NULL);
116   g_assert_cmpint (type, ==, G_FILE_TYPE_DIRECTORY);
117
118   g_file_read (file, NULL, &error);
119   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_IS_DIRECTORY);
120   g_error_free (error);
121   g_object_unref (file);
122
123   g_object_unref (datapath_f);
124 }
125
126 static void
127 test_parse_name (void)
128 {
129   GFile *file;
130   gchar *name;
131
132   file = g_file_new_for_uri ("file://somewhere");
133   name = g_file_get_parse_name (file);
134   g_assert_cmpstr (name, ==, "file://somewhere");
135   g_object_unref (file);
136   g_free (name);
137
138   file = g_file_parse_name ("~foo");
139   name = g_file_get_parse_name (file);
140   g_assert_nonnull (name);
141   g_object_unref (file);
142   g_free (name);
143 }
144
145 typedef struct
146 {
147   GMainContext *context;
148   GFile *file;
149   GFileMonitor *monitor;
150   GOutputStream *ostream;
151   GInputStream *istream;
152   gint buffersize;
153   gint monitor_created;
154   gint monitor_deleted;
155   gint monitor_changed;
156   gchar *monitor_path;
157   gint pos;
158   const gchar *data;
159   gchar *buffer;
160   guint timeout;
161   gboolean file_deleted;
162   gboolean timed_out;
163 } CreateDeleteData;
164
165 static void
166 monitor_changed (GFileMonitor      *monitor,
167                  GFile             *file,
168                  GFile             *other_file,
169                  GFileMonitorEvent  event_type,
170                  gpointer           user_data)
171 {
172   CreateDeleteData *data = user_data;
173   gchar *path;
174   const gchar *peeked_path;
175
176   path = g_file_get_path (file);
177   peeked_path = g_file_peek_path (file);
178   g_assert_cmpstr (data->monitor_path, ==, path);
179   g_assert_cmpstr (path, ==, peeked_path);
180   g_free (path);
181
182   if (event_type == G_FILE_MONITOR_EVENT_CREATED)
183     data->monitor_created++;
184   if (event_type == G_FILE_MONITOR_EVENT_DELETED)
185     data->monitor_deleted++;
186   if (event_type == G_FILE_MONITOR_EVENT_CHANGED)
187     data->monitor_changed++;
188
189   g_main_context_wakeup (data->context);
190 }
191
192 static void
193 iclosed_cb (GObject      *source,
194             GAsyncResult *res,
195             gpointer      user_data)
196 {
197   CreateDeleteData *data = user_data;
198   GError *error;
199   gboolean ret;
200
201   error = NULL;
202   ret = g_input_stream_close_finish (data->istream, res, &error);
203   g_assert_no_error (error);
204   g_assert_true (ret);
205
206   g_assert_true (g_input_stream_is_closed (data->istream));
207
208   ret = g_file_delete (data->file, NULL, &error);
209   g_assert_true (ret);
210   g_assert_no_error (error);
211
212   data->file_deleted = TRUE;
213   g_main_context_wakeup (data->context);
214 }
215
216 static void
217 read_cb (GObject      *source,
218          GAsyncResult *res,
219          gpointer      user_data)
220 {
221   CreateDeleteData *data = user_data;
222   GError *error;
223   gssize size;
224
225   error = NULL;
226   size = g_input_stream_read_finish (data->istream, res, &error);
227   g_assert_no_error (error);
228
229   data->pos += size;
230   if (data->pos < strlen (data->data))
231     {
232       g_input_stream_read_async (data->istream,
233                                  data->buffer + data->pos,
234                                  strlen (data->data) - data->pos,
235                                  0,
236                                  NULL,
237                                  read_cb,
238                                  data);
239     }
240   else
241     {
242       g_assert_cmpstr (data->buffer, ==, data->data);
243       g_assert_false (g_input_stream_is_closed (data->istream));
244       g_input_stream_close_async (data->istream, 0, NULL, iclosed_cb, data);
245     }
246 }
247
248 static void
249 ipending_cb (GObject      *source,
250              GAsyncResult *res,
251              gpointer      user_data)
252 {
253   CreateDeleteData *data = user_data;
254   GError *error;
255
256   error = NULL;
257   g_input_stream_read_finish (data->istream, res, &error);
258   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_PENDING);
259   g_error_free (error);
260 }
261
262 static void
263 skipped_cb (GObject      *source,
264             GAsyncResult *res,
265             gpointer      user_data)
266 {
267   CreateDeleteData *data = user_data;
268   GError *error;
269   gssize size;
270
271   error = NULL;
272   size = g_input_stream_skip_finish (data->istream, res, &error);
273   g_assert_no_error (error);
274   g_assert_cmpint (size, ==, data->pos);
275
276   g_input_stream_read_async (data->istream,
277                              data->buffer + data->pos,
278                              strlen (data->data) - data->pos,
279                              0,
280                              NULL,
281                              read_cb,
282                              data);
283   /* check that we get a pending error */
284   g_input_stream_read_async (data->istream,
285                              data->buffer + data->pos,
286                              strlen (data->data) - data->pos,
287                              0,
288                              NULL,
289                              ipending_cb,
290                              data);
291 }
292
293 static void
294 opened_cb (GObject      *source,
295            GAsyncResult *res,
296            gpointer      user_data)
297 {
298   GFileInputStream *base;
299   CreateDeleteData *data = user_data;
300   GError *error;
301
302   error = NULL;
303   base = g_file_read_finish (data->file, res, &error);
304   g_assert_no_error (error);
305
306   if (data->buffersize == 0)
307     data->istream = G_INPUT_STREAM (g_object_ref (base));
308   else
309     data->istream = g_buffered_input_stream_new_sized (G_INPUT_STREAM (base), data->buffersize);
310   g_object_unref (base);
311
312   data->buffer = g_new0 (gchar, strlen (data->data) + 1);
313
314   /* copy initial segment directly, then skip */
315   memcpy (data->buffer, data->data, 10);
316   data->pos = 10;
317
318   g_input_stream_skip_async (data->istream,
319                              10,
320                              0,
321                              NULL,
322                              skipped_cb,
323                              data);
324 }
325
326 static void
327 oclosed_cb (GObject      *source,
328             GAsyncResult *res,
329             gpointer      user_data)
330 {
331   CreateDeleteData *data = user_data;
332   GError *error;
333   gboolean ret;
334
335   error = NULL;
336   ret = g_output_stream_close_finish (data->ostream, res, &error);
337   g_assert_no_error (error);
338   g_assert_true (ret);
339   g_assert_true (g_output_stream_is_closed (data->ostream));
340
341   g_file_read_async (data->file, 0, NULL, opened_cb, data);
342 }
343
344 static void
345 written_cb (GObject      *source,
346             GAsyncResult *res,
347             gpointer      user_data)
348 {
349   CreateDeleteData *data = user_data;
350   gssize size;
351   GError *error;
352
353   error = NULL;
354   size = g_output_stream_write_finish (data->ostream, res, &error);
355   g_assert_no_error (error);
356
357   data->pos += size;
358   if (data->pos < strlen (data->data))
359     {
360       g_output_stream_write_async (data->ostream,
361                                    data->data + data->pos,
362                                    strlen (data->data) - data->pos,
363                                    0,
364                                    NULL,
365                                    written_cb,
366                                    data);
367     }
368   else
369     {
370       g_assert_false (g_output_stream_is_closed (data->ostream));
371       g_output_stream_close_async (data->ostream, 0, NULL, oclosed_cb, data);
372     }
373 }
374
375 static void
376 opending_cb (GObject      *source,
377              GAsyncResult *res,
378              gpointer      user_data)
379 {
380   CreateDeleteData *data = user_data;
381   GError *error;
382
383   error = NULL;
384   g_output_stream_write_finish (data->ostream, res, &error);
385   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_PENDING);
386   g_error_free (error);
387 }
388
389 static void
390 created_cb (GObject      *source,
391             GAsyncResult *res,
392             gpointer      user_data)
393 {
394   GFileOutputStream *base;
395   CreateDeleteData *data = user_data;
396   GError *error;
397
398   error = NULL;
399   base = g_file_create_finish (G_FILE (source), res, &error);
400   g_assert_no_error (error);
401   g_assert_true (g_file_query_exists (data->file, NULL));
402
403   if (data->buffersize == 0)
404     data->ostream = G_OUTPUT_STREAM (g_object_ref (base));
405   else
406     data->ostream = g_buffered_output_stream_new_sized (G_OUTPUT_STREAM (base), data->buffersize);
407   g_object_unref (base);
408
409   g_output_stream_write_async (data->ostream,
410                                data->data,
411                                strlen (data->data),
412                                0,
413                                NULL,
414                                written_cb,
415                                data);
416   /* check that we get a pending error */
417   g_output_stream_write_async (data->ostream,
418                                data->data,
419                                strlen (data->data),
420                                0,
421                                NULL,
422                                opending_cb,
423                                data);
424 }
425
426 static gboolean
427 stop_timeout (gpointer user_data)
428 {
429   CreateDeleteData *data = user_data;
430
431   data->timed_out = TRUE;
432   g_main_context_wakeup (data->context);
433
434   return G_SOURCE_REMOVE;
435 }
436
437 /*
438  * This test does a fully async create-write-read-delete.
439  * Callbackistan.
440  */
441 static void
442 test_create_delete (gconstpointer d)
443 {
444   GError *error;
445   CreateDeleteData *data;
446   GFileIOStream *iostream;
447
448   data = g_new0 (CreateDeleteData, 1);
449
450   data->buffersize = GPOINTER_TO_INT (d);
451   data->data = "abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVXYZ0123456789";
452   data->pos = 0;
453
454   data->file = g_file_new_tmp ("g_file_create_delete_XXXXXX",
455                                &iostream, NULL);
456   g_assert_nonnull (data->file);
457   g_object_unref (iostream);
458
459   data->monitor_path = g_file_get_path (data->file);
460   remove (data->monitor_path);
461
462   g_assert_false (g_file_query_exists (data->file, NULL));
463
464   error = NULL;
465   data->monitor = g_file_monitor_file (data->file, 0, NULL, &error);
466   g_assert_no_error (error);
467
468   /* This test doesn't work with GPollFileMonitor, because it assumes
469    * that the monitor will notice a create immediately followed by a
470    * delete, rather than coalescing them into nothing.
471    */
472   /* This test also doesn't work with GKqueueFileMonitor because of
473    * the same reason. Kqueue is able to return a kevent when a file is
474    * created or deleted in a directory. However, the kernel doesn't tell
475    * the program file names, so GKqueueFileMonitor has to calculate the
476    * difference itself. This is usually too slow for rapid file creation
477    * and deletion tests.
478    */
479   if (strcmp (G_OBJECT_TYPE_NAME (data->monitor), "GPollFileMonitor") == 0 ||
480       strcmp (G_OBJECT_TYPE_NAME (data->monitor), "GKqueueFileMonitor") == 0)
481     {
482       g_test_skip ("skipping test for this GFileMonitor implementation");
483       goto skip;
484     }
485
486   g_file_monitor_set_rate_limit (data->monitor, 100);
487
488   g_signal_connect (data->monitor, "changed", G_CALLBACK (monitor_changed), data);
489
490   /* Use the global default main context */
491   data->context = NULL;
492   data->timeout = g_timeout_add_seconds (10, stop_timeout, data);
493
494   g_file_create_async (data->file, 0, 0, NULL, created_cb, data);
495
496   while (!data->timed_out &&
497          (data->monitor_created == 0 ||
498           data->monitor_deleted == 0 ||
499           data->monitor_changed == 0 ||
500           !data->file_deleted))
501     g_main_context_iteration (data->context, TRUE);
502
503   g_source_remove (data->timeout);
504
505   g_assert_false (data->timed_out);
506   g_assert_true (data->file_deleted);
507   g_assert_cmpint (data->monitor_created, ==, 1);
508   g_assert_cmpint (data->monitor_deleted, ==, 1);
509   g_assert_cmpint (data->monitor_changed, >, 0);
510
511   g_assert_false (g_file_monitor_is_cancelled (data->monitor));
512   g_file_monitor_cancel (data->monitor);
513   g_assert_true (g_file_monitor_is_cancelled (data->monitor));
514
515   g_clear_pointer (&data->context, g_main_context_unref);
516   g_object_unref (data->ostream);
517   g_object_unref (data->istream);
518
519  skip:
520   g_object_unref (data->monitor);
521   g_object_unref (data->file);
522   g_free (data->monitor_path);
523   g_free (data->buffer);
524   g_free (data);
525 }
526
527 static const gchar *original_data =
528     "/**\n"
529     " * g_file_replace_contents_async:\n"
530     "**/\n";
531
532 static const gchar *replace_data =
533     "/**\n"
534     " * g_file_replace_contents_async:\n"
535     " * @file: input #GFile.\n"
536     " * @contents: string of contents to replace the file with.\n"
537     " * @length: the length of @contents in bytes.\n"
538     " * @etag: (nullable): a new <link linkend=\"gfile-etag\">entity tag</link> for the @file, or %NULL\n"
539     " * @make_backup: %TRUE if a backup should be created.\n"
540     " * @flags: a set of #GFileCreateFlags.\n"
541     " * @cancellable: optional #GCancellable object, %NULL to ignore.\n"
542     " * @callback: a #GAsyncReadyCallback to call when the request is satisfied\n"
543     " * @user_data: the data to pass to callback function\n"
544     " * \n"
545     " * Starts an asynchronous replacement of @file with the given \n"
546     " * @contents of @length bytes. @etag will replace the document's\n"
547     " * current entity tag.\n"
548     " * \n"
549     " * When this operation has completed, @callback will be called with\n"
550     " * @user_user data, and the operation can be finalized with \n"
551     " * g_file_replace_contents_finish().\n"
552     " * \n"
553     " * If @cancellable is not %NULL, then the operation can be cancelled by\n"
554     " * triggering the cancellable object from another thread. If the operation\n"
555     " * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned. \n"
556     " * \n"
557     " * If @make_backup is %TRUE, this function will attempt to \n"
558     " * make a backup of @file.\n"
559     " **/\n";
560
561 typedef struct
562 {
563   GFile *file;
564   const gchar *data;
565   GMainLoop *loop;
566   gboolean again;
567 } ReplaceLoadData;
568
569 static void replaced_cb (GObject      *source,
570                          GAsyncResult *res,
571                          gpointer      user_data);
572
573 static void
574 loaded_cb (GObject      *source,
575            GAsyncResult *res,
576            gpointer      user_data)
577 {
578   ReplaceLoadData *data = user_data;
579   gboolean ret;
580   GError *error;
581   gchar *contents;
582   gsize length;
583
584   error = NULL;
585   ret = g_file_load_contents_finish (data->file, res, &contents, &length, NULL, &error);
586   g_assert_true (ret);
587   g_assert_no_error (error);
588   g_assert_cmpint (length, ==, strlen (data->data));
589   g_assert_cmpstr (contents, ==, data->data);
590
591   g_free (contents);
592
593   if (data->again)
594     {
595       data->again = FALSE;
596       data->data = "pi pa po";
597
598       g_file_replace_contents_async (data->file,
599                                      data->data,
600                                      strlen (data->data),
601                                      NULL,
602                                      FALSE,
603                                      0,
604                                      NULL,
605                                      replaced_cb,
606                                      data);
607     }
608   else
609     {
610        error = NULL;
611        ret = g_file_delete (data->file, NULL, &error);
612        g_assert_no_error (error);
613        g_assert_true (ret);
614        g_assert_false (g_file_query_exists (data->file, NULL));
615
616        g_main_loop_quit (data->loop);
617     }
618 }
619
620 static void
621 replaced_cb (GObject      *source,
622              GAsyncResult *res,
623              gpointer      user_data)
624 {
625   ReplaceLoadData *data = user_data;
626   GError *error;
627
628   error = NULL;
629   g_file_replace_contents_finish (data->file, res, NULL, &error);
630   g_assert_no_error (error);
631
632   g_file_load_contents_async (data->file, NULL, loaded_cb, data);
633 }
634
635 static void
636 test_replace_load (void)
637 {
638   ReplaceLoadData *data;
639   const gchar *path;
640   GFileIOStream *iostream;
641
642   data = g_new0 (ReplaceLoadData, 1);
643   data->again = TRUE;
644   data->data = replace_data;
645
646   data->file = g_file_new_tmp ("g_file_replace_load_XXXXXX",
647                                &iostream, NULL);
648   g_assert_nonnull (data->file);
649   g_object_unref (iostream);
650
651   path = g_file_peek_path (data->file);
652   remove (path);
653
654   g_assert_false (g_file_query_exists (data->file, NULL));
655
656   data->loop = g_main_loop_new (NULL, FALSE);
657
658   g_file_replace_contents_async (data->file,
659                                  data->data,
660                                  strlen (data->data),
661                                  NULL,
662                                  FALSE,
663                                  0,
664                                  NULL,
665                                  replaced_cb,
666                                  data);
667
668   g_main_loop_run (data->loop);
669
670   g_main_loop_unref (data->loop);
671   g_object_unref (data->file);
672   g_free (data);
673 }
674
675 static void
676 test_replace_cancel (void)
677 {
678   GFile *tmpdir, *file;
679   GFileOutputStream *ostream;
680   GFileEnumerator *fenum;
681   GFileInfo *info;
682   GCancellable *cancellable;
683   gchar *path;
684   gchar *contents;
685   gsize nwrote, length;
686   guint count;
687   GError *error = NULL;
688
689   g_test_bug ("https://bugzilla.gnome.org/629301");
690
691   path = g_dir_make_tmp ("g_file_replace_cancel_XXXXXX", &error);
692   g_assert_no_error (error);
693   tmpdir = g_file_new_for_path (path);
694   g_free (path);
695
696   file = g_file_get_child (tmpdir, "file");
697   g_file_replace_contents (file,
698                            original_data,
699                            strlen (original_data),
700                            NULL, FALSE, 0, NULL,
701                            NULL, &error);
702   g_assert_no_error (error);
703
704   ostream = g_file_replace (file, NULL, TRUE, 0, NULL, &error);
705   g_assert_no_error (error);
706
707   g_output_stream_write_all (G_OUTPUT_STREAM (ostream),
708                              replace_data, strlen (replace_data),
709                              &nwrote, NULL, &error);
710   g_assert_no_error (error);
711   g_assert_cmpint (nwrote, ==, strlen (replace_data));
712
713   /* At this point there should be two files; the original and the
714    * temporary.
715    */
716   fenum = g_file_enumerate_children (tmpdir, NULL, 0, NULL, &error);
717   g_assert_no_error (error);
718
719   info = g_file_enumerator_next_file (fenum, NULL, &error);
720   g_assert_no_error (error);
721   g_assert_nonnull (info);
722   g_object_unref (info);
723   info = g_file_enumerator_next_file (fenum, NULL, &error);
724   g_assert_no_error (error);
725   g_assert_nonnull (info);
726   g_object_unref (info);
727
728   g_file_enumerator_close (fenum, NULL, &error);
729   g_assert_no_error (error);
730   g_object_unref (fenum);
731
732   /* Also test the g_file_enumerator_iterate() API */
733   fenum = g_file_enumerate_children (tmpdir, NULL, 0, NULL, &error);
734   g_assert_no_error (error);
735   count = 0;
736
737   while (TRUE)
738     {
739       gboolean ret = g_file_enumerator_iterate (fenum, &info, NULL, NULL, &error);
740       g_assert_true (ret);
741       g_assert_no_error (error);
742       if (!info)
743         break;
744       count++;
745     }
746   g_assert_cmpint (count, ==, 2);
747
748   g_file_enumerator_close (fenum, NULL, &error);
749   g_assert_no_error (error);
750   g_object_unref (fenum);
751
752   /* Now test just getting child from the g_file_enumerator_iterate() API */
753   fenum = g_file_enumerate_children (tmpdir, "standard::name", 0, NULL, &error);
754   g_assert_no_error (error);
755   count = 0;
756
757   while (TRUE)
758     {
759       GFile *child;
760       gboolean ret = g_file_enumerator_iterate (fenum, NULL, &child, NULL, &error);
761
762       g_assert_true (ret);
763       g_assert_no_error (error);
764
765       if (!child)
766         break;
767
768       g_assert_true (G_IS_FILE (child));
769       count++;
770     }
771   g_assert_cmpint (count, ==, 2);
772
773   g_file_enumerator_close (fenum, NULL, &error);
774   g_assert_no_error (error);
775   g_object_unref (fenum);
776
777   /* Make sure the temporary gets deleted even if we cancel. */
778   cancellable = g_cancellable_new ();
779   g_cancellable_cancel (cancellable);
780   g_output_stream_close (G_OUTPUT_STREAM (ostream), cancellable, &error);
781   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_CANCELLED);
782   g_clear_error (&error);
783
784   g_object_unref (cancellable);
785   g_object_unref (ostream);
786
787   /* Make sure that file contents wasn't actually replaced. */
788   g_file_load_contents (file,
789                         NULL,
790                         &contents,
791                         &length,
792                         NULL,
793                         &error);
794   g_assert_no_error (error);
795   g_assert_cmpstr (contents, ==, original_data);
796   g_free (contents);
797
798   g_file_delete (file, NULL, &error);
799   g_assert_no_error (error);
800   g_object_unref (file);
801
802   /* This will only succeed if the temp file was deleted. */
803   g_file_delete (tmpdir, NULL, &error);
804   g_assert_no_error (error);
805   g_object_unref (tmpdir);
806 }
807
808 static void
809 test_replace_symlink (void)
810 {
811 #ifdef G_OS_UNIX
812   gchar *tmpdir_path = NULL;
813   GFile *tmpdir = NULL, *source_file = NULL, *target_file = NULL;
814   GFileOutputStream *stream = NULL;
815   const gchar *new_contents = "this is a test message which should be written to source and not target";
816   gsize n_written;
817   GFileEnumerator *enumerator = NULL;
818   GFileInfo *info = NULL;
819   gchar *contents = NULL;
820   gsize length = 0;
821   GError *local_error = NULL;
822
823   g_test_bug ("https://gitlab.gnome.org/GNOME/glib/-/issues/2325");
824   g_test_summary ("Test that G_FILE_CREATE_REPLACE_DESTINATION doesn’t follow symlinks");
825
826   /* Create a fresh, empty working directory. */
827   tmpdir_path = g_dir_make_tmp ("g_file_replace_symlink_XXXXXX", &local_error);
828   g_assert_no_error (local_error);
829   tmpdir = g_file_new_for_path (tmpdir_path);
830
831   g_test_message ("Using temporary directory %s", tmpdir_path);
832   g_free (tmpdir_path);
833
834   /* Create symlink `source` which points to `target`. */
835   source_file = g_file_get_child (tmpdir, "source");
836   target_file = g_file_get_child (tmpdir, "target");
837   g_file_make_symbolic_link (source_file, "target", NULL, &local_error);
838   g_assert_no_error (local_error);
839
840   /* Ensure that `target` doesn’t exist */
841   g_assert_false (g_file_query_exists (target_file, NULL));
842
843   /* Replace the `source` symlink with a regular file using
844    * %G_FILE_CREATE_REPLACE_DESTINATION, which should replace it *without*
845    * following the symlink */
846   stream = g_file_replace (source_file, NULL, FALSE  /* no backup */,
847                            G_FILE_CREATE_REPLACE_DESTINATION, NULL, &local_error);
848   g_assert_no_error (local_error);
849
850   g_output_stream_write_all (G_OUTPUT_STREAM (stream), new_contents, strlen (new_contents),
851                              &n_written, NULL, &local_error);
852   g_assert_no_error (local_error);
853   g_assert_cmpint (n_written, ==, strlen (new_contents));
854
855   g_output_stream_close (G_OUTPUT_STREAM (stream), NULL, &local_error);
856   g_assert_no_error (local_error);
857
858   g_clear_object (&stream);
859
860   /* At this point, there should still only be one file: `source`. It should
861    * now be a regular file. `target` should not exist. */
862   enumerator = g_file_enumerate_children (tmpdir,
863                                           G_FILE_ATTRIBUTE_STANDARD_NAME ","
864                                           G_FILE_ATTRIBUTE_STANDARD_TYPE,
865                                           G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, NULL, &local_error);
866   g_assert_no_error (local_error);
867
868   info = g_file_enumerator_next_file (enumerator, NULL, &local_error);
869   g_assert_no_error (local_error);
870   g_assert_nonnull (info);
871
872   g_assert_cmpstr (g_file_info_get_name (info), ==, "source");
873   g_assert_cmpint (g_file_info_get_file_type (info), ==, G_FILE_TYPE_REGULAR);
874
875   g_clear_object (&info);
876
877   info = g_file_enumerator_next_file (enumerator, NULL, &local_error);
878   g_assert_no_error (local_error);
879   g_assert_null (info);
880
881   g_file_enumerator_close (enumerator, NULL, &local_error);
882   g_assert_no_error (local_error);
883   g_clear_object (&enumerator);
884
885   /* Double-check that `target` doesn’t exist */
886   g_assert_false (g_file_query_exists (target_file, NULL));
887
888   /* Check the content of `source`. */
889   g_file_load_contents (source_file,
890                         NULL,
891                         &contents,
892                         &length,
893                         NULL,
894                         &local_error);
895   g_assert_no_error (local_error);
896   g_assert_cmpstr (contents, ==, new_contents);
897   g_assert_cmpuint (length, ==, strlen (new_contents));
898   g_free (contents);
899
900   /* Tidy up. */
901   g_file_delete (source_file, NULL, &local_error);
902   g_assert_no_error (local_error);
903
904   g_file_delete (tmpdir, NULL, &local_error);
905   g_assert_no_error (local_error);
906
907   g_clear_object (&target_file);
908   g_clear_object (&source_file);
909   g_clear_object (&tmpdir);
910 #else  /* if !G_OS_UNIX */
911   g_test_skip ("Symlink replacement tests can only be run on Unix")
912 #endif
913 }
914
915 static void
916 on_file_deleted (GObject      *object,
917                  GAsyncResult *result,
918                  gpointer      user_data)
919 {
920   GError *local_error = NULL;
921   GMainLoop *loop = user_data;
922
923   (void) g_file_delete_finish ((GFile*)object, result, &local_error);
924   g_assert_no_error (local_error);
925
926   g_main_loop_quit (loop);
927 }
928
929 static void
930 test_async_delete (void)
931 {
932   GFile *file;
933   GFileIOStream *iostream;
934   GError *local_error = NULL;
935   GError **error = &local_error;
936   GMainLoop *loop;
937
938   file = g_file_new_tmp ("g_file_delete_XXXXXX",
939                          &iostream, error);
940   g_assert_no_error (local_error);
941   g_object_unref (iostream);
942
943   g_assert_true (g_file_query_exists (file, NULL));
944
945   loop = g_main_loop_new (NULL, TRUE);
946
947   g_file_delete_async (file, G_PRIORITY_DEFAULT, NULL, on_file_deleted, loop);
948
949   g_main_loop_run (loop);
950
951   g_assert_false (g_file_query_exists (file, NULL));
952
953   g_main_loop_unref (loop);
954   g_object_unref (file);
955 }
956
957 static void
958 test_copy_preserve_mode (void)
959 {
960 #ifdef G_OS_UNIX
961   mode_t current_umask = umask (0);
962   const struct
963     {
964       guint32 source_mode;
965       guint32 expected_destination_mode;
966       gboolean create_destination_before_copy;
967       GFileCopyFlags copy_flags;
968     }
969   vectors[] =
970     {
971       /* Overwriting the destination file should copy the permissions from the
972        * source file, even if %G_FILE_COPY_ALL_METADATA is set: */
973       { 0600, 0600, TRUE, G_FILE_COPY_OVERWRITE | G_FILE_COPY_NOFOLLOW_SYMLINKS | G_FILE_COPY_ALL_METADATA },
974       { 0600, 0600, TRUE, G_FILE_COPY_OVERWRITE | G_FILE_COPY_NOFOLLOW_SYMLINKS },
975       /* The same behaviour should hold if the destination file is not being
976        * overwritten because it doesn’t already exist: */
977       { 0600, 0600, FALSE, G_FILE_COPY_NOFOLLOW_SYMLINKS | G_FILE_COPY_ALL_METADATA },
978       { 0600, 0600, FALSE, G_FILE_COPY_NOFOLLOW_SYMLINKS },
979       /* Anything with %G_FILE_COPY_TARGET_DEFAULT_PERMS should use the current
980        * umask for the destination file: */
981       { 0600, 0666 & ~current_umask, TRUE, G_FILE_COPY_TARGET_DEFAULT_PERMS | G_FILE_COPY_OVERWRITE | G_FILE_COPY_NOFOLLOW_SYMLINKS | G_FILE_COPY_ALL_METADATA },
982       { 0600, 0666 & ~current_umask, TRUE, G_FILE_COPY_TARGET_DEFAULT_PERMS | G_FILE_COPY_OVERWRITE | G_FILE_COPY_NOFOLLOW_SYMLINKS },
983       { 0600, 0666 & ~current_umask, FALSE, G_FILE_COPY_TARGET_DEFAULT_PERMS | G_FILE_COPY_NOFOLLOW_SYMLINKS | G_FILE_COPY_ALL_METADATA },
984       { 0600, 0666 & ~current_umask, FALSE, G_FILE_COPY_TARGET_DEFAULT_PERMS | G_FILE_COPY_NOFOLLOW_SYMLINKS },
985     };
986   gsize i;
987
988   /* Reset the umask after querying it above. There’s no way to query it without
989    * changing it. */
990   umask (current_umask);
991   g_test_message ("Current umask: %u", current_umask);
992
993   for (i = 0; i < G_N_ELEMENTS (vectors); i++)
994     {
995       GFile *tmpfile;
996       GFile *dest_tmpfile;
997       GFileInfo *dest_info;
998       GFileIOStream *iostream;
999       GError *local_error = NULL;
1000       guint32 romode = vectors[i].source_mode;
1001       guint32 dest_mode;
1002
1003       g_test_message ("Vector %" G_GSIZE_FORMAT, i);
1004
1005       tmpfile = g_file_new_tmp ("tmp-copy-preserve-modeXXXXXX",
1006                                 &iostream, &local_error);
1007       g_assert_no_error (local_error);
1008       g_io_stream_close ((GIOStream*)iostream, NULL, &local_error);
1009       g_assert_no_error (local_error);
1010       g_clear_object (&iostream);
1011
1012       g_file_set_attribute (tmpfile, G_FILE_ATTRIBUTE_UNIX_MODE, G_FILE_ATTRIBUTE_TYPE_UINT32,
1013                             &romode, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
1014                             NULL, &local_error);
1015       g_assert_no_error (local_error);
1016
1017       dest_tmpfile = g_file_new_tmp ("tmp-copy-preserve-modeXXXXXX",
1018                                      &iostream, &local_error);
1019       g_assert_no_error (local_error);
1020       g_io_stream_close ((GIOStream*)iostream, NULL, &local_error);
1021       g_assert_no_error (local_error);
1022       g_clear_object (&iostream);
1023
1024       if (!vectors[i].create_destination_before_copy)
1025         {
1026           g_file_delete (dest_tmpfile, NULL, &local_error);
1027           g_assert_no_error (local_error);
1028         }
1029
1030       g_file_copy (tmpfile, dest_tmpfile, vectors[i].copy_flags,
1031                    NULL, NULL, NULL, &local_error);
1032       g_assert_no_error (local_error);
1033
1034       dest_info = g_file_query_info (dest_tmpfile, G_FILE_ATTRIBUTE_UNIX_MODE, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
1035                                      NULL, &local_error);
1036       g_assert_no_error (local_error);
1037
1038       dest_mode = g_file_info_get_attribute_uint32 (dest_info, G_FILE_ATTRIBUTE_UNIX_MODE);
1039
1040       g_assert_cmpint (dest_mode & ~S_IFMT, ==, vectors[i].expected_destination_mode);
1041       g_assert_cmpint (dest_mode & S_IFMT, ==, S_IFREG);
1042
1043       (void) g_file_delete (tmpfile, NULL, NULL);
1044       (void) g_file_delete (dest_tmpfile, NULL, NULL);
1045
1046       g_clear_object (&tmpfile);
1047       g_clear_object (&dest_tmpfile);
1048       g_clear_object (&dest_info);
1049     }
1050 #else  /* if !G_OS_UNIX */
1051   g_test_skip ("File permissions tests can only be run on Unix")
1052 #endif
1053 }
1054
1055 static gchar *
1056 splice_to_string (GInputStream   *stream,
1057                   GError        **error)
1058 {
1059   GMemoryOutputStream *buffer = NULL;
1060   char *ret = NULL;
1061
1062   buffer = (GMemoryOutputStream*)g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
1063   if (g_output_stream_splice ((GOutputStream*)buffer, stream, 0, NULL, error) < 0)
1064     goto out;
1065
1066   if (!g_output_stream_write ((GOutputStream*)buffer, "\0", 1, NULL, error))
1067     goto out;
1068
1069   if (!g_output_stream_close ((GOutputStream*)buffer, NULL, error))
1070     goto out;
1071
1072   ret = g_memory_output_stream_steal_data (buffer);
1073  out:
1074   g_clear_object (&buffer);
1075   return ret;
1076 }
1077
1078 static gboolean
1079 get_size_from_du (const gchar *path, guint64 *size)
1080 {
1081   GSubprocess *du;
1082   gboolean ok;
1083   gchar *result;
1084   gchar *endptr;
1085   GError *error = NULL;
1086   gchar *du_path = NULL;
1087
1088   /* If we can’t find du, don’t try and run the test. */
1089   du_path = g_find_program_in_path ("du");
1090   if (du_path == NULL)
1091     return FALSE;
1092   g_free (du_path);
1093
1094   du = g_subprocess_new (G_SUBPROCESS_FLAGS_STDOUT_PIPE,
1095                          &error,
1096                          "du", "--bytes", "-s", path, NULL);
1097   g_assert_no_error (error);
1098
1099   result = splice_to_string (g_subprocess_get_stdout_pipe (du), &error);
1100   g_assert_no_error (error);
1101
1102   *size = g_ascii_strtoll (result, &endptr, 10);
1103
1104   g_subprocess_wait (du, NULL, &error);
1105   g_assert_no_error (error);
1106
1107   ok = g_subprocess_get_successful (du);
1108
1109   g_object_unref (du);
1110   g_free (result);
1111
1112   return ok;
1113 }
1114
1115 static void
1116 test_measure (void)
1117 {
1118   GFile *file;
1119   guint64 size;
1120   guint64 num_bytes;
1121   guint64 num_dirs;
1122   guint64 num_files;
1123   GError *error = NULL;
1124   gboolean ok;
1125   gchar *path;
1126
1127   path = g_test_build_filename (G_TEST_DIST, "desktop-files", NULL);
1128   file = g_file_new_for_path (path);
1129
1130   if (!get_size_from_du (path, &size))
1131     {
1132       g_test_message ("du not found or fail to run, skipping byte measurement");
1133       size = 0;
1134     }
1135
1136   ok = g_file_measure_disk_usage (file,
1137                                   G_FILE_MEASURE_APPARENT_SIZE,
1138                                   NULL,
1139                                   NULL,
1140                                   NULL,
1141                                   &num_bytes,
1142                                   &num_dirs,
1143                                   &num_files,
1144                                   &error);
1145   g_assert_true (ok);
1146   g_assert_no_error (error);
1147
1148   if (size > 0)
1149     g_assert_cmpuint (num_bytes, ==, size);
1150   g_assert_cmpuint (num_dirs, ==, 6);
1151   g_assert_cmpuint (num_files, ==, 32);
1152
1153   g_object_unref (file);
1154   g_free (path);
1155 }
1156
1157 typedef struct {
1158   guint64 expected_bytes;
1159   guint64 expected_dirs;
1160   guint64 expected_files;
1161   gint progress_count;
1162   guint64 progress_bytes;
1163   guint64 progress_dirs;
1164   guint64 progress_files;
1165 } MeasureData;
1166
1167 static void
1168 measure_progress (gboolean reporting,
1169                   guint64  current_size,
1170                   guint64  num_dirs,
1171                   guint64  num_files,
1172                   gpointer user_data)
1173 {
1174   MeasureData *data = user_data;
1175
1176   data->progress_count += 1;
1177
1178   g_assert_cmpuint (current_size, >=, data->progress_bytes);
1179   g_assert_cmpuint (num_dirs, >=, data->progress_dirs);
1180   g_assert_cmpuint (num_files, >=, data->progress_files);
1181
1182   data->progress_bytes = current_size;
1183   data->progress_dirs = num_dirs;
1184   data->progress_files = num_files;
1185 }
1186
1187 static void
1188 measure_done (GObject      *source,
1189               GAsyncResult *res,
1190               gpointer      user_data)
1191 {
1192   MeasureData *data = user_data;
1193   guint64 num_bytes, num_dirs, num_files;
1194   GError *error = NULL;
1195   gboolean ok;
1196
1197   ok = g_file_measure_disk_usage_finish (G_FILE (source), res, &num_bytes, &num_dirs, &num_files, &error);
1198   g_assert_true (ok);
1199   g_assert_no_error (error);
1200
1201   if (data->expected_bytes > 0)
1202     g_assert_cmpuint (data->expected_bytes, ==, num_bytes);
1203   g_assert_cmpuint (data->expected_dirs, ==, num_dirs);
1204   g_assert_cmpuint (data->expected_files, ==, num_files);
1205
1206   g_assert_cmpuint (data->progress_count, >, 0);
1207   g_assert_cmpuint (num_bytes, >=, data->progress_bytes);
1208   g_assert_cmpuint (num_dirs, >=, data->progress_dirs);
1209   g_assert_cmpuint (num_files, >=, data->progress_files);
1210
1211   g_free (data);
1212   g_object_unref (source);
1213 }
1214
1215 static void
1216 test_measure_async (void)
1217 {
1218   gchar *path;
1219   GFile *file;
1220   MeasureData *data;
1221
1222   data = g_new (MeasureData, 1);
1223
1224   data->progress_count = 0;
1225   data->progress_bytes = 0;
1226   data->progress_files = 0;
1227   data->progress_dirs = 0;
1228
1229   path = g_test_build_filename (G_TEST_DIST, "desktop-files", NULL);
1230   file = g_file_new_for_path (path);
1231
1232   if (!get_size_from_du (path, &data->expected_bytes))
1233     {
1234       g_test_message ("du not found or fail to run, skipping byte measurement");
1235       data->expected_bytes = 0;
1236     }
1237
1238   g_free (path);
1239
1240   data->expected_dirs = 6;
1241   data->expected_files = 32;
1242
1243   g_file_measure_disk_usage_async (file,
1244                                    G_FILE_MEASURE_APPARENT_SIZE,
1245                                    0, NULL,
1246                                    measure_progress, data,
1247                                    measure_done, data);
1248 }
1249
1250 static void
1251 test_load_bytes (void)
1252 {
1253   gchar filename[] = "g_file_load_bytes_XXXXXX";
1254   GError *error = NULL;
1255   GBytes *bytes;
1256   GFile *file;
1257   int len;
1258   int fd;
1259   int ret;
1260
1261   fd = g_mkstemp (filename);
1262   g_assert_cmpint (fd, !=, -1);
1263   len = strlen ("test_load_bytes");
1264   ret = write (fd, "test_load_bytes", len);
1265   g_assert_cmpint (ret, ==, len);
1266   close (fd);
1267
1268   file = g_file_new_for_path (filename);
1269   bytes = g_file_load_bytes (file, NULL, NULL, &error);
1270   g_assert_no_error (error);
1271   g_assert_nonnull (bytes);
1272   g_assert_cmpint (len, ==, g_bytes_get_size (bytes));
1273   g_assert_cmpstr ("test_load_bytes", ==, (gchar *)g_bytes_get_data (bytes, NULL));
1274
1275   g_file_delete (file, NULL, NULL);
1276
1277   g_bytes_unref (bytes);
1278   g_object_unref (file);
1279 }
1280
1281 typedef struct
1282 {
1283   GMainLoop *main_loop;
1284   GFile *file;
1285   GBytes *bytes;
1286 } LoadBytesAsyncData;
1287
1288 static void
1289 test_load_bytes_cb (GObject      *object,
1290                     GAsyncResult *result,
1291                     gpointer      user_data)
1292 {
1293   GFile *file = G_FILE (object);
1294   LoadBytesAsyncData *data = user_data;
1295   GError *error = NULL;
1296
1297   data->bytes = g_file_load_bytes_finish (file, result, NULL, &error);
1298   g_assert_no_error (error);
1299   g_assert_nonnull (data->bytes);
1300
1301   g_main_loop_quit (data->main_loop);
1302 }
1303
1304 static void
1305 test_load_bytes_async (void)
1306 {
1307   LoadBytesAsyncData data = { 0 };
1308   gchar filename[] = "g_file_load_bytes_XXXXXX";
1309   int len;
1310   int fd;
1311   int ret;
1312
1313   fd = g_mkstemp (filename);
1314   g_assert_cmpint (fd, !=, -1);
1315   len = strlen ("test_load_bytes_async");
1316   ret = write (fd, "test_load_bytes_async", len);
1317   g_assert_cmpint (ret, ==, len);
1318   close (fd);
1319
1320   data.main_loop = g_main_loop_new (NULL, FALSE);
1321   data.file = g_file_new_for_path (filename);
1322
1323   g_file_load_bytes_async (data.file, NULL, test_load_bytes_cb, &data);
1324   g_main_loop_run (data.main_loop);
1325
1326   g_assert_cmpint (len, ==, g_bytes_get_size (data.bytes));
1327   g_assert_cmpstr ("test_load_bytes_async", ==, (gchar *)g_bytes_get_data (data.bytes, NULL));
1328
1329   g_file_delete (data.file, NULL, NULL);
1330   g_object_unref (data.file);
1331   g_bytes_unref (data.bytes);
1332   g_main_loop_unref (data.main_loop);
1333 }
1334
1335 static void
1336 test_writev_helper (GOutputVector *vectors,
1337                     gsize          n_vectors,
1338                     gboolean       use_bytes_written,
1339                     const guint8  *expected_contents,
1340                     gsize          expected_length)
1341 {
1342   GFile *file;
1343   GFileIOStream *iostream = NULL;
1344   GOutputStream *ostream;
1345   GError *error = NULL;
1346   gsize bytes_written = 0;
1347   gboolean res;
1348   guint8 *contents;
1349   gsize length;
1350
1351   file = g_file_new_tmp ("g_file_writev_XXXXXX",
1352                          &iostream, NULL);
1353   g_assert_nonnull (file);
1354   g_assert_nonnull (iostream);
1355
1356   ostream = g_io_stream_get_output_stream (G_IO_STREAM (iostream));
1357
1358   res = g_output_stream_writev_all (ostream, vectors, n_vectors, use_bytes_written ? &bytes_written : NULL, NULL, &error);
1359   g_assert_no_error (error);
1360   g_assert_true (res);
1361   if (use_bytes_written)
1362     g_assert_cmpuint (bytes_written, ==, expected_length);
1363
1364   res = g_io_stream_close (G_IO_STREAM (iostream), NULL, &error);
1365   g_assert_no_error (error);
1366   g_assert_true (res);
1367   g_object_unref (iostream);
1368
1369   res = g_file_load_contents (file, NULL, (gchar **) &contents, &length, NULL, &error);
1370   g_assert_no_error (error);
1371   g_assert_true (res);
1372
1373   g_assert_cmpmem (contents, length, expected_contents, expected_length);
1374
1375   g_free (contents);
1376
1377   g_file_delete (file, NULL, NULL);
1378   g_object_unref (file);
1379 }
1380
1381 /* Test that writev() on local file output streams works on a non-empty vector */
1382 static void
1383 test_writev (void)
1384 {
1385   GOutputVector vectors[3];
1386   const guint8 buffer[] = {1, 2, 3, 4, 5,
1387                            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
1388                            1, 2, 3};
1389
1390   vectors[0].buffer = buffer;
1391   vectors[0].size = 5;
1392
1393   vectors[1].buffer = buffer + 5;
1394   vectors[1].size = 12;
1395
1396   vectors[2].buffer = buffer + 5 + 12;
1397   vectors[2].size = 3;
1398
1399   test_writev_helper (vectors, G_N_ELEMENTS (vectors), TRUE, buffer, sizeof buffer);
1400 }
1401
1402 /* Test that writev() on local file output streams works on a non-empty vector without returning bytes_written */
1403 static void
1404 test_writev_no_bytes_written (void)
1405 {
1406   GOutputVector vectors[3];
1407   const guint8 buffer[] = {1, 2, 3, 4, 5,
1408                            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
1409                            1, 2, 3};
1410
1411   vectors[0].buffer = buffer;
1412   vectors[0].size = 5;
1413
1414   vectors[1].buffer = buffer + 5;
1415   vectors[1].size = 12;
1416
1417   vectors[2].buffer = buffer + 5 + 12;
1418   vectors[2].size = 3;
1419
1420   test_writev_helper (vectors, G_N_ELEMENTS (vectors), FALSE, buffer, sizeof buffer);
1421 }
1422
1423 /* Test that writev() on local file output streams works on 0 vectors */
1424 static void
1425 test_writev_no_vectors (void)
1426 {
1427   test_writev_helper (NULL, 0, TRUE, NULL, 0);
1428 }
1429
1430 /* Test that writev() on local file output streams works on empty vectors */
1431 static void
1432 test_writev_empty_vectors (void)
1433 {
1434   GOutputVector vectors[3];
1435
1436   vectors[0].buffer = NULL;
1437   vectors[0].size = 0;
1438   vectors[1].buffer = NULL;
1439   vectors[1].size = 0;
1440   vectors[2].buffer = NULL;
1441   vectors[2].size = 0;
1442
1443   test_writev_helper (vectors, G_N_ELEMENTS (vectors), TRUE, NULL, 0);
1444 }
1445
1446 /* Test that writev() fails if the sum of sizes in the vector is too big */
1447 static void
1448 test_writev_too_big_vectors (void)
1449 {
1450   GFile *file;
1451   GFileIOStream *iostream = NULL;
1452   GOutputStream *ostream;
1453   GError *error = NULL;
1454   gsize bytes_written = 0;
1455   gboolean res;
1456   guint8 *contents;
1457   gsize length;
1458   GOutputVector vectors[3];
1459
1460   vectors[0].buffer = (void*) 1;
1461   vectors[0].size = G_MAXSIZE / 2;
1462
1463   vectors[1].buffer = (void*) 1;
1464   vectors[1].size = G_MAXSIZE / 2;
1465
1466   vectors[2].buffer = (void*) 1;
1467   vectors[2].size = G_MAXSIZE / 2;
1468
1469   file = g_file_new_tmp ("g_file_writev_XXXXXX",
1470                          &iostream, NULL);
1471   g_assert_nonnull (file);
1472   g_assert_nonnull (iostream);
1473
1474   ostream = g_io_stream_get_output_stream (G_IO_STREAM (iostream));
1475
1476   res = g_output_stream_writev_all (ostream, vectors, G_N_ELEMENTS (vectors), &bytes_written, NULL, &error);
1477   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT);
1478   g_assert_cmpuint (bytes_written, ==, 0);
1479   g_assert_false (res);
1480   g_clear_error (&error);
1481
1482   res = g_io_stream_close (G_IO_STREAM (iostream), NULL, &error);
1483   g_assert_no_error (error);
1484   g_assert_true (res);
1485   g_object_unref (iostream);
1486
1487   res = g_file_load_contents (file, NULL, (gchar **) &contents, &length, NULL, &error);
1488   g_assert_no_error (error);
1489   g_assert_true (res);
1490
1491   g_assert_cmpmem (contents, length, NULL, 0);
1492
1493   g_free (contents);
1494
1495   g_file_delete (file, NULL, NULL);
1496   g_object_unref (file);
1497 }
1498
1499 typedef struct
1500 {
1501   gsize bytes_written;
1502   GOutputVector *vectors;
1503   gsize n_vectors;
1504   GError *error;
1505   gboolean done;
1506 } WritevAsyncData;
1507
1508 static void
1509 test_writev_async_cb (GObject      *object,
1510                       GAsyncResult *result,
1511                       gpointer      user_data)
1512 {
1513   GOutputStream *ostream = G_OUTPUT_STREAM (object);
1514   WritevAsyncData *data = user_data;
1515   GError *error = NULL;
1516   gsize bytes_written;
1517   gboolean res;
1518
1519   res = g_output_stream_writev_finish (ostream, result, &bytes_written, &error);
1520   g_assert_true (res);
1521   g_assert_no_error (error);
1522   data->bytes_written += bytes_written;
1523
1524   /* skip vectors that have been written in full */
1525   while (data->n_vectors > 0 && bytes_written >= data->vectors[0].size)
1526     {
1527       bytes_written -= data->vectors[0].size;
1528       ++data->vectors;
1529       --data->n_vectors;
1530     }
1531   /* skip partially written vector data */
1532   if (bytes_written > 0 && data->n_vectors > 0)
1533     {
1534       data->vectors[0].size -= bytes_written;
1535       data->vectors[0].buffer = ((guint8 *) data->vectors[0].buffer) + bytes_written;
1536     }
1537
1538   if (data->n_vectors > 0)
1539     g_output_stream_writev_async (ostream, data->vectors, data->n_vectors, 0, NULL, test_writev_async_cb, &data);
1540 }
1541
1542 /* Test that writev_async() on local file output streams works on a non-empty vector */
1543 static void
1544 test_writev_async (void)
1545 {
1546   WritevAsyncData data = { 0 };
1547   GFile *file;
1548   GFileIOStream *iostream = NULL;
1549   GOutputVector vectors[3];
1550   const guint8 buffer[] = {1, 2, 3, 4, 5,
1551                            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
1552                            1, 2, 3};
1553   GOutputStream *ostream;
1554   GError *error = NULL;
1555   gboolean res;
1556   guint8 *contents;
1557   gsize length;
1558
1559   vectors[0].buffer = buffer;
1560   vectors[0].size = 5;
1561
1562   vectors[1].buffer = buffer + 5;
1563   vectors[1].size = 12;
1564
1565   vectors[2].buffer = buffer + 5  + 12;
1566   vectors[2].size = 3;
1567
1568   file = g_file_new_tmp ("g_file_writev_XXXXXX",
1569                          &iostream, NULL);
1570   g_assert_nonnull (file);
1571   g_assert_nonnull (iostream);
1572
1573   data.vectors = vectors;
1574   data.n_vectors = G_N_ELEMENTS (vectors);
1575
1576   ostream = g_io_stream_get_output_stream (G_IO_STREAM (iostream));
1577
1578   g_output_stream_writev_async (ostream, data.vectors, data.n_vectors, 0, NULL, test_writev_async_cb, &data);
1579
1580   while (data.n_vectors > 0)
1581     g_main_context_iteration (NULL, TRUE);
1582
1583   g_assert_cmpuint (data.bytes_written, ==, sizeof buffer);
1584
1585   res = g_io_stream_close (G_IO_STREAM (iostream), NULL, &error);
1586   g_assert_no_error (error);
1587   g_assert_true (res);
1588   g_object_unref (iostream);
1589
1590   res = g_file_load_contents (file, NULL, (gchar **) &contents, &length, NULL, &error);
1591   g_assert_no_error (error);
1592   g_assert_true (res);
1593
1594   g_assert_cmpmem (contents, length, buffer, sizeof buffer);
1595
1596   g_free (contents);
1597
1598   g_file_delete (file, NULL, NULL);
1599   g_object_unref (file);
1600 }
1601
1602 static void
1603 test_writev_all_cb (GObject      *object,
1604                     GAsyncResult *result,
1605                     gpointer      user_data)
1606 {
1607   GOutputStream *ostream = G_OUTPUT_STREAM (object);
1608   WritevAsyncData *data = user_data;
1609
1610   g_output_stream_writev_all_finish (ostream, result, &data->bytes_written, &data->error);
1611   data->done = TRUE;
1612 }
1613
1614 /* Test that writev_async_all() on local file output streams works on a non-empty vector */
1615 static void
1616 test_writev_async_all (void)
1617 {
1618   WritevAsyncData data = { 0 };
1619   GFile *file;
1620   GFileIOStream *iostream = NULL;
1621   GOutputStream *ostream;
1622   GOutputVector vectors[3];
1623   const guint8 buffer[] = {1, 2, 3, 4, 5,
1624                            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
1625                            1, 2, 3};
1626   GError *error = NULL;
1627   gboolean res;
1628   guint8 *contents;
1629   gsize length;
1630
1631   vectors[0].buffer = buffer;
1632   vectors[0].size = 5;
1633
1634   vectors[1].buffer = buffer + 5;
1635   vectors[1].size = 12;
1636
1637   vectors[2].buffer = buffer + 5  + 12;
1638   vectors[2].size = 3;
1639
1640   file = g_file_new_tmp ("g_file_writev_XXXXXX",
1641                          &iostream, NULL);
1642   g_assert_nonnull (file);
1643   g_assert_nonnull (iostream);
1644
1645   ostream = g_io_stream_get_output_stream (G_IO_STREAM (iostream));
1646
1647   g_output_stream_writev_all_async (ostream, vectors, G_N_ELEMENTS (vectors), 0, NULL, test_writev_all_cb, &data);
1648
1649   while (!data.done)
1650     g_main_context_iteration (NULL, TRUE);
1651
1652   g_assert_cmpuint (data.bytes_written, ==, sizeof buffer);
1653   g_assert_no_error (data.error);
1654
1655   res = g_io_stream_close (G_IO_STREAM (iostream), NULL, &error);
1656   g_assert_no_error (error);
1657   g_assert_true (res);
1658   g_object_unref (iostream);
1659
1660   res = g_file_load_contents (file, NULL, (gchar **) &contents, &length, NULL, &error);
1661   g_assert_no_error (error);
1662   g_assert_true (res);
1663
1664   g_assert_cmpmem (contents, length, buffer, sizeof buffer);
1665
1666   g_free (contents);
1667
1668   g_file_delete (file, NULL, NULL);
1669   g_object_unref (file);
1670 }
1671
1672 /* Test that writev_async_all() on local file output streams handles cancellation correctly */
1673 static void
1674 test_writev_async_all_cancellation (void)
1675 {
1676   WritevAsyncData data = { 0 };
1677   GFile *file;
1678   GFileIOStream *iostream = NULL;
1679   GOutputVector vectors[3];
1680   const guint8 buffer[] = {1, 2, 3, 4, 5,
1681                            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
1682                            1, 2, 3};
1683   GOutputStream *ostream;
1684   GError *error = NULL;
1685   gboolean res;
1686   guint8 *contents;
1687   gsize length;
1688   GCancellable *cancellable;
1689
1690   vectors[0].buffer = buffer;
1691   vectors[0].size = 5;
1692
1693   vectors[1].buffer = buffer + 5;
1694   vectors[1].size = 12;
1695
1696   vectors[2].buffer = buffer + 5  + 12;
1697   vectors[2].size = 3;
1698
1699   file = g_file_new_tmp ("g_file_writev_XXXXXX",
1700                          &iostream, NULL);
1701   g_assert_nonnull (file);
1702   g_assert_nonnull (iostream);
1703
1704   ostream = g_io_stream_get_output_stream (G_IO_STREAM (iostream));
1705
1706   cancellable = g_cancellable_new ();
1707   g_cancellable_cancel (cancellable);
1708
1709   g_output_stream_writev_all_async (ostream, vectors, G_N_ELEMENTS (vectors), 0, cancellable, test_writev_all_cb, &data);
1710
1711   while (!data.done)
1712     g_main_context_iteration (NULL, TRUE);
1713
1714   g_assert_cmpuint (data.bytes_written, ==, 0);
1715   g_assert_error (data.error, G_IO_ERROR, G_IO_ERROR_CANCELLED);
1716   g_clear_error (&data.error);
1717
1718   res = g_io_stream_close (G_IO_STREAM (iostream), NULL, &error);
1719   g_assert_no_error (error);
1720   g_assert_true (res);
1721   g_object_unref (iostream);
1722
1723   res = g_file_load_contents (file, NULL, (gchar **) &contents, &length, NULL, &error);
1724   g_assert_no_error (error);
1725   g_assert_true (res);
1726   g_assert_cmpuint (length, ==, 0);
1727
1728   g_free (contents);
1729
1730   g_file_delete (file, NULL, NULL);
1731   g_object_unref (file);
1732   g_object_unref (cancellable);
1733 }
1734
1735 /* Test that writev_async_all() with empty vectors is handled correctly */
1736 static void
1737 test_writev_async_all_empty_vectors (void)
1738 {
1739   WritevAsyncData data = { 0 };
1740   GFile *file;
1741   GFileIOStream *iostream = NULL;
1742   GOutputVector vectors[3];
1743   GOutputStream *ostream;
1744   GError *error = NULL;
1745   gboolean res;
1746   guint8 *contents;
1747   gsize length;
1748
1749   vectors[0].buffer = NULL;
1750   vectors[0].size = 0;
1751
1752   vectors[1].buffer = NULL;
1753   vectors[1].size = 0;
1754
1755   vectors[2].buffer = NULL;
1756   vectors[2].size = 0;
1757
1758   file = g_file_new_tmp ("g_file_writev_XXXXXX",
1759                          &iostream, NULL);
1760   g_assert_nonnull (file);
1761   g_assert_nonnull (iostream);
1762
1763   ostream = g_io_stream_get_output_stream (G_IO_STREAM (iostream));
1764
1765   g_output_stream_writev_all_async (ostream, vectors, G_N_ELEMENTS (vectors), 0, NULL, test_writev_all_cb, &data);
1766
1767   while (!data.done)
1768     g_main_context_iteration (NULL, TRUE);
1769
1770   g_assert_cmpuint (data.bytes_written, ==, 0);
1771   g_assert_no_error (data.error);
1772   g_clear_error (&data.error);
1773
1774   res = g_io_stream_close (G_IO_STREAM (iostream), NULL, &error);
1775   g_assert_no_error (error);
1776   g_assert_true (res);
1777   g_object_unref (iostream);
1778
1779   res = g_file_load_contents (file, NULL, (gchar **) &contents, &length, NULL, &error);
1780   g_assert_no_error (error);
1781   g_assert_true (res);
1782   g_assert_cmpuint (length, ==, 0);
1783
1784   g_free (contents);
1785
1786   g_file_delete (file, NULL, NULL);
1787   g_object_unref (file);
1788 }
1789
1790 /* Test that writev_async_all() with no vectors is handled correctly */
1791 static void
1792 test_writev_async_all_no_vectors (void)
1793 {
1794   WritevAsyncData data = { 0 };
1795   GFile *file;
1796   GFileIOStream *iostream = NULL;
1797   GOutputStream *ostream;
1798   GError *error = NULL;
1799   gboolean res;
1800   guint8 *contents;
1801   gsize length;
1802
1803   file = g_file_new_tmp ("g_file_writev_XXXXXX",
1804                          &iostream, NULL);
1805   g_assert_nonnull (file);
1806   g_assert_nonnull (iostream);
1807
1808   ostream = g_io_stream_get_output_stream (G_IO_STREAM (iostream));
1809
1810   g_output_stream_writev_all_async (ostream, NULL, 0, 0, NULL, test_writev_all_cb, &data);
1811
1812   while (!data.done)
1813     g_main_context_iteration (NULL, TRUE);
1814
1815   g_assert_cmpuint (data.bytes_written, ==, 0);
1816   g_assert_no_error (data.error);
1817   g_clear_error (&data.error);
1818
1819   res = g_io_stream_close (G_IO_STREAM (iostream), NULL, &error);
1820   g_assert_no_error (error);
1821   g_assert_true (res);
1822   g_object_unref (iostream);
1823
1824   res = g_file_load_contents (file, NULL, (gchar **) &contents, &length, NULL, &error);
1825   g_assert_no_error (error);
1826   g_assert_true (res);
1827   g_assert_cmpuint (length, ==, 0);
1828
1829   g_free (contents);
1830
1831   g_file_delete (file, NULL, NULL);
1832   g_object_unref (file);
1833 }
1834
1835 /* Test that writev_async_all() with too big vectors is handled correctly */
1836 static void
1837 test_writev_async_all_too_big_vectors (void)
1838 {
1839   WritevAsyncData data = { 0 };
1840   GFile *file;
1841   GFileIOStream *iostream = NULL;
1842   GOutputVector vectors[3];
1843   GOutputStream *ostream;
1844   GError *error = NULL;
1845   gboolean res;
1846   guint8 *contents;
1847   gsize length;
1848
1849   vectors[0].buffer = (void*) 1;
1850   vectors[0].size = G_MAXSIZE / 2;
1851
1852   vectors[1].buffer = (void*) 1;
1853   vectors[1].size = G_MAXSIZE / 2;
1854
1855   vectors[2].buffer = (void*) 1;
1856   vectors[2].size = G_MAXSIZE / 2;
1857
1858   file = g_file_new_tmp ("g_file_writev_XXXXXX",
1859                          &iostream, NULL);
1860   g_assert_nonnull (file);
1861   g_assert_nonnull (iostream);
1862
1863   ostream = g_io_stream_get_output_stream (G_IO_STREAM (iostream));
1864
1865   g_output_stream_writev_all_async (ostream, vectors, G_N_ELEMENTS (vectors), 0, NULL, test_writev_all_cb, &data);
1866
1867   while (!data.done)
1868     g_main_context_iteration (NULL, TRUE);
1869
1870   g_assert_cmpuint (data.bytes_written, ==, 0);
1871   g_assert_error (data.error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT);
1872   g_clear_error (&data.error);
1873
1874   res = g_io_stream_close (G_IO_STREAM (iostream), NULL, &error);
1875   g_assert_no_error (error);
1876   g_assert_true (res);
1877   g_object_unref (iostream);
1878
1879   res = g_file_load_contents (file, NULL, (gchar **) &contents, &length, NULL, &error);
1880   g_assert_no_error (error);
1881   g_assert_true (res);
1882   g_assert_cmpuint (length, ==, 0);
1883
1884   g_free (contents);
1885
1886   g_file_delete (file, NULL, NULL);
1887   g_object_unref (file);
1888 }
1889
1890 int
1891 main (int argc, char *argv[])
1892 {
1893   g_test_init (&argc, &argv, NULL);
1894
1895   g_test_add_func ("/file/basic", test_basic);
1896   g_test_add_func ("/file/build-filename", test_build_filename);
1897   g_test_add_func ("/file/parent", test_parent);
1898   g_test_add_func ("/file/child", test_child);
1899   g_test_add_func ("/file/type", test_type);
1900   g_test_add_func ("/file/parse-name", test_parse_name);
1901   g_test_add_data_func ("/file/async-create-delete/0", GINT_TO_POINTER (0), test_create_delete);
1902   g_test_add_data_func ("/file/async-create-delete/1", GINT_TO_POINTER (1), test_create_delete);
1903   g_test_add_data_func ("/file/async-create-delete/10", GINT_TO_POINTER (10), test_create_delete);
1904   g_test_add_data_func ("/file/async-create-delete/25", GINT_TO_POINTER (25), test_create_delete);
1905   g_test_add_data_func ("/file/async-create-delete/4096", GINT_TO_POINTER (4096), test_create_delete);
1906   g_test_add_func ("/file/replace-load", test_replace_load);
1907   g_test_add_func ("/file/replace-cancel", test_replace_cancel);
1908   g_test_add_func ("/file/replace-symlink", test_replace_symlink);
1909   g_test_add_func ("/file/async-delete", test_async_delete);
1910   g_test_add_func ("/file/copy-preserve-mode", test_copy_preserve_mode);
1911   g_test_add_func ("/file/measure", test_measure);
1912   g_test_add_func ("/file/measure-async", test_measure_async);
1913   g_test_add_func ("/file/load-bytes", test_load_bytes);
1914   g_test_add_func ("/file/load-bytes-async", test_load_bytes_async);
1915   g_test_add_func ("/file/writev", test_writev);
1916   g_test_add_func ("/file/writev/no-bytes-written", test_writev_no_bytes_written);
1917   g_test_add_func ("/file/writev/no-vectors", test_writev_no_vectors);
1918   g_test_add_func ("/file/writev/empty-vectors", test_writev_empty_vectors);
1919   g_test_add_func ("/file/writev/too-big-vectors", test_writev_too_big_vectors);
1920   g_test_add_func ("/file/writev/async", test_writev_async);
1921   g_test_add_func ("/file/writev/async_all", test_writev_async_all);
1922   g_test_add_func ("/file/writev/async_all-empty-vectors", test_writev_async_all_empty_vectors);
1923   g_test_add_func ("/file/writev/async_all-no-vectors", test_writev_async_all_no_vectors);
1924   g_test_add_func ("/file/writev/async_all-to-big-vectors", test_writev_async_all_too_big_vectors);
1925   g_test_add_func ("/file/writev/async_all-cancellation", test_writev_async_all_cancellation);
1926
1927   return g_test_run ();
1928 }