|
| 1 | +import Execute from './execute.js' |
| 2 | +import {prepareExecuteContext} from '../../utilities/execute-command-helpers.js' |
| 3 | +import {createAdminSessionAsApp, resolveApiVersion} from '../../services/graphql/common.js' |
| 4 | +import { |
| 5 | + testAppLinked, |
| 6 | + testOrganization, |
| 7 | + testOrganizationApp, |
| 8 | + testOrganizationStore, |
| 9 | + testProject, |
| 10 | +} from '../../models/app/app.test-data.js' |
| 11 | +import {Config} from '@oclif/core' |
| 12 | +import {afterEach, beforeEach, expect, test, vi} from 'vitest' |
| 13 | +import {ClientError} from 'graphql-request' |
| 14 | +// eslint-disable-next-line @shopify/typescript-prefer-build-client-schema -- Local execution fixture without an introspection response. |
| 15 | +import {GraphQLError, buildSchema, graphql} from 'graphql' |
| 16 | +import {adminRequestDoc} from '@shopify/cli-kit/node/api/admin' |
| 17 | +import {runWithCommandEventsForCommand} from '@shopify/cli-kit/node/command-events' |
| 18 | +import {handler} from '@shopify/cli-kit/node/error' |
| 19 | +import {unstyled} from '@shopify/cli-kit/node/output' |
| 20 | +import {inTemporaryDirectory, readFile, writeFile} from '@shopify/cli-kit/node/fs' |
| 21 | +import {withCapturedStandardStreams} from '@shopify/cli-kit/node/testing/output' |
| 22 | +import {joinPath} from '@shopify/cli-kit/node/path' |
| 23 | +import * as ui from '@shopify/cli-kit/node/ui' |
| 24 | + |
| 25 | +vi.mock('../../utilities/execute-command-helpers.js') |
| 26 | +vi.mock('../../services/graphql/common.js') |
| 27 | +vi.mock('@shopify/cli-kit/node/api/admin') |
| 28 | + |
| 29 | +const query = 'query { shop { name } }' |
| 30 | +const app = testAppLinked() |
| 31 | + |
| 32 | +beforeEach(() => { |
| 33 | + const remoteApp = testOrganizationApp() |
| 34 | + vi.mocked(prepareExecuteContext).mockResolvedValue({ |
| 35 | + query, |
| 36 | + appContextResult: { |
| 37 | + app, |
| 38 | + remoteApp, |
| 39 | + organization: testOrganization(), |
| 40 | + developerPlatformClient: remoteApp.developerPlatformClient, |
| 41 | + project: testProject(), |
| 42 | + specifications: [], |
| 43 | + activeConfig: {} as never, |
| 44 | + }, |
| 45 | + store: testOrganizationStore({shopDomain: 'shop.myshopify.com'}), |
| 46 | + }) |
| 47 | + vi.mocked(createAdminSessionAsApp).mockResolvedValue({token: 'test-token', storeFqdn: 'shop.myshopify.com'}) |
| 48 | + vi.mocked(resolveApiVersion).mockResolvedValue('2026-10') |
| 49 | +}) |
| 50 | + |
| 51 | +afterEach(() => { |
| 52 | + vi.unstubAllEnvs() |
| 53 | +}) |
| 54 | + |
| 55 | +async function runCommand(flags: string[]) { |
| 56 | + const argv = ['--query', query, '--store', 'shop.myshopify.com', ...flags] |
| 57 | + const command = new Execute(argv, await Config.load()) |
| 58 | + const textTask = flags.includes('--json') |
| 59 | + ? undefined |
| 60 | + : vi.spyOn(ui, 'renderSingleTask').mockImplementation(async ({task}) => task(() => {})) |
| 61 | + try { |
| 62 | + return await runWithCommandEventsForCommand(argv, () => command.run()) |
| 63 | + } finally { |
| 64 | + textTask?.mockRestore() |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +test('preserves native GraphQL aliases, order, and UTF-8 on stdout and in output files', async () => { |
| 69 | + const response = await graphql({ |
| 70 | + schema: buildSchema('type Query { name: String! nested: Query }'), |
| 71 | + source: 'query { last: name __proto__: name constructor: name nested { __proto__: name constructor: name } }', |
| 72 | + rootValue: {name: 'Café', nested: {name: 'Nested'}}, |
| 73 | + }) |
| 74 | + expect(response.errors).toBeUndefined() |
| 75 | + const extensions = JSON.parse('{"__proto__":{"trace":"preserved"},"constructor":false,"nullable":null,"empty":[]}') |
| 76 | + vi.mocked(adminRequestDoc).mockImplementation(async ({responseOptions}) => { |
| 77 | + responseOptions?.onResponse?.({data: response.data, extensions, status: 200, headers: new Headers()}) |
| 78 | + return response.data |
| 79 | + }) |
| 80 | + const json = JSON.stringify({data: response.data, extensions}, null, 2) |
| 81 | + const text = JSON.stringify(response.data, null, 2) |
| 82 | + |
| 83 | + await withCapturedStandardStreams(async ({stdout, stderr}) => { |
| 84 | + await runCommand(['--json']) |
| 85 | + expect(stdout()).toBe(`${json}\n`) |
| 86 | + expect( |
| 87 | + stderr() |
| 88 | + .trim() |
| 89 | + .split('\n') |
| 90 | + .map((line) => JSON.parse(line)), |
| 91 | + ).toEqual([ |
| 92 | + expect.objectContaining({type: 'progress', status: 'started', message: 'Authenticating'}), |
| 93 | + expect.objectContaining({type: 'progress', status: 'completed', message: 'Authenticating'}), |
| 94 | + expect.objectContaining({type: 'progress', status: 'started', message: 'Executing GraphQL operation'}), |
| 95 | + expect.objectContaining({type: 'progress', status: 'completed', message: 'Executing GraphQL operation'}), |
| 96 | + ]) |
| 97 | + }) |
| 98 | + await withCapturedStandardStreams(async ({stdout, stderr}) => { |
| 99 | + await runCommand([]) |
| 100 | + expect(stdout()).toBe(`${text}\n`) |
| 101 | + expect(stderr()).toContain('Operation succeeded.') |
| 102 | + }) |
| 103 | + await inTemporaryDirectory(async (directory) => { |
| 104 | + const path = joinPath(directory, 'result.json') |
| 105 | + await withCapturedStandardStreams(async ({stdout}) => { |
| 106 | + await runCommand(['--json', '--output-file', path]) |
| 107 | + expect(JSON.parse(stdout())).toEqual({path, format: 'json'}) |
| 108 | + }) |
| 109 | + await expect(readFile(path)).resolves.toBe(json) |
| 110 | + await withCapturedStandardStreams(async ({stdout, stderr}) => { |
| 111 | + await runCommand(['--output-file', path]) |
| 112 | + expect(stdout()).toBe('') |
| 113 | + expect(stderr()).toContain('Operation succeeded.') |
| 114 | + expect(unstyled(stderr()).replace(/[│\s]/g, '')).toContain(`Resultswrittento${path}`) |
| 115 | + }) |
| 116 | + await expect(readFile(path)).resolves.toBe(text) |
| 117 | + }) |
| 118 | +}) |
| 119 | + |
| 120 | +test('uses one shared fatal error document and preserves an existing output file', async () => { |
| 121 | + await inTemporaryDirectory(async (directory) => { |
| 122 | + const outputFile = joinPath(directory, 'result.json') |
| 123 | + await writeFile(outputFile, 'existing result') |
| 124 | + const details = { |
| 125 | + errors: [new GraphQLError('Denied', {extensions: {code: 'ACCESS_DENIED'}})], |
| 126 | + data: {shop: null}, |
| 127 | + extensions: {cost: {actualQueryCost: 1}}, |
| 128 | + } |
| 129 | + vi.mocked(adminRequestDoc).mockRejectedValue(new ClientError({...details, status: 200}, {query})) |
| 130 | + vi.stubEnv('SHOPIFY_FLAG_JSON', '1') |
| 131 | + await withCapturedStandardStreams(async ({stdout, stderr}) => { |
| 132 | + await runCommand(['--json', '--output-file', outputFile]).catch(handler) |
| 133 | + expect(JSON.parse(stdout())).toEqual({ |
| 134 | + error: {type: 'abort', message: 'GraphQL operation failed.', details: JSON.parse(JSON.stringify(details))}, |
| 135 | + }) |
| 136 | + expect(stderr()).not.toContain('GraphQL operation failed.') |
| 137 | + }) |
| 138 | + await expect(readFile(outputFile)).resolves.toBe('existing result') |
| 139 | + }) |
| 140 | +}) |
| 141 | + |
| 142 | +test('preserves the text error banner without a fatal error for a GraphQL failure', async () => { |
| 143 | + const errors = [new GraphQLError('Field invalidField does not exist')] |
| 144 | + vi.mocked(adminRequestDoc).mockRejectedValue(new ClientError({errors, status: 200}, {query})) |
| 145 | + await withCapturedStandardStreams(async ({stdout, stderr}) => { |
| 146 | + await expect(runCommand([])).resolves.toEqual({app}) |
| 147 | + expect(stdout()).toBe('') |
| 148 | + expect(stderr()).toContain('GraphQL operation failed.') |
| 149 | + expect(stderr()).toContain('invalidField') |
| 150 | + }) |
| 151 | +}) |
0 commit comments