Fixtures (JSON file) for UI Testing - javascript

Has anybody used fixtures (json file) to load the data in postgres database and execute UI testing ?

Using node-postgres and node-pg-copy-streams can load and remove/delete data from postgres database.
Code and example:
[https://github.com/AmitKulkarni9/fixtures-tests][1]
LoadData.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;

Related

Calling a smart contract function using truffle/hdwallet-provider

I have a contract on polygon and I want to call a write function setPrice(uint256 _price) but when I run this code then I am getting an error:
{ code: -32000, message: 'transaction underpriced' }
Smart Contract: https://polygonscan.com/address/0x8835c31178f8f3407d4588be49532de1c02c3a04
this is my code:
const Web3 = require("web3");
const WalletProvider = require("#truffle/hdwallet-provider");
const http = require("http");
const { release } = require("os");
const mysql = require('mysql');
const conn = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database:"nft",
});
conn.connect(function(err) {
if (err) throw err;
//console.error("Connected!");
});
let provider = new WalletProvider({
mnemonic: {
phrase: '*****myWalletPhrase*****'
},
providerOrUrl: "https://rpc-mainnet.matic.quiknode.pro/"
});
const web3 = new Web3(provider);
const dexABI ="smartContractAbi";
const contract_address = "0x8835c31178F8f3407d4588Be49532De1c02C3A04";
const contract = new web3.eth.Contract(dexABI, contract_address);
function toFixed(x) {
// some code
}
http.createServer(async (req, res) => {
if(req.url != '/favicon.ico')
{
try {
const accounts = await web3.eth.getAccounts();
//console.error(accounts);
let user= accounts[6];
let amount=0;
conn.query(`SELECT * FROM dollor_rate`, async function(err,result){
if (err) return err;
console.error("this",result[0].usd_rate);
amount=toFixed(result[0].usd_rate).toString();
await contract.methods.setPrice(''+amount).send({from:user,gas:21000},function(err1,receipt){
if(err1)
console.error("Error==>",err1);
else
console.error("Erorr1=======",receipt);
});
});
} catch (error) {
console.log(error);
}
res.end();
}
})
.listen(8080);
The gas fee you are providing with the transaction is low. Try increasing the gas you provide with the transaction.
This is similar to this,
https://stackoverflow.com/a/67974018/7453857

Cannot POST /api/sentiment

I'm testing the endpoint for /api/sentiment in postman and I'm not sure why I am getting the cannot POST error. I believe I'm passing the correct routes and the server is listening on port 8080. All the other endpoints run with no issue so I'm unsure what is causing the error here.
server.js file
const express = require("express");
const cors = require("cors");
const dbConfig = require("./app/config/db.config");
const app = express();
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
const db = require("./app/models");
const Role = db.role;
db.mongoose
.connect(`mongodb+srv://tami00:MEUxClWqUNbLz359#cluster0.gmvao.mongodb.net/test?retryWrites=true&w=majority`, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Successfully connect to MongoDB.");
initial();
})
.catch(err => {
console.error("Connection error", err);
process.exit();
});
// simple route
app.use('/api/favourite', require('./app/routes/favourite.routes'));
app.use('/api/review', require('./app/routes/review.routes'));
app.use('/api/sentiment', require('./app/routes/sentiment-analysis.routes'));
// routes
// require(".app/routes/favourite.routes")(app);
require("./app/routes/auth.routes")(app);
require("./app/routes/user.routes")(app);
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
function initial() {
Role.estimatedDocumentCount((err, count) => {
if (!err && count === 0) {
new Role({
name: "user"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'user' to roles collection");
});
new Role({
name: "creator"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'creator' to roles collection");
});
new Role({
name: "watcher"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'watcher' to roles collection");
});
}
});
}
sentiment-analysis routes file
const express = require('express');
const router = express.Router();
const getSentiment = require('../sentiment-analysis/sentimentAnalysis')
router.post('/api/sentiment', (req, res) => {
const data = req.body.data
const sentiment = getSentiment(data)
return res.send({sentiment})
})
module.exports = router;
sentimentAnalysis.js file
const aposToLexForm = require("apos-to-lex-form");
const {WordTokenizer, SentimentAnalyzer, PorterStemmer} = require("natural");
const SpellCorrector = require("spelling-corrector");
const stopword = require("stopword");
const tokenizer = new WordTokenizer();
const spellCorrector = new SpellCorrector();
spellCorrector.loadDictionary();
const analyzer = new SentimentAnalyzer('English', PorterStemmer, 'afinn')
function getSentiment(text){
if(!text.trim()) {
return 0;
}
const lexed = aposToLexForm(text).toLowerCase().replace(/[^a-zA-Z\s]+/g, "");
const tokenized = tokenizer.tokenize(lexed)
const correctSpelling = tokenized.map((word) => spellCorrector.correct(word))
const stopWordsRemoved = stopword.removeStopwords(correctSpelling)
console.log(stopWordsRemoved)
const analyzed = analyzer.getSentiment(stopWordsRemoved);
console.log(analyzed)
}
module.exports = getSentiment;
console.log(getSentiment("Wow this is fantaztic!"))
console.log(getSentiment("let's go together?"))
console.log(getSentiment("this is so bad, I hate it, it sucks!"))
I see that you use your routes like: app.use('/api/sentiment', require('./app/routes/sentiment-analysis.routes'));. But then in your sentiment-analysis you again use /api/sentiment so your request URL should be /api/sentiment/api/sentiment
Shouldn't it be:
const data = req.body.data

fs database will not save for some reason?

I'm trying to generate a code, add it to a database, and then return it to the request server. I'm getting no errors, but the database remains empty, nothing gets added. I'm using glitch as a temporary host, my json file is just {}
My code:
const Discord = require('discord.js')
const rbx = require('noblox.js')
const fs = require("fs")
const express = require("express")
const app = express()
app.use(express.json())
const client = new Discord.Client()
client.verificationCodes = require("./codes.json")
require("dotenv").config()
const port = process.env.PORT
const serverKey = process.env.SERVER_KEY
const cookie = process.env.COOKIE
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
client.on("ready", () => {
console.log("Client is ready.")
})
app.post("/getVerificationCode", function(req,res,next) {
console.log("Recieved")
if (req.body.serverKey !== serverKey) {
console.log("Invalid serverKey supplied.")
return res.status(403).json({
error: "You do not have permission to use this."
})
}
let verificationCode = randomString(4,'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').toUpperCase()
const userID = parseInt(req.body.userid)
console.log(verificationCode)
client.verificationCodes[userID] = {
code: verificationCode
}
fs.writeFile("./codes.json", JSON.stringify(client.verificationCodes,null,4), err => {
if (err) throw err
})
return res.status(200).json({
VerificationCode: verificationCode
})
})
app.get("/*", function(req,res,next) {
return res.status(200).json({})
})
app.listen(port)
console.log(`App listening on port ${port}`)
function rbxLogin(newCookie) {
try {
rbx.setCookie(newCookie)
} catch(err) {
console.log(`Invalid cookie supplied, or expired. ${err}`)
}
}
// rbxLogin(cookie)
client.login(process.env.BOT_TOKEN)
I watched a video on how to use an fs database. I appreciate any help!

How to modify common mongodb query to async with try and catch

This is my code with written with express js
this query works but I think that using async is more reliable than this
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = "mongodb://localhost:27017/nodejs_crud";
const db_n = "nodejs_crud"
const client = new MongoClient(url, { useUnifiedTopology: true });
app.get("/", async (req, res) => {
// this is myquery code with right result
client.connect((err) => {
assert.equal(null, err);
const db = client.db(db_n)
db.collection("list").find({}).toArray((err, result) => {
if(err) throw res.send({ status: "Error when react data", bool: false}).status(450);
res.send(result).status(200);
})
})
});
Try this, not exactly the same as yours, but will give you the idea on how to use async/await with try/catch
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/nodejs_crud";
const db_n = "nodejs_crud"
const client = new MongoClient(url, { useUnifiedTopology: true });
app.get('/', async (req, res) => {
// Connect client if it's not connected
if(!client.isConnected()) {
await client.connect();
// you can also catch connection error
try {
await client.connect();
catch(err) {
return res.status(500).send();
}
}
const db = client.db(db_n);
try {
// Run queries
const result = db.collection("list").find({});
res.json(await result.toArray());
} catch (err) {
// Catch any error
console.log(err.message);
res.status(450).send();
}
});
I have not tested this, but try something along the lines of:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = "mongodb://localhost:27017/nodejs_crud";
const db_n = "nodejs_crud"
let client;
const getDb = async () => {
// If we don't have a client, create one.
if (!client) client = new MongoClient(url, { useUnifiedTopology: true });
// If we are not connected, then connect.
if (!client.connected()) await client.connect();
// Get our database
return client.db(db_n);
}
app.get("/", async (req, res) => {
try {
const db = await getDb();
const results = await db.collection("list").find({}).toArray();
res.send(result).status(200);
} catch (err) {
res.send({ status: "Error when react data", bool: false}).status(450);
}
});

Every second run throws: MongoError: Topology was destroyed

I am building a REST API but every second time I load my site I get a MongoError: Topology was destroyed. Can someone help me fixing this? I have a feeling that there is something wrong with the asynchronous running.
const client = new MongoClient(apiconfig.mongoUrl, {
useNewUrlParser: true
});
app.get("/api/:object", (req, res) => {
mongodb(req.params["object"], async (collection: Collection) => {
if (collection !== undefined) {
let result = await collection.find().toArray();
res.send(result);
}
else {
res.sendStatus(404);
}
});
});
const mongodb = (coll: string, operation: (collection: Collection) => Promise<void>) => {
client.connect((err) => {
const db = client.db("VaorraJS");
db.collections().then((collections) => {
operation(collections.find((collection) => collection.collectionName === coll)).then(() => {
client.close();
});
}).catch((error) => {
console.log("ERROR: " + error);
});
});
}
app.listen(5000);
I would suggest the use Mongoose
you are creating DB connection for every request, which is not the correct way
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = '<some db>';
// Use connect method to connect to the server
let db;
MongoClient.connect(url, function (err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
db = client.db(dbName);
});
app.get("/api/:object", async(req, res) => {
const collection = db.collection(req.params["object"]);
let result = await collection.find().toArray();
res.send(result);
});

Categories