testutil.h 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. #ifndef __TEST_UTIL_H__
  2. #define __TEST_UTIL_H__
  3. #include <stdarg.h>
  4. #include <string.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include "jsmn.h"
  8. static int vtokeq(const char *s, jsmntok_t *t, int numtok, va_list ap)
  9. {
  10. if (numtok > 0)
  11. {
  12. int i, start, end, size;
  13. int type;
  14. char *value;
  15. size = -1;
  16. value = NULL;
  17. for (i = 0; i < numtok; i++)
  18. {
  19. type = va_arg(ap, int);
  20. if (type == JSMN_STRING)
  21. {
  22. value = va_arg(ap, char *);
  23. size = va_arg(ap, int);
  24. start = end = -1;
  25. }
  26. else if (type == JSMN_PRIMITIVE)
  27. {
  28. value = va_arg(ap, char *);
  29. start = end = size = -1;
  30. }
  31. else
  32. {
  33. start = va_arg(ap, int);
  34. end = va_arg(ap, int);
  35. size = va_arg(ap, int);
  36. value = NULL;
  37. }
  38. if (t[i].type != type)
  39. {
  40. printf("token %d type is %d, not %d\n", i, t[i].type, type);
  41. return 0;
  42. }
  43. if (start != -1 && end != -1)
  44. {
  45. if (t[i].start != start)
  46. {
  47. printf("token %d start is %d, not %d\n", i, t[i].start, start);
  48. return 0;
  49. }
  50. if (t[i].end != end)
  51. {
  52. printf("token %d end is %d, not %d\n", i, t[i].end, end);
  53. return 0;
  54. }
  55. }
  56. if (size != -1 && t[i].size != size)
  57. {
  58. printf("token %d size is %d, not %d\n", i, t[i].size, size);
  59. return 0;
  60. }
  61. if (s != NULL && value != NULL)
  62. {
  63. const char *p = s + t[i].start;
  64. if (strlen(value) != t[i].end - t[i].start ||
  65. strncmp(p, value, t[i].end - t[i].start) != 0)
  66. {
  67. printf("token %d value is %.*s, not %s\n", i, t[i].end - t[i].start,
  68. s + t[i].start, value);
  69. return 0;
  70. }
  71. }
  72. }
  73. }
  74. return 1;
  75. }
  76. static int tokeq(const char *s, jsmntok_t *tokens, int numtok, ...)
  77. {
  78. int ok;
  79. va_list args;
  80. va_start(args, numtok);
  81. ok = vtokeq(s, tokens, numtok, args);
  82. va_end(args);
  83. return ok;
  84. }
  85. static int parse(const char *s, int status, int numtok, ...)
  86. {
  87. int r;
  88. int ok = 1;
  89. va_list args;
  90. jsmn_parser p;
  91. jsmntok_t *t = malloc(numtok * sizeof(jsmntok_t));
  92. jsmn_init(&p);
  93. r = jsmn_parse(&p, s, strlen(s), t, numtok);
  94. if (r != status)
  95. {
  96. printf("status is %d, not %d\n", r, status);
  97. return 0;
  98. }
  99. if (status >= 0)
  100. {
  101. va_start(args, numtok);
  102. ok = vtokeq(s, t, numtok, args);
  103. va_end(args);
  104. }
  105. free(t);
  106. return ok;
  107. }
  108. #endif /* __TEST_UTIL_H__ */