~timkross/cjdns/cjdns

« back to all changes in this revision

Viewing changes to dht/test/DHTModules_serialization_test.c

  • Committer: cjdelisle
  • Date: 2011-02-16 23:03:00 UTC
  • Revision ID: git-v1:d475c9c10adc25590bea5e7dc5383b32f66d5eb8
First commit for cjdns.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 * This test tests the ability of DHTModules.c to serialize the contexts
 
3
 * of the modules. For (de)serialization of the messages go in and out,
 
4
 * see SerializationModule_test.c
 
5
 */
 
6
 
 
7
#include <stdio.h>
 
8
#include "libbenc/bencode.h"
 
9
#include "dht/DHTModules.h"
 
10
 
 
11
int testSerialization()
 
12
{
 
13
    benc_bstr_t* serialize(void* vcontext)
 
14
    {
 
15
        char* context = (char*) vcontext;
 
16
        benc_bstr_t* out = calloc(sizeof(benc_bstr_t), 1);
 
17
        if (out == NULL) {
 
18
            return NULL;
 
19
        }
 
20
        out->len = strlen(context);
 
21
        out->bytes = context;
 
22
        return out;
 
23
    }
 
24
 
 
25
    char* context = "Hello World";
 
26
 
 
27
    struct DHTModule module = {
 
28
        .name = "TestModule",
 
29
        .context = context,
 
30
        .serialize = serialize
 
31
    };
 
32
 
 
33
    struct DHTModuleRegistry* reg = DHTModules_new();
 
34
    DHTModules_register(&module, reg);
 
35
 
 
36
    benc_bstr_t* serialized = DHTModules_serialize(reg);
 
37
    DHTModules_free(reg);
 
38
 
 
39
    /* This is ok because the output is null padded at the end. */
 
40
    /*
 
41
    printf("The content is: %s\nand the length is: %d\n",
 
42
           serialized->bytes,
 
43
           (int) serialized->len);
 
44
    */
 
45
 
 
46
    return memcmp(serialized->bytes,
 
47
                  "d10:TestModule11:Hello Worlde",
 
48
                  serialized->len);
 
49
}
 
50
 
 
51
int testDeserialization()
 
52
{
 
53
    void deserialize(const benc_bstr_t serialData, void* vcontext)
 
54
    {
 
55
        char* context = (char*) vcontext;
 
56
        memcpy(context, serialData.bytes, serialData.len);
 
57
    }
 
58
 
 
59
    char context[12];
 
60
 
 
61
    struct DHTModule module = {
 
62
        .name = "TestModule",
 
63
        .context = context,
 
64
        .deserialize = deserialize
 
65
    };
 
66
 
 
67
    benc_bstr_t serialized = {29, "d10:TestModule11:Hello Worlde"};
 
68
 
 
69
    struct DHTModuleRegistry* reg = DHTModules_deserialize(serialized);
 
70
    DHTModules_register(&module, reg);
 
71
 
 
72
    context[11] = '\0';
 
73
 
 
74
    /*printf("Deserialization output is: %s\n", context);*/
 
75
 
 
76
    return memcmp(context, "Hello World", 11);
 
77
}
 
78
 
 
79
int main()
 
80
{
 
81
    return
 
82
        testSerialization()
 
83
      | testDeserialization();
 
84
}