factory-defaults-contract.test.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { readFileSync } from 'node:fs';
  2. import { resolve } from 'node:path';
  3. import { describe, expect, it } from 'vitest';
  4. import { matchesFactoryDefault } from '@/components/ui/DefaultSettingTag';
  5. import { AllSetting } from '@/models/setting';
  6. /*
  7. * Contract test between the three homes of a setting's default value: the Go
  8. * defaultValueMap (authoritative, served by /setting/factoryDefaults), the
  9. * frontend AllSetting class defaults (what the form shows when the API omits
  10. * a value), and the tag's own comparison. If someone bumps a default on one
  11. * side only, the Default tag would start calling a different value "Default"
  12. * than the one the form displays — this test fails instead.
  13. */
  14. function goDefaultLiterals(): Record<string, string> {
  15. const source = readFileSync(
  16. resolve(process.cwd(), '..', 'internal', 'web', 'service', 'setting.go'),
  17. 'utf8',
  18. );
  19. const start = source.indexOf('var defaultValueMap = map[string]string{');
  20. const end = source.indexOf('\n}', start);
  21. const block = source.slice(start, end);
  22. const literals: Record<string, string> = {};
  23. for (const match of block.matchAll(/"([A-Za-z0-9]+)":\s+"((?:[^"\\]|\\.)*)"\s*,/g)) {
  24. literals[match[1]] = JSON.parse(`"${match[2]}"`);
  25. }
  26. return literals;
  27. }
  28. describe('factory defaults contract', () => {
  29. const goDefaults = goDefaultLiterals();
  30. const frontend = new AllSetting() as unknown as Record<string, unknown>;
  31. const sharedKeys = Object.keys(goDefaults).filter((key) => {
  32. const value = frontend[key];
  33. return typeof value === 'number' || typeof value === 'boolean' || typeof value === 'string';
  34. });
  35. it('parses a plausible slice of the Go map', () => {
  36. expect(goDefaults.webPort).toBe('2053');
  37. expect(goDefaults.subPort).toBe('2096');
  38. expect(sharedKeys.length).toBeGreaterThan(20);
  39. });
  40. it.each(sharedKeys)('frontend default for %s matches the shipped default', (key) => {
  41. expect(
  42. matchesFactoryDefault(frontend[key], goDefaults[key]),
  43. `AllSetting.${key} = ${JSON.stringify(frontend[key])} vs defaultValueMap ${JSON.stringify(goDefaults[key])}`,
  44. ).toBe(true);
  45. });
  46. });