Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Use fixture as request body shortcut #27934

Closed
wants to merge 21 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions cli/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
<!-- See the ../guides/writing-the-cypress-changelog.md for details on writing the changelog. -->
## 13.7.0

_Released 12/6/2023 (PENDING)_

**Features:**

- Introduces shorthand version of using cy.request() with fixture data. Addresses [#3387](https://github.com/cypress-io/cypress/issues/3387).

## 13.6.1

_Released 12/5/2023_
Expand Down
80 changes: 80 additions & 0 deletions packages/driver/cypress/e2e/commands/request.cy.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,54 @@ describe('src/cy/commands/request', () => {
})
})

it('accepts object with url, method, headers, fixture with encoding', () => {
cy.request({
url: 'http://github.com/users',
method: 'POST',
fixture: 'path,encoding',
headers: {
'x-token': 'abc123',
},
})
.then(function () {
this.expectOptionsToBe({
url: 'http://github.com/users',
method: 'POST',
fixture: {
filePath: 'path',
encoding: 'encoding',
},
headers: {
'x-token': 'abc123',
},
})
})
})

it('accepts object with url, method, headers, fixture', () => {
cy.request({
url: 'http://github.com/users',
method: 'POST',
fixture: 'path',
headers: {
'x-token': 'abc123',
},
})
.then(function () {
this.expectOptionsToBe({
url: 'http://github.com/users',
method: 'POST',
fixture: {
filePath: 'path',
encoding: undefined,
},
headers: {
'x-token': 'abc123',
},
})
})
})

it('accepts object with url + timeout', () => {
cy.request({ url: 'http://localhost:8000/foo', timeout: 23456 }).then(function () {
this.expectOptionsToBe({
Expand Down Expand Up @@ -886,6 +934,38 @@ describe('src/cy/commands/request', () => {
cy.request()
})

it('throws when body is combined with fixture', function (done) {
cy.on('fail', (err) => {
const { lastLog } = this

assertLogLength(this.logs, 1)
expect(lastLog.get('error')).to.eq(err)
expect(lastLog.get('state')).to.eq('failed')
expect(err.message).to.eq('`cy.request()` was called with the `body` and `fixture` options which cannot be combined.')
expect(err.docsUrl).to.eq('https://on.cypress.io/request')

done()
})

cy.request({ url: 'http://localhost:8080/users', method: 'POST', fixture: 'number', body: { data: 14 } })
})

it('throws when fixture option is used without method', function (done) {
cy.on('fail', (err) => {
const { lastLog } = this

assertLogLength(this.logs, 1)
expect(lastLog.get('error')).to.eq(err)
expect(lastLog.get('state')).to.eq('failed')
expect(err.message).to.eq('`cy.request()` was called with the `fixture` option but is missing the `method` option.')
expect(err.docsUrl).to.eq('https://on.cypress.io/request')

done()
})

cy.request({ url: 'http://localhost:8080/users', fixture: 'number' })
})

it('throws when url is not FQDN', {
baseUrl: null,
}, function (done) {
Expand Down
15 changes: 15 additions & 0 deletions packages/driver/src/cy/commands/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ const REQUEST_DEFAULTS = {
encoding: 'utf8',
gzip: true,
timeout: null,
fixture: null,
followRedirect: true,
failOnStatusCode: true,
retryIntervals: [0, 100, 200, 200],
Expand Down Expand Up @@ -138,6 +139,20 @@ export default (Commands, Cypress, cy, state, config) => {
$errUtils.throwErrByPath('request.url_wrong_type')
}

if (options.fixture) {
if (options.body) {
$errUtils.throwErrByPath('request.body_and_fixture')
}

if (!userOptions.method) {
$errUtils.throwErrByPath('request.fixture_without_method')
}

const [filePath, encoding] = options.fixture.split(',')

options.fixture = { filePath, encoding: encoding === 'null' ? null : encoding }
}
Crustum7 marked this conversation as resolved.
Show resolved Hide resolved

// normalize the url by prepending it with our current origin
// or the baseUrl
// or just using the options.url if its FQDN
Expand Down
8 changes: 8 additions & 0 deletions packages/driver/src/cypress/error_messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1391,6 +1391,14 @@ export default {
message: `${cmd('request')} was called with an invalid method: \`{{method}}\`. Method can be: \`GET\`, \`POST\`, \`PUT\`, \`DELETE\`, \`PATCH\`, \`HEAD\`, \`OPTIONS\`, or any other method supported by Node's HTTP parser.`,
docsUrl: 'https://on.cypress.io/request',
},
body_and_fixture: {
message: `${cmd('request')} was called with the \`body\` and \`fixture\` options which cannot be combined.`,
docsUrl: 'https://on.cypress.io/request',
},
fixture_without_method: {
message: `${cmd('request')} was called with the \`fixture\` option but is missing the \`method\` option.`,
docsUrl: 'https://on.cypress.io/request',
},
form_invalid: {
message: stripIndent`\
${cmd('request')} requires the \`form\` option to be a boolean.
Expand Down
6 changes: 5 additions & 1 deletion packages/server/lib/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -662,14 +662,18 @@ module.exports = function (options = {}) {
})
},

sendPromise (userAgent, automationFn, options = {}) {
async sendPromise (userAgent, automationFn, getFixture, options = {}) {
_.defaults(options, {
headers: {},
gzip: true,
cookies: true,
followRedirect: true,
})

if (options.fixture) {
options.form = await getFixture(options.fixture.filePath, options.fixture.encoding)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My original suggestion was a bit naive with the amount of messaging we are doing in the cy.request() command with assigning headers, validating the body structure etc. Your original approach was definitely better than this suggestion.

What you have here makes assumptions that the fixture data that's for a form, where someone may want it for any body type.

Using the cy.fixture() command will cache the fixture data for the duration fo the spec, which we won't want to introduce, but we can call into the backend directly. something like?

// request.ts
Promise.try(() => {
  if (!options.fixture) return
  return Cypress.backend('get:fixture', options.fixture.filePath, options.fixture.filePath.encoding)`. 
}).then((fixtureData) => {
    options.body = fixtureData
    // handle fixture data
    // handle blob data
}).then(() => {
   return Cypress.backend('http:request', requestOpts)
})
....

I was really hoping to avoid an extra client-side->backend-> exchange with the introduction of this feature.

@chrisbreiding maybe you have some ideas on keeping this a single exchange? maybe its not necessary?

}

if (!caseInsensitiveGet(options.headers, 'user-agent') && userAgent) {
options.headers['user-agent'] = userAgent
}
Expand Down
4 changes: 2 additions & 2 deletions packages/server/lib/server-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -538,9 +538,9 @@ export class ServerBase<TSocket extends SocketE2E | SocketCt> {
})
}

_onRequest (userAgent, automationRequest, options) {
_onRequest (userAgent, automationRequest, getFixture, options) {
// @ts-ignore
return this.request.sendPromise(userAgent, automationRequest, options)
return this.request.sendPromise(userAgent, automationRequest, getFixture, options)
}

_callRequestListeners (server, listeners, req, res) {
Expand Down
2 changes: 1 addition & 1 deletion packages/server/lib/socket-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ export class SocketBase {
return options.onResolveUrl(url, userAgent, automationRequest, resolveOpts)
}
case 'http:request':
return options.onRequest(userAgent, automationRequest, args[0])
return options.onRequest(userAgent, automationRequest, getFixture, args[0])
case 'reset:server:state':
return options.onResetServerState()
case 'log:memory:pressure':
Expand Down
Loading
Loading