casperjs unable to download CSV from APEX application - casperjs

I'm trying to automate download CSV file from APEX application.
var casper = require('casper').create({verbose: true, logLevel: "debug", viewportSize: { width: 1600, height: 400 } });
var url = "https://example.com"
casper.start(url);
casper.then(function () {
this.fill('#wwvFlowForm', {'P101_USERNAME': 'user', 'P101_PASSWORD': 'password'}, false);
});
casper.then(function () {
this.click('#P101_LOGIN');
}).wait(5000).then(function () {
this.echo('downloading file');
this.download('https://example/apex/f?p=1002:173:10072525691961:CSV','report.csv')
});
casper.run();
I am able to login, but when i try to download file i am getting login page html.
I have tried using getBase64 method with same result. Does casper.download using different session?
Screenshots before and after download shows that i am logged in.

Issue was that this apex app is using instance_id in url so working code is:
var casper = require('casper').create({verbose: true, logLevel: "debug",
viewportSize: { width: 1600, height: 400 } });
var url = "https://example.com"
casper.start(url);
casper.then(function () {
this.fill('#wwvFlowForm', {'P101_USERNAME': 'user', 'P101_PASSWORD': 'password'}, false);
});
casper.then(function () {
this.click('#P101_LOGIN');
}).wait(5000).then(function () {
this.echo('downloading file');
var instance_id = this.getCurrentUrl().split(':')[3];
var download_url = url + '/apex/f?p=1002:173:' + instance_id;
this.download('download_url' + ':CSV','report.csv')
});
casper.run();

Related

Error when try open connection with indexedDB in Cypress

I make request to server for login, and then before redirect user to home page I try to
open indexedDB connection in order to see this page, bacause home page go to the indexedDB
and get some data. So below is my code and photo of error
beforeEach(() => {
cy.request({
method: 'POST',
url :'http://localhost:3000/api/auth/login',
body : {
email: "email",
password: "password"
}
}).then(function(response) {
window.indexedDB.open("testDB");
localforage.config({
driver: [localforage.INDEXEDDB],
name: 'testDB',
storeName: 'testDB',
version: '1.0',
});
localforage.clear().then(() => {
localforage.setItem('jobs', [{name: 'fdf'}]);
});
}).then(()=>{
cy.visit('http://localhost:3000/');
})
})
I also try this way but it doesnt works too, what I do wrong?
function open() {
var request = window.indexedDB.open("testDB", 1);
request.onerror = function(event) {
};
request.onsuccess = function(event) {
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("jobs", { keyPath: "name" });
objectStore.createIndex("name", "name", { unique: false });
objectStore.add({name: 'fsdf'});
}
}
describe('The Login Page', () => {
beforeEach(() => {
open()
cy.request({
method: 'POST',
url :'http://localhost:3000/api/auth/login',
body : {
email: "gfdgfdg",
password: "gdfgfdg"
}
})
.then(function(response) {
})
.then(()=>{
cy.visit('http://localhost:3000/');
})
})
One thing that is (probably) incorrect is the window reference.
Cypress runs the browser window as an automation "shell", which is what you get when you use
window.indexedDB.open("testDB")
but the app window is inside an iframe.
You can access either with
cy.window().then(win => win.indexedDB.open("testDB"))
or
cy.state('window').indexedDB.open("testDB") // undocumented!

How to get file from Image in NativeScript and upload it to server

I have an component that displays and image either taken by camera or selected from gallery. The point is when a user clicks the upload button i should send that Image to my server, but i am having difficulties extracting the file from the Image component.
<Image ref="profileImage" borderRadius="100" width="150" height="150" marginTop="20" stretch="aspectFill" :src="profileImage" />
And i have two functions for picking an image or capturing one
capture: function() {
var isAvailable = camera.isAvailable();
if (isAvailable) {
var options = {
width: 300,
height: 300,
keepAspectRatio: false,
saveToGallery: false,
cameraFacing: 'front'
};
var self = this;
var imageModule = require("tns-core-modules/ui/image");
camera.requestPermissions().then(
function success() {
camera.takePicture(options)
.then(function(imageAsset) {
self.profileImage = imageAsset;
}).catch(function(err) {
console.log("Error -> " + err.message);
});
},
function failure() {
// permission request rejected
}
);
}
},
pick() {
var self = this;
let context = imagepicker.create({
mode: 'single',
mediaType: 'image'
});
context.authorize()
.then(function() {
return context.present();
})
.then(selection => {
selection.forEach(selected => {
self.profileImage = selected;
});
}).catch(function(e) {
console.log('error in selectPicture', e);
});
},
What i need to do next is get the uploaded image and send it to server but i can't seem to find an options for that, i have the src of the and that's it in this case...
You can simply get ImageSource from ImageAsset and write it as file in data or temp directory, then upload it to server.
const imageSourceModule = require("tns-core-modules/image-source");
const fileSystemModule = require("tns-core-modules/file-system");
function uploadAsset(asset) {
imageSourceModule.fromAsset(asset)
.then(function(imageSource) {
var folderDest = fileSystemModule.knownFolders.documents();
var pathDest = fileSystemModule.path.join(folderDest.path, "test.png");
var saved = imageSource.saveToFile(pathDest, "png");
if (saved) {
console.log("Image saved successfully!");
// Now file is written at path `pathDest`
}
}).catch(function(err) {
console.log(err);
});
}
....
uploadAsset(profileImage);
Learn more at docs

How can I use NativeScript 3 to capture image and send to a remote server

I'm new to NativeScript and I'm trying to capture an image with the camera module (this works fine), and convert it to base64 (this is not working) and POST to server.
I've googled for days. Any help you can lend would be immensely appreciated.
I've tried this about 16 billion different ways and this is my current code:
viewModel.takePicture1 = function() {
camera.requestPermissions();
var isAvailable = camera.isAvailable();
console.log(isAvailable);
var options = { width: 640, keepAspectRatio: true, saveToGallery: false };
camera.takePicture().then(function (img) {
try{
var imageData = img.toBase64String("jpeg"); // fails here
console.log(imageData);
}catch(err){
console.log("Error: "+err);
}
http.request({
url: "http://[server address]/lab/ns_exp/upload_test.php",
method: "POST",
headers: { "Content-Type": "application/base64" },
content: imageData
}).then(function() {
console.log("Upload successful");
}).catch(function(e) {
console.log("Unsuccessful upload", e);
});
});
}//
Oh, I do want to make clear that I'm not using angular (obviously), so please don't provide an answer that does so. : ) (Vuejs Holdout)
The key here is that base64 needs to know that the image is a JPEG, and what quality the image should be. The code should look like this:
camera.takePicture(cameraOptions)
.then(imageAsset => {
imageSource.fromAsset(imageAsset).then(res => {
myImageSource = res;
var base64 = myImageSource.toBase64String("jpeg", 100);
Just in case someone finds this later and wonders about putting the image (UI) and/or the image (base64) into an observableArray, here is my complete function:
viewModel.takePhoto = function(){
var self = this;
camera.requestPermissions();
var cameraOptions = { width: 640, keepAspectRatio: true, saveToGallery: false };
camera.takePicture(cameraOptions)
.then(imageAsset => {
imageSource.fromAsset(imageAsset).then(res => {
myImageSource = res;
var base64 = myImageSource.toBase64String("jpeg", 100);
self.photoData.push({"data": base64});
var image = new imageModule.Image();
image.src = imageAsset;
self.photoUI.push({"src": image.src});
listView.refresh();
})
}).catch(function (err) {
console.log("Error -> " + err.message);
});
}

CasperJS: clicking checkbox not triggering events as it does in browser

I am trying to automate a process in CasperJS. However, I am facing some discrepancy between the behavior on a real browser vs the same in CasperJS.
Update: Process works fine with slimerJS but gives issue with headless
Here is my script:
var casper = require('casper').create({
"waitTimeout": 10000
});
var inputElements = {
"url": "http://www.jabong.com/incult-Tapered-Jeans-In-Indigo-1032119.html?pos=4",
"size": "34",
"address": {
"email": "someemail#xyz.com"
}
}
casper.options.viewportSize = {width: 1679, height: 902};
casper.start(inputElements.url, function (){
this.wait(10000, function (){
console.log("loaded");
})
});
var x = require('casper').selectXPath;
var sizeToSelect = inputElements.size;
// select size
casper.thenClick(x("//*[contains(#class,'size-desktop')]//"+
"li[contains(#class,'first') and contains(#class,'popover-options')]//"+
"span[contains(text(),'"+sizeToSelect+"')]/"+
".."));
// add to bag
casper.thenClick(x("//*[#id='add-to-cart']"));
// view cart
casper.thenClick(x("//*[#id='header-bag-sec']/a"))
// take a screenshot
casper.then(function() {
console.log("saving screenshot");
this.capture('../../1_view_cart.png');
});
casper.then(function() {
console.log('clicked ok, new location is ' + this.getCurrentUrl());
});
// place order
casper.then(function (){
this.click("[href='https://www.jabong.com/checkout/']");
})
// take a screenshot
casper.then(function() {
console.log("saving screenshot");
this.capture('../../2_address_details.png');
});
casper.then(function (){
this.sendKeys("#login-email", inputElements.address.email);
})
casper.then(function (){
this.click("#do-guest-checkout");
});
// take a screenshot
casper.then(function() {
console.log("saving screenshot");
this.capture('../../3_guest_checkout.png');
});
casper.waitFor(function check() {
return this.evaluate(function() {
return document.querySelector('#btn-login-checkout').textContent == "Continue as Guest";
});
}, function then() {
this.click('#btn-login-checkout');
});
casper.run();
On the last page, clicking on checkbox "Checkout as Guest" on a browser removes the password input field and changes the text of the Login button to "Continue as Guest". Attached screenshot:
However, in CasperJS, the password input field and the Login button are not changing. Any idea what am I doing wrong ?

Unit-testing remote methods of a strongloop loopback.io model

I am trying to write unittests for a loopback model using jasmine. My model has the usual CRUD endpoints but I have defined a custom '/products/:id/upload' endpoint which expects a form with files.
My model looks like
'use strict';
var loopback = require('loopback');
var ProductSchema = {
location: {
type: String,
required: true
},
version: {
type: String,
required: true
},
id: { type: Number, id: 1, generated: true }
};
var opts = {
strict: true
};
var dataSource = loopback.createDataSource({
connector: loopback.Memory
});
var Product = dataSource.createModel('Product', ProductSchema, opts);
Product.beforeRemote('upload', function(ctx){
var uploader = function(req, res){
// parse a multipart form
res({
result:'success'
});
};
function createProduct(uploaderResult){
// create a product out of the uploaded file
ctx.res.send({
result: uploaderResult.result
});
}
uploader.upload(ctx.req, createProduct);
});
Product.upload = function () {
// empty function - all the logic takes place inside before remote
};
loopback.remoteMethod(
Product.upload,
{
accepts : [{arg: 'uploadedFiles', http: function(ctx){
return function() {
return { files : ctx.req.body.uploadedFiles, context : ctx };
};
}},
{arg: 'id', type: 'string'}],
returns : {arg: 'upload_result', type: String},
http: {path:'/:id/upload', verb: 'post'}
}
);
module.exports = Product;
My end goal is to test the logic of the "createProduct".
My test looks like
'use strict';
describe('Product Model', function(){
var app = require('../../app');
var loopback = require('loopback');
var ProductModel;
beforeEach(function(){
app = loopback();
app.boot(__dirname+'/../../'); // contains a 'models' folder
ProductModel = loopback.getModel('Product');
var dataSource = loopback.createDataSource({
connector: loopback.Memory
});
ProductModel.attachTo(dataSource);
});
it('should load file ', function(){
console.log(ProductModel.beforeRemote.toString());
console.log(ProductModel);
ProductModel.upload();
});
});
By calling ProductModel.upload(); I was hoping to trigger the before remote hook which would exercise the the createProduct. I could test "createProduct" in isolation but then I would omit the fact that createProduct ends up being called as a result of upload.
To be perfectly clear, the core question is:
How do I exercise remote method hooks inside unittests ?
It was suggested to use supertest as an http server. Below there is a code snippet illustrating how to do it in jasmine
describe('My product suite', function(){
var request = require('supertest');
var app;
beforeEach(function(){
app = loopback();
// don't forget to add REST to the app
app.use(app.rest());
});
it('should load file', function() {
request(app).post('/products/id-of-existing-product/upload')
.attach('file', 'path/to/local/file/to/upload.png')
.expect(200)
.end(function(err, res) {
if (err) return done(err);
// res is the HTTP response
// you can assert on res.body, etc.
});
});
});

Resources