how to run a polymer app via "Run in Dartium" from console? - dart

I want to call a polymer webapp directly via command line or via 'Process' in a dart file.
I know when running it via the dart editor, a server on port 8080 is created and listening to requests for the /web folder.
but when launching
dartium/chrome.exe path/To/Index.html
from console its simply loading the files inside the browser but wont start a server for the client.
via
file:://path/to/file.html [no 'dart is not runnning' warning, but no polymer content]
or
127.x.x.x.x.x.x.x.x:xxxxxxxx/app/index.html will obviously tell me
'This webpage is not available'

DartEditor lauches pub serve. You can do this manually without Darteditor (since Dart 1.5 AFAIK). Just launch
pub serve
from within your Polymer app package directory.
Inside your console app launch the browser with the URL that loads the page from this server.
You could also include web server functionality into your console application that serves the Polymer app to your browser.
pub help serve
lists the available options.

You can try this script as an example how to call a polymer webapp directly via 'Process' in a dart file.
This example also includes launch of default browser.
import "dart:async";
import "dart:io";
import "package:path/path.dart" as pathos;
void main(List<String> args) {
String app;
String file;
switch (args.length) {
case 1:
app = args[0];
break;
case 2:
app = args[0];
file = args[1];
break;
default:
print("Usage: pubserve.dart app_path [file_name]");
exit(0);
}
if(!new Directory(app).existsSync()) {
print("Directory not exists: $app");
exit(-1);
}
pubServe(app, file).then((exitCode) {
exit(exitCode);
});
}
Future<int> pubServe(String app, String file) {
var sdk = Platform.environment["DART_SDK"];
if (sdk == null) {
print("Dart SDK not found");
return new Future(() => -1);
}
var executable = pathos.join(sdk, "bin", "pub");
var pattern = r"^Serving (?:.*) web on (.*)$";
var regexp = new RegExp(pattern);
return Process.start(executable, ["serve"], runInShell: true,
workingDirectory: app).then((process) {
process.stdout.listen((data) {
var string = new String.fromCharCodes(data);
for (var c in data) {
stdout.writeCharCode(c);
}
var match = regexp.matchAsPrefix(string);
if (match != null) {
var url = match.group(1);
if (file != null) {
url += "/$file";
}
Timer.run(() => runBrowser(url));
}
});
process.stderr.pipe(stderr);
stdin.pipe(process.stdin);
return process.exitCode.then((exitCode) {
return exitCode;
});
});
}
void runBrowser(String url) {
var fail = false;
switch (Platform.operatingSystem) {
case "linux":
Process.run("x-www-browser", [url]);
break;
case "macos":
Process.run("open", [url]);
break;
case "windows":
Process.run("explorer", [url]);
break;
default:
fail = true;
break;
}
if (!fail) {
//print("Start browsing...");
}
}
P.S.
NOTE:
If you run this script from Dart Editor, Editor will never stops execution of subprocess (pub serve in our case) when you stop current script in Dart Editor.
This is not related only to this script. Editor always keep subprocesses alive.
If you run it from cmd-line it terminates pub serve correctly.

Related

How to get the arguments for opening file with electron app

Perhaps I'm being stupid but I can't seem to find any documentation on how to get the startup arguments for an electron app. My scenario is something like this:
Right-click file in Windows Explorer
Open with -> My electron app
Electron app opens and can work with the file
I can get the electron app to open, but how do I work with the file that was right-clicked?
Assuming that you have the "Open with" portion working, Windows will pass the filename as a command line argument. So just get the file name/path from process.argv
if(process.argv.length >= 2) {
let filePath = process.argv[1];
//open, read, handle file
}
try {
var electron = require('electron');
var app = electron.remote;
if (app.process.platform == 'win32' && app.process.argv.length >= 2) {
var openFilePath = app.process.argv[1];
if (openFilePath !== "") {
console.log(openFilePath);
}
}
} catch (e) {
}

Appium ios automation nodejs scripts

I am trying to automate an iOS native app on a real device using Appium(from terminal) and nodejs script. I am able to install and launch the app till the first screen of the app but after that no nodejs scripts other than sleep is getting executed. I need to type in some text in the the textfields present in the screen but the cursor is getting pointed and nothing happens after that. Please tell me whether I am using the correct nodejs commands here.
NB:The same nodejs script was working fine for android automation
var wd = require("wd");
require('colors');
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
var capture = require("capture");
chai.use(chaiAsPromised);
chai.should();
chaiAsPromised.transferPromiseness = wd.transferPromiseness;
var host, port, username, accessKey, desired;
console.log("Print 1");
var desired = {
'browserName': '',
'automationName': 'Appium',
'platformName': 'iOS',
'platformVersion': '6.1.4',
'deviceType':'iPhone',
'deviceName' :'xxx’s iPhone',
// 'nativeInstrumentsLib' : 'true',
'app': "/Users/Desktop/xxx_my_appname-358.ipa",
'bundleId': 'com.xxx.myapp',
'deviceOrientation': 'portrait'
};
host = "localhost";
port = 4723;
// Instantiate a new browser session
var browser = wd.promiseChainRemote(host, port, username, accessKey);
// See whats going on
browser.on('status', function (info) {
console.log(info.cyan);
});
browser.on('command', function (meth, path, data) {
console.log(' > ' + meth.yellow, path.grey, data || '');
});
// Run the test
browser.init(desired)
// then(function () {
browser
// yield.elementByName("userNameTextField").click()
.sleep(30000) // **** WORKING FINE**
.elementByName('User Id').type('userID') // ** NOT WORKING **
.elementByName('Next').click() // ** NOT WORKING **
.elementByName('Password').type('password') // ** NOT WORKING *
.sleep(30000) // **** WORKING FINE**
.fin(function () {
return browser
.sleep(30000)
.quit()
console.log("inside click");
// });
})
.catch(function (err) {
console.log(err);
console.log("Entering into error Catch...")
throw err;
})
.done();
Try using the Appium app inspector to get the xpath of the elements:
.elementByXPath("//UIAApplication[1]/UIAWindow[1]/UIATextField[1]").sendKeys("userID")
.elementByXPath("//UIAApplication[1]/UIAWindow[1]/UIASecureTextField[1]").sendKeys("password")

Set the dart-editor server responses

My apache server is setup to respond to any request with the index.html. The idea behind this is to let the web app we are creating handle the routing. The dart-editor test environment does not do this by default.
Instead when i go to http://127.0.0.1.8080/something/that/does/not/exisit it will return a 404. I would like it to respond with the index.html and let the app handle the routing.
Is it possible to setup this behaviour for the dart test environment?
The suggested way is to use a custom server that acts as a proxy that forwards to pub serve.
see also
https://code.google.com/p/dart/issues/detail?id=20432
The code (copied from the linked issue)
Future proxyToPub(HttpRequest request, String path) {
const RESPONSE_HEADERS = const [
HttpHeaders.CONTENT_LENGTH,
HttpHeaders.CONTENT_TYPE ];
var uri = pubServeUrl.resolve(path);
return client.openUrl(request.method, uri)
.then((proxyRequest) {
proxyRequest.headers.removeAll(HttpHeaders.ACCEPT_ENCODING);
return proxyRequest.close();
})
.then((proxyResponse) {
proxyResponse.headers.forEach((name, values) {
if (RESPONSE_HEADERS.contains(name)) {
request.response.headers.set(name, values);
}
});
request.response.statusCode = proxyResponse.statusCode;
request.response.reasonPhrase = proxyResponse.reasonPhrase;
return proxyResponse.pipe(request.response);
})
.catchError((e) {
print("Unable to connect to 'pub serve' for '${request.uri}': $e");
var error = new AssetError(
"Unable to connect to 'pub serve' for '${request.uri}': $e");
return new Future.error(error);
});
}
I use the route_hierarchical package in a way that it works the same with usePushState enabled or disabled. This way I can use URL fragments for development and pushState for deployment.
See https://stackoverflow.com/a/25256858/217408
or the two similar (simple) examples where one uses usePushState false and the other true https://github.com/bwu-dart/bwu_polymer_routing

Control firefox tabs

I'm working on a firefox extension, until now I was working with XUL browser, to control the user navigation across web sites and save the visited pages, but the browser is limited, I tried a simple google search, when I click on some result, it won't be displayed in the browser.
One idea is to move the xul application to Dialog and control the actual firefox tabs.
But I have no idea how to do this.
(per your comment....)
To create an addon that logs TAB 'load' events, create a bootstrapped (restartless) addon:
bootstrap.js (The JavaScript file containing your 'privileged' code)
install.rdf (an XML file describing your addon to Firefrox)
To build the addon, simply place both files inside the top-level (no folders!) of a ZIP file with the file extension .xpi. To install the addon, navigate to about:addons then from the tools menu, click Install from file, find your XPI, open it, then after a short delay choose Install.
In install.rdf put something like this:
<?xml version="1.0"?>
<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:em="http://www.mozilla.org/2004/em-rdf#">
<Description about="urn:mozilla:install-manifest">
<em:id>youraddonname#yourdomain</em:id>
<em:type>2</em:type>
<em:name>Name of your addon</em:name>
<em:version>1.0</em:version>
<em:bootstrap>true</em:bootstrap>
<em:description>Describe your addon.</em:description>
<em:creator>Your name</em:creator>
<!-- Firefox Desktop -->
<em:targetApplication>
<Description>
<em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
<em:minVersion>4.0.*</em:minVersion>
<em:maxVersion>29.0.*</em:maxVersion>
</Description>
</em:targetApplication>
</Description>
</RDF>
You need to implement two mandatory JavaScript functions in the bootstrap.js:
startup() - called when you install the addon, and when your browser starts up.
shutdown() - called when you uninstall the addon, and when your browser shuts down.
You should call all of the 'privileged' code from startup(). For hygiene, you can (and probably should) also implement install() and uninstall() functions.
Start by implementing the following code in bootstrap.js:
const Cc = Components.classes;
const Ci = Components.interfaces;
let consoleService = Cc["#mozilla.org/consoleservice;1"]
.getService(Ci.nsIConsoleService);
let wm = Cc["#mozilla.org/appshell/window-mediator;1"]
.getService(Ci.nsIWindowMediator);
function LOG(msg) {
consoleService.logStringMessage("EXTENSION: "+msg);
}
function startup() {
try {
LOG("starting up...");
let windows = wm.getEnumerator("navigator:browser");
while (windows.hasMoreElements()) {
let chromeWindow = windows.getNext().QueryInterface(Ci.nsIDOMWindow);
WindowListener.setupBrowserUI(chromeWindow);
}
wm.addListener(WindowListener);
LOG("done startup.");
} catch (e) {
LOG("error starting up: "+e);
}
}
function shutdown() {
try {
LOG("shutting down...");
let windows = wm.getEnumerator("navigator:browser");
while (windows.hasMoreElements()) {
let chromeWindow = windows.getNext().QueryInterface(Ci.nsIDOMWindow);
WindowListener.tearDownBrowserUI(chromeWindow);
}
wm.addListener(WindowListener);
LOG("done shutdown.");
} catch (e) {
LOG("error shutting down: "+e);
}
}
Basically, that calls WindowListener.setupBrowserUI() for each current & future window of your web-browser. WindowListener is defined as follows:
var WindowListener = {
setupBrowserUI: function(chromeWindow) {
chromeWindow.gBrowser.addEventListener('load', my_load_handler, true);
},
tearDownBrowserUI: function(chromeWindow) {
chromeWindow.gBrowser.removeEventListener('load', my_load_handler, true);
},
onOpenWindow: function(xulWindow) {
let chromeWindow = xulWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindow);
chromeWindow.addEventListener("load", function listener() {
chromeWindow.removeEventListener("load", listener, false);
var domDocument = chromeWindow.document.documentElement;
var windowType = domDocument.getAttribute("windowtype");
if (windowType == "navigator:browser")
WindowListener.setupBrowserUI(chromeWindow);
}, false);
},
onCloseWindow: function(chromeWindow) { },
onWindowTitleChange: function(chromeWindow, newTitle) { }
};
That sets up an event listener for the OpenWindow event, and in turn installs an event listener for load events in the TabBrowser of each ChromeWindow. The load event handler is defined as:
var my_load_handler = function (evt) {
try {
var browserEnumerator = wm.getEnumerator("navigator:browser");
while (browserEnumerator.hasMoreElements()) {
var browserWin = browserEnumerator.getNext();
var tabbrowser = browserWin.gBrowser;
var numTabs = tabbrowser.browsers.length;
for (var index = 0; index < numTabs; index++) {
var currentBrowser = tabbrowser.getBrowserAtIndex(index);
var domWindow = currentBrowser.contentWindow.wrappedJSObject;
if (!domWindow.hasOwnProperty('__logged_this_window__')) {
LOG("TAB loaded:");
LOG(" URL: "+domWindow.location.href);
LOG(" TITLE: "+domWindow.title)
domWindow.__logged_this_window__ = 1;
}
}
}
} catch (e) {
LOG(e);
}
}
So basically, if there's a load event on any of the TabBrowser elements in Firefox, that function will run. It'll enumerate all of the Firefox windows, and all of those windows' tabs (Browser elements). The trick is that when a page reloads all the custom properties on a "content" DomWindow are lost, so we check to see if a custom property is present. If not, then we log details of the TAB's content page.

can't run the automated project in testcomplete when it calls from jenkins

can't run the automated project in testcomplete when calls from jenkins.
In our continuous integration part ,the project is automated using testcomplete and it is calling through jenkins with the help of bat file.The scripts inside the bat file is
"C:\Program Files\Automated QA\TestComplete 7\Bin\TestComplete.exe " "D:\Test Complete7 Projects\ProjectInput_AllSamples\ProjecInputs.pjs" /r /p:Samples /rt:Main "iexplore" /e
It will open testcomplete and iexplorer ,but it is not filling the data(automation).
It is working perfectly when we directly call the bat file with out jenkins.Is there any solution
From your description it sounds like something in Windows stopping you from allowing your test application to work normally. It might be the fact that the second user could be a problem but I can't confirm that as I was not able find any definite explanations of how it works in Windows XP. I am pretty sure that this won't work on a Windows Vista, 7, 8 or server machine though because of the changes in architecture.
It sounds like the best solution is to make sure that your automated UI tests are started by an interactive user. When I was trying to add automated testing to our builds we used TestComplete 7 on a Windows XP SP2 virtual machine. In order to start our tests as an interactive user we:
Made an user log on when windows started, this way there was always an interactive user which means there was an actual desktop session which has access to the keyboard / mouse. I seem to remember (but can't find any links at the moment) that without an interactive user there is no active desktop that can access the keyboard / mouse.
We wrote a little app that would start when the interactive user logged on. This app would look at a specific file and when that file changed / was created it would read the file and start the application. The code for this app looked somewhat like this:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ApplicationStarter
{
class Program
{
// The string used to indicate that the application should quit.
private const string ExitString = "exit";
// The path which is being watched for changes.
private static string s_LoadFilePath;
static void Main(string[] args)
{
try
{
{
Debug.Assert(
args != null,
"The arguments array should not be null.");
Debug.Assert(
args.Length == 1,
"There should only be one argument.");
}
s_LoadFilePath = args[0];
{
Console.WriteLine(
string.Format(
CultureInfo.InvariantCulture,
"Watching: {0}",
s_LoadFilePath));
}
if (File.Exists(s_LoadFilePath))
{
RunApplication(s_LoadFilePath);
}
using (var watcher = new FileSystemWatcher())
{
watcher.IncludeSubdirectories = false;
watcher.NotifyFilter =
NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName;
watcher.Path = Path.GetDirectoryName(s_LoadFilePath);
watcher.Filter = Path.GetFileName(s_LoadFilePath);
try
{
watcher.Created += OnConfigFileCreate;
watcher.EnableRaisingEvents = true;
// Now just sit here and wait until hell freezes over
// or until the user tells us that it has
string line = string.Empty;
while (!string.Equals(line, ExitString, StringComparison.OrdinalIgnoreCase))
{
line = Console.ReadLine();
}
}
finally
{
watcher.Created -= OnConfigFileCreate;
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
private static void RunApplication(string configFilePath)
{
var appPath = string.Empty;
var arguments = string.Empty;
using (var reader = new StreamReader(configFilePath, Encoding.UTF8))
{
appPath = reader.ReadLine();
arguments = reader.ReadLine();
}
// Run the application
StartProcess(appPath, arguments);
}
private static void StartProcess(string path, string arguments)
{
var startInfo = new ProcessStartInfo();
{
startInfo.FileName = path;
startInfo.Arguments = arguments;
startInfo.ErrorDialog = false;
startInfo.UseShellExecute = true;
startInfo.RedirectStandardOutput = false;
startInfo.RedirectStandardError = false;
}
Console.WriteLine(
string.Format(
CultureInfo.InvariantCulture,
"{0} Starting process {1}",
DateTime.Now,
path));
using (var exec = new Process())
{
exec.StartInfo = startInfo;
exec.Start();
}
}
private static void OnConfigFileCreate(
object sender,
FileSystemEventArgs e)
{
Console.WriteLine(
string.Format(
CultureInfo.InvariantCulture,
"{0} File change event ({1}) for: {2}",
DateTime.Now,
e.ChangeType,
e.FullPath));
// See that the file is there. If so then start the app
if (File.Exists(e.FullPath) &&
string.Equals(s_LoadFilePath, e.FullPath, StringComparison.OrdinalIgnoreCase))
{
// Wait for a bit so that the file is no
// longer locked by other processes
Thread.Sleep(500);
// Now run the application
RunApplication(e.FullPath);
}
}
}
}
This app expects the file to have 2 lines, the first with the app you want to start and the second with the arguments, so in your case something like this:
C:\Program Files\Automated QA\TestComplete 7\Bin\TestComplete.exe
"D:\Test Complete7 Projects\ProjectInput_AllSamples\ProjecInputs.pjs" /r /p:Samples /rt:Main "iexplore" /e
You should be able to generate this file from Jenkins in a build step.
Finally you may need to watch the TestComplete process for exit so that you can grab the results at the end but I'll leave that as an exercise to reader.
If you are running Jenkins (either master or slave) as a windows service, ensure it is running as a user and not as Local System.
We also do the same as Gentlesea's recommends, we run TestExecute on our Jenkins Slaves and keepo the TestComplete licenses for the people designing the TestComplete scripts.

Resources