如何通过SSH隧道连接Cypress和MySQL?

3

目前Cypress支持在不使用SSH的情况下连接MySQL,如下链接所示:

https://docs.cypress.io/api/commands/task#Allows-a-single-argument-only

但我正在尝试通过SSH隧道将Cypress连接到MySQL。 我正在使用npm包mysql-ssh建立连接。

我能够直接使用node.js实现这一点,但我在通过Cypress实现时遇到了问题。以下是我在node.js中尝试的片段。

const mysqlssh = require('mysql-ssh');
const fs = require('fs');

mysqlssh.connect(
    {
        host: 'x.x.x.x',
        user: 'xyz',
        privateKey: fs.readFileSync('filePath')  //this is the ssh filePath
    },
    {
        host: 'HOST_NAME',
        user: 'USER_NAME',
        password: 'xxxx',
        database: 'DB_NAME'
    }
)
.then(client => {
    client.query('select * from TABLE_NAME',  function (err, results, fields) {
        if (err)
        {
            console.log(err)
        }
        console.log(results);
        mysqlssh.close()
    })
})
.catch(err => {
    console.log(err)
})

我希望通过cypress/plugins/index.js文件或直接在cypress/integration中实现此操作。有简单的方法吗?

1个回答

3

我已经找到了解决方案,这是我在cypress/plugins/index.js文件中的代码:

const dotenvPlugin = require('cypress-dotenv');
const mysqlssh = require('mysql-ssh');
const fs = require('fs');

module.exports = (on, config) => {
  //  `config` is the resolved Cypress config
    config = dotenvPlugin(config);

    on('task', {
        executeSql (sql, ...args) {
            return new Promise(async (resolve, reject) => {
                try {
                    let connection = await mysqlssh.connect(  {
                            host: process.env.SSH_HOST,
                            user: process.env.SSH_USER,
                            privateKey: fs.readFileSync(process.env.HOME + '/.ssh/id_rsa_old')
                        },
                        {
                            host: process.env.MYSQL_HOST,
                            user: process.env.MYSQL_USER,
                            password: process.env.MYSQL_PASSWORD,
                            database: process.env.MYSQL_DB
                        });
                    let result = await connection.promise().query(sql, args);
                    mysqlssh.close();
                    resolve(result[0][0]); 
                } catch (err) {
                    reject(err);
                }
            });
        }
    })

    return config
}

所以,必须在此文件中建立此连接,因为Cypress不与主机提供的Node进程通信。因此,我们需要使用Cypress任务来运行Node代码。请参阅此处的文档-https://docs.cypress.io/api/commands/task#Examples 在测试文件示例中,我使用它的方式如下:
describe('Db Test',  () => {
    it('Query Test', () => {
        cy.task('executeSql', 'SELECT count(id) as cnt FROM table_name').then(result => {
            expect(result.cnt, 'Does not equal to 8').to.equal(2000);
        })
    })
})

P.S. cypress-dotenv包只是用来从.env文件中加载环境变量。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接