有没有人使用fixtures(json文件)在postgres数据库中加载数据并执行UI测试?
问问题
48 次
1 回答
0
使用 node-postgres 和 node-pg-copy-streams 可以从 postgres 数据库加载和删除/删除数据。代码和示例:[https://github.com/AmitKulkarni9/fixtures-tests][1]
加载数据.js
const fs = require('fs');
const path = require('path');
const {Client} = require('pg');
const copyFrom = require('pg-copy-streams').from;
const config = require('./config.json');
// Getting connection parameters from config.json
const host = config.host;
const user = config.user;
const pw = config.pw;
const db = config.db;
const port = config.port;
const conString = `postgres://${user}:${pw}@${host}:${port}/${db}`;
class LoadData {
async Load (targetTable) {
try {
const inputFile = path.join(__dirname, `/data/${targetTable}.csv`);
const client = new Client({connectionString: conString,});
client.connect(); // gets connection
const stream = client.query(copyFrom(`COPY ${targetTable} FROM STDIN WITH CSV HEADER`));
const fileStream = fs.createReadStream(inputFile);
fileStream.on('error', (error) =>{
console.log(`Error in creating read stream ${error}`);
client.end();
return;
})
stream.on('error', (error) => {
console.log(`Error in creating stream ${error}`);
client.end();
return;
})
stream.on('finish', () => {
console.log(`Completed loading data into ${targetTable}`);
client.end();
})
fileStream.pipe(stream);
return;
} catch (e) {
console.error(e);
client.end();
return;
}
}
}
module.exports = LoadData;
RemoveData.js
const path = require('path');
const {Client} = require('pg');
const config = require('./config.json');
// Getting connection parameters from config.json
const host = config.host;
const user = config.user;
const pw = config.pw;
const db = config.db;
const port = config.port;
const conString = `postgres://${user}:${pw}@${host}:${port}/${db}`;
class RemoveData {
async Remove (table) {
try {
const client = new Client({connectionString: conString,});
client.connect(); // gets connection
client.query(`DELETE FROM ${table} WHERE id IN ($1,$2,$3) RETURNING *`, [1,2,3], (err, result) => {
if(err) {
console.log(err);
client.end();
return;
} else {
console.log(`Deleted data from ${table}`);
//let results= result.rows;
//console.log(results);
client.end();
return;
}
});
} catch (e) {
console.error(e);
client.end();
return;
}
}
}
module.exports = RemoveData;
于 2021-08-23T07:49:21.633 回答