parser.spec.tsx 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import {loadFixtures} from 'sentry-test/loadFixtures';
  2. import {
  3. ParseResult,
  4. parseSearch,
  5. Token,
  6. TokenResult,
  7. } from 'sentry/components/searchSyntax/parser';
  8. import {treeTransformer} from 'sentry/components/searchSyntax/utils';
  9. type TestCase = {
  10. /**
  11. * The search query string under parsing test
  12. */
  13. query: string;
  14. /**
  15. * The expected result for the query
  16. */
  17. result: ParseResult;
  18. /**
  19. * This is set when the query is expected to completely fail to parse.
  20. */
  21. raisesError?: boolean;
  22. };
  23. /**
  24. * Normalize results to match the json test cases
  25. */
  26. const normalizeResult = (tokens: TokenResult<Token>[]) =>
  27. treeTransformer({
  28. tree: tokens,
  29. transform: token => {
  30. // XXX: This attempts to keep the test data simple, only including keys
  31. // that are really needed to validate functionality.
  32. // @ts-expect-error
  33. delete token.location;
  34. // @ts-expect-error
  35. delete token.text;
  36. // @ts-expect-error
  37. delete token.config;
  38. if (token.type === Token.Filter && token.invalid === null) {
  39. // @ts-expect-error
  40. delete token.invalid;
  41. }
  42. if (token.type === Token.ValueIso8601Date) {
  43. // Date values are represented as ISO strings in the test case json
  44. return {...token, value: token.value.toISOString()};
  45. }
  46. return token;
  47. },
  48. });
  49. describe('searchSyntax/parser', function () {
  50. const testData = loadFixtures('search-syntax') as unknown as Record<string, TestCase[]>;
  51. const registerTestCase = (testCase: TestCase) =>
  52. it(`handles ${testCase.query}`, () => {
  53. const result = parseSearch(testCase.query);
  54. // Handle errors
  55. if (testCase.raisesError) {
  56. expect(result).toBeNull();
  57. return;
  58. }
  59. if (result === null) {
  60. throw new Error('Parsed result as null without raiseError true');
  61. }
  62. expect(normalizeResult(result)).toEqual(testCase.result);
  63. });
  64. Object.entries(testData).map(([name, cases]) =>
  65. describe(`${name}`, () => {
  66. cases.map(registerTestCase);
  67. })
  68. );
  69. });