How casperjs passing arguments with space? - casperjs

casperjs script.js "myurl" "myemail" "my name"
Here is the script:
url = (casper.cli.get(0));
email = (casper.cli.get(1));
name = (casper.cli.get(2));
this.echo(name);
console.log(name);
The result is: my (and not my name).
I also tried with single quotes.

You can just escape the spaces with a backslash and DON'T use quotes, for example:
casperjs test.js myurl myemail my\ name
I don't know for sure if it is dependend to the console you are using, under ubuntu (docker) that worked for me:
var casper = require('casper').create();
var targetUrl = 'http://www.test.com/';
casper.start(targetUrl, function() {
url = (casper.cli.get(0));
email = (casper.cli.get(1));
name = (casper.cli.get(2));
this.echo(url);
this.echo(email);
this.echo(name);
console.log(name);
});
casper.run();
Result was:
myurl
myemail
my name
my name
For a windows command line that worked:
casperjs test.js myurl myemail \"my name\"

Related

URLS Redirects with Cypress automation

I passed 100+ URLs path(legacy) in the scenario outlines and i want to hit each one of them and to redirect to a new path(new).
I passed a code like below;
function createNewUrlFromLegacy(legacyPageUrl) {
const urlPath = legacyPageUrl.split('/');
let newUrl;
if (urlPath.length == 7) {
newUrl = 'new-homes/' + urlPath[5];
} else {
newUrl = 'new-homes/' + urlPath[0];
}
return newUrl
}
I passed this following in my stepDef file
const expectedUrl = createNewUrlFromLegacy(legacyUrl);
cy.url().should('include', expectedUrl);
And it run successfully.
But i want to use response code 301 as an assertion instead relying on expectedUrl only.
How can i do this pls?.
I have managed to get it working using the following steps;
First visit the legacy url and then set followRedirects: false using alias.
cy.visit(legacyUrl);
cy.request({url: legacyUrl, followRedirect: false}).as('response');`
cy.get('#response').its('status').should('eq', 301); --> Assert Response code is 301
cy.get('#response').its('redirectedToUrl').should('contain', expectedUrl); -->Assert expected URL is displayed.

How to create file of user selected image

I am developing cross platform app with nativescript, I get a problem with getting user selected image from gallery, the library I used return user selected image path. It is very easy in android, it is my code for create File for user selected image that I used in android.
String File_Path = "/storage/emulated/0/Pictures/Screenshots/Screenshot_20171016-173404.png"
File file = new File(File_Path);
The reason I need to create File of user selected image is I will need to send user selected image as a File in Multipar/FormData.
I tried many ways can't find soluction. Any suggestion greatly appreciated.
Thanks
It is my sample code for formdata
The answer above works, however another option would be to convert the selected image to a Base64String and treat it as any other string.
To do that just create a new ImageSource from file path and than simply use the toBase64String method provided.
Simlpy pass the format (jpg, png etc) and you're all set
Use nativescript background http, pass the path to this function
viewModel.uploadImage = function (imageUrl) {
var token = applicationSettings.getString("accessToken");
var form = new FormData();
form.append("file", imageUrl);
var bghttp = require("nativescript-background-http");
var session = bghttp.session("image-upload");
var request = {
url: <url>,
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
"File-Name": "somename",
"Authorization": token
},
description: "image for something"
};
var params = [
{ name: "somename", value: "value" },
{ name: "fileToUpload", filename: imageUrl, mimeType: 'image/jpeg' }
];
let task = session.multipartUpload(params, request);
return task;
}

gulp-connect and gulp-open file not load through the server

I'am trying to run a web server and open an HTML file via gulp-connect and gulp-open.
The server is running, the html is opened correctly but not through the server but as a file from the HDD.
On the URL address bar I can see: "file:///Users/...." instead of "http://localhost:9000/"
Does anyone know what could be the issue ?
Thanks for your help
"use strict";
var gulp = require('gulp');
var gulpConnect = require('gulp-connect'); // run a local dev server
var gulpOpen = require('gulp-open'); // open a URL in the browser
var config ={
port:'9000',
baseDevUrl:'http://localhost',
paths: {
html: './src/*.html',
dist:'./dist'
}
};
// start a local development server
gulp.task('connect',function(){
gulpConnect.server({
root:['dist'],
port: config.port,
base: config.baseDevUrl,
livereload:true
});
});
gulp.task('open',['connect'],function(){
gulp.src('dist/index.html')
.pipe(gulpOpen('',{ url: config.baseDevUrl +':'+ config.port +'/', app:'google chrome'}));
});
gulp.task('html',function(){
gulp.src(config.paths.html)
.pipe(gulp.dest(config.paths.dist))
.pipe(gulpConnect.reload());
});
gulp.task('watch',function(){
gulp.watch(config.paths.html,['html']);
});
gulp.task('default',['html','open','watch']);
OK here is how you open things:
gulp.src('./index.html').pipe(gulpOpen({uri: 'http://localhost:8888', app: 'Google Chrome'}));
You've got an extra first parameter in gulpOpen and url should be uri
Good luck!

How to get Casper JS to return an exit code that indicates test success status?

I want to be able to have a set of Casper JS tests and get an exit code back of 0 on success and non-zero on error or test failure (I want to run the casper command from java and determine if a test passed).
The problem I am having is that an exit code of 0 is always returned. Here is an example test where this happens:
var casper = require('casper').create();
casper.start('http://www.google.com', function() {
this.test.assertEquals(true, casper.cli.options['value']);
});
casper.run(function() {
casper.test.done(1);
});
All of the following commands result in an exit code of 0:
C:/casperjs/bin/casperjs test --value=true C:/Temp/simpletest.js
C:/casperjs/bin/casperjs test --value=false C:/Temp/simpletest.js
C:/casperjs/bin/casperjs --value=true C:/Temp/simpletest.js
C:/casperjs/bin/casperjs --value=false C:/Temp/simpletest.js
How can I invoke Casper and determine whether the tests succeeded or failed/errored from Java?
First, you cannot overwrite the casper instance in test mode, see http://docs.casperjs.org/en/latest/testing.html#test-command-args-and-options
Remove
var casper = require('casper').create();
from your code.
Then try
casper.start('http://www.google.com', function(test) {
test.assertEquals(true, casper.cli.options['value']);
});
Start casperjs with
--fail-fast
so that each test will exit with code 1.
Then in Java
String[] args = {"/bin/sh", "-c", "casperjs test --fail-fast simpletest.js"};
Process proc = Runtime.getRuntime().exec(args);
logger.log(Level.INFO, IOUtils.toString(proc.getInputStream()));
String warnings = IOUtils.toString(proc.getErrorStream());
if (StringUtils.isNotBlank(warnings)) {
logger.log(Level.WARNING, warnings);
}
int exitValue = proc.exitValue();
assertEquals(0, exitValue);
Of course you need to change the paths to suit your environment.
Hope that helps!
The problem I am having is that an exit code of 0 is always returned.
Your casper test should be like that:
var casper = require('casper').create();
var system = require('system');
var param;
casper.start('http://www.google.com', function() {
//get parameter from command line
system.args.forEach(function (arg, i) {
if(arg.search(/--value=/i) != -1){
param = arg.replace(/--value=/g, "");
}
});
this.test.assertEquals(true, Boolean(param));
});
casper.run(function() {
this.test.done(1);
this.test.renderResults(true);
});
To run:
casperjs simpletest.js --value=true
How can I invoke Casper and determine whether the tests succeeded or failed/errored from Java?
You should look this answer:
CasperJS passing data back to PHP
Return the Predefined code for failure (for eg for us we gave 99 (random))
//Capture all fails
casper.test.on("fail", function () {
casper.exit(99);
});
Similarly you can define different code for other issues at high level
eg: to get the retry logic in place we can use onWaitTimeout codes
casper.options.onWaitTimeout = function () {
casper.screenCapture('POETerror', true);
this.exit(98);
};

Get current URL from within a Firefox Addon panel

So I've collected 5 different methods to do this, none of which work from within a panel. Firefox is stunningly effective at blocking access to a basic task.
Here's what I've tried:
Attempt 1:
var url = window.top.getBrowser().selectedBrowser.contentWindow.location.href;
Error: window.top.getBrowser is not a function
Attempt 2:
var url = window.content.document.location;
Error: Permission denied to access property 'document'
Attempt 3:
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
var url = mainWindow.getBrowser().selectedBrowser.contentWindow.location.href;
Error: Permission denied to create wrapper for object of class UnnamedClass
Attempt 4:
var url = window.content.location.href;
Error: Permission denied to access property 'href'
Attempt 5:
var currentWindow = Components.classes["#mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser");
var currBrowser = currentWindow.getBrowser();
var url = currBrowser.currentURI.spec;
Error: Permission denied to get property XPCComponents.classes
Coding this for Chrome was a breeze. Not sure why this is so tough for FF.
Anyone got a solution?
I think you can use firefox local object:
var url = gBrowser.contentDocument.location;
I guess "Firefox Addon panel" refers to the Addon SDK's panel module?
If so you're probably trying to use those snippets in a content script. Instead you have to send an event to the main addon's code (example), and in the main addon's code use the tabs module:
require("tabs").activeTab.url
[update] complete testcase, which works for me:
// http://stackoverflow.com/questions/7856282/get-current-url-from-within-a-firefox-addon-panel
exports.main = function() {
var panel = require("panel").Panel({
contentURL: "data:text/html,<input type=button value='click me' id='b'>",
contentScript: "document.getElementById('b').onclick = " +
"function() {" +
" self.port.emit('myEvent');" +
"}"
});
panel.port.on("myEvent", function() {
console.log(require("tabs").activeTab.url)
})
require("widget").Widget({
id: "my-panel",
contentURL: "http://www.google.com/favicon.ico",
label: "Test Widget",
panel: panel
});
};

Resources