1 #include "tap.h"
2 #include "test.h"
3 #include "bson.h"
4 
5 #include <string.h>
6 
7 void
test_bson_js_code(void)8 test_bson_js_code (void)
9 {
10   bson *b;
11 
12   /* Test #1: A single JS element, with default size. */
13   b = bson_new ();
14   ok (bson_append_javascript (b, "hello",
15                               "function () { print (\"hello world!\"); }", -1),
16       "bson_append_javascript() works");
17   bson_finish (b);
18 
19   cmp_ok (bson_size (b), "==", 56, "BSON javascript element size check");
20   ok (memcmp (bson_data (b),
21               "\070\000\000\000\015\150\145\154\154\157\000\050\000\000\000"
22               "\146\165\156\143\164\151\157\156\040\050\051\040\173\040\160"
23               "\162\151\156\164\040\050\042\150\145\154\154\157\040\167\157"
24               "\162\154\144\041\042\051\073\040\175\000\000",
25               bson_size (b)) == 0,
26       "BSON javascript element contents check");
27   bson_free (b);
28 
29   /* Test #2: A single javascript element, with explicit length. */
30   b = bson_new ();
31   ok (bson_append_javascript (b, "hello",
32                               "print (\"hello world!\"); garbage is gone.",
33                           strlen ("print (\"hello world!\");")),
34       "bson_append_javascript() with explicit length works");
35   bson_finish (b);
36 
37   cmp_ok (bson_size (b), "==", 40, "BSON javascript element size check, #2");
38   ok (memcmp (bson_data (b),
39               "\050\000\000\000\015\150\145\154\154\157\000\030\000\000\000"
40               "\160\162\151\156\164\040\050\042\150\145\154\154\157\040\167"
41               "\157\162\154\144\041\042\051\073\000\000",
42               bson_size (b)) == 0,
43       "BSON javascript element contents check, #2");
44   bson_free (b);
45 
46   /* Test #3: Negative test, passing an invalid arguments. */
47   b = bson_new ();
48   ok (bson_append_javascript (b, "hello", "print();", -42) == FALSE,
49       "bson_append_javascript() with an invalid length should fail");
50   ok (bson_append_javascript (b, NULL, "print();", -1) == FALSE,
51       "bson_append_javascript() should fail without a key name");
52   ok (bson_append_javascript (b, "hello", NULL, -1) == FALSE,
53       "bson_append_javascript() should fail without javascript code");
54   ok (bson_append_javascript (NULL, "hello", "print();", -1) == FALSE,
55       "bson_append_javascript() should fail without a BSON object");
56   bson_finish (b);
57   cmp_ok (bson_size (b), "==", 5,
58           "BSON object should be empty");
59 
60   ok (bson_append_javascript (b, "js", "print();", -1) == FALSE,
61       "Appending to a finished element should fail");
62 
63   bson_free (b);
64 }
65 
66 RUN_TEST (12, bson_js_code);
67