目前,柏树不使用ssh支持mysql连接,如下面的链接所示。
https://docs.cypress.io/api/commands/task#Allows-a-single-argument-only
但我正试图通过ssh隧道将柏树连接到mysql。我正在使用npm包mysql-ssh来建立连接。
我能够直接使用node.js实现这一点,但我在通过柏树实现时面临问题。这是我在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中这样做。有什么简单的方法吗?
发布于 2021-12-17 23:09:29
我已经找到了解决办法。下面是我的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
}因此,必须在此文件中建立此连接,b/c柏树不与主机提供的节点进程通信。因此,我们需要使用柏树任务来运行节点代码。见这里的文档- 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);
})
})
})额外的cypress-dotenv包只是用来从.env文件中加载env。
https://stackoverflow.com/questions/70112565
复制相似问题