ronantakizawa/codereview-bench huggingface dataset:
Repository: cypress-io/cypress
File: packages/network/lib/agent.ts (TypeScript)

Code before:
          // as of Node 12, a ServerName cannot be an IP address
          // https://github.com/cypress-io/cypress/issues/5729
          if (!net.isIP(hostname)) {
            options.servername = hostname
          }

          return cb(undefined, super.createConnection(options) as any)
        }

        cb(undefined, proxySocket)
      }

      proxySocket.once('close', onClose)
      proxySocket.once('error', onError)
      proxySocket.once('data', onData)

      const connectReq = buildConnectReqHead(hostname, port, proxy)

      proxySocket.setNoDelay(true)
      proxySocket.write(connectReq)
    })
  }
}

// This agent honors NODE_TLS_REJECT_UNAUTHORIZED (though this is overridden
// in some places; for example, by request promise defaults in api/index.ts).
const agent = new CombinedAgent()

// This agent always rejects unauthorized certificates.
const strictAgent = new CombinedAgent({}, {
  rejectUnauthorized: true,
})

export default agent

export { strictAgent }


Review comment (security):
```suggestion
// NODE_TLS_REJECT_UNAUTHORIZED is set to '0' in Cypress to cover
// all traffic to the user's app and `agent` honors this by default. 
// Calls to the Cloud should use the `strictAgent` or `api/index`'s 
// request promise implementation instead as they override 
// this functionality to actually reject in unauthorized situations.
```

Code after:
          if (!net.isIP(hostname)) {
            options.servername = hostname
          }

          return cb(undefined, super.createConnection(options) as any)
        }

        cb(undefined, proxySocket)
      }

      proxySocket.once('close', onClose)
      proxySocket.once('error', onError)
      proxySocket.once('data', onData)

      const connectReq = buildConnectReqHead(hostname, port, proxy)

      proxySocket.setNoDelay(true)
      proxySocket.write(connectReq)
    })
  }
}

// NODE_TLS_REJECT_UNAUTHORIZED is set to '0' in Cypress to cover
// all traffic to the user's app and `agent` honors this by default.
// Calls to the Cloud should use the `strictAgent` or `api/index`'s
// request promise implementation instead as they override
// this functionality to actually reject in unauthorized situations.
const agent = new CombinedAgent()

// This agent always rejects unauthorized certificates.
const strictAgent = new CombinedAgent({}, {
  rejectUnauthorized: true,
})

export default agent

export { strictAgent }
Repository: cypress-io/cypress
File: packages/driver/cypress/e2e/commands/prompt/prompt-initialization-error.cy.ts (TypeScript)

Code before:

    cy.on('fail', (err) => {
      expect(err.message).to.include('Failed to download `cy.prompt` Cloud code')
      expect(err.message).to.include(`no space left on device, open /Users/ruby/dev/bundle.tar`)

      done()
    })

    cy.visit('http://www.foobar.com:3500/fixtures/dom.html')

    cy['commandFns']['prompt'].__resetPrompt()
    cy.prompt(['Hello, world!'])
  })

  it('errors with a proxy error', (done) => {
    const backendStub = cy.stub(Cypress, 'backend').log(false)

    const error = new Error('UNABLE_TO_VERIFY_LEAF_SIGNATURE')

    ;(error as any).code = 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'

    backendStub.callThrough()
    backendStub.withArgs('wait:for:prompt:ready').resolves({ success: false, error })

    cy.on('fail', (err) => {
      expect(err.message).to.include('`cy.prompt` requires internet access to work. To continue, you may need to configure Cypress with your proxy settings.')
      done()
    })

    cy.visit('http://www.foobar.com:3500/fixtures/dom.html')

    cy['commandFns']['prompt'].__resetPrompt()
    cy.prompt(['Hello, world!'])
  })
})


Review comment (suggestion):
```suggestion
      expect(err.message).to.include('`cy.prompt` requires an internet connection to work. To continue, you may need to configure Cypress with your proxy settings.')
```

Code after:

    cy.on('fail', (err) => {
      expect(err.message).to.include('Failed to download `cy.prompt` Cloud code')
      expect(err.message).to.include(`no space left on device, open /Users/ruby/dev/bundle.tar`)

      done()
    })

    cy.visit('http://www.foobar.com:3500/fixtures/dom.html')

    cy['commandFns']['prompt'].__resetPrompt()
    cy.prompt(['Hello, world!'])
  })

  it('errors with a proxy error', (done) => {
    const backendStub = cy.stub(Cypress, 'backend').log(false)

    const error = new Error('UNABLE_TO_VERIFY_LEAF_SIGNATURE')

    ;(error as any).code = 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'

    backendStub.callThrough()
    backendStub.withArgs('wait:for:prompt:ready').resolves({ success: false, error })

    cy.on('fail', (err) => {
      expect(err.message).to.include('`cy.prompt` requires an internet connection to work. To continue, you may need to configure Cypress with your proxy settings.')
      done()
    })

    cy.visit('http://www.foobar.com:3500/fixtures/dom.html')

    cy['commandFns']['prompt'].__resetPrompt()
    cy.prompt(['Hello, world!'])
  })
})
Repository: cypress-io/cypress
File: packages/data-context/src/sources/UtilDataSource.ts (TypeScript)

Code before:
import fetch from 'cross-fetch'
import type { DataContext } from '../DataContext'
import { isDependencyInstalled, isDependencyInstalledByName } from '@packages/scaffold-config'

// Require rather than import since data-context is stricter than network and there are a fair amount of errors in agent.
const { strictAgent } = require('@packages/network')

/**
 * this.ctx.util....
 *
 * Used as a central location for grab-bag utilities used
 * within the DataContext layer
 */
export class UtilDataSource {
  constructor (private ctx: DataContext) {}

  fetch (input: RequestInfo | URL, init?: RequestInit) {
    // @ts-ignore agent isn't a part of cross-fetch's API since it's not a part of the browser's fetch but it is a part of node-fetch
    // which is what will be used here
    return fetch(input, { agent: strictAgent, ...init })
  }

  isDependencyInstalled (dependency: Cypress.CypressComponentDependency, projectPath: string) {
    return isDependencyInstalled(dependency, projectPath)
  }

  isDependencyInstalledByName (packageName: string, projectPath: string) {
    return isDependencyInstalledByName(packageName, projectPath)
  }
}


Review comment (suggestion):
```suggestion
    return fetch(input, { ...init, agent: strictAgent })
```

Code after:
import fetch from 'cross-fetch'
import type { DataContext } from '../DataContext'
import { isDependencyInstalled, isDependencyInstalledByName } from '@packages/scaffold-config'

// Require rather than import since data-context is stricter than network and there are a fair amount of errors in agent.
const { strictAgent } = require('@packages/network')

/**
 * this.ctx.util....
 *
 * Used as a central location for grab-bag utilities used
 * within the DataContext layer
 */
export class UtilDataSource {
  constructor (private ctx: DataContext) {}

  fetch (input: RequestInfo | URL, init?: RequestInit) {
    // @ts-ignore agent isn't a part of cross-fetch's API since it's not a part of the browser's fetch but it is a part of node-fetch
    // which is what will be used here
    return fetch(input, { ...init, agent: strictAgent })
  }

  isDependencyInstalled (dependency: Cypress.CypressComponentDependency, projectPath: string) {
    return isDependencyInstalled(dependency, projectPath)
  }

  isDependencyInstalledByName (packageName: string, projectPath: string) {
    return isDependencyInstalledByName(packageName, projectPath)
  }
}
Repository: cypress-io/cypress
File: packages/server/test/unit/cloud/api/studio/post_studio_session_spec.ts (TypeScript)

Code before:
import { SystemError } from '../../../../../lib/cloud/network/system_error'
import { proxyquire } from '../../../../spec_helper'
import os from 'os'
import { agent } from '@packages/network'
import pkg from '@packages/root'
import { ParseKinds } from '../../../../../lib/cloud/network/fetch'

describe('postStudioSession', () => {
  let postStudioSession: typeof import('@packages/server/lib/cloud/api/studio/post_studio_session').postStudioSession
  let postFetchStub: sinon.SinonStub = sinon.stub()

  beforeEach(() => {
    postFetchStub.reset()
    postStudioSession = (proxyquire('@packages/server/lib/cloud/api/studio/post_studio_session', {
      '../../network/fetch': {
        postFetch: postFetchStub,
      },
    }) as typeof import('@packages/server/lib/cloud/api/studio/post_studio_session')).postStudioSession
  })

  it('should post a studio session', async () => {
    postFetchStub.resolves({
      studioUrl: 'http://localhost:1234/studio/bundle/abc.tgz',
      protocolUrl: 'http://localhost:1234/capture-protocol/script/def.js',
    })

    const result = await postStudioSession({
      projectId: '12345',
    })


Review comment (suggestion):
```suggestion
import pkg from '@packages/root'
```

Code after:
import { SystemError } from '../../../../../lib/cloud/network/system_error'
import { proxyquire } from '../../../../spec_helper'
import os from 'os'
import pkg from '@packages/root'
import { ParseKinds } from '../../../../../lib/cloud/network/fetch'
import sinon from 'sinon'

describe('postStudioSession', () => {
  let postStudioSession: typeof import('@packages/server/lib/cloud/api/studio/post_studio_session').postStudioSession
  let postFetchStub: sinon.SinonStub = sinon.stub()

  beforeEach(() => {
    postFetchStub.reset()
    postStudioSession = (proxyquire('@packages/server/lib/cloud/api/studio/post_studio_session', {
      '../../network/fetch': {
        postFetch: postFetchStub,
      },
    }) as typeof import('@packages/server/lib/cloud/api/studio/post_studio_session')).postStudioSession
  })

  it('should post a studio session', async () => {
    postFetchStub.resolves({
      studioUrl: 'http://localhost:1234/studio/bundle/abc.tgz',
      protocolUrl: 'http://localhost:1234/capture-protocol/script/def.js',
    })

    const result = await postStudioSession({
      projectId: '12345',
    })
Repository: cypress-io/cypress
File: packages/server/test/unit/cloud/api/studio/post_studio_session_spec.ts (TypeScript)

Code before:
import { SystemError } from '../../../../../lib/cloud/network/system_error'
import { proxyquire } from '../../../../spec_helper'
import os from 'os'
import { agent } from '@packages/network'
import pkg from '@packages/root'
import { ParseKinds } from '../../../../../lib/cloud/network/fetch'

describe('postStudioSession', () => {
  let postStudioSession: typeof import('@packages/server/lib/cloud/api/studio/post_studio_session').postStudioSession
  let postFetchStub: sinon.SinonStub = sinon.stub()

  beforeEach(() => {
    postFetchStub.reset()
    postStudioSession = (proxyquire('@packages/server/lib/cloud/api/studio/post_studio_session', {
      '../../network/fetch': {
        postFetch: postFetchStub,
      },
    }) as typeof import('@packages/server/lib/cloud/api/studio/post_studio_session')).postStudioSession
  })

  it('should post a studio session', async () => {
    postFetchStub.resolves({
      studioUrl: 'http://localhost:1234/studio/bundle/abc.tgz',
      protocolUrl: 'http://localhost:1234/capture-protocol/script/def.js',
    })

    const result = await postStudioSession({
      projectId: '12345',
    })


Review comment (suggestion):
```suggestion
import { ParseKinds } from '../../../../../lib/cloud/network/fetch'
import sinon from 'sinon'
```

Code after:
import { SystemError } from '../../../../../lib/cloud/network/system_error'
import { proxyquire } from '../../../../spec_helper'
import os from 'os'
import pkg from '@packages/root'
import { ParseKinds } from '../../../../../lib/cloud/network/fetch'
import sinon from 'sinon'

describe('postStudioSession', () => {
  let postStudioSession: typeof import('@packages/server/lib/cloud/api/studio/post_studio_session').postStudioSession
  let postFetchStub: sinon.SinonStub = sinon.stub()

  beforeEach(() => {
    postFetchStub.reset()
    postStudioSession = (proxyquire('@packages/server/lib/cloud/api/studio/post_studio_session', {
      '../../network/fetch': {
        postFetch: postFetchStub,
      },
    }) as typeof import('@packages/server/lib/cloud/api/studio/post_studio_session')).postStudioSession
  })

  it('should post a studio session', async () => {
    postFetchStub.resolves({
      studioUrl: 'http://localhost:1234/studio/bundle/abc.tgz',
      protocolUrl: 'http://localhost:1234/capture-protocol/script/def.js',
    })

    const result = await postStudioSession({
      projectId: '12345',
    })
Repository: cypress-io/cypress
File: packages/driver/cypress/e2e/commands/prompt/prompt.cy.ts (TypeScript)

Code before:
describe('src/cy/commands/prompt', () => {
  afterEach(() => {
    Cypress.testingType = 'e2e'
  })

  it('executes the prompt command', (done) => {
    // TODO: (cy.prompt) We will look into supporting other browsers
    // as this is rolled out. We will add error messages for other browsers
    // and add tests if necessary
    if (Cypress.isBrowser('webkit') || Cypress.isBrowser('firefox')) {
      return
    }

    const contributorPr = !Cypress.env('RECORD_KEY') && Cypress.config('isTextTerminal')

    if (contributorPr) {
      cy.on('fail', (err) => {
        expect(err.message).to.include('Record key not provided')

        done()
      })

      cy.visit('http://www.foobar.com:3500/fixtures/prompt.html')
      cy.prompt(['Click the "click me" button']).then(() => {
        done(new Error('Expected prompt to fail'))
      })
    } else {
      cy.visit('http://www.foobar.com:3500/fixtures/prompt.html')
      cy.prompt(['Click the "click me" button'])
      cy.get('#log').should('contain', 'clicked').then(() => {
        done()
      })
    }
  })

  it('fails when testingType is component', (done) => {
    cy.on('fail', (err) => {
      expect(err.message).to.eq('`cy.prompt` is currently only supported in end-to-end tests.')
      done()
    })

    Cypress.testingType = 'component'

    cy.visit('http://www.foobar.com:3500/fixtures/prompt.html')

    cy.prompt(['Click the "click me" button'])
  })
})


Review comment (suggestion):
```suggestion
      cy.prompt(['Click the "click me" button'])
```

Code after:
describe('src/cy/commands/prompt', () => {
  afterEach(() => {
    Cypress.testingType = 'e2e'
  })

  // TODO: (cy.prompt) We will look into supporting other browsers
  // as this is rolled out. We will add error messages for other browsers
  // and add tests if necessary
  if (!Cypress.isBrowser('webkit') && !Cypress.isBrowser('firefox')) {
    const contributorPr = Cypress.env('CI') && !Cypress.env('RECORD_KEY') && Cypress.config('isTextTerminal')

    if (contributorPr) {
      it('executes the prompt command - contributor PR', (done) => {
        cy.on('fail', (err) => {
          expect(err.message).to.include('Record key not provided')

          done()
        })

        cy.visit('http://www.foobar.com:3500/fixtures/prompt.html')
        cy.prompt(['Click the "click me" button'])
      })
    } else {
      it('executes the prompt command - normal PR', () => {
        cy.visit('http://www.foobar.com:3500/fixtures/prompt.html')
        cy.prompt(['Click the "click me" button'])
        cy.get('#log').should('contain', 'clicked')
      })
    }
  }

  it('fails when testingType is component', (done) => {
    cy.on('fail', (err) => {
      expect(err.message).to.eq('`cy.prompt` is currently only supported in end-to-end tests.')
      done()
    })

    Cypress.testingType = 'component'

    cy.visit('http://www.foobar.com:3500/fixtures/prompt.html')

    cy.prompt(['Click the "click me" button'])
  })
})
Repository: cypress-io/cypress
File: packages/app/cypress/e2e/studio/studio-new-tests.cy.ts (TypeScript)

Code before:
    })
  })

  it('visits a basic html page', () => {
    cy.visit('cypress/e2e/index.html')
  })

  /* ==== Test Created with Cypress Studio ==== */
  it('new-test', function() {
    /* ==== Generated with Cypress Studio ==== */
    cy.visit('http://foobar.com:4455/cypress/e2e/index.html');
    /* ==== End Cypress Studio ==== */
  });
})`.trim())
    })
  })

  it('creates a new test for a specific suite with the url already defined', () => {
    launchStudio({ specName: 'spec-w-visit.cy.js', createNewTestFromSuite: true })

    inputNewTestName({ creatingNewTestFromWelcomeScreen: false })

    cy.percySnapshot()

    // make sure that the visit has run and we're recording studio commands
    cy.get('[data-cy="record-button-recording"]').should('be.visible')

    incrementCounter(0)

    cy.findByTestId('studio-save-button').click()

    // we should have the commands we executed after we save
    cy.withCtx(async (ctx) => {
      const spec = await ctx.actions.file.readFileInProject('cypress/e2e/spec-w-visit.cy.js')

      expect(spec.trim().replace(/\r/g, '')).to.equal(`
describe('studio functionality', () => {
  beforeEach(() => {
    cy.visit('cypress/e2e/index.html')
  });

  it('visits a basic html page', () => {
    cy.get('h1').should('have.text', 'Hello, Studio!')
  })

  it('new-test', function() {
    cy.get('#increment').click();
  });
})`.trim())
    })
  })

Review comment (suggestion):
Suggest taking the snapshot after we know we're ready.
```suggestion
    // make sure that the visit has run and we're recording studio commands
    cy.get('[data-cy="record-button-recording"]').should('be.visible')

    cy.percySnapshot()
```

Code after:
    })
  })

  it('visits a basic html page', () => {
    cy.visit('cypress/e2e/index.html')
  })

  /* ==== Test Created with Cypress Studio ==== */
  it('new-test', function() {
    /* ==== Generated with Cypress Studio ==== */
    cy.visit('http://foobar.com:4455/cypress/e2e/index.html');
    /* ==== End Cypress Studio ==== */
  });
})`.trim())
    })
  })

  it('creates a new test for a specific suite with the url already defined', () => {
    launchStudio({ specName: 'spec-w-visit.cy.js', createNewTestFromSuite: true })

    inputNewTestName({ creatingNewTestFromWelcomeScreen: false })

    // make sure that the visit has run and we're recording studio commands
    cy.get('[data-cy="record-button-recording"]').should('be.visible')

    cy.percySnapshot()

    incrementCounter(0)

    cy.findByTestId('studio-save-button').click()

    // we should have the commands we executed after we save
    cy.withCtx(async (ctx) => {
      const spec = await ctx.actions.file.readFileInProject('cypress/e2e/spec-w-visit.cy.js')

      expect(spec.trim().replace(/\r/g, '')).to.equal(`
describe('studio functionality', () => {
  beforeEach(() => {
    cy.visit('cypress/e2e/index.html')
  });

  it('visits a basic html page', () => {
    cy.get('h1').should('have.text', 'Hello, Studio!')
  })

  it('new-test', function() {
    cy.get('#increment').click();
  });
})`.trim())
    })
  })
Repository: cypress-io/cypress
File: packages/data-context/src/data/ProjectConfigIpc.ts (TypeScript)

Code before:
      projectRoot: this.projectRoot,
      configFile: this.configFilePath,
      version: pkg.version,
      testingType,
    })

    return promise
  }

  private registerSetupIpcHandlers (): Promise<SetupNodeEventsReply> {
    return new Promise((resolve, reject) => {
      let resolved = false

      this._childProcess.on('error', (err: NodeJS.ErrnoException) => {
        if (err.code === 'EPIPE') {
          return
        }

        this.handleChildProcessError(err, this, resolved, reject)
        reject(err)
      })

      // For every registration event, we want to turn into an RPC with the child process
      this.once('setupTestingType:reply', (val) => {
        resolved = true
        resolve(val)
      })

      this.once('setupTestingType:error', (err) => {
        this.onError(err)
        reject(err)
      })

      this.once('file:preprocessor:overridden', ({ handlerText }) => {
        this.onDebugData({
          filePreprocessorHandlerText: handlerText,
        })
      })

      const handleWarning = (warningErr: CypressError) => {
        debug('plugins process warning:', warningErr.stack)

        return this.onWarning(warningErr)
      }

      this.on('warning', handleWarning)
    })
  }

  private forkConfigProcess (): ChildProcess {
    const configProcessArgs = ['--projectRoot', this.projectRoot, '--file', this.configFilePath]

Review comment (bug):
are you able to add a `debug` statement here that prints the error before we return? 

Code after:
      orderedConfig[k] = mergedConfig[k]
    })

    this.send('setupTestingType', testingType, {
      ...orderedConfig,
      projectRoot: this.projectRoot,
      configFile: this.configFilePath,
      version: pkg.version,
      testingType,
    })

    return promise
  }

  private registerSetupIpcHandlers (): Promise<SetupNodeEventsReply> {
    return new Promise((resolve, reject) => {
      let resolved = false

      this._childProcess.on('error', (err: NodeJS.ErrnoException) => {
        if (err.code === 'EPIPE') {
          debug('EPIPE error in registerSetupIpcHandlers() of child process %s', err)

          // @ts-ignore
          resolve()

          return
        }

        this.handleChildProcessError(err, this, resolved, reject)
        reject(err)
      })

      // For every registration event, we want to turn into an RPC with the child process
      this.once('setupTestingType:reply', (val) => {
        resolved = true
        resolve(val)
      })

      this.once('setupTestingType:error', (err) => {
        this.onError(err)
        reject(err)
      })

      this.once('file:preprocessor:overridden', ({ handlerText }) => {
        debug('file:preprocessor:overridden: %s', handlerText)
        this.onDebugData({
          filePreprocessorHandlerText: handlerText,
        })
      })

      const handleWarning = (warningErr: CypressError) => {