New APIs: guestfs_first_private, guestfs_next_private to walk over
[libguestfs.git] / capitests / test-private-data.c
1 /* libguestfs
2  * Copyright (C) 2011 Red Hat Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  */
18
19 /* Test aspects of the private data area API. */
20
21 #include <config.h>
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <assert.h>
28
29 #include "guestfs.h"
30
31 #define PREFIX "test_"
32
33 int
34 main (int argc, char *argv[])
35 {
36   guestfs_h *g;
37   const char *key;
38   void *data;
39   size_t count;
40
41   g = guestfs_create ();
42   if (g == NULL) {
43     fprintf (stderr, "failed to create handle\n");
44     exit (EXIT_FAILURE);
45   }
46
47   guestfs_set_private (g, PREFIX "a", (void *) 1);
48   guestfs_set_private (g, PREFIX "b", (void *) 2);
49   guestfs_set_private (g, PREFIX "c", (void *) 3);
50   guestfs_set_private (g, PREFIX "a", (void *) 4); /* overwrites previous */
51
52   /* Check we can fetch keys. */
53   assert (guestfs_get_private (g, PREFIX "a") == (void *) 4);
54   assert (guestfs_get_private (g, PREFIX "b") == (void *) 2);
55   assert (guestfs_get_private (g, PREFIX "c") == (void *) 3);
56   assert (guestfs_get_private (g, PREFIX "d") == NULL);
57
58   /* Check we can count keys by iterating. */
59   count = 0;
60   data = guestfs_first_private (g, &key);
61   while (data != NULL) {
62     if (strncmp (key, PREFIX, strlen (PREFIX)) == 0)
63       count++;
64     data = guestfs_next_private (g, &key);
65   }
66   assert (count == 3);
67
68   /* Delete some keys. */
69   guestfs_set_private (g, PREFIX "a", NULL);
70   guestfs_set_private (g, PREFIX "b", NULL);
71
72   /* Count them again. */
73   count = 0;
74   data = guestfs_first_private (g, &key);
75   while (data != NULL) {
76     if (strncmp (key, PREFIX, strlen (PREFIX)) == 0)
77       count++;
78     data = guestfs_next_private (g, &key);
79   }
80   assert (count == 1);
81
82   guestfs_close (g);
83
84   exit (EXIT_SUCCESS);
85 }