How to upload csv file through Protractor - protractor

I am automating a scenario, need to upload a CSV file and validate the result after uploading the file.
The application code will be as follows:
var assetBulkInUploadJson = "./src/resources/scm-test-data/evin/asserts/create-assets-bulk-upload.csv";
var path = require('path');
var assetsTestData = require(path.resolve(assetBulkInUploadJson));
var chooseFileButton= element(by.css("input[file-model='fileData']"));
//send the file address to choose file
chooseFileButton.sendKeys(assetsTestData);
I stuck at uploading CSV file, getting the below error
E/launcher - Error: /Users/Sarada/IdeaProjects/scm-ui-automation/src/resources/scm-test-data/evin/asserts/create-assets-bulk-upload.csv:1 (function (exports, require, module, __filename, __dirname) { //data in csv file displayed
SyntaxError: Unexpected identifier
at new Script (vm.js:79:7)
at createScript (vm.js:251:10)
at Object.runInThisContext (vm.js:303:10)
at Module._compile (internal/modules/cjs/loader.js:657:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
If I pass the absolute path directly to the sendKeys() it is working fine.
chooseFileButton.sendKeys("/Users/Sarada/IdeaProjects/scm-ui-automation/src/resources/scm-test-data/evin/asserts/create-assets-bulk-upload.csv");
How to resolve this issue, how to convert relative path to absolute and send as variable argument? please help me.

try with this
var assetsTestData = (file) => (path.resolve(__dirname, `${file}`));
then
chooseFileButton.sendKeys(assetsTestData(assetBulkInUploadJson);

You don't need to require your file, just specify the path and send it to input
var assetBulkInUploadJson = "./src/resources/scm-test-data/evin/asserts/create-assets-bulk-upload.csv";
var path = require('path');
var assetsTestData = path.resolve(__dirname, assetBulkInUploadJson);
var chooseFileButton= element(by.css("input[file-model='fileData']"));
//send the file address to choose file
chooseFileButton.sendKeys(assetsTestData);

Two ways to solve the issue
Solution 1:
var assetBulkInUploadJson = "./src/resources/scm-test-data/evin/asserts/create-assets-bulk-upload.csv";
var path = require('path');
var assetsTestData = path.resolve(assetBulkInUploadJson);
var chooseFileButton= element(by.css("input[file-model='fileData']"));
//send the file address to choose file
chooseFileButton.sendKeys(assetsTestData);
Solution 2:
var assetBulkInUploadJson = "./src/resources/scm-test-data/evin/asserts/create-assets-bulk-upload.csv";
var path = require('path');
var assetsTestData = (file) => (path.resolve(`${file}`));
var chooseFileButton= element(by.css("input[file-model='fileData']"));
//send the file address to choose file
chooseFileButton.sendKeys(assetsTestData(assetBulkInUploadJson));
Thanks #Sergey and #Joaquin

Related

unable to upload folder with files using protractor for web application testing

Iam using protractor for testing my web application that has a button to popup window to open file explorer where I need to select a folder that contains 5 files that needs to be uploaded.
I have the code as
''''
var fileUpload = '/home/indu/jpg';
require("./logger");
console.file("./test.log");
var absolutePath = path.resolve(__dirname, fileUpload);
fs.readdir(absolutePath, (err, files) => {
for (i = 0; i < files.length; i++) {
filelst.push(fileUpload +"/"+files[i]);
}
console.log("fuull is ",filelst);
});
var remote = require('/usr/lib/node_modules/protractor/node_modules/selenium-webdriver/remote');
browser.setFileDetector(new remote.FileDetector());
var absolutePath = path.resolve(__dirname, fileUpload);
console.log("value of absolutePath",absolutePath);
var fileElem = element(by.css('input[type="file"]'));
// Unhide file input
browser.executeScript("arguments[0].style.visibility = 'visible'; arguments[0].style.height = '1px'; arguments[0].style.width = '1px'; arguments[0].style.opacity = 1", fileElem.getWebElement());
fileElem.sendKeys(absolutePath);
when I execute I get below error
Failed: unexpected alert open: {Alert text : Error during upload, redirecting to login page .... }
(Session info: chrome=96.0.4664.110): Error during upload, redirecting to login page ....
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'indu-Latitude-E6420', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '5.4.0-91-generic', java.version: '1.8.0_312'
Driver info: driver.version: unknown
I have tried on windows10 as well as ubuntu 18.04.05 and on both I get chrome driver info version unknown error. I have searched for this error and tried suggested solution in
Unable to start e2e tesing in angular project
but that didnt work too.
Pls suggest
I resolved the problem by a
browser.wait(ExpectedConditions.elementToBeClickable(buttonelementlocator),
100, 'Element is not clickable.').then( () => {
uploadfiles();
});
function uploadfiles(){
var shell = require('shelljs');
var exec = require('child_process').execFile;
// uploadfile.bat contains the autoit exe to upload the files and handle
chromebrowser alert
var task = shell.exec('uploadfile.bat');
if (task.code !== 0) {
console.log("execute AutoIt script fail: " + task.stdout);
shell.exit(1);
}
}

Libre office configuration file bootstrap.ini corrupt

I am using the libreoffice-convert package to convert a Word file into PDF. But when I try to convert I get this error. How do I fix this? I have installed LibreOffice 7.0.5
Console log is showing this error:
'C:\\Program Files\\LibreOffice\\program\\soffice.exe -env:UserInstallation=file://C:\\Users\\thesa\\AppData\\Local\\Temp\\soffice-10416-bQefydwUfs2F --headless --convert-to .pdf --outdir C:\\Users\\thesa\\AppData\\Local\\Temp\\libreofficeConvert_-10416-v46bO7ljGHRe C:\\Users\\thesa\\AppData\\Local\\Temp\\libreofficeConvert_-10416-v46bO7ljGHRe\\source'
Try this, you will probably need administrator rights.
Locate and copy your orignal file, for example to "bootstrap.ini.org", in the same directory1.
Open the file and replace its contents with this, which is a copy of my file:
[Bootstrap]
InstallMode=<installmode>
ProductKey=LibreOffice 7.0
UserInstallation=$SYSUSERCONFIG/LibreOffice/4
Another option is to re-install or repair the installation.
Note 1: This copy is just in case you need to revert.
//let data = await fs.promises.readFile(path_to_excel_file);
let data = fs.readFileSync(path_to_excel_file)
let pdfFile = await libreConvert(data, '.pdf', undefined);
await fs.promises.writeFile(`${__dirname}/${docName}.pdf`, pdfFile);
res.download(`${__dirname}/${docName}.pdf`)
It will works File.
Even If don't work then follow
below step:
Add this line 14 after instalDir
const installDir = tmp.dirSync({prefix: 'soffice', unsafeCleanup: true, ...tmpOptions});
const posixInstallDir = installDir.name.split(path.sep).join(path.posix.sep);
then Replace commant
let command = `${results.soffice} --headless --convert-to ${format}`;
That's it..
-env:UserInstallation needs to be in URI form.
Note: also that you using file:// this should be file:/// see File URI scheme
-env:UserInstallation=file:///C:/Users/thesa/AppData/Local/Temp/soffice-10416-bQefydwUfs2F
>>> from pathlib import Path
>>> def get_posix(mypath) -> str:
>>> p = Path(mypath)
>>> return p.as_posix()
>>> tmp = "C:\\Users\\thesa\\AppData\\Local\\Temp\\soffice-10416-bQefydwUfs2F"
>>> get_posix(tmp)
'C:/Users/thesa/AppData/Local/Temp/soffice-10416-bQefydwUfs2F'
or
>>> from pathlib import Path
>>> tmp = Path("C:\\Users\\thesa\\AppData\\Local\\Temp\\soffice-10416-bQefydwUfs2F")
>>> tmp.as_uri()
'file:///C:/Users/thesa/AppData/Local/Temp/soffice-10416-bQefydwUfs2F'

Save a file in a flask-wtf form to MongoDB's GridFS

I'm using the flask-user extension (https://flask-user.readthedocs.io/) along with the mongoengine adapter and flask-wtf to create an HTML form that'll accept several files (images, mp4). The goal is to directly store those files in MongoDB using GridFS but I can't get it to work without storing the image locally on the flask server first...
Here's my non-working code:
#bp.route('/video1', methods=['GET', 'POST'])
#login_required
def video1():
video1Form = Video1Form()
if request.method == 'POST' and video1Form.validate_on_submit():
newVideo1 = Video1(
slogan = video1Form.slogan.data,
objectif = video1Form.objectif.data,
stat1 = video1Form.stat1.data,
stat2 = video1Form.stat2.data
)
name = secure_filename(str(current_user.id) + "__" + "logo.png")
fh = open(video1Form.logo.data, 'rb')
newVideo1.logo.put(fh, filename=name, content_type = "image/jpeg")
newVideo1.save()
return redirect(url_for('video.download'))
if video1Form.errors:
flash(video1Form.errors, 'alert-danger')
return render_template('video/video1.html', video1Form=video1Form)
`
I get the following error on:
[...]File "/home/lucaspierru/Documents/IKADA/sos_sponsors/app/video/routes.py", line 35, in video1
fh = open(video1Form.logo.data, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'name_of_the_uploaded_file.ext'
Is it possible to point directly to the file's content and not just get the filename without saving it to the server first ?
I found my mistake:
I forgot to add the enctype="multipart/form-data" attribute to my HTML <form> tag and apparently it is needed to properly upload files, otherwise they'll be considered as text data.

Unable to deploy Googlecloud function despite adding trigger

I have the following cloud function which is trying to use sendgrid to send email when a new user signs up. This was a modified version of original firebase repo on how to send emails using nodemailer. This was working fine earlier with out sendgrid functionality. So, what you see below is a heavily modified version of the code.
'use strict';
const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
const SEND_GRID_API_KEY = functions.config().sengrid.key
const sgMail = require('#sengrid/mail');
sgMail.setApiKey(SEND_GRID_API_KEY);
// Your company name to include in the emails
// TODO: Change this to your app or company name to customize the email sent.
const APP_NAME = 'Asia Rubber';
// [START sendWelcomeEmail]
/**
* Sends a welcome email to new user.
*/
// [START onCreateTrigger]
exports.sendWelcomeEmail = functions.auth.user().onCreate((event) => {
// [END onCreateTrigger]
// [START eventAttributes]
const user = event.data; // The Firebase user.
const email = user.email; // The email of the user.
const displayName = user.displayName; // The display name of the user.
// [END eventAttributes]
return sendWelcomeEmail(email, displayName);
});
// [END sendWelcomeEmail]
// [END sendByeEmail]
// Sends a welcome email to the given user.
function sendWelcomeEmail(email, displayName) {
const msg = {
from: `${APP_NAME} <Welcome#rubber.asia>`,
to: email,
subject: 'Welcome to ${APP_NAME}!',
//custom templates
templateId: 'e3978a51-5343-4b3a-9128-8c4a493f265e'
};
return sgMail.send(msg)
.then( () => console.log('email sent'))
.catch(err => console.log(err))
}
when I am trying to deploy I am getting an error
PS E:\Cloudfunctions\erubberFunctions\functions> firebase deploy --only functions
=== Deploying to 'erubber'...
i deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint
> functions# lint E:\Cloudfunctions\erubberFunctions\functions
> eslint .
E:\Cloudfunctions\erubberFunctions\functions\index.js
79:14 warning Unexpected template string expression no-template-curly-in-string
✖ 1 problem (0 errors, 1 warning)
+ functions: Finished running predeploy script.
i functions: ensuring necessary APIs are enabled...
+ functions: all necessary APIs are enabled
i functions: preparing functions directory for uploading...
Error: Error occurred while parsing your function triggers.
TypeError: Cannot read property 'key' of undefined
at Object.<anonymous> (E:\Cloudfunctions\erubberFunctions\functions\index.js:5:53)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
at C:\Users\bhara\AppData\Roaming\npm\node_modules\firebase-tools\lib\triggerParser.js:18:11
at Object.<anonymous> (C:\Users\bhara\AppData\Roaming\npm\node_modules\firebase-tools\lib\triggerParser.js:38:3)
So, from my code the only key I have is sendgrid api key which I already added like this
firebase functions:config:set sendgrid.key=SG.YOUR_API_KEY
No quotes for the key btw.
What am I doing wrong?
Also in general is there anything wrong with the code in general? Tks
Your cloud function has a small typo. You're trying to access the property sengrid (Missing the d in send).
The correct line of code should be;
const SEND_GRID_API_KEY = functions.config().sendgrid.key

Adding a websocket "put" request in the bootstrap.js file in sails : cannot find io

I need to call a socket request from the bootstrap.js file in sails.
The bootstrap.js file has some code checking if some game engine has updated some file. If so, it needs send a message with some updated data via socket to some defined route called "/update"... e.g.
io.socket.put('/update', {history:{sessions:[1,2,3,4]}},function gotResponse(body, response) {
console.log('Server sending request ot server ');
})
The problem is that it tells me that io is not recognised.
I tried to do npm install for both sails.io.js and socket.io-client and then write:
var io = require('sails.io.js')( require('socket.io-client') );
at the top.
Unfortunately, it gives me the following error message:
C:\Users\Evolver\Documents\programming\pipegame\game6\node_modules\socket.io-client\lib\url.js:29
if (null == uri) uri = loc.protocol + '//' + loc.host;
^
TypeError: Cannot read property 'protocol' of undefined
at url (C:\Users\Evolver\Documents\programming\pipegame\game6\node_modules\socket.io-client\lib\url.js:29:29)
at lookup (C:\Users\Evolver\Documents\programming\pipegame\game6\node_modules\socket.io-client\lib\index.js:44:16)
at goAheadAndActuallyConnect (C:\Users\Evolver\Documents\programming\pipegame\game6\node_modules\sails.io.js\sails.io.js:835:21)
at selfInvoking (C:\Users\Evolver\Documents\programming\pipegame\game6\node_modules\sails.io.js\sails.io.js:812:18)
at SailsSocket.SailsIOClient.SailsSocket._connect (C:\Users\Evolver\Documents\programming\pipegame\game6\node_modules\sails.io.js\sails.io.js:831:9)
at null._onTimeout (C:\Users\Evolver\Documents\programming\pipegame\game6\node_modules\sails.io.js\sails.io.js:1463:17)
at Timer.listOnTimeout (timers.js:92:15)
Any idea ?
Ok.
It now works, once npm install has been done for socket.io-client and sails.io.js if I do exactly the following:
var socketIOClient = require('socket.io-client');
var sailsIOClient = require('sails.io.js');
// Instantiate the socket client (`io`)
var io = sailsIOClient(socketIOClient);
io.sails.url = 'http://localhost:1337';
// then I send something via my socket
io.socket.put('/update', {history:{sessions:[1,2,3,4]}},function gotResponse(body, response) {
console.log('Server sending request ot server ');
})