诸暨麻将添加redis
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

1018 行
35 KiB

  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 = NULL;
  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 = NULL;
  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. /* Make sure passing NULL to redisGetReply is safe */
  508. test("Can pass NULL to redisGetReply: ");
  509. assert(redisAppendCommand(c, "PING") == REDIS_OK);
  510. test_cond(redisGetReply(c, NULL) == REDIS_OK);
  511. disconnect(c, 0);
  512. }
  513. static void test_blocking_connection_timeouts(struct config config) {
  514. redisContext *c;
  515. redisReply *reply;
  516. ssize_t s;
  517. const char *cmd = "DEBUG SLEEP 3\r\n";
  518. struct timeval tv;
  519. c = do_connect(config);
  520. test("Successfully completes a command when the timeout is not exceeded: ");
  521. reply = redisCommand(c,"SET foo fast");
  522. freeReplyObject(reply);
  523. tv.tv_sec = 0;
  524. tv.tv_usec = 10000;
  525. redisSetTimeout(c, tv);
  526. reply = redisCommand(c, "GET foo");
  527. test_cond(reply != NULL && reply->type == REDIS_REPLY_STRING && memcmp(reply->str, "fast", 4) == 0);
  528. freeReplyObject(reply);
  529. disconnect(c, 0);
  530. c = do_connect(config);
  531. test("Does not return a reply when the command times out: ");
  532. redisAppendFormattedCommand(c, cmd, strlen(cmd));
  533. s = c->funcs->write(c);
  534. tv.tv_sec = 0;
  535. tv.tv_usec = 10000;
  536. redisSetTimeout(c, tv);
  537. reply = redisCommand(c, "GET foo");
  538. test_cond(s > 0 && reply == NULL && c->err == REDIS_ERR_IO && strcmp(c->errstr, "Resource temporarily unavailable") == 0);
  539. freeReplyObject(reply);
  540. test("Reconnect properly reconnects after a timeout: ");
  541. do_reconnect(c, config);
  542. reply = redisCommand(c, "PING");
  543. test_cond(reply != NULL && reply->type == REDIS_REPLY_STATUS && strcmp(reply->str, "PONG") == 0);
  544. freeReplyObject(reply);
  545. test("Reconnect properly uses owned parameters: ");
  546. config.tcp.host = "foo";
  547. config.unix_sock.path = "foo";
  548. do_reconnect(c, config);
  549. reply = redisCommand(c, "PING");
  550. test_cond(reply != NULL && reply->type == REDIS_REPLY_STATUS && strcmp(reply->str, "PONG") == 0);
  551. freeReplyObject(reply);
  552. disconnect(c, 0);
  553. }
  554. static void test_blocking_io_errors(struct config config) {
  555. redisContext *c;
  556. redisReply *reply;
  557. void *_reply;
  558. int major, minor;
  559. /* Connect to target given by config. */
  560. c = do_connect(config);
  561. {
  562. /* Find out Redis version to determine the path for the next test */
  563. const char *field = "redis_version:";
  564. char *p, *eptr;
  565. reply = redisCommand(c,"INFO");
  566. p = strstr(reply->str,field);
  567. major = strtol(p+strlen(field),&eptr,10);
  568. p = eptr+1; /* char next to the first "." */
  569. minor = strtol(p,&eptr,10);
  570. freeReplyObject(reply);
  571. }
  572. test("Returns I/O error when the connection is lost: ");
  573. reply = redisCommand(c,"QUIT");
  574. if (major > 2 || (major == 2 && minor > 0)) {
  575. /* > 2.0 returns OK on QUIT and read() should be issued once more
  576. * to know the descriptor is at EOF. */
  577. test_cond(strcasecmp(reply->str,"OK") == 0 &&
  578. redisGetReply(c,&_reply) == REDIS_ERR);
  579. freeReplyObject(reply);
  580. } else {
  581. test_cond(reply == NULL);
  582. }
  583. /* On 2.0, QUIT will cause the connection to be closed immediately and
  584. * the read(2) for the reply on QUIT will set the error to EOF.
  585. * On >2.0, QUIT will return with OK and another read(2) needed to be
  586. * issued to find out the socket was closed by the server. In both
  587. * conditions, the error will be set to EOF. */
  588. assert(c->err == REDIS_ERR_EOF &&
  589. strcmp(c->errstr,"Server closed the connection") == 0);
  590. redisFree(c);
  591. c = do_connect(config);
  592. test("Returns I/O error on socket timeout: ");
  593. struct timeval tv = { 0, 1000 };
  594. assert(redisSetTimeout(c,tv) == REDIS_OK);
  595. test_cond(redisGetReply(c,&_reply) == REDIS_ERR &&
  596. c->err == REDIS_ERR_IO && errno == EAGAIN);
  597. redisFree(c);
  598. }
  599. static void test_invalid_timeout_errors(struct config config) {
  600. redisContext *c;
  601. test("Set error when an invalid timeout usec value is given to redisConnectWithTimeout: ");
  602. config.tcp.timeout.tv_sec = 0;
  603. config.tcp.timeout.tv_usec = 10000001;
  604. c = redisConnectWithTimeout(config.tcp.host, config.tcp.port, config.tcp.timeout);
  605. test_cond(c->err == REDIS_ERR_IO && strcmp(c->errstr, "Invalid timeout specified") == 0);
  606. redisFree(c);
  607. test("Set error when an invalid timeout sec value is given to redisConnectWithTimeout: ");
  608. config.tcp.timeout.tv_sec = (((LONG_MAX) - 999) / 1000) + 1;
  609. config.tcp.timeout.tv_usec = 0;
  610. c = redisConnectWithTimeout(config.tcp.host, config.tcp.port, config.tcp.timeout);
  611. test_cond(c->err == REDIS_ERR_IO && strcmp(c->errstr, "Invalid timeout specified") == 0);
  612. redisFree(c);
  613. }
  614. static void test_throughput(struct config config) {
  615. redisContext *c = do_connect(config);
  616. redisReply **replies;
  617. int i, num;
  618. long long t1, t2;
  619. test("Throughput:\n");
  620. for (i = 0; i < 500; i++)
  621. freeReplyObject(redisCommand(c,"LPUSH mylist foo"));
  622. num = 1000;
  623. replies = malloc(sizeof(redisReply*)*num);
  624. t1 = usec();
  625. for (i = 0; i < num; i++) {
  626. replies[i] = redisCommand(c,"PING");
  627. assert(replies[i] != NULL && replies[i]->type == REDIS_REPLY_STATUS);
  628. }
  629. t2 = usec();
  630. for (i = 0; i < num; i++) freeReplyObject(replies[i]);
  631. free(replies);
  632. printf("\t(%dx PING: %.3fs)\n", num, (t2-t1)/1000000.0);
  633. replies = malloc(sizeof(redisReply*)*num);
  634. t1 = usec();
  635. for (i = 0; i < num; i++) {
  636. replies[i] = redisCommand(c,"LRANGE mylist 0 499");
  637. assert(replies[i] != NULL && replies[i]->type == REDIS_REPLY_ARRAY);
  638. assert(replies[i] != NULL && replies[i]->elements == 500);
  639. }
  640. t2 = usec();
  641. for (i = 0; i < num; i++) freeReplyObject(replies[i]);
  642. free(replies);
  643. printf("\t(%dx LRANGE with 500 elements: %.3fs)\n", num, (t2-t1)/1000000.0);
  644. replies = malloc(sizeof(redisReply*)*num);
  645. t1 = usec();
  646. for (i = 0; i < num; i++) {
  647. replies[i] = redisCommand(c, "INCRBY incrkey %d", 1000000);
  648. assert(replies[i] != NULL && replies[i]->type == REDIS_REPLY_INTEGER);
  649. }
  650. t2 = usec();
  651. for (i = 0; i < num; i++) freeReplyObject(replies[i]);
  652. free(replies);
  653. printf("\t(%dx INCRBY: %.3fs)\n", num, (t2-t1)/1000000.0);
  654. num = 10000;
  655. replies = malloc(sizeof(redisReply*)*num);
  656. for (i = 0; i < num; i++)
  657. redisAppendCommand(c,"PING");
  658. t1 = usec();
  659. for (i = 0; i < num; i++) {
  660. assert(redisGetReply(c, (void*)&replies[i]) == REDIS_OK);
  661. assert(replies[i] != NULL && replies[i]->type == REDIS_REPLY_STATUS);
  662. }
  663. t2 = usec();
  664. for (i = 0; i < num; i++) freeReplyObject(replies[i]);
  665. free(replies);
  666. printf("\t(%dx PING (pipelined): %.3fs)\n", num, (t2-t1)/1000000.0);
  667. replies = malloc(sizeof(redisReply*)*num);
  668. for (i = 0; i < num; i++)
  669. redisAppendCommand(c,"LRANGE mylist 0 499");
  670. t1 = usec();
  671. for (i = 0; i < num; i++) {
  672. assert(redisGetReply(c, (void*)&replies[i]) == REDIS_OK);
  673. assert(replies[i] != NULL && replies[i]->type == REDIS_REPLY_ARRAY);
  674. assert(replies[i] != NULL && replies[i]->elements == 500);
  675. }
  676. t2 = usec();
  677. for (i = 0; i < num; i++) freeReplyObject(replies[i]);
  678. free(replies);
  679. printf("\t(%dx LRANGE with 500 elements (pipelined): %.3fs)\n", num, (t2-t1)/1000000.0);
  680. replies = malloc(sizeof(redisReply*)*num);
  681. for (i = 0; i < num; i++)
  682. redisAppendCommand(c,"INCRBY incrkey %d", 1000000);
  683. t1 = usec();
  684. for (i = 0; i < num; i++) {
  685. assert(redisGetReply(c, (void*)&replies[i]) == REDIS_OK);
  686. assert(replies[i] != NULL && replies[i]->type == REDIS_REPLY_INTEGER);
  687. }
  688. t2 = usec();
  689. for (i = 0; i < num; i++) freeReplyObject(replies[i]);
  690. free(replies);
  691. printf("\t(%dx INCRBY (pipelined): %.3fs)\n", num, (t2-t1)/1000000.0);
  692. disconnect(c, 0);
  693. }
  694. // static long __test_callback_flags = 0;
  695. // static void __test_callback(redisContext *c, void *privdata) {
  696. // ((void)c);
  697. // /* Shift to detect execution order */
  698. // __test_callback_flags <<= 8;
  699. // __test_callback_flags |= (long)privdata;
  700. // }
  701. //
  702. // static void __test_reply_callback(redisContext *c, redisReply *reply, void *privdata) {
  703. // ((void)c);
  704. // /* Shift to detect execution order */
  705. // __test_callback_flags <<= 8;
  706. // __test_callback_flags |= (long)privdata;
  707. // if (reply) freeReplyObject(reply);
  708. // }
  709. //
  710. // static redisContext *__connect_nonblock() {
  711. // /* Reset callback flags */
  712. // __test_callback_flags = 0;
  713. // return redisConnectNonBlock("127.0.0.1", port, NULL);
  714. // }
  715. //
  716. // static void test_nonblocking_connection() {
  717. // redisContext *c;
  718. // int wdone = 0;
  719. //
  720. // test("Calls command callback when command is issued: ");
  721. // c = __connect_nonblock();
  722. // redisSetCommandCallback(c,__test_callback,(void*)1);
  723. // redisCommand(c,"PING");
  724. // test_cond(__test_callback_flags == 1);
  725. // redisFree(c);
  726. //
  727. // test("Calls disconnect callback on redisDisconnect: ");
  728. // c = __connect_nonblock();
  729. // redisSetDisconnectCallback(c,__test_callback,(void*)2);
  730. // redisDisconnect(c);
  731. // test_cond(__test_callback_flags == 2);
  732. // redisFree(c);
  733. //
  734. // test("Calls disconnect callback and free callback on redisFree: ");
  735. // c = __connect_nonblock();
  736. // redisSetDisconnectCallback(c,__test_callback,(void*)2);
  737. // redisSetFreeCallback(c,__test_callback,(void*)4);
  738. // redisFree(c);
  739. // test_cond(__test_callback_flags == ((2 << 8) | 4));
  740. //
  741. // test("redisBufferWrite against empty write buffer: ");
  742. // c = __connect_nonblock();
  743. // test_cond(redisBufferWrite(c,&wdone) == REDIS_OK && wdone == 1);
  744. // redisFree(c);
  745. //
  746. // test("redisBufferWrite against not yet connected fd: ");
  747. // c = __connect_nonblock();
  748. // redisCommand(c,"PING");
  749. // test_cond(redisBufferWrite(c,NULL) == REDIS_ERR &&
  750. // strncmp(c->error,"write:",6) == 0);
  751. // redisFree(c);
  752. //
  753. // test("redisBufferWrite against closed fd: ");
  754. // c = __connect_nonblock();
  755. // redisCommand(c,"PING");
  756. // redisDisconnect(c);
  757. // test_cond(redisBufferWrite(c,NULL) == REDIS_ERR &&
  758. // strncmp(c->error,"write:",6) == 0);
  759. // redisFree(c);
  760. //
  761. // test("Process callbacks in the right sequence: ");
  762. // c = __connect_nonblock();
  763. // redisCommandWithCallback(c,__test_reply_callback,(void*)1,"PING");
  764. // redisCommandWithCallback(c,__test_reply_callback,(void*)2,"PING");
  765. // redisCommandWithCallback(c,__test_reply_callback,(void*)3,"PING");
  766. //
  767. // /* Write output buffer */
  768. // wdone = 0;
  769. // while(!wdone) {
  770. // usleep(500);
  771. // redisBufferWrite(c,&wdone);
  772. // }
  773. //
  774. // /* Read until at least one callback is executed (the 3 replies will
  775. // * arrive in a single packet, causing all callbacks to be executed in
  776. // * a single pass). */
  777. // while(__test_callback_flags == 0) {
  778. // assert(redisBufferRead(c) == REDIS_OK);
  779. // redisProcessCallbacks(c);
  780. // }
  781. // test_cond(__test_callback_flags == 0x010203);
  782. // redisFree(c);
  783. //
  784. // test("redisDisconnect executes pending callbacks with NULL reply: ");
  785. // c = __connect_nonblock();
  786. // redisSetDisconnectCallback(c,__test_callback,(void*)1);
  787. // redisCommandWithCallback(c,__test_reply_callback,(void*)2,"PING");
  788. // redisDisconnect(c);
  789. // test_cond(__test_callback_flags == 0x0201);
  790. // redisFree(c);
  791. // }
  792. int main(int argc, char **argv) {
  793. struct config cfg = {
  794. .tcp = {
  795. .host = "127.0.0.1",
  796. .port = 6379
  797. },
  798. .unix_sock = {
  799. .path = "/tmp/redis.sock"
  800. }
  801. };
  802. int throughput = 1;
  803. int test_inherit_fd = 1;
  804. /* Ignore broken pipe signal (for I/O error tests). */
  805. signal(SIGPIPE, SIG_IGN);
  806. /* Parse command line options. */
  807. argv++; argc--;
  808. while (argc) {
  809. if (argc >= 2 && !strcmp(argv[0],"-h")) {
  810. argv++; argc--;
  811. cfg.tcp.host = argv[0];
  812. } else if (argc >= 2 && !strcmp(argv[0],"-p")) {
  813. argv++; argc--;
  814. cfg.tcp.port = atoi(argv[0]);
  815. } else if (argc >= 2 && !strcmp(argv[0],"-s")) {
  816. argv++; argc--;
  817. cfg.unix_sock.path = argv[0];
  818. } else if (argc >= 1 && !strcmp(argv[0],"--skip-throughput")) {
  819. throughput = 0;
  820. } else if (argc >= 1 && !strcmp(argv[0],"--skip-inherit-fd")) {
  821. test_inherit_fd = 0;
  822. #ifdef HIREDIS_TEST_SSL
  823. } else if (argc >= 2 && !strcmp(argv[0],"--ssl-port")) {
  824. argv++; argc--;
  825. cfg.ssl.port = atoi(argv[0]);
  826. } else if (argc >= 2 && !strcmp(argv[0],"--ssl-host")) {
  827. argv++; argc--;
  828. cfg.ssl.host = argv[0];
  829. } else if (argc >= 2 && !strcmp(argv[0],"--ssl-ca-cert")) {
  830. argv++; argc--;
  831. cfg.ssl.ca_cert = argv[0];
  832. } else if (argc >= 2 && !strcmp(argv[0],"--ssl-cert")) {
  833. argv++; argc--;
  834. cfg.ssl.cert = argv[0];
  835. } else if (argc >= 2 && !strcmp(argv[0],"--ssl-key")) {
  836. argv++; argc--;
  837. cfg.ssl.key = argv[0];
  838. #endif
  839. } else {
  840. fprintf(stderr, "Invalid argument: %s\n", argv[0]);
  841. exit(1);
  842. }
  843. argv++; argc--;
  844. }
  845. test_format_commands();
  846. test_reply_reader();
  847. test_blocking_connection_errors();
  848. test_free_null();
  849. printf("\nTesting against TCP connection (%s:%d):\n", cfg.tcp.host, cfg.tcp.port);
  850. cfg.type = CONN_TCP;
  851. test_blocking_connection(cfg);
  852. test_blocking_connection_timeouts(cfg);
  853. test_blocking_io_errors(cfg);
  854. test_invalid_timeout_errors(cfg);
  855. test_append_formatted_commands(cfg);
  856. if (throughput) test_throughput(cfg);
  857. printf("\nTesting against Unix socket connection (%s):\n", cfg.unix_sock.path);
  858. cfg.type = CONN_UNIX;
  859. test_blocking_connection(cfg);
  860. test_blocking_connection_timeouts(cfg);
  861. test_blocking_io_errors(cfg);
  862. if (throughput) test_throughput(cfg);
  863. #ifdef HIREDIS_TEST_SSL
  864. if (cfg.ssl.port && cfg.ssl.host) {
  865. printf("\nTesting against SSL connection (%s:%d):\n", cfg.ssl.host, cfg.ssl.port);
  866. cfg.type = CONN_SSL;
  867. test_blocking_connection(cfg);
  868. test_blocking_connection_timeouts(cfg);
  869. test_blocking_io_errors(cfg);
  870. test_invalid_timeout_errors(cfg);
  871. test_append_formatted_commands(cfg);
  872. if (throughput) test_throughput(cfg);
  873. }
  874. #endif
  875. if (test_inherit_fd) {
  876. printf("\nTesting against inherited fd (%s):\n", cfg.unix_sock.path);
  877. cfg.type = CONN_FD;
  878. test_blocking_connection(cfg);
  879. }
  880. if (fails) {
  881. printf("*** %d TESTS FAILED ***\n", fails);
  882. return 1;
  883. }
  884. printf("ALL TESTS PASSED\n");
  885. return 0;
  886. }