2
0

test.c 35 KB

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