Can you use a string value as a page for a fixture? - testcafe

I would like to use string values as my Testcafe pages, is that possible?
fixture('My project')
.page('<body>Hello World</body>')
test('Something', (t) => {
// test code
})
I have tried using a clientScript({ content: 'document.write('Hello World') '}) But it either doesn't work or has issues with escaping quotes.
Can TestCafe do this?

The parameter of the "Fixture.page" method is intended for passing the URL of a tested web page. As a workaround, generate a temporary ".html" file for testing and pass the generated file's path to the "Fixture.Page" method via the "file://" scheme.

Related

How to access local webpage with parameters in vb?

I've scenario where i want open local web page (index.html) passing parameters in query which i can used in index.html but i'm having problem as it gives error as per below,
The system cannot find the file specified.
Vb.net Code
Dim url As String = ConfigurationManager.AppSettings("Url")
url = url & "?id=" & txtFilePath.Text
//Url example
"C:\Program Files\Products\Bella\index.html?id=232"
Process.Start(url)
i do not completely understand your question but i will try.
I do not know what the value of "Url" is, neither what the txtFilePath.text is supposed to be. but if you are trying to open a URL like
localhost/index.html?id=example
in a browser, you should use that as the first parameter.
Process.Start("IExplore.exe", url)
If you are trying to get the server to read the parameter you put into the URL, i do not know if you can make html-pages get parameters like that, maybe PHP or something else? But that should not make a difference at all for launching the browser and stuff, just a heads-up :)
But if you just want to open a static html file in a browser-window, you are, as far as i know, out of luck with passing parameters, but you SHOULD test for the existence of your file, so you are completely sure it exists in that path.
File.Exists(url)
EDIT:
Since your url is "C:\Program Files\Products\Bella\index.html?id=232" i do not believe you could pass parameters, i think it will try to find a file with the extension ".html?id=232", which obviously does not exist.
It seems there are two issues:
First:
I think the reason for the error is you need to have "file://" before the URL (as Mych mentioned in the comments) in order to access a local web page. Many browsers will automatically assume the URL should have "http://" unless you specify that it's a local file.
Depending on your browser it may add more forward slashes, but two should be sufficient to get Process.Start to recognize it.
So your URL should look like this:
"file://C:\Program Files\Products\Bella\index.html?id=232"
Second:
As far as passing a parameter to the URL the best way I have found (as jakobS suggested) you would have to use:
Process.Start("IExplore.exe", url)
'or
Process.Start("Chrome.exe", url)
or whichever browser you prefer.
So you could modify your code this way:
Dim url As String = ConfigurationManager.AppSettings("Url")
url = url & "?id=" & txtFilePath.Text
'Add "file://" to the beginning of the url.
url = "file://" & url
Process.Start("IExplore.exe", url)
That should get rid of your error and load the page with your parameters.
Hope it helps!

Highcharts numericSymbols when rendered server-side with Phantomjs

Is there a way to change the numericSymbols when rendering a Highchart on a server with Phantomjs?
I generate the JSON locally on the server and pass it to Phantomjs as a parameter along with the highcharts-convert.js script and my output file
My graphs are rendered to images fine but I need to in effect do the same server-side (or via JSON) that is done on a browser client by setting the global options with:
Highcharts.setOptions({
lang:{
numericSymbols: null
}
});
Is there a way of doing it with the callback maybe?
Or is there a JSON object that this can be done with?
This might help you:
http://forum.highcharts.com/highcharts-usage/setting-global-options-on-export-server-t28909/
It helped me to solve my decimalPoint problem.
If you are using the POST method, just follow the instructions in the link, if using the command line method (like me), just add globaloptions as a parameter:
phantomjs highcharts-convert.js -infile temp/test.js -outfile temp/chart.png -globaloptions temp/test2.js
And the content of temp/test2.js was in my case:
{
lang:{
decimalPoint:",",
thousandsSep:"."
}
};

Understanding JSON-RPC in Perl

I am trying to understand the concept of JSON RPC and it's Perl implementation. Though I can fin d a lot of examples for Python/Java, I find surprisingly little or no examples for it in Perl.
I am following this example but am not sure it is complete. The example I had in mind was to add 2 integers. Now I have a very basic HTML page set up, like so:
<html>
<body>
<input type="text" name="num1"><br>
<input type="text" name="num2"><br>
<button>Add</button>
</body>
</html>
Next, based on the example above, I have 3 files:
test1.pl
# Daemon version
use JSON::RPC::Server::Daemon;
# see documentation at:
# https://metacpan.org/pod/distribution/JSON-RPC/lib/JSON/RPC/Legacy.pm
my $server = JSON::RPC::Server::Daemon->new(LocalPort => 8080);
$server -> dispatch({'/test' => 'myApp'});
$server -> handle();
test2.pl
#!/usr/bin/perl
use JSON::RPC::Client;
my $client = new JSON::RPC::Client;
my $uri = 'http://localhost:8080/test';
my $obj = {
method => 'sum', # or 'MyApp.sum'
params => [10, 20],
};
my $res = $client->call( $uri, $obj );
if($res){
if ($res->is_error) {
print "Error : ", $res->error_message;
} else {
print $res->result;
}
} else {
print $client->status_line;
}
myApp.pl
package myApp;
#optionally, you can also
use base qw(JSON::RPC::Procedure); # for :Public and :Private attributes
sub sum : Public(a:num, b:num) {
my ($s, $obj) = #_;
return $obj->{a} + $obj->{b};
}
1;
While I understand what these files individually do, I am at a complete loss when it comes to combining them and making them work together.
My questions are as follows:
Does the button in the HTML page come inside a tag (like we would normally do in a CGI-based program)? If yes, what file does that call? If no, then how do I pass the values to be added?
What is the order of execution of the 3 Perl files? Which one calls which one? How is the flow of execution?
When I tried to run the perl files from the CLI, i.e using $./test2.pl, I got the following error: Error 301 Moved Permanently. What moved permanently? which file was it trying to access? I tried running the files from withing /var/www/html and /var/www/html/test.
Some help in understanding the nuances of this would really be appreciated. Thanks in advance
Does the button in the HTML page come inside a tag (like we would
*normally do in a CGI-based program)? If yes, what file does that call?*
If no, then how do I pass the values to be added?
HTML has nothing at all to do with JSON-RPC. While the RPC call is done via an HTTP POST request, if you're doing that from the browser, you'll need to use XMLHttpRequest (i.e: AJAX). Unlink an HTML form post the Content-encoding: header will need to be something specific to JSON-RPC (e.g: application/json or similar), and you'll need to encode your form data via JSON.stringify and correctly construct the JSON-RPC "envelope", including the id, jsonrpc, method and params properties.
Rather than doing this by hand you might use a purpose-build JSON-RPC JavaScript client like the jQuery-JSONRP plugin (there are many others) -- although the protocol is so simple that implementations usually are less than 20 lines of code.
From the jQuery-RPC documentation, you'd set up the connection like this:
$.jsonRPC.setup({
endPoint: '/ENDPOINT-ROUTE-GOES-HERE'
});
and you'd call the server-side method like this:
$.jsonRPC.request('sum', {
params: [YOURNUMBERINPUTELEMENT1.value, YOURNUMBERINPUT2.value],
success: function(result) {
/* Do something with the result here */
},
error: function(result) {
/* Result is an RPC 2.0 compatible response object */
}
});
What is the order of execution of the 3 Perl files? Which one calls
*which one? How is the flow of execution?*
You'll likely only need test2.pl for testing. It's an example implementation of a JSON-RPC client. You likely want your client to run in your web-browser (as described above). The client JavaScript will make an HTTP POST request to wherever test1.pl is serving content. (e.g: http://localhost:8080).
Or, if you want to keep your code as HTML<-->CGI, then you'll need to make JSON-RPC client calls from within your Perl CGI server-side code (which seems silly if it's on the same machine).
When test1.pl calls dispatch, the MyApp module will be loaded.
Then, when test1.pl calls handle, the sum function in the MyApp package will be called.
The JSON::RPC::Server module takes care of marshalling from JSON-RPC to perl datastructures and back again around the call to handle. die()ing in sum should result in a JSON-RPC exception being transmitted to the calling client, rather than death of the test1.pl script.
When I tried to run the perl files from the CLI, i.e using
*$./test2.pl, I got the following error: Error 301 Moved Permanently.*
What moved permanently? which file was it trying to access? I tried
*running the files from withing /var/www/html and /var/www/html/test.*
This largely depends the configuration of your machine. There's nothing obvious (in your code) to suggest that a 301 Moved Permanently would be issued in response to a valid JSON-RPC request.

Importing local json file using d3.json does not work

I try to import a local .json-file using d3.json().
The file filename.json is stored in the same folder as my html file.
Yet the (json)-parameter is null.
d3.json("filename.json", function(json) {
root = json;
root.x0 = h / 2;
root.y0 = 0;});
. . .
}
My code is basically the same as in this d3.js example
If you're running in a browser, you cannot load local files.
But it's fairly easy to run a dev server, on the commandline, simply cd into the directory with your files, then:
python -m SimpleHTTPServer
(or python -m http.server using python 3)
Now in your browser, go to localhost:3000 (or :8000 or whatever is shown on the commandline).
The following used to work in older versions of d3:
var json = {"my": "json"};
d3.json(json, function(json) {
root = json;
root.x0 = h / 2;
root.y0 = 0;
});
In version d3.v5, you should do it as
d3.json("file.json").then(function(data){ console.log(data)});
Similarly, with csv and other file formats.
You can find more details at https://github.com/d3/d3/blob/master/CHANGES.md
Adding to the previous answers it's simpler to use an HTTP server provided by most Linux/ Mac machines (just by having python installed).
Run the following command in the root of your project
python -m SimpleHTTPServer
Then instead of accessing file://.....index.html open your browser on http://localhost:8080 or the port provided by running the server. This way will make the browser fetch all the files in your project without being blocked.
http://bl.ocks.org/eyaler/10586116
Refer to this code, this is reading from a file and creating a graph.
I also had the same problem, but later I figured out that the problem was in the json file I was using(an extra comma). If you are getting null here try printing the error you are getting, like this may be.
d3.json("filename.json", function(error, graph) {
alert(error)
})
This is working in firefox, in chrome somehow its not printing the error.
Loading a local csv or json file with (d3)js is not safe to do. They prevent you from doing it. There are some solutions to get it working though. The following line basically does not work (csv or json) because it is a local import:
d3.csv("path_to_your_csv", function(data) {console.log(data) });
Solution 1:
Disable the security in your browser
Different browsers have different security setting that you can disable. This solution can work and you can load your files. Disabling is however not advisable. It will make you vulnerable for all kind of threads. On the other hand, who is going to use your software if you tell them to manually disable the security?
Disable the security in Chrome:
--disable-web-security
--allow-file-access-from-files
Solution 2:
Load your csv/json file from a website.
This may seem like a weird solution but it will work. It is an easy fix but can be unpractical though. See here for an example. Check out the page-source. This is the idea:
d3.csv("https://path_to_your_csv", function(data) {console.log(data) });
Solution 3:
Start you own browser, with e.g. Python.
Such a browser does not include all kind of security checks. This may be a solution when you experiment with your code on your own machine. In many cases, this may not be the solution when you have users. This example will serve HTTP on port 8888 unless it is already taken:
python -m http.server 8888
python -m SimpleHTTPServer 8888 &
Open the (Chrome) browser address bar and type the underneath. This will open the index.html. In case you have a different name, type the path to that local HTML page.
localhost:8888
Solution 4:
Use local-host and CORS
You may can use local-host and CORS but the approach is not user-friendly coz setting up this, may not be so straightforward.
Solution 5:
Embed your data in the HTML file
I like this solution the most. Instead of loading your csv, you can write a script that embeds your data directly in the html. This will allow users use their favorite browser, and there are no security issues. This solution may not be so elegant because your html file can grow very hard depending on your data but it will work though. See here for an example. Check out the page-source.
Remove this line:
d3.csv("path_to_your_csv", function(data) { })
Replace with this:
var data =
[
$DATA_COMES_HERE$
]
You can't readily read local files, at least not in Chrome, and possibly not in other browsers either.
The simplest workaround is to simply include your JSON data in your script file and then simply get rid of your d3.json call and keep the code in the callback you pass to it.
Your code would then look like this:
json = { ... };
root = json;
root.x0 = h / 2;
root.y0 = 0;
...
I have used this
d3.json("graph.json", function(error, xyz) {
if (error) throw error;
// the rest of my d3 graph code here
}
so you can refer to your json file by using the variable xyz and graph is the name of my local json file
Use resource as local variable
var filename = {x0:0,y0:0};
//you can change different name for the function than json
d3.json = (x,cb)=>cb.call(null,x);
d3.json(filename, function(json) {
root = json;
root.x0 = h / 2;
root.y0 = 0;});
//...
}

Is there any way to get command line parameters in Google Chrome extension?

I need to launch Chrome from command line with custom parameter, which
contains path to some js-file. Further this path will be used in
extension.
I browsed carefully all related documentation and clicked all nodes in
Chrome debugger, but found nothing which can resemble on command line
parameters. Is it possible anyway to get these parameters or it's need
to write more complex npapi-extension? (theoretically in such npapi-
extension we able to get self process through win-api, command line of
self process and so on).
Hack alert: this post suggests passing a fake URL to open that has all the command-line parameters as query string parameters, e.g.,
chrome.exe http://fakeurl.com/?param1=val1&param2=val2
Perhaps pass the path to your extension in a custom user agent string set via the command line. For example:
chrome.exe --user-agent='Chrome 43. My path is:/path/to/file'
Then, in your extension:
var path = navigator.userAgent.split(":");
console.log(path[1])
Basically I use the technique given in #dfrankow's answer, but I open 127.0.0.1:0 instead of a fake URL. This approach has two advantages:
The name resolution attempt is skipped. OK, if I've chosen the fake URL carefully to avoid opening an existing URL, the name resolution would fail for sure. But there is no need for it, so why not just skip this step?
No server listens on TCP port 0. Using simply 127.0.0.1 is not enough, since it is possible that a web server runs on the client machine, and I don't want the extension to connect to it accidentally. So I have to specify a port number, but which one? Port 0 is the perfect choice: according to RFC 1700, this port number is "reserved", that is, servers are not allowed to use it.
Example command line to pass arguments abc and xyz to your extension:
chrome "http://127.0.0.1:0/?abc=42&xyz=hello"
You can read these arguments in background.js this way:
chrome.windows.onCreated.addListener(function (window) {
chrome.tabs.query({}, function (tabs) {
var args = { abc: null, xyz: null }, argName, regExp, match;
for (argName in args) {
regExp = new RegExp(argName + "=([^\&]+)")
match = regExp.exec(tabs[0].url);
if (!match) return;
args[argName] = match[1];
}
console.log(JSON.stringify(args));
});
});
Console output (in the console of the background page of the extension):
{"abc":"42","xyz":"hello"}
You could try:
var versionPage = "chrome://version/strings.js";
$.post(versionPage, function(data){
data = data.replace("var templateData = ", "");
data = data.slice(0, -1);
var jsonOb = $.parseJSON(data);
alert(jsonOb.command_line);
});
This assumes you are using jQuery in your loading sequence, you could always substitute with any other AJAX method
Further to the answers above about using the URL to pass parameters in, note that only Extensions, not Apps, can do this. I've published a Chrome Extension that just intercepts the URL and makes it available to another App.
https://chrome.google.com/webstore/detail/gafgnggdglmjplpklcfhcgfaeehecepg/
The source code is available at:
https://github.com/appazur/kiosk-launcher
for Wi-Fi Public Display Screens