1 #include "fmacros.h"
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <strings.h>
6 #include <sys/time.h>
7 #include <assert.h>
8 #include <unistd.h>
9 #include <signal.h>
10 #include <errno.h>
11 #include <limits.h>
12 
13 #include "hiredis.h"
14 #include "net.h"
15 
16 enum connection_type {
17     CONN_TCP,
18     CONN_UNIX,
19     CONN_FD
20 };
21 
22 struct config {
23     enum connection_type type;
24 
25     struct {
26         const char *host;
27         int port;
28         struct timeval timeout;
29     } tcp;
30 
31     struct {
32         const char *path;
33     } unix;
34 };
35 
36 /* The following lines make up our testing "framework" :) */
37 static int tests = 0, fails = 0;
38 #define test(_s) { printf("#%02d ", ++tests); printf(_s); }
39 #define test_cond(_c) if(_c) printf("\033[0;32mPASSED\033[0;0m\n"); else {printf("\033[0;31mFAILED\033[0;0m\n"); fails++;}
40 
usec(void)41 static long long usec(void) {
42     struct timeval tv;
43     gettimeofday(&tv,NULL);
44     return (((long long)tv.tv_sec)*1000000)+tv.tv_usec;
45 }
46 
47 /* The assert() calls below have side effects, so we need assert()
48  * even if we are compiling without asserts (-DNDEBUG). */
49 #ifdef NDEBUG
50 #undef assert
51 #define assert(e) (void)(e)
52 #endif
53 
select_database(redisContext * c)54 static redisContext *select_database(redisContext *c) {
55     redisReply *reply;
56 
57     /* Switch to DB 9 for testing, now that we know we can chat. */
58     reply = redisCommand(c,"SELECT 9");
59     assert(reply != NULL);
60     freeReplyObject(reply);
61 
62     /* Make sure the DB is emtpy */
63     reply = redisCommand(c,"DBSIZE");
64     assert(reply != NULL);
65     if (reply->type == REDIS_REPLY_INTEGER && reply->integer == 0) {
66         /* Awesome, DB 9 is empty and we can continue. */
67         freeReplyObject(reply);
68     } else {
69         printf("Database #9 is not empty, test can not continue\n");
70         exit(1);
71     }
72 
73     return c;
74 }
75 
disconnect(redisContext * c,int keep_fd)76 static int disconnect(redisContext *c, int keep_fd) {
77     redisReply *reply;
78 
79     /* Make sure we're on DB 9. */
80     reply = redisCommand(c,"SELECT 9");
81     assert(reply != NULL);
82     freeReplyObject(reply);
83     reply = redisCommand(c,"FLUSHDB");
84     assert(reply != NULL);
85     freeReplyObject(reply);
86 
87     /* Free the context as well, but keep the fd if requested. */
88     if (keep_fd)
89         return redisFreeKeepFd(c);
90     redisFree(c);
91     return -1;
92 }
93 
connect(struct config config)94 static redisContext *connect(struct config config) {
95     redisContext *c = NULL;
96 
97     if (config.type == CONN_TCP) {
98         c = redisConnect(config.tcp.host, config.tcp.port);
99     } else if (config.type == CONN_UNIX) {
100         c = redisConnectUnix(config.unix.path);
101     } else if (config.type == CONN_FD) {
102         /* Create a dummy connection just to get an fd to inherit */
103         redisContext *dummy_ctx = redisConnectUnix(config.unix.path);
104         if (dummy_ctx) {
105             int fd = disconnect(dummy_ctx, 1);
106             printf("Connecting to inherited fd %d\n", fd);
107             c = redisConnectFd(fd);
108         }
109     } else {
110         assert(NULL);
111     }
112 
113     if (c == NULL) {
114         printf("Connection error: can't allocate redis context\n");
115         exit(1);
116     } else if (c->err) {
117         printf("Connection error: %s\n", c->errstr);
118         redisFree(c);
119         exit(1);
120     }
121 
122     return select_database(c);
123 }
124 
test_format_commands(void)125 static void test_format_commands(void) {
126     char *cmd;
127     int len;
128 
129     test("Format command without interpolation: ");
130     len = redisFormatCommand(&cmd,"SET foo bar");
131     test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n",len) == 0 &&
132         len == 4+4+(3+2)+4+(3+2)+4+(3+2));
133     free(cmd);
134 
135     test("Format command with %%s string interpolation: ");
136     len = redisFormatCommand(&cmd,"SET %s %s","foo","bar");
137     test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n",len) == 0 &&
138         len == 4+4+(3+2)+4+(3+2)+4+(3+2));
139     free(cmd);
140 
141     test("Format command with %%s and an empty string: ");
142     len = redisFormatCommand(&cmd,"SET %s %s","foo","");
143     test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$0\r\n\r\n",len) == 0 &&
144         len == 4+4+(3+2)+4+(3+2)+4+(0+2));
145     free(cmd);
146 
147     test("Format command with an empty string in between proper interpolations: ");
148     len = redisFormatCommand(&cmd,"SET %s %s","","foo");
149     test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$0\r\n\r\n$3\r\nfoo\r\n",len) == 0 &&
150         len == 4+4+(3+2)+4+(0+2)+4+(3+2));
151     free(cmd);
152 
153     test("Format command with %%b string interpolation: ");
154     len = redisFormatCommand(&cmd,"SET %b %b","foo",(size_t)3,"b\0r",(size_t)3);
155     test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nb\0r\r\n",len) == 0 &&
156         len == 4+4+(3+2)+4+(3+2)+4+(3+2));
157     free(cmd);
158 
159     test("Format command with %%b and an empty string: ");
160     len = redisFormatCommand(&cmd,"SET %b %b","foo",(size_t)3,"",(size_t)0);
161     test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$0\r\n\r\n",len) == 0 &&
162         len == 4+4+(3+2)+4+(3+2)+4+(0+2));
163     free(cmd);
164 
165     test("Format command with literal %%: ");
166     len = redisFormatCommand(&cmd,"SET %% %%");
167     test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$1\r\n%\r\n$1\r\n%\r\n",len) == 0 &&
168         len == 4+4+(3+2)+4+(1+2)+4+(1+2));
169     free(cmd);
170 
171     /* Vararg width depends on the type. These tests make sure that the
172      * width is correctly determined using the format and subsequent varargs
173      * can correctly be interpolated. */
174 #define INTEGER_WIDTH_TEST(fmt, type) do {                                                \
175     type value = 123;                                                                     \
176     test("Format command with printf-delegation (" #type "): ");                          \
177     len = redisFormatCommand(&cmd,"key:%08" fmt " str:%s", value, "hello");               \
178     test_cond(strncmp(cmd,"*2\r\n$12\r\nkey:00000123\r\n$9\r\nstr:hello\r\n",len) == 0 && \
179         len == 4+5+(12+2)+4+(9+2));                                                       \
180     free(cmd);                                                                            \
181 } while(0)
182 
183 #define FLOAT_WIDTH_TEST(type) do {                                                       \
184     type value = 123.0;                                                                   \
185     test("Format command with printf-delegation (" #type "): ");                          \
186     len = redisFormatCommand(&cmd,"key:%08.3f str:%s", value, "hello");                   \
187     test_cond(strncmp(cmd,"*2\r\n$12\r\nkey:0123.000\r\n$9\r\nstr:hello\r\n",len) == 0 && \
188         len == 4+5+(12+2)+4+(9+2));                                                       \
189     free(cmd);                                                                            \
190 } while(0)
191 
192     INTEGER_WIDTH_TEST("d", int);
193     INTEGER_WIDTH_TEST("hhd", char);
194     INTEGER_WIDTH_TEST("hd", short);
195     INTEGER_WIDTH_TEST("ld", long);
196     INTEGER_WIDTH_TEST("lld", long long);
197     INTEGER_WIDTH_TEST("u", unsigned int);
198     INTEGER_WIDTH_TEST("hhu", unsigned char);
199     INTEGER_WIDTH_TEST("hu", unsigned short);
200     INTEGER_WIDTH_TEST("lu", unsigned long);
201     INTEGER_WIDTH_TEST("llu", unsigned long long);
202     FLOAT_WIDTH_TEST(float);
203     FLOAT_WIDTH_TEST(double);
204 
205     test("Format command with invalid printf format: ");
206     len = redisFormatCommand(&cmd,"key:%08p %b",(void*)1234,"foo",(size_t)3);
207     test_cond(len == -1);
208 
209     const char *argv[3];
210     argv[0] = "SET";
211     argv[1] = "foo\0xxx";
212     argv[2] = "bar";
213     size_t lens[3] = { 3, 7, 3 };
214     int argc = 3;
215 
216     test("Format command by passing argc/argv without lengths: ");
217     len = redisFormatCommandArgv(&cmd,argc,argv,NULL);
218     test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n",len) == 0 &&
219         len == 4+4+(3+2)+4+(3+2)+4+(3+2));
220     free(cmd);
221 
222     test("Format command by passing argc/argv with lengths: ");
223     len = redisFormatCommandArgv(&cmd,argc,argv,lens);
224     test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$7\r\nfoo\0xxx\r\n$3\r\nbar\r\n",len) == 0 &&
225         len == 4+4+(3+2)+4+(7+2)+4+(3+2));
226     free(cmd);
227 }
228 
test_append_formatted_commands(struct config config)229 static void test_append_formatted_commands(struct config config) {
230     redisContext *c;
231     redisReply *reply;
232     char *cmd;
233     int len;
234 
235     c = connect(config);
236 
237     test("Append format command: ");
238 
239     len = redisFormatCommand(&cmd, "SET foo bar");
240 
241     test_cond(redisAppendFormattedCommand(c, cmd, len) == REDIS_OK);
242 
243     assert(redisGetReply(c, (void*)&reply) == REDIS_OK);
244 
245     free(cmd);
246     freeReplyObject(reply);
247 
248     disconnect(c, 0);
249 }
250 
test_reply_reader(void)251 static void test_reply_reader(void) {
252     redisReader *reader;
253     void *reply;
254     int ret;
255     int i;
256 
257     test("Error handling in reply parser: ");
258     reader = redisReaderCreate();
259     redisReaderFeed(reader,(char*)"@foo\r\n",6);
260     ret = redisReaderGetReply(reader,NULL);
261     test_cond(ret == REDIS_ERR &&
262               strcasecmp(reader->errstr,"Protocol error, got \"@\" as reply type byte") == 0);
263     redisReaderFree(reader);
264 
265     /* when the reply already contains multiple items, they must be free'd
266      * on an error. valgrind will bark when this doesn't happen. */
267     test("Memory cleanup in reply parser: ");
268     reader = redisReaderCreate();
269     redisReaderFeed(reader,(char*)"*2\r\n",4);
270     redisReaderFeed(reader,(char*)"$5\r\nhello\r\n",11);
271     redisReaderFeed(reader,(char*)"@foo\r\n",6);
272     ret = redisReaderGetReply(reader,NULL);
273     test_cond(ret == REDIS_ERR &&
274               strcasecmp(reader->errstr,"Protocol error, got \"@\" as reply type byte") == 0);
275     redisReaderFree(reader);
276 
277     test("Set error on nested multi bulks with depth > 7: ");
278     reader = redisReaderCreate();
279 
280     for (i = 0; i < 9; i++) {
281         redisReaderFeed(reader,(char*)"*1\r\n",4);
282     }
283 
284     ret = redisReaderGetReply(reader,NULL);
285     test_cond(ret == REDIS_ERR &&
286               strncasecmp(reader->errstr,"No support for",14) == 0);
287     redisReaderFree(reader);
288 
289     test("Works with NULL functions for reply: ");
290     reader = redisReaderCreate();
291     reader->fn = NULL;
292     redisReaderFeed(reader,(char*)"+OK\r\n",5);
293     ret = redisReaderGetReply(reader,&reply);
294     test_cond(ret == REDIS_OK && reply == (void*)REDIS_REPLY_STATUS);
295     redisReaderFree(reader);
296 
297     test("Works when a single newline (\\r\\n) covers two calls to feed: ");
298     reader = redisReaderCreate();
299     reader->fn = NULL;
300     redisReaderFeed(reader,(char*)"+OK\r",4);
301     ret = redisReaderGetReply(reader,&reply);
302     assert(ret == REDIS_OK && reply == NULL);
303     redisReaderFeed(reader,(char*)"\n",1);
304     ret = redisReaderGetReply(reader,&reply);
305     test_cond(ret == REDIS_OK && reply == (void*)REDIS_REPLY_STATUS);
306     redisReaderFree(reader);
307 
308     test("Don't reset state after protocol error: ");
309     reader = redisReaderCreate();
310     reader->fn = NULL;
311     redisReaderFeed(reader,(char*)"x",1);
312     ret = redisReaderGetReply(reader,&reply);
313     assert(ret == REDIS_ERR);
314     ret = redisReaderGetReply(reader,&reply);
315     test_cond(ret == REDIS_ERR && reply == NULL);
316     redisReaderFree(reader);
317 
318     /* Regression test for issue #45 on GitHub. */
319     test("Don't do empty allocation for empty multi bulk: ");
320     reader = redisReaderCreate();
321     redisReaderFeed(reader,(char*)"*0\r\n",4);
322     ret = redisReaderGetReply(reader,&reply);
323     test_cond(ret == REDIS_OK &&
324         ((redisReply*)reply)->type == REDIS_REPLY_ARRAY &&
325         ((redisReply*)reply)->elements == 0);
326     freeReplyObject(reply);
327     redisReaderFree(reader);
328 }
329 
test_free_null(void)330 static void test_free_null(void) {
331     void *redisContext = NULL;
332     void *reply = NULL;
333 
334     test("Don't fail when redisFree is passed a NULL value: ");
335     redisFree(redisContext);
336     test_cond(redisContext == NULL);
337 
338     test("Don't fail when freeReplyObject is passed a NULL value: ");
339     freeReplyObject(reply);
340     test_cond(reply == NULL);
341 }
342 
test_blocking_connection_errors(void)343 static void test_blocking_connection_errors(void) {
344     redisContext *c;
345 
346     test("Returns error when host cannot be resolved: ");
347     c = redisConnect((char*)"idontexist.test", 6379);
348     test_cond(c->err == REDIS_ERR_OTHER &&
349         (strcmp(c->errstr,"Name or service not known") == 0 ||
350          strcmp(c->errstr,"Can't resolve: idontexist.test") == 0 ||
351          strcmp(c->errstr,"nodename nor servname provided, or not known") == 0 ||
352          strcmp(c->errstr,"No address associated with hostname") == 0 ||
353          strcmp(c->errstr,"Temporary failure in name resolution") == 0 ||
354          strcmp(c->errstr,"hostname nor servname provided, or not known") == 0 ||
355          strcmp(c->errstr,"no address associated with name") == 0));
356     redisFree(c);
357 
358     test("Returns error when the port is not open: ");
359     c = redisConnect((char*)"localhost", 1);
360     test_cond(c->err == REDIS_ERR_IO &&
361         strcmp(c->errstr,"Connection refused") == 0);
362     redisFree(c);
363 
364     test("Returns error when the unix socket path doesn't accept connections: ");
365     c = redisConnectUnix((char*)"/tmp/idontexist.sock");
366     test_cond(c->err == REDIS_ERR_IO); /* Don't care about the message... */
367     redisFree(c);
368 }
369 
test_blocking_connection(struct config config)370 static void test_blocking_connection(struct config config) {
371     redisContext *c;
372     redisReply *reply;
373 
374     c = connect(config);
375 
376     test("Is able to deliver commands: ");
377     reply = redisCommand(c,"PING");
378     test_cond(reply->type == REDIS_REPLY_STATUS &&
379         strcasecmp(reply->str,"pong") == 0)
380     freeReplyObject(reply);
381 
382     test("Is a able to send commands verbatim: ");
383     reply = redisCommand(c,"SET foo bar");
384     test_cond (reply->type == REDIS_REPLY_STATUS &&
385         strcasecmp(reply->str,"ok") == 0)
386     freeReplyObject(reply);
387 
388     test("%%s String interpolation works: ");
389     reply = redisCommand(c,"SET %s %s","foo","hello world");
390     freeReplyObject(reply);
391     reply = redisCommand(c,"GET foo");
392     test_cond(reply->type == REDIS_REPLY_STRING &&
393         strcmp(reply->str,"hello world") == 0);
394     freeReplyObject(reply);
395 
396     test("%%b String interpolation works: ");
397     reply = redisCommand(c,"SET %b %b","foo",(size_t)3,"hello\x00world",(size_t)11);
398     freeReplyObject(reply);
399     reply = redisCommand(c,"GET foo");
400     test_cond(reply->type == REDIS_REPLY_STRING &&
401         memcmp(reply->str,"hello\x00world",11) == 0)
402 
403     test("Binary reply length is correct: ");
404     test_cond(reply->len == 11)
405     freeReplyObject(reply);
406 
407     test("Can parse nil replies: ");
408     reply = redisCommand(c,"GET nokey");
409     test_cond(reply->type == REDIS_REPLY_NIL)
410     freeReplyObject(reply);
411 
412     /* test 7 */
413     test("Can parse integer replies: ");
414     reply = redisCommand(c,"INCR mycounter");
415     test_cond(reply->type == REDIS_REPLY_INTEGER && reply->integer == 1)
416     freeReplyObject(reply);
417 
418     test("Can parse multi bulk replies: ");
419     freeReplyObject(redisCommand(c,"LPUSH mylist foo"));
420     freeReplyObject(redisCommand(c,"LPUSH mylist bar"));
421     reply = redisCommand(c,"LRANGE mylist 0 -1");
422     test_cond(reply->type == REDIS_REPLY_ARRAY &&
423               reply->elements == 2 &&
424               !memcmp(reply->element[0]->str,"bar",3) &&
425               !memcmp(reply->element[1]->str,"foo",3))
426     freeReplyObject(reply);
427 
428     /* m/e with multi bulk reply *before* other reply.
429      * specifically test ordering of reply items to parse. */
430     test("Can handle nested multi bulk replies: ");
431     freeReplyObject(redisCommand(c,"MULTI"));
432     freeReplyObject(redisCommand(c,"LRANGE mylist 0 -1"));
433     freeReplyObject(redisCommand(c,"PING"));
434     reply = (redisCommand(c,"EXEC"));
435     test_cond(reply->type == REDIS_REPLY_ARRAY &&
436               reply->elements == 2 &&
437               reply->element[0]->type == REDIS_REPLY_ARRAY &&
438               reply->element[0]->elements == 2 &&
439               !memcmp(reply->element[0]->element[0]->str,"bar",3) &&
440               !memcmp(reply->element[0]->element[1]->str,"foo",3) &&
441               reply->element[1]->type == REDIS_REPLY_STATUS &&
442               strcasecmp(reply->element[1]->str,"pong") == 0);
443     freeReplyObject(reply);
444 
445     disconnect(c, 0);
446 }
447 
test_blocking_connection_timeouts(struct config config)448 static void test_blocking_connection_timeouts(struct config config) {
449     redisContext *c;
450     redisReply *reply;
451     ssize_t s;
452     const char *cmd = "DEBUG SLEEP 3\r\n";
453     struct timeval tv;
454 
455     c = connect(config);
456     test("Successfully completes a command when the timeout is not exceeded: ");
457     reply = redisCommand(c,"SET foo fast");
458     freeReplyObject(reply);
459     tv.tv_sec = 0;
460     tv.tv_usec = 10000;
461     redisSetTimeout(c, tv);
462     reply = redisCommand(c, "GET foo");
463     test_cond(reply != NULL && reply->type == REDIS_REPLY_STRING && memcmp(reply->str, "fast", 4) == 0);
464     freeReplyObject(reply);
465     disconnect(c, 0);
466 
467     c = connect(config);
468     test("Does not return a reply when the command times out: ");
469     s = write(c->fd, cmd, strlen(cmd));
470     tv.tv_sec = 0;
471     tv.tv_usec = 10000;
472     redisSetTimeout(c, tv);
473     reply = redisCommand(c, "GET foo");
474     test_cond(s > 0 && reply == NULL && c->err == REDIS_ERR_IO && strcmp(c->errstr, "Resource temporarily unavailable") == 0);
475     freeReplyObject(reply);
476 
477     test("Reconnect properly reconnects after a timeout: ");
478     redisReconnect(c);
479     reply = redisCommand(c, "PING");
480     test_cond(reply != NULL && reply->type == REDIS_REPLY_STATUS && strcmp(reply->str, "PONG") == 0);
481     freeReplyObject(reply);
482 
483     test("Reconnect properly uses owned parameters: ");
484     config.tcp.host = "foo";
485     config.unix.path = "foo";
486     redisReconnect(c);
487     reply = redisCommand(c, "PING");
488     test_cond(reply != NULL && reply->type == REDIS_REPLY_STATUS && strcmp(reply->str, "PONG") == 0);
489     freeReplyObject(reply);
490 
491     disconnect(c, 0);
492 }
493 
test_blocking_io_errors(struct config config)494 static void test_blocking_io_errors(struct config config) {
495     redisContext *c;
496     redisReply *reply;
497     void *_reply;
498     int major, minor;
499 
500     /* Connect to target given by config. */
501     c = connect(config);
502     {
503         /* Find out Redis version to determine the path for the next test */
504         const char *field = "redis_version:";
505         char *p, *eptr;
506 
507         reply = redisCommand(c,"INFO");
508         p = strstr(reply->str,field);
509         major = strtol(p+strlen(field),&eptr,10);
510         p = eptr+1; /* char next to the first "." */
511         minor = strtol(p,&eptr,10);
512         freeReplyObject(reply);
513     }
514 
515     test("Returns I/O error when the connection is lost: ");
516     reply = redisCommand(c,"QUIT");
517     if (major > 2 || (major == 2 && minor > 0)) {
518         /* > 2.0 returns OK on QUIT and read() should be issued once more
519          * to know the descriptor is at EOF. */
520         test_cond(strcasecmp(reply->str,"OK") == 0 &&
521             redisGetReply(c,&_reply) == REDIS_ERR);
522         freeReplyObject(reply);
523     } else {
524         test_cond(reply == NULL);
525     }
526 
527     /* On 2.0, QUIT will cause the connection to be closed immediately and
528      * the read(2) for the reply on QUIT will set the error to EOF.
529      * On >2.0, QUIT will return with OK and another read(2) needed to be
530      * issued to find out the socket was closed by the server. In both
531      * conditions, the error will be set to EOF. */
532     assert(c->err == REDIS_ERR_EOF &&
533         strcmp(c->errstr,"Server closed the connection") == 0);
534     redisFree(c);
535 
536     c = connect(config);
537     test("Returns I/O error on socket timeout: ");
538     struct timeval tv = { 0, 1000 };
539     assert(redisSetTimeout(c,tv) == REDIS_OK);
540     test_cond(redisGetReply(c,&_reply) == REDIS_ERR &&
541         c->err == REDIS_ERR_IO && errno == EAGAIN);
542     redisFree(c);
543 }
544 
test_invalid_timeout_errors(struct config config)545 static void test_invalid_timeout_errors(struct config config) {
546     redisContext *c;
547 
548     test("Set error when an invalid timeout usec value is given to redisConnectWithTimeout: ");
549 
550     config.tcp.timeout.tv_sec = 0;
551     config.tcp.timeout.tv_usec = 10000001;
552 
553     c = redisConnectWithTimeout(config.tcp.host, config.tcp.port, config.tcp.timeout);
554 
555     test_cond(c->err == REDIS_ERR_IO);
556     redisFree(c);
557 
558     test("Set error when an invalid timeout sec value is given to redisConnectWithTimeout: ");
559 
560     config.tcp.timeout.tv_sec = (((LONG_MAX) - 999) / 1000) + 1;
561     config.tcp.timeout.tv_usec = 0;
562 
563     c = redisConnectWithTimeout(config.tcp.host, config.tcp.port, config.tcp.timeout);
564 
565     test_cond(c->err == REDIS_ERR_IO);
566     redisFree(c);
567 }
568 
test_throughput(struct config config)569 static void test_throughput(struct config config) {
570     redisContext *c = connect(config);
571     redisReply **replies;
572     int i, num;
573     long long t1, t2;
574 
575     test("Throughput:\n");
576     for (i = 0; i < 500; i++)
577         freeReplyObject(redisCommand(c,"LPUSH mylist foo"));
578 
579     num = 1000;
580     replies = malloc(sizeof(redisReply*)*num);
581     t1 = usec();
582     for (i = 0; i < num; i++) {
583         replies[i] = redisCommand(c,"PING");
584         assert(replies[i] != NULL && replies[i]->type == REDIS_REPLY_STATUS);
585     }
586     t2 = usec();
587     for (i = 0; i < num; i++) freeReplyObject(replies[i]);
588     free(replies);
589     printf("\t(%dx PING: %.3fs)\n", num, (t2-t1)/1000000.0);
590 
591     replies = malloc(sizeof(redisReply*)*num);
592     t1 = usec();
593     for (i = 0; i < num; i++) {
594         replies[i] = redisCommand(c,"LRANGE mylist 0 499");
595         assert(replies[i] != NULL && replies[i]->type == REDIS_REPLY_ARRAY);
596         assert(replies[i] != NULL && replies[i]->elements == 500);
597     }
598     t2 = usec();
599     for (i = 0; i < num; i++) freeReplyObject(replies[i]);
600     free(replies);
601     printf("\t(%dx LRANGE with 500 elements: %.3fs)\n", num, (t2-t1)/1000000.0);
602 
603     num = 10000;
604     replies = malloc(sizeof(redisReply*)*num);
605     for (i = 0; i < num; i++)
606         redisAppendCommand(c,"PING");
607     t1 = usec();
608     for (i = 0; i < num; i++) {
609         assert(redisGetReply(c, (void*)&replies[i]) == REDIS_OK);
610         assert(replies[i] != NULL && replies[i]->type == REDIS_REPLY_STATUS);
611     }
612     t2 = usec();
613     for (i = 0; i < num; i++) freeReplyObject(replies[i]);
614     free(replies);
615     printf("\t(%dx PING (pipelined): %.3fs)\n", num, (t2-t1)/1000000.0);
616 
617     replies = malloc(sizeof(redisReply*)*num);
618     for (i = 0; i < num; i++)
619         redisAppendCommand(c,"LRANGE mylist 0 499");
620     t1 = usec();
621     for (i = 0; i < num; i++) {
622         assert(redisGetReply(c, (void*)&replies[i]) == REDIS_OK);
623         assert(replies[i] != NULL && replies[i]->type == REDIS_REPLY_ARRAY);
624         assert(replies[i] != NULL && replies[i]->elements == 500);
625     }
626     t2 = usec();
627     for (i = 0; i < num; i++) freeReplyObject(replies[i]);
628     free(replies);
629     printf("\t(%dx LRANGE with 500 elements (pipelined): %.3fs)\n", num, (t2-t1)/1000000.0);
630 
631     disconnect(c, 0);
632 }
633 
634 // static long __test_callback_flags = 0;
635 // static void __test_callback(redisContext *c, void *privdata) {
636 //     ((void)c);
637 //     /* Shift to detect execution order */
638 //     __test_callback_flags <<= 8;
639 //     __test_callback_flags |= (long)privdata;
640 // }
641 //
642 // static void __test_reply_callback(redisContext *c, redisReply *reply, void *privdata) {
643 //     ((void)c);
644 //     /* Shift to detect execution order */
645 //     __test_callback_flags <<= 8;
646 //     __test_callback_flags |= (long)privdata;
647 //     if (reply) freeReplyObject(reply);
648 // }
649 //
650 // static redisContext *__connect_nonblock() {
651 //     /* Reset callback flags */
652 //     __test_callback_flags = 0;
653 //     return redisConnectNonBlock("127.0.0.1", port, NULL);
654 // }
655 //
656 // static void test_nonblocking_connection() {
657 //     redisContext *c;
658 //     int wdone = 0;
659 //
660 //     test("Calls command callback when command is issued: ");
661 //     c = __connect_nonblock();
662 //     redisSetCommandCallback(c,__test_callback,(void*)1);
663 //     redisCommand(c,"PING");
664 //     test_cond(__test_callback_flags == 1);
665 //     redisFree(c);
666 //
667 //     test("Calls disconnect callback on redisDisconnect: ");
668 //     c = __connect_nonblock();
669 //     redisSetDisconnectCallback(c,__test_callback,(void*)2);
670 //     redisDisconnect(c);
671 //     test_cond(__test_callback_flags == 2);
672 //     redisFree(c);
673 //
674 //     test("Calls disconnect callback and free callback on redisFree: ");
675 //     c = __connect_nonblock();
676 //     redisSetDisconnectCallback(c,__test_callback,(void*)2);
677 //     redisSetFreeCallback(c,__test_callback,(void*)4);
678 //     redisFree(c);
679 //     test_cond(__test_callback_flags == ((2 << 8) | 4));
680 //
681 //     test("redisBufferWrite against empty write buffer: ");
682 //     c = __connect_nonblock();
683 //     test_cond(redisBufferWrite(c,&wdone) == REDIS_OK && wdone == 1);
684 //     redisFree(c);
685 //
686 //     test("redisBufferWrite against not yet connected fd: ");
687 //     c = __connect_nonblock();
688 //     redisCommand(c,"PING");
689 //     test_cond(redisBufferWrite(c,NULL) == REDIS_ERR &&
690 //               strncmp(c->error,"write:",6) == 0);
691 //     redisFree(c);
692 //
693 //     test("redisBufferWrite against closed fd: ");
694 //     c = __connect_nonblock();
695 //     redisCommand(c,"PING");
696 //     redisDisconnect(c);
697 //     test_cond(redisBufferWrite(c,NULL) == REDIS_ERR &&
698 //               strncmp(c->error,"write:",6) == 0);
699 //     redisFree(c);
700 //
701 //     test("Process callbacks in the right sequence: ");
702 //     c = __connect_nonblock();
703 //     redisCommandWithCallback(c,__test_reply_callback,(void*)1,"PING");
704 //     redisCommandWithCallback(c,__test_reply_callback,(void*)2,"PING");
705 //     redisCommandWithCallback(c,__test_reply_callback,(void*)3,"PING");
706 //
707 //     /* Write output buffer */
708 //     wdone = 0;
709 //     while(!wdone) {
710 //         usleep(500);
711 //         redisBufferWrite(c,&wdone);
712 //     }
713 //
714 //     /* Read until at least one callback is executed (the 3 replies will
715 //      * arrive in a single packet, causing all callbacks to be executed in
716 //      * a single pass). */
717 //     while(__test_callback_flags == 0) {
718 //         assert(redisBufferRead(c) == REDIS_OK);
719 //         redisProcessCallbacks(c);
720 //     }
721 //     test_cond(__test_callback_flags == 0x010203);
722 //     redisFree(c);
723 //
724 //     test("redisDisconnect executes pending callbacks with NULL reply: ");
725 //     c = __connect_nonblock();
726 //     redisSetDisconnectCallback(c,__test_callback,(void*)1);
727 //     redisCommandWithCallback(c,__test_reply_callback,(void*)2,"PING");
728 //     redisDisconnect(c);
729 //     test_cond(__test_callback_flags == 0x0201);
730 //     redisFree(c);
731 // }
732 
main(int argc,char ** argv)733 int main(int argc, char **argv) {
734     struct config cfg = {
735         .tcp = {
736             .host = "127.0.0.1",
737             .port = 6379
738         },
739         .unix = {
740             .path = "/tmp/redis.sock"
741         }
742     };
743     int throughput = 1;
744     int test_inherit_fd = 1;
745 
746     /* Ignore broken pipe signal (for I/O error tests). */
747     signal(SIGPIPE, SIG_IGN);
748 
749     /* Parse command line options. */
750     argv++; argc--;
751     while (argc) {
752         if (argc >= 2 && !strcmp(argv[0],"-h")) {
753             argv++; argc--;
754             cfg.tcp.host = argv[0];
755         } else if (argc >= 2 && !strcmp(argv[0],"-p")) {
756             argv++; argc--;
757             cfg.tcp.port = atoi(argv[0]);
758         } else if (argc >= 2 && !strcmp(argv[0],"-s")) {
759             argv++; argc--;
760             cfg.unix.path = argv[0];
761         } else if (argc >= 1 && !strcmp(argv[0],"--skip-throughput")) {
762             throughput = 0;
763         } else if (argc >= 1 && !strcmp(argv[0],"--skip-inherit-fd")) {
764             test_inherit_fd = 0;
765         } else {
766             fprintf(stderr, "Invalid argument: %s\n", argv[0]);
767             exit(1);
768         }
769         argv++; argc--;
770     }
771 
772     test_format_commands();
773     test_reply_reader();
774     test_blocking_connection_errors();
775     test_free_null();
776 
777     printf("\nTesting against TCP connection (%s:%d):\n", cfg.tcp.host, cfg.tcp.port);
778     cfg.type = CONN_TCP;
779     test_blocking_connection(cfg);
780     test_blocking_connection_timeouts(cfg);
781     test_blocking_io_errors(cfg);
782     test_invalid_timeout_errors(cfg);
783     test_append_formatted_commands(cfg);
784     if (throughput) test_throughput(cfg);
785 
786     printf("\nTesting against Unix socket connection (%s):\n", cfg.unix.path);
787     cfg.type = CONN_UNIX;
788     test_blocking_connection(cfg);
789     test_blocking_connection_timeouts(cfg);
790     test_blocking_io_errors(cfg);
791     if (throughput) test_throughput(cfg);
792 
793     if (test_inherit_fd) {
794         printf("\nTesting against inherited fd (%s):\n", cfg.unix.path);
795         cfg.type = CONN_FD;
796         test_blocking_connection(cfg);
797     }
798 
799 
800     if (fails) {
801         printf("*** %d TESTS FAILED ***\n", fails);
802         return 1;
803     }
804 
805     printf("ALL TESTS PASSED\n");
806     return 0;
807 }
808