Merge remote-tracking branch 'origin/main' into play-app-record
# Conflicts: # CHANGELOG.md
This commit is contained in:
commit
962cd3cb9d
45 changed files with 1236 additions and 175 deletions
77
tests/apple-name.test.ts
Normal file
77
tests/apple-name.test.ts
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
// apple.name: the App Store name when the plain app.name is taken on the App Store. Fallback order (### name block >
|
||||
// apple.name > app.name), validation, the console answer, check's length error and same-name hint, listing pull.
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { run as check } from '../cli/check';
|
||||
import { appleName, type ShipConfig, validateConfig } from '../cli/lib/config';
|
||||
import { consoleAnswers } from '../cli/lib/console-answers';
|
||||
import { navPlan } from '../cli/lib/console-forms';
|
||||
import { appleNameIssues } from '../cli/lib/copy';
|
||||
import { mergeAppleListing } from '../cli/lib/listing-pull';
|
||||
import { listingCompleteness } from '../cli/lib/project-files';
|
||||
import { BASE, capture, jsonOut, project, restore } from './helpers/store-mock';
|
||||
|
||||
afterEach(restore);
|
||||
|
||||
const NAMED: ShipConfig = { ...BASE, app: { ...BASE.app, name: 'STAR DASH' }, apple: { ...BASE.apple!, name: 'STAR DASH: Stone Age to 2100', primaryLocale: 'en-US' } };
|
||||
const PLAIN: ShipConfig = { ...BASE, app: { ...BASE.app, name: 'STAR DASH' }, apple: { ...BASE.apple!, primaryLocale: 'en-US' } };
|
||||
const sec = (loc: string, name?: string) => `## ${loc}\n\n${name ? `### name\n\`\`\`\n${name}\n\`\`\`\n\n` : ''}### subtitle\n\`\`\`\nSub\n\`\`\`\n\n### promotionalText\n\`\`\`\nPromo\n\`\`\`\n\n### keywords\n\`\`\`\nrun,time\n\`\`\`\n\n### description\n\`\`\`\nText.\n\`\`\`\n\n`;
|
||||
|
||||
describe('apple.name', () => {
|
||||
test('fallback order: apple.name, else app.name', () => {
|
||||
expect(appleName(NAMED)).toBe('STAR DASH: Stone Age to 2100');
|
||||
expect(appleName(PLAIN)).toBe('STAR DASH');
|
||||
expect(appleName({ ...PLAIN, apple: { ...PLAIN.apple!, name: ' ' } })).toBe('STAR DASH');
|
||||
});
|
||||
test('validated: at most 30 characters, text', () => {
|
||||
expect(validateConfig(NAMED)).toEqual([]);
|
||||
expect(validateConfig({ ...NAMED, apple: { ...NAMED.apple!, name: 'STAR DASH: Stone Age to the Year 2100' } }).join('\n')).toContain('apple.name: 37 characters > 30');
|
||||
expect(validateConfig({ ...NAMED, apple: { ...NAMED.apple!, name: '' } }).join('\n')).toContain('apple.name: the App Store name');
|
||||
});
|
||||
test('console fill apple-app-record answers Name from apple.name, else app.name', () => {
|
||||
const a = new Map(consoleAnswers('apple-app-record', NAMED).map(x => [x.id, x]));
|
||||
expect(a.get('name')).toMatchObject({ value: 'STAR DASH: Stone Age to 2100', source: 'apple.name', certain: true });
|
||||
const b = new Map(consoleAnswers('apple-app-record', PLAIN).map(x => [x.id, x]));
|
||||
expect(b.get('name')).toMatchObject({ value: 'STAR DASH', source: 'app.name' });
|
||||
expect(b.get('name')!.note).toContain('apple.name');
|
||||
const pick = navPlan('apple-app-privacy', { ...NAMED, apple: { ...NAMED.apple!, appId: undefined } }).find(s => s.kind === 'pickApp') as { name?: string } | undefined;
|
||||
expect(pick?.name).toBe('STAR DASH: Stone Age to 2100');
|
||||
});
|
||||
test('name issues: length error per locale, same-name hint only without apple.name or own names', () => {
|
||||
const long = 'A Name That Is Way Too Long For Apple';
|
||||
expect(appleNameIssues({}, ['en-US'], long, long)).toEqual([expect.objectContaining({ level: 'error', msg: expect.stringContaining('app.name; set apple.name') }), expect.objectContaining({ level: 'info' })]);
|
||||
expect(appleNameIssues({ 'de-DE': { name: long } }, ['en-US'], 'Short', 'Short').map(i => `${i.level} ${i.msg.slice(0, 31)}`)).toEqual(['error App Store name of de-DE is 37 >']);
|
||||
const hint = appleNameIssues({ 'en-US': {} , 'de-DE': {} }, ['en-US', 'de-DE'], 'STAR DASH', 'STAR DASH');
|
||||
expect(hint).toHaveLength(1);
|
||||
expect(hint[0]!.msg).toContain('already being used');
|
||||
expect(appleNameIssues({}, ['en-US', 'de-DE'], 'STAR DASH: Stone Age to 2100', 'STAR DASH')).toEqual([]);
|
||||
expect(appleNameIssues({ 'de-DE': { name: 'STAR DASH: Steinzeit bis 2100' } }, ['en-US', 'de-DE'], 'STAR DASH', 'STAR DASH')).toEqual([]);
|
||||
});
|
||||
test('check: hint with the plain name, error when the fallback is too long', async () => {
|
||||
const files = { 'store/appstore.md': `# App Store\n\n${sec('en-US')}${sec('de-DE')}${sec('tr')}`, '.gitignore': '.storebound/\n' };
|
||||
let p = project({ ...PLAIN, play: undefined }, files);
|
||||
let j = jsonOut((await capture(() => check(p.ctx(['--json'], ['json'])))).out);
|
||||
expect(j.ok).toBe(true);
|
||||
expect((j.hints as string[]).join('\n')).toContain('already being used');
|
||||
p = project({ ...NAMED, play: undefined }, files);
|
||||
j = jsonOut((await capture(() => check(p.ctx(['--json'], ['json'])))).out);
|
||||
expect(j.hints).toEqual([]);
|
||||
p = project({ ...PLAIN, app: { ...PLAIN.app, name: 'STAR DASH Stone Age to the Year 2100' }, play: undefined }, files);
|
||||
const r = await capture(() => check(p.ctx(['--json'], ['json'])));
|
||||
j = jsonOut(r.out);
|
||||
expect(j.ok).toBe(false);
|
||||
expect((j.problems as string[]).filter(x => x.includes('App Store name of'))).toHaveLength(3);
|
||||
});
|
||||
test('listing completeness and listing pull use apple.name as the default name', () => {
|
||||
const p = project({ ...NAMED, play: undefined }, { 'store/appstore.md': `# App Store\n\n${sec('en-US')}${sec('de-DE', 'STAR DASH: Steinzeit bis 2100')}` });
|
||||
const l = listingCompleteness(p.loaded.config, p.root);
|
||||
const name = (code: string) => l.locales.find(x => x.apple?.code === code)!.apple!.fields.find(f => f.field === 'name');
|
||||
expect(name('en-US')).toMatchObject({ length: 28, state: 'ok' });
|
||||
expect(name('de-DE')).toMatchObject({ length: 29, state: 'ok' });
|
||||
const md = `# App Store\n\n${sec('en-US')}`;
|
||||
const r = mergeAppleListing(md, { 'en-US': { name: 'STAR DASH: Stone Age to 2100' }, 'fr-FR': { name: 'STAR DASH: Stone Age to 2100', subtitle: 'Sous-titre' } }, 'STAR DASH: Stone Age to 2100');
|
||||
expect(r.changes.map(c => `${c.section} ${c.field}`)).toEqual(['fr-FR subtitle']);
|
||||
expect(r.md).not.toContain('### name');
|
||||
const own = mergeAppleListing(`# App Store\n\n${sec('en-US', 'Old')}`, { 'en-US': { name: 'STAR DASH: Stone Age to 2100' } }, 'STAR DASH: Stone Age to 2100');
|
||||
expect(own.changes.map(c => c.field)).toEqual(['name']);
|
||||
});
|
||||
});
|
||||
157
tests/listing-plan.test.ts
Normal file
157
tests/listing-plan.test.ts
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
// Write plans of apple listing, play listing and apple appinfo: the dry run reads only and prints old -> new per field,
|
||||
// drafts are skipped, the version decision is explicit; the real run applies exactly the plan. Recorded answers only
|
||||
// (placeholders, no network).
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { run as appInfo } from '../cli/apple/appinfo';
|
||||
import { run as appleListing } from '../cli/apple/listing';
|
||||
import { run as playListing } from '../cli/play/listing';
|
||||
import { planItem, planVersion, short } from '../cli/lib/listing-plan';
|
||||
import { ascEnv, BASE, capture, jsonOut, mockFetch, playEnv, project, restore, type Call } from './helpers/store-mock';
|
||||
|
||||
afterEach(restore);
|
||||
const page = (data: unknown[]) => ({ data, links: { self: 'x' } });
|
||||
const v = (id: string, versionString: string, appVersionState: string) => ({ type: 'appStoreVersions', id, attributes: { versionString, appVersionState, platform: 'IOS', copyright: `${new Date().getFullYear()} Example Notes`, releaseType: 'MANUAL' } });
|
||||
const fence = (t: string) => '```\n' + t + '\n```';
|
||||
const sec = (loc: string, f: Record<string, string>, mark = '') => `## ${loc}\n${mark}\n` + Object.entries(f).map(([k, t]) => `### ${k}\n${fence(t)}\n`).join('\n') + '\n';
|
||||
const TEXT = { subtitle: 'Notes that sync', promotionalText: 'Now with lists.', keywords: 'notes,lists', description: 'Write things down.' };
|
||||
const APPLE_MD = '# App Store\n\n' + sec('en-US', TEXT) + sec('de-DE', { ...TEXT, subtitle: 'Notizen, synchron', description: 'Schreib es auf.' })
|
||||
+ sec('tr', { ...TEXT, subtitle: 'Senkron notlar' }, '<!-- storebound-translation from=en-US status=draft -->');
|
||||
const methods = (calls: Call[]) => calls.filter(c => c.method !== 'GET').map(c => `${c.method} ${c.path.split('?')[0]}`);
|
||||
|
||||
describe('version decision', () => {
|
||||
const attrs = { copyright: '2026 Example Notes', releaseType: 'MANUAL' };
|
||||
test('update the editable version string while PREPARE_FOR_SUBMISSION', () => {
|
||||
const p = planVersion([v('v-1', '1.0', 'PREPARE_FOR_SUBMISSION')], '1.0.0', attrs);
|
||||
expect(p).toMatchObject({ action: 'update', id: 'v-1', first: true, reason: 'update the editable version 1.0 (PREPARE_FOR_SUBMISSION) to 1.0.0' });
|
||||
expect(p.changes.find(c => c.field === 'versionString')).toEqual({ field: 'versionString', from: '1.0', to: '1.0.0' });
|
||||
});
|
||||
test('keep, create, refuse', () => {
|
||||
expect(planVersion([{ ...v('v-1', '1.0.0', 'PREPARE_FOR_SUBMISSION'), attributes: { ...v('v-1', '1.0.0', 'x').attributes, appVersionState: 'PREPARE_FOR_SUBMISSION', copyright: '2026 Example Notes' } }], '1.0.0', attrs).action).toBe('keep');
|
||||
expect(planVersion([v('v-0', '1.0.0', 'READY_FOR_DISTRIBUTION')], '1.1.0', attrs)).toMatchObject({ action: 'create', first: false });
|
||||
expect(planVersion([v('v-0', '1.0.0', 'READY_FOR_DISTRIBUTION')], '1.0.0', attrs).reason).toContain('already exists (READY_FOR_DISTRIBUTION)');
|
||||
expect(planVersion([v('v-0', '1.2.0', 'READY_FOR_DISTRIBUTION')], '1.1.0', attrs).reason).toContain('not higher than 1.2.0');
|
||||
expect(planVersion([v('v-0', '1.0.0', 'READY_FOR_DISTRIBUTION'), v('v-1', '1.1.0', 'WAITING_FOR_REVIEW')], '1.2.0', attrs).reason).toContain('1.1.0 is WAITING_FOR_REVIEW');
|
||||
expect(planVersion([v('v-0', '1.0.0', 'READY_FOR_DISTRIBUTION'), v('v-1', '1.1', 'REJECTED')], '1.1.0', attrs)).toMatchObject({ action: 'refuse', reason: expect.stringContaining('only while PREPARE_FOR_SUBMISSION') });
|
||||
expect(planVersion([], '1.0.0', attrs)).toMatchObject({ action: 'create', first: true });
|
||||
});
|
||||
test('field diff and long values cut with their length', () => {
|
||||
expect(planItem('en-US', { attributes: { subtitle: 'A', keywords: null } }, { subtitle: 'B', keywords: '', description: undefined })).toMatchObject({ action: 'update', changes: [{ field: 'subtitle', from: 'A', to: 'B' }], unchanged: ['keywords'] });
|
||||
expect(short('x'.repeat(100))).toBe(`"${'x'.repeat(60)}…" (100 chars)`);
|
||||
});
|
||||
});
|
||||
|
||||
function ascRoutes(versions: unknown[], o: { versionLocs?: unknown[]; created?: boolean } = {}) {
|
||||
return mockFetch([
|
||||
{ match: /^\/v1\/apps\/6400000101\/appStoreVersions\?filter\[platform\]=IOS/, answer: page(versions) },
|
||||
{ match: /^\/v1\/apps\/6400000101\/appInfos/, answer: page([{ type: 'appInfos', id: 'ai-1', attributes: { state: 'PREPARE_FOR_SUBMISSION' } }]) },
|
||||
{ match: /^\/v1\/appInfos\/ai-1\/appInfoLocalizations/, answer: page([{ type: 'appInfoLocalizations', id: 'il-en', attributes: { locale: 'en-US', name: 'Example Notes', subtitle: 'Old subtitle', privacyPolicyUrl: 'https://example.com/privacy' } }]) },
|
||||
{ match: /^\/v1\/appStoreVersions\/(v-1|v-new)\/appStoreVersionLocalizations/, answer: page(o.versionLocs ?? [{ type: 'appStoreVersionLocalizations', id: 'vl-en', attributes: { locale: 'en-US', ...TEXT, whatsNew: null, supportUrl: 'https://example.com/support', marketingUrl: 'https://example.com' } }]) },
|
||||
{ method: 'PATCH', match: /^\/v1\/appStoreVersions\/v-1$/, answer: { data: v('v-1', '1.0.0', 'PREPARE_FOR_SUBMISSION') } },
|
||||
{ method: 'POST', match: /^\/v1\/appStoreVersions$/, answer: { data: v('v-new', '1.1.0', 'PREPARE_FOR_SUBMISSION') } },
|
||||
{ method: 'POST', match: /^\/v1\/(appInfoLocalizations|appStoreVersionLocalizations)$/, answer: c => ({ data: { id: 'new', attributes: (c.body as { data: { attributes: unknown } }).data.attributes } }) },
|
||||
{ method: 'PATCH', match: /^\/v1\/(appInfoLocalizations|appStoreVersionLocalizations)\//, answer: { data: {} } },
|
||||
]);
|
||||
}
|
||||
|
||||
describe('apple listing plan', () => {
|
||||
test('--dry --json: version update, per-locale create / update with old -> new, draft skipped; GETs only', async () => {
|
||||
ascEnv();
|
||||
const p = project({ ...BASE, play: undefined }, { 'store/appstore.md': APPLE_MD });
|
||||
const calls = ascRoutes([v('v-1', '1.0', 'PREPARE_FOR_SUBMISSION')]);
|
||||
const r = await capture(() => appleListing(p.ctx(['--version', '1.0.0', '--dry', '--json'])));
|
||||
expect(methods(calls)).toEqual([]);
|
||||
const j = jsonOut(r.out) as any;
|
||||
expect(j.versionPlan).toMatchObject({ action: 'update', reason: 'update the editable version 1.0 (PREPARE_FOR_SUBMISSION) to 1.0.0' });
|
||||
expect(j.versionPlan.existing).toEqual([{ id: 'v-1', versionString: '1.0', state: 'PREPARE_FOR_SUBMISSION', platform: 'IOS' }]);
|
||||
expect(j.appInfo.locales.map((l: any) => `${l.key} ${l.action}`)).toEqual(['en-US update', 'de-DE create']);
|
||||
expect(j.appInfo.locales[0].changes).toEqual([{ field: 'subtitle', from: 'Old subtitle', to: 'Notes that sync' }]);
|
||||
expect(j.versionLocales.map((l: any) => `${l.key} ${l.action}`)).toEqual(['en-US same', 'de-DE create']);
|
||||
expect(j.skipped).toEqual([{ key: 'tr', reason: expect.stringContaining('machine-translated draft') }]);
|
||||
expect(j.changes).toBe(4);
|
||||
const t = await capture(() => appleListing(p.ctx(['--version', '1.0.0', '--dry'])));
|
||||
expect(t.out).toContain('UPDATE: update the editable version 1.0 (PREPARE_FOR_SUBMISSION) to 1.0.0');
|
||||
expect(t.out).toContain('subtitle: "Old subtitle" -> "Notes that sync"');
|
||||
expect(t.out).toContain('en-US: unchanged (5 fields)');
|
||||
expect(t.out).toContain('Skipped tr: machine-translated draft');
|
||||
});
|
||||
test('--include-drafts plans the draft locale too', async () => {
|
||||
ascEnv();
|
||||
const p = project({ ...BASE, play: undefined }, { 'store/appstore.md': APPLE_MD });
|
||||
ascRoutes([v('v-1', '1.0.0', 'PREPARE_FOR_SUBMISSION')]);
|
||||
const j = jsonOut((await capture(() => appleListing(p.ctx(['--version', '1.0.0', '--dry', '--json', '--include-drafts'])))).out) as any;
|
||||
expect(j.skipped).toEqual([]);
|
||||
expect(j.appInfo.locales.map((l: any) => l.key)).toEqual(['en-US', 'de-DE', 'tr']);
|
||||
});
|
||||
test('the real run applies exactly the plan: no write for unchanged locales', async () => {
|
||||
ascEnv();
|
||||
const p = project({ ...BASE, play: undefined }, { 'store/appstore.md': APPLE_MD });
|
||||
const calls = ascRoutes([v('v-1', '1.0', 'PREPARE_FOR_SUBMISSION')]);
|
||||
await capture(() => appleListing(p.ctx(['--version', '1.0.0'])));
|
||||
expect(methods(calls)).toEqual(['PATCH /v1/appStoreVersions/v-1', 'PATCH /v1/appInfoLocalizations/il-en', 'POST /v1/appInfoLocalizations', 'POST /v1/appStoreVersionLocalizations']);
|
||||
expect((calls.find(c => c.path === '/v1/appInfoLocalizations/il-en')!.body as any).data.attributes).toEqual({ subtitle: 'Notes that sync' });
|
||||
expect((calls.find(c => c.path === '/v1/appStoreVersions/v-1')!.body as any).data.attributes).toEqual({ versionString: '1.0.0' });
|
||||
});
|
||||
test('a new version is created, then its copied texts are planned again and applied', async () => {
|
||||
ascEnv();
|
||||
const p = project({ ...BASE, play: undefined }, { 'store/appstore.md': APPLE_MD });
|
||||
const calls = ascRoutes([v('v-0', '1.0.0', 'READY_FOR_DISTRIBUTION')]);
|
||||
const j = jsonOut((await capture(() => appleListing(p.ctx(['--version', '1.1.0', '--dry', '--json'])))).out) as any;
|
||||
expect(j.versionPlan).toMatchObject({ action: 'create', reason: 'create version 1.1.0 (no editable iOS version)' });
|
||||
expect(j.versionLocales).toBeNull();
|
||||
await capture(() => appleListing(p.ctx(['--version', '1.1.0'])));
|
||||
expect(methods(calls).filter(m => m.includes('appStoreVersion'))).toEqual(['POST /v1/appStoreVersions', 'POST /v1/appStoreVersionLocalizations']);
|
||||
});
|
||||
test('a refused version stops the run; the dry run says so and exits 1', async () => {
|
||||
ascEnv();
|
||||
const p = project({ ...BASE, play: undefined }, { 'store/appstore.md': APPLE_MD });
|
||||
const calls = ascRoutes([v('v-0', '1.2.0', 'READY_FOR_DISTRIBUTION')]);
|
||||
const r = await capture(() => appleListing(p.ctx(['--version', '1.1.0', '--dry'])));
|
||||
expect(r.out).toContain('REFUSE: version 1.1.0 is not higher than 1.2.0');
|
||||
expect(r.exit).toBe(1);
|
||||
await expect(appleListing(p.ctx(['--version', '1.1.0']))).rejects.toThrow('not higher than 1.2.0');
|
||||
expect(methods(calls)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('play listing plan', () => {
|
||||
const PLAY_MD = '# Play\n\n## English\n<!-- play: en-US -->\n\n### title\n```\nExample Notes\n```\n\n### short\n```\nNew short\n```\n\n### full\n```\nFull text.\n```\n\n'
|
||||
+ '## German\n<!-- play: de-DE -->\n<!-- storebound-translation from=en-US status=draft -->\n\n### short\n```\nKurz\n```\n\n### full\n```\nLang.\n```\n';
|
||||
const routes = () => mockFetch([
|
||||
{ method: 'POST', match: /\/edits$/, answer: { id: 'edit-1' } },
|
||||
{ match: /\/edits\/edit-1\/details$/, answer: { defaultLanguage: 'en-US', contactEmail: 'support@example.com', contactWebsite: 'https://example.com' } },
|
||||
{ match: /\/edits\/edit-1\/listings$/, answer: { listings: [{ language: 'en-US', title: 'Example Notes', shortDescription: 'Old short', fullDescription: 'Full text.' }] } },
|
||||
{ method: 'DELETE', match: /\/edits\/edit-1$/, answer: new Response(null, { status: 204 }) },
|
||||
{ method: 'PUT', match: /\/edits\/edit-1\/listings\/en-US$/, answer: {} },
|
||||
{ method: 'POST', match: /\/edits\/edit-1:commit$/, answer: {} },
|
||||
]);
|
||||
test('--dry --json: old -> new per field, unchanged details, draft language skipped; real run PUTs only the change', async () => {
|
||||
playEnv();
|
||||
const p = project({ ...BASE, apple: undefined }, { 'store/listing.md': PLAY_MD });
|
||||
let calls = routes();
|
||||
const j = jsonOut((await capture(() => playListing(p.ctx(['--dry', '--json'])))).out) as any;
|
||||
expect(j.details.action).toBe('same');
|
||||
expect(j.listings).toEqual([expect.objectContaining({ key: 'en-US', action: 'update', changes: [{ field: 'shortDescription', from: 'Old short', to: 'New short' }] })]);
|
||||
expect(j.skipped).toEqual([{ key: 'de-DE', reason: expect.stringContaining('draft') }]);
|
||||
expect(calls.some(c => c.method === 'PUT' || c.path.includes(':commit'))).toBe(false);
|
||||
calls = routes();
|
||||
await capture(() => playListing(p.ctx([])));
|
||||
expect(calls.filter(c => c.method === 'PUT').map(c => c.path.split('/').slice(-2).join('/'))).toEqual(['listings/en-US']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('apple appinfo plan', () => {
|
||||
test('--dry --json: categories and age rating old -> new; nothing written', async () => {
|
||||
ascEnv();
|
||||
const p = project({ ...BASE, play: undefined, apple: { ...BASE.apple!, info: { categories: { primary: 'PRODUCTIVITY' }, ageRating: { advertising: true }, free: false } } });
|
||||
const calls = mockFetch([
|
||||
{ match: /^\/v1\/apps\/6400000101\/appInfos/, answer: page([{ type: 'appInfos', id: 'ai-1', attributes: { state: 'PREPARE_FOR_SUBMISSION' } }]) },
|
||||
{ match: /^\/v1\/appInfos\/ai-1\?include=/, answer: { data: { id: 'ai-1', relationships: { primaryCategory: { data: { type: 'appCategories', id: 'UTILITIES' } } } } } },
|
||||
{ match: /^\/v1\/appInfos\/ai-1\/ageRatingDeclaration/, answer: { data: { id: 'ai-1', attributes: { advertising: false, gambling: false, violenceRealistic: 'NONE' } } } },
|
||||
]);
|
||||
const j = jsonOut((await capture(() => appInfo(p.ctx(['--dry', '--json'])))).out) as any;
|
||||
expect(methods(calls)).toEqual([]);
|
||||
expect(j.items[0]).toMatchObject({ key: 'categories', action: 'update', changes: [{ field: 'primaryCategory', from: 'UTILITIES', to: 'PRODUCTIVITY' }] });
|
||||
expect(j.items[1].changes).toContainEqual({ field: 'advertising', from: 'false', to: 'true' });
|
||||
expect(j.items[1].changes.find((c: any) => c.field === 'gambling')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
164
tests/pitfalls.test.ts
Normal file
164
tests/pitfalls.test.ts
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
// Guardrails for lessons from real use (docs/pitfalls.md, skills/store-pitfalls): the store's product list lagging
|
||||
// right after a create, and dry runs that print a count instead of a plan. Recorded App Store Connect / Google Play
|
||||
// answers; every id is a placeholder.
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Glob } from 'bun';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { countOnlyDryExits, dryPlan, isPlanLine } from '../cli/lib/dry';
|
||||
import { LAG_HINT, missingFromStore } from '../cli/lib/store-lag';
|
||||
import { run as iapReview } from '../cli/apple/iap-review';
|
||||
import { run as iap } from '../cli/apple/iap';
|
||||
import { run as playProducts } from '../cli/play/products';
|
||||
import type { Product } from '../cli/lib/config';
|
||||
import { ascEnv, BASE, capture, mockFetch, notFound, playEnv, project, restore } from './helpers/store-mock';
|
||||
|
||||
const env = { ...process.env };
|
||||
afterEach(() => { restore(); if (env.STOREBOUND_LIST_SETTLE_MS === undefined) delete process.env.STOREBOUND_LIST_SETTLE_MS; });
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const page = (data: unknown[]): any => ({ data, links: { self: 'https://api.appstoreconnect.apple.com/v1/x' }, meta: { paging: { total: data.length, limit: 200 } } });
|
||||
const product = (id: string): Product => ({ id, type: 'non_consumable', usd: 2.99, listings: { en: { title: 'No Ads', description: 'Removes ads' } } });
|
||||
// a PNG header of an App Store screenshot size (the size check reads IHDR only)
|
||||
const png = (w = 1290, h = 2796) => { const b = Buffer.alloc(33); b.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], 0); b.writeUInt32BE(13, 8); b.write('IHDR', 12); b.writeUInt32BE(w, 16); b.writeUInt32BE(h, 20); b[24] = 8; b[25] = 2; return b; };
|
||||
const PRO = 'com.example.notes.pro', GEMS = 'com.example.notes.gems';
|
||||
const CONFIG = { ...BASE, products: [product(PRO), { ...product(GEMS), type: 'consumable' as const }] };
|
||||
|
||||
describe('store list lag after create', () => {
|
||||
test('missingFromStore keeps config order and ignores duplicates', () => {
|
||||
expect(missingFromStore(['a', 'b', 'c', 'b'], ['c'])).toEqual(['a', 'b']);
|
||||
expect(missingFromStore(['a'], new Set(['a']))).toEqual([]);
|
||||
});
|
||||
|
||||
test('apple iap-review --dry: a product missing from /inAppPurchasesV2 is named with the lag hint and exits 1', async () => {
|
||||
ascEnv();
|
||||
const p = project(CONFIG, { [`store/iap-review/${PRO}.png`]: png(), [`store/iap-review/${GEMS}.png`]: png() });
|
||||
// as answered a few seconds after `apple iap` created both: only the older product is listed
|
||||
const calls = mockFetch([
|
||||
{ match: /^\/v1\/apps\/6400000101\/inAppPurchasesV2\?limit=200/, answer: page([{ type: 'inAppPurchases', id: 'i-pro', attributes: { productId: PRO, state: 'READY_TO_SUBMIT' } }]) },
|
||||
{ match: /^\/v2\/inAppPurchases\/i-pro\/appStoreReviewScreenshot/, answer: notFound() },
|
||||
]);
|
||||
const r = await capture(() => iapReview(p.ctx(['--dry'])));
|
||||
expect(r.err).toContain(`1 of 2 products not in the store's list: ${GEMS} (${LAG_HINT})`);
|
||||
expect(r.out).toMatch(new RegExp(`${GEMS.replace(/\./g, '\\.')}\\s+skip\\s+not in the store's list yet`));
|
||||
expect(r.out).toMatch(new RegExp(`${PRO.replace(/\./g, '\\.')}\\s+upload\\s+store/iap-review/${PRO.replace(/\./g, '\\.')}\\.png \\(none in App Store Connect\\)`));
|
||||
expect(r.exit).toBe(1);
|
||||
expect(calls.filter(c => c.method !== 'GET')).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('apple iap-review --dry: every product listed exits 0', async () => {
|
||||
ascEnv();
|
||||
const p = project({ ...CONFIG, products: [product(PRO)] }, { [`store/iap-review/${PRO}.png`]: png() });
|
||||
mockFetch([
|
||||
{ match: /^\/v1\/apps\/6400000101\/inAppPurchasesV2\?limit=200/, answer: page([{ type: 'inAppPurchases', id: 'i-pro', attributes: { productId: PRO, state: 'READY_TO_SUBMIT' } }]) },
|
||||
{ match: /^\/v2\/inAppPurchases\/i-pro\/appStoreReviewScreenshot/, answer: notFound() },
|
||||
]);
|
||||
const r = await capture(() => iapReview(p.ctx(['--dry'])));
|
||||
expect(r.err).not.toContain(LAG_HINT);
|
||||
expect(r.exit).toBeNull();
|
||||
});
|
||||
|
||||
test('apple iap --dry prints a plan row per product (create with type, locales and prices; update with what is missing)', async () => {
|
||||
ascEnv();
|
||||
const p = project({ ...CONFIG, products: [product(PRO), { ...product(GEMS), type: 'consumable', overrides: [{ region: 'TR', currency: 'TRY', price: 49.99 }] }] });
|
||||
const calls = mockFetch([
|
||||
{ match: /^\/v1\/territories/, answer: page([{ type: 'territories', id: 'USA' }, { type: 'territories', id: 'TUR' }]) },
|
||||
{ match: new RegExp(`^/v1/apps/6400000101/inAppPurchasesV2\\?filter\\[productId\\]=${PRO}`), answer: page([{ type: 'inAppPurchases', id: 'i-pro', attributes: { productId: PRO, state: 'MISSING_METADATA' } }]) },
|
||||
{ match: new RegExp(`^/v1/apps/6400000101/inAppPurchasesV2\\?filter\\[productId\\]=${GEMS}`), answer: page([]) },
|
||||
{ match: /^\/v2\/inAppPurchases\/i-pro\/inAppPurchaseLocalizations/, answer: page([]) },
|
||||
{ match: /^\/v2\/inAppPurchases\/i-pro\/iapPriceSchedule/, answer: notFound() },
|
||||
{ match: /^\/v2\/inAppPurchases\/i-pro\/inAppPurchaseAvailability/, answer: { data: { type: 'inAppPurchaseAvailabilities', id: 'av' } } },
|
||||
]);
|
||||
const r = await capture(() => iap(p.ctx(['--dry'])));
|
||||
expect(r.out).toContain('dry run: apple iap: 2 change(s); nothing written');
|
||||
expect(r.out).toMatch(/com\.example\.notes\.pro\s+update\s+localizations en-US; prices USA 2\.99 \(state MISSING_METADATA\)/);
|
||||
expect(r.out).toMatch(/com\.example\.notes\.gems\s+create\s+CONSUMABLE; localizations en-US; prices USA 2\.99, TUR 49\.99; 2 territories/);
|
||||
expect(r.out).toContain(`not on App Store Connect: ${GEMS}`);
|
||||
expect(calls.filter(c => c.method !== 'GET')).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('apple iap: a product created this run but missing from the list read after it is named', async () => {
|
||||
ascEnv();
|
||||
process.env.STOREBOUND_LIST_SETTLE_MS = '0';
|
||||
const p = project({ ...CONFIG, products: [product(GEMS)] });
|
||||
const calls = mockFetch([
|
||||
{ match: /^\/v1\/territories/, answer: page([{ type: 'territories', id: 'USA' }]) },
|
||||
{ match: /^\/v1\/apps\/6400000101\/inAppPurchasesV2\?filter/, answer: page([]) },
|
||||
{ method: 'POST', match: /^\/v2\/inAppPurchases$/, answer: { data: { type: 'inAppPurchases', id: 'i-gems', attributes: { productId: GEMS } } } },
|
||||
{ match: /^\/v2\/inAppPurchases\/i-gems\/inAppPurchaseLocalizations/, answer: page([]) },
|
||||
{ method: 'POST', match: /^\/v1\/inAppPurchaseLocalizations$/, answer: { data: { type: 'inAppPurchaseLocalizations', id: 'l1' } } },
|
||||
{ match: /^\/v2\/inAppPurchases\/i-gems\/iapPriceSchedule/, answer: notFound() },
|
||||
{ match: /^\/v2\/inAppPurchases\/i-gems\/pricePoints\?filter\[territory\]=USA/, answer: page([{ type: 'inAppPurchasePricePoints', id: 'pp-usa-299', attributes: { customerPrice: '2.99' } }]) },
|
||||
{ method: 'POST', match: /^\/v1\/inAppPurchasePriceSchedules$/, answer: { data: { type: 'inAppPurchasePriceSchedules', id: 'ps' } } },
|
||||
{ match: /^\/v2\/inAppPurchases\/i-gems\/inAppPurchaseAvailability/, answer: notFound() },
|
||||
{ method: 'POST', match: /^\/v1\/inAppPurchaseAvailabilities$/, answer: { data: { type: 'inAppPurchaseAvailabilities', id: 'av' } } },
|
||||
// the full list read right after the create does not have it yet
|
||||
{ match: /^\/v1\/apps\/6400000101\/inAppPurchasesV2\?limit=200/, answer: page([]) },
|
||||
]);
|
||||
const r = await capture(() => iap(p.ctx([])));
|
||||
expect(calls.filter(c => c.method === 'POST').map(c => c.path)).toEqual(['/v2/inAppPurchases', '/v1/inAppPurchaseLocalizations', '/v1/inAppPurchasePriceSchedules', '/v1/inAppPurchaseAvailabilities']);
|
||||
expect(r.err).toContain(`1 of 1 new products not in the store's list: ${GEMS} (${LAG_HINT})`);
|
||||
expect(r.out).toContain('wait a minute before apple iap-review');
|
||||
expect(r.exit).toBeNull();
|
||||
});
|
||||
|
||||
test('play products: a product created this run but missing from the list read after it is named; --dry shows the plan table', async () => {
|
||||
playEnv();
|
||||
const p = project({ ...CONFIG, products: [product(GEMS)] });
|
||||
const API = '/androidpublisher/v3/applications/com.example.notes';
|
||||
const conv = { convertedRegionPrices: { US: { regionCode: 'US', price: { currencyCode: 'USD', units: '2', nanos: 990000000 } } },
|
||||
convertedOtherRegionsPrice: { usdPrice: { currencyCode: 'USD', units: '2', nanos: 990000000 }, eurPrice: { currencyCode: 'EUR', units: '2', nanos: 790000000 } }, regionVersion: { version: '2026/01' } };
|
||||
const routes = () => mockFetch([
|
||||
{ match: new RegExp(`^${API}/oneTimeProducts\\?`), answer: { oneTimeProducts: [] } },
|
||||
{ method: 'POST', match: new RegExp(`^${API}/pricing:convertRegionPrices$`), answer: conv },
|
||||
{ method: 'PATCH', match: new RegExp(`^${API}/onetimeproducts/`), answer: {} },
|
||||
{ method: 'POST', match: /purchaseOptions:batchUpdateStates$/, answer: {} },
|
||||
]);
|
||||
routes();
|
||||
let r = await capture(() => playProducts(p.ctx(['--dry'])));
|
||||
expect(r.out).toMatch(/dry run: play products: 1 change\(s\); nothing written\n.*\n.*\ncom\.example\.notes\.gems\s+create\s+1 regions, 1 listings, USD 2\.99/);
|
||||
expect(r.out).toContain(`not on Google Play: ${GEMS}`);
|
||||
const calls = routes();
|
||||
r = await capture(() => playProducts(p.ctx([])));
|
||||
expect(calls.filter(c => c.method === 'PATCH')).toHaveLength(1);
|
||||
expect(r.err).toContain(`1 of 1 new products not in the store's list: ${GEMS} (${LAG_HINT})`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('dry runs show a plan, not a count', () => {
|
||||
test('dryPlan: title with counts, kept rows left out of the table', () => {
|
||||
expect(dryPlan('apple iap', [{ item: 'a', action: 'keep' }])).toBe('dry run: apple iap: nothing to change, 1 unchanged; nothing written');
|
||||
expect(dryPlan('play products', [{ item: 'com.example.a', action: 'create', detail: '174 regions' }, { item: 'b', action: 'keep' }]).split('\n')).toEqual([
|
||||
'dry run: play products: 1 change(s), 1 unchanged; nothing written',
|
||||
'item action detail',
|
||||
'------------- ------ -----------',
|
||||
'com.example.a create 174 regions',
|
||||
]);
|
||||
});
|
||||
|
||||
test('the scanner flags a --dry exit after a count-only line and accepts a plan', () => {
|
||||
const countOnly = ['export async function run(ctx: Ctx): Promise<void> {', ' const listing = read();',
|
||||
" log('apple', `listing: ${Object.keys(listing).length} locales (${Object.keys(listing).join(', ')})`);", " if (a.has('dry')) return;", ' await write();', '}'].join('\n');
|
||||
expect(countOnlyDryExits(countOnly)).toEqual([4]);
|
||||
const counted = ['export async function run(): Promise<void> {', " if (dry) { done(TAG, `dry run: ${reqs.length} change(s)`); return; }", '}'].join('\n');
|
||||
expect(countOnlyDryExits(counted)).toEqual([2]);
|
||||
const planned = ['export async function run(): Promise<void> {', " console.log(dryPlan('apple listing', rows));", " if (dry) return;", '}'].join('\n');
|
||||
expect(countOnlyDryExits(planned)).toEqual([]);
|
||||
expect(isPlanLine(" log('apple', `${tag}: would upload ${file}`);")).toBe(true);
|
||||
expect(isPlanLine(" log(TAG, 'would POST /v1/analyticsReportRequests {accessType=ONGOING} (dry)');")).toBe(true);
|
||||
expect(isPlanLine(" done(TAG, 'dry run: nothing changed');")).toBe(false);
|
||||
});
|
||||
|
||||
// TODO: remove each entry once its branch lands (the test fails on a stale entry).
|
||||
const ALLOW: Record<string, string> = {};
|
||||
test('no write command in cli/** leaves its --dry branch after printing only a count', () => {
|
||||
const root = join(import.meta.dir, '..');
|
||||
const flagged: string[] = [];
|
||||
for (const f of [...new Glob('cli/**/*.ts').scanSync(root)].sort()) {
|
||||
const lines = countOnlyDryExits(readFileSync(join(root, f), 'utf8'));
|
||||
if (lines.length) flagged.push(`${f}:${lines.join(',')}`);
|
||||
}
|
||||
const files = flagged.map(x => x.split(':')[0]!);
|
||||
expect(flagged.filter(x => !ALLOW[x.split(':')[0]!])).toEqual([]);
|
||||
expect(Object.keys(ALLOW).filter(f => !files.includes(f))).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
|
@ -80,12 +80,12 @@ describe('listing pull commands', () => {
|
|||
let r = await capture(() => appleListing(p.ctx(['pull', '--json'])));
|
||||
const j = jsonOut(r.out);
|
||||
expect(j).toMatchObject({ version: '1.1.0', write: false, added: [] });
|
||||
expect((j.changes as { field: string }[]).map(c => c.field)).toEqual(['name', 'description', 'whatsNew']);
|
||||
expect((j.changes as { field: string }[]).map(c => c.field)).toEqual(['description', 'whatsNew']); // the live name equals app.name: not written into the file
|
||||
expect(j.diff).toContain('-Old text.');
|
||||
expect(readFileSync(join(p.root, 'store/appstore.md'), 'utf8')).toBe(APPLE_MD);
|
||||
r = await capture(() => appleListing(p.ctx(['pull', '--write'])));
|
||||
expect(readFileSync(join(p.root, 'store/appstore.md'), 'utf8')).toContain('### whatsNew\n```\nFaster sync.\n```');
|
||||
expect(r.out).toContain('3 change(s) written');
|
||||
expect(r.out).toContain('2 change(s) written');
|
||||
});
|
||||
test('play listing pull: one read-only edit, deleted; --write updates the file', async () => {
|
||||
playEnv();
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue