首页 > 解决方案 > 尝试使用赛普拉斯执行系统命令时出现系统性故障

问题描述

我是赛普拉斯和 Javascript 的新手

我正在尝试通过赛普拉斯发送系统命令。我已经经历了几个例子,但即使是最简单的也不起作用。它总是失败并显示以下消息

Information about the failure:
Code: 127

Stderr:
/c/Program: Files\Git\usr\bin\bash.exe: No such file or directory`

我正在尝试 cy.exec('pwd') 或 'ls' 来查看它是从哪里启动的,但它不起作用。是否有我遗漏的特定内容?一些特殊的配置?

编辑:确实,我不清楚我试图在其中使用命令的上下文。但是,我没有明确设置任何路径。

我在 linux 服务器上发送请求,但我也想发送系统命令。

我的 cypress 项目在/c/Cypress/test_integration/cypress 我使用位于的 .feature 文件/c/Cypress/test_integration/cypress/features/System,我的场景调用位于的文件 system.js 中的函数/c/Cypress/test_integration/cypress/step_definitions/generic

System_operations.features:
Scenario: [0004] - Restore HBox configuration
    Given I am logging with "Administrator" account from API
    And I store the actual configuration
...

然后我的 .js 文件,我想发送一个系统命令

system.js:
Given('I store the actual configuration', () => {
    let nb_elem = 0
    
    cy.exec('ls -l')
...
})

我没有在 VS Code 中为使用 bash 命令进行特定的路径配置(我只是在 bash 而不是 powershell 中配置了终端)

标签: cmdcypress

解决方案


最后,在一些帮助下,我设法通过使用任务来调用系统函数。在我的函数中,我调用:

cy.task('send_system_cmd', 'pwd').then((output) => {
  console.log("output = ", output)
})

创建的任务如下:

  on('task', {
    send_system_cmd(cmd) {
      console.log("task test command system")

    const execSync = require('child_process').execSync;
    const output = execSync(cmd, { encoding: 'utf-8' }); 
    return output
      }
  })

这至少适用于简单的命令,目前我还没有进一步尝试。

更新 LINUX 系统命令,因为以前的方法适用于 WINDOWS

(对不起,我不记得我在哪里找到了这个方法,这不是我的功劳。虽然它满足了我的需求)

这种情况需要node-ssh

还是用tasks,函数调用是这样完成的

cy.task('send_system_cmd', {cmd:"<my_command>", endpoint:<address>,user:<ssh_login>, pwd:<ssh_password>}).then((output) => {
    <process output.stdout or output.stderr>
})

像这样构建任务:

  // send system command - remote
  on('task', {
    send_system_cmd({cmd, endpoint, user, pwd}) {     
      return new Promise((resolve, reject) => {

        const { NodeSSH } = require('node-ssh')

        const ssh = new NodeSSH()
        let ssh_output = {}

        ssh.connect({
          host: endpoint,
          username: user,
          password: pwd
        })
        .then(() => {
          if(!ssh.isConnected())
            reject("ssh connection not set")

          //console.log("ssh connection OK, send command")
          ssh.execCommand(cmd).then(function (result) {
            ssh_output["stderr"] = result.stderr
            ssh_output["stdout"] = result.stdout

            resolve(ssh_output)
          });
        })
        .catch((err)=>{
          console.log(err)
          reject(err)
        })
      })
    }
  })

推荐阅读