GMappedFile: return an error when trying to map a device
[platform/upstream/glib.git] / glib / tests / mappedfile.c
1 #include <config.h>
2 #include <glib.h>
3 #include <string.h>
4 #ifdef HAVE_UNISTD_H
5 #include <unistd.h>
6 #endif
7
8 static void
9 test_basic (void)
10 {
11   GMappedFile *file;
12   GError *error;
13
14   error = NULL;
15   file = g_mapped_file_new (SRCDIR "/empty", FALSE, &error);
16   g_assert_no_error (error);
17
18   g_mapped_file_ref (file);
19   g_mapped_file_unref (file);
20
21   g_mapped_file_unref (file);
22 }
23
24 static void
25 test_empty (void)
26 {
27   GMappedFile *file;
28   GError *error;
29
30   error = NULL;
31   file = g_mapped_file_new (SRCDIR "/empty", FALSE, &error);
32   g_assert_no_error (error);
33
34   g_assert (g_mapped_file_get_contents (file) == NULL);
35
36   g_mapped_file_free (file);
37 }
38
39 static void
40 test_device (void)
41 {
42   GError *error = NULL;
43   GMappedFile *file;
44
45   file = g_mapped_file_new ("/dev/null", FALSE, &error);
46   g_assert_error (error, G_FILE_ERROR, G_FILE_ERROR_INVAL);
47   g_assert (file == NULL);
48   g_error_free (error);
49 }
50
51 static void
52 test_nonexisting (void)
53 {
54   GMappedFile *file;
55   GError *error;
56
57   error = NULL;
58   file = g_mapped_file_new ("no-such-file", FALSE, &error);
59   g_assert_error (error, G_FILE_ERROR, G_FILE_ERROR_NOENT);
60   g_clear_error (&error);
61   g_assert (file == NULL);
62 }
63
64 static void
65 test_writable (void)
66 {
67   GMappedFile *file;
68   GError *error;
69   gchar *contents;
70   const gchar *old = "MMMMMMMMMMMMMMMMMMMMMMMMM";
71   const gchar *new = "abcdefghijklmnopqrstuvxyz";
72
73   if (access (SRCDIR "/4096-random-bytes", W_OK) != 0)
74     {
75       g_test_message ("Skipping writable mapping test");
76       return;
77     }
78
79   error = NULL;
80   file = g_mapped_file_new (SRCDIR "/4096-random-bytes", TRUE, &error);
81   g_assert_no_error (error);
82
83   contents = g_mapped_file_get_contents (file);
84   g_assert (strncmp (contents, old, strlen (old)) == 0);
85
86   memcpy (contents, new, strlen (new));
87   g_assert (strncmp (contents, new, strlen (new)) == 0);
88
89   g_mapped_file_free (file);
90
91   error = NULL;
92   file = g_mapped_file_new (SRCDIR "/4096-random-bytes", TRUE, &error);
93   g_assert_no_error (error);
94
95   contents = g_mapped_file_get_contents (file);
96   g_assert (strncmp (contents, old, strlen (old)) == 0);
97
98   g_mapped_file_free (file);
99 }
100
101 int
102 main (int argc, char *argv[])
103 {
104   g_test_init (&argc, &argv, NULL);
105
106   g_test_add_func ("/mappedfile/basic", test_basic);
107   g_test_add_func ("/mappedfile/empty", test_empty);
108   g_test_add_func ("/mappedfile/nonexisting", test_nonexisting);
109   g_test_add_func ("/mappedfile/writable", test_writable);
110
111   return g_test_run ();
112 }