<|start_filename|>tests/automation/menu_item/mocha_test.js<|end_filename|>
var gui = require('nw.gui');
var assert = require('assert');

describe('MenuItem', function(){
  var menu;
  beforeEach(function(){
    menu = new gui.Menu();
  })

  describe('.type', function(){
    
    it('should be separator', function(){  
      menu.append(new gui.MenuItem({ label : 'Item 1', type : 'separator' }));
      assert.equal(menu.items.length, 1);
      assert.equal(menu.items[0].type, 'separator');
    })

    it('should be normal', function(){
      menu.append(new gui.MenuItem({ label : 'Item 1' }));
      assert.equal(menu.items.length, 1);
      assert.equal(menu.items[0].type, 'normal');
    })

    it('should be checkbox', function(){
      menu.append(new gui.MenuItem({ label : 'Item 1', type : 'checkbox' }));
      assert.equal(menu.items.length, 1);
      assert.equal(menu.items[0].type, 'checkbox');
    })
    
  })

  describe('.label', function(){
    it('set label', function(){
      menu.append(new gui.MenuItem({ label : 'Item 1'}));
      assert.equal(menu.items.length, 1);
      assert.equal(menu.items[0].label, 'Item 1');

    })

    it('after change',function(){
      menu.append(new gui.MenuItem({ label : 'Item 1'}));
      assert.equal(menu.items.length, 1);
      menu.items[0].label = 'Item Mama';
      assert.equal(menu.items[0].label, 'Item Mama');
    })

  })

  describe('.icon', function(){
    it('set menu icon', function(){
      menu.append(new gui.MenuItem({ label : 'Item icon' }));
      assert.equal(menu.items.length, 1);
      menu.items[0].icon = 'icon1.png';
      assert.equal(menu.items[0].icon, 'icon1.png');

    })

    it('clear menu icon', function(){
      menu.append(new gui.MenuItem({ label : 'Item icon' }));
      menu.items[0].icon = 'icon1.png';
      menu.items[0].icon = '';
      assert.equal(menu.items[0].icon, '');
    })
  })

  describe('.tooltip', function(){
    it('set tooltip', function(){
      menu.append(new gui.MenuItem({ label : 'Item 0', tooltip : 'tooltip' }));
      assert.equal(menu.items[0].tooltip, 'tooltip');
    })

    it('change tooltip', function(){
      menu.append(new gui.MenuItem({ label : 'Item 0', tooltip : 'tooltip' }));
      menu.items[0].tooltip = '';
      assert.equal(menu.items[0].tooltip, '');
    })
  })

  
  describe('.checked', function(){
    it('set enabled', function(){
      menu.append(new gui.MenuItem({ type : 'checkbox', label : 'Item 0', checked : true }));
      assert.equal(menu.items[0].checked, true);
    })

    it('change checked', function(){
      menu.append(new gui.MenuItem({ type : 'checkbox', label : 'Item 0', checked: true }));     
      menu.items[0].checked = false;
      assert.equal(menu.items[0].checked, false);

    })
  })
 

  describe('.enabled', function(){
    it('set enabled', function(){
      menu.append(new gui.MenuItem({ type : 'checkbox', label : 'Item 0', enabled : true }));
      assert.equal(menu.items[0].enabled, true);
    })

    it('change enabled', function(){
      menu.append(new gui.MenuItem({ type : 'checkbox', label : 'Item 0', enabled : true }));
      menu.items[0].enabled = false;
      assert.equal(menu.items[0].enabled, false);

    })
  })

  describe('.submenu', function(){
    it('set submenu', function(){
      var submenu = new gui.Menu();
      submenu.append(new gui.MenuItem({ type: 'checkbox', label: 'Sub 1', checked: true, enabled: false }));
      submenu.append(new gui.MenuItem({ type: 'checkbox', label: 'Sub 2', checked: true, enabled: false }));
      submenu.append(new gui.MenuItem({ type: 'checkbox', label: 'Sub 3', checked: true, enabled: false }));
      submenu.append(new gui.MenuItem({ type: 'checkbox', label: 'Sub 4', checked: true, enabled: false }));
      menu.append(new gui.MenuItem({ label: 'I have submenu', submenu: submenu }));

      assert.equal(menu.items.length, 1);
      assert.equal(menu.items[0].label, 'I have submenu');
      assert.equal(menu.items[0].submenu, submenu);
      assert.equal(submenu.items.length, 4);
    })
  })

  describe('#click()', function(){
    
    var menu_item = new gui.MenuItem({label : 'item 1'});
    

    it('before click',function(){
      assert.equal(menu_item.label, 'item 1');    
    })

    it('after click',function(done){
      menu_item.on('click', function(){
        menu_item.label = '2';
        assert.equal(menu_item.label, '2'); 
        done();
      })
      menu_item.emit('click');
         
    })



  })

})


<|start_filename|>tests/server/config.js<|end_filename|>
exports.Expires = {
    fileMatch: /^(.gif|.png|.jpg|.js|.css)$/ig,
    maxAge: 606024365
};


<|start_filename|>tests/automatic_tests/document_cookies/mocha_test.js<|end_filename|>
var path = require('path');
var app_test = require('./nw_test_app');
var assert = require('assert');
var gui = require('nw.gui');
var results = new Array();
describe('document.cookies', function() {

    describe('http', function() {
	before(function(done) {
	    this.timeout(0);
	    var url = "http://127.0.0.1:8123/document_cookies.html";
	    var win = gui.Window.open(url);

	    setTimeout(function() {
		results.push(win.window.msg.textContent);
		done();
		win.window.close();
	    }, 1000);
	});
	it('should be set', function() {
	    assert.equal(results[0], '123');
	});
    });

    describe('file', function() {
	before(function(done) {
	    this.timeout(0);
	    var child = app_test.createChildProcess({
		execPath: process.execPath,
		appPath: path.join(global.tests_dir, 'document_cookies', 'file'),
		end: function(data, app) {
		    results.push(data);
                    app.kill();
                    done();
		}
	    });
	    setTimeout(done, 3000);
	});
	it ('should be set', function() {
	    assert.equal(results[1], '123');
	});
    });

    describe('app', function() {
	before(function(done) {
	    this.timeout(0);
	    var child = app_test.createChildProcess({
		execPath: process.execPath,
		appPath: path.join(global.tests_dir, 'document_cookies', 'app'),
		end: function(data, app) {
		    results.push(data);
                    app.kill();
                    done();
		}
	    });
	    setTimeout(done, 3000);
	});
	it ('should be set', function() {
	    assert.equal(results[2], '123');
	});
    });

});


<|start_filename|>tests/automatic_tests/inject-js/mocha_test.js<|end_filename|>
var path = require('path');
var spawn = require('child_process').spawn;
var server = global.server;
var server_port = global.port;
var assert = require('assert');



describe('inject-js',function(){
	var result = null;
	var child = null;

	var connection_handler_callback = undefined;
	var connection_handler = function(socket){
		socket.on('data',function(data){
			result = JSON.parse(data);
			if (typeof connection_handler_callback === 'function'){
				(connection_handler_callback)();
			}
		});
	};
	
	before(function(done){
		this.timeout(0);
		var app_path = path.join(global.tests_dir,'inject-js');
		var exec_argv = [app_path,server_port];
		child = spawn(process.execPath,exec_argv);
		server.on('connection',connection_handler);
		connection_handler_callback = done;
	});
	
	after(function(done){
		server.removeListener('connection',connection_handler);
		child.kill();
		done();
	});

	it('result.length should equal 4',function(done){
		assert.notEqual(result,null);
		assert.equal(result.length,4);
		done();
	});
	it('inject-js-start should run first',function(done){
		assert.equal(result[0],'inject-js-start');
		done();
	});
	it('document script should run after inject-js-start',function(done){
		assert.equal(result[1],'script-start');
		done();
	});
	it('inject-js-end should before window.onload',function(done){
		assert.equal(result[2],'inject-js-end');
		done();
	});
	it('inject-js-start should run last',function(done){
		assert.equal(result[3],'onload');
		done();
	});
});

<|start_filename|>tests/automatic_tests/nw_fork/mocha_test.js<|end_filename|>
var assert = require('assert');
var spawn = require('child_process').spawn;
var path = require('path');
var result = false;
describe('fork()',function(){
	var server = global.server;
	var get_result = function(socket){
		socket.on('data',function(data){
			if (data.toString() == "true"){
				result = true;
			}
		});
	};

	before(function(done){
		this.timeout(0);
		server.on('connection',get_result);
		var app_path = path.join('automatic_tests','nw_fork');
		var port = global.port || 13013;
		var child = spawn(process.execPath,[app_path,port]);
		child.on('exit',function(){
			done();
		});
	});

	it("child_process.fork() should have a workaround solution",function(done){
		assert.equal(result,true);
		done();
	});
	
	after(function(done){
		server.removeListener('connection',get_result);
		done();
	});
});

<|start_filename|>tests/automatic_tests/node/node_modules/module4 space.js<|end_filename|>
exports.test = function() {
  return "module4";
}



<|start_filename|>tests/automation/config.json<|end_filename|>
{
  "format": "xunit-file",
  "exclude": ["node_modules", "output", "internal", "res", "node-remote", "save_devtools_settings", "single_instance",
    "call_require_with_node-main_set", "show_devtool_after_http_server_created_in_node_main", "reference-node-main"],
  "single": "",
  "timeout": "8000",
  "slow": "200",
  "quiet": false
}



<|start_filename|>tests/automation/datapath/mocha_test.js<|end_filename|>
var path = require('path');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');


describe('data-path', function() {

    var server;

	before(function(done){
		this.timeout(0);
        if (!fs.existsSync(path.join(curDir, 'data-cash')))
	      fs.mkdirsSync(path.join(curDir, 'data-cash'));
        if (!fs.existsSync(path.join(curDir, 'dataPath')))
	      fs.mkdirsSync(path.join(curDir, 'dataPath'));
        if (!fs.existsSync(path.join(curDir, 'dataPath', 'data-cash')))
	      fs.mkdirsSync(path.join(curDir, 'dataPath', 'data-cash'));
        if (!fs.existsSync(path.join(curDir, 'data-cash', 'dataPath')))
	      fs.mkdirsSync(path.join(curDir, 'data-cash', 'dataPath'));

        server = createTCPServer(13013);

	    done();
	  });

	  after(function() {
	    setTimeout(function() {
          server.close();
	      fs.remove(path.join(curDir, 'data-cash'));
	      fs.remove(path.join(curDir, 'dataPath'));
	      fs.remove(path.join(curDir, 'dataPath', 'data-cash'));
	      fs.remove(path.join(curDir, 'data-cash', 'dataPath'));
	    }, 1000);
	  });


  it('setting datapath as ./data-cash/ should pass',
    function(done) {
      this.timeout(0);
      var child = spawnChildProcess(path.join(curDir, 'datacash'));
      server.on('connection', function(socket) {
        socket.setEncoding('utf8');
        socket.on('data', function(data) {
          child.kill();
          server.removeAllListeners('connection');
          done();
      });});
  });

  it('setting datapath as ./dataPath/ should pass',
    function(done) {
      this.timeout(0);

      var child = spawnChildProcess(path.join(curDir, 'datapath'));
      server.on('connection', function(socket) {
        socket.setEncoding('utf8');
        socket.on('data', function(data) {
          child.kill();
          server.removeAllListeners('connection');
          done();
      });});
  });

  it('setting datapath as ./dataPath/data-cash/ should pass',
    function(done) {
      this.timeout(0);
      var child = spawnChildProcess(path.join(curDir, 'datapath-cash'));
      server.on('connection', function(socket) {
        socket.setEncoding('utf8');
        socket.on('data', function(data) {
          child.kill();
          server.removeAllListeners('connection');
          done();
      });});

  });

  it('setting datapath as ./data-cash/dataPath/ should pass',
    function(done) {
      this.timeout(0);

      var child = spawnChildProcess(path.join(curDir, 'datacash-path'));
      server.on('connection', function(socket) {
        socket.setEncoding('utf8');
        socket.on('data', function(data) {
          child.kill();
          server.removeAllListeners('connection');
          done();
      });});

  });


});





<|start_filename|>tests/automation/menu/mocha_test.js<|end_filename|>
var gui = require('nw.gui');
var assert = require('assert');


describe('Menu', function(){
  
  describe('#append()', function(){
    it('should append a value', function(){
      var menu = new gui.Menu();
      menu.append(new gui.MenuItem({ label:'Item 1'}));
      assert.equal(menu.items[0].label, 'Item 1');
    })
    
  })

  describe('#.length', function(){
    it('should return correct value', function(){
      var menu = new gui.Menu();
      menu.append(new gui.MenuItem({label : 'Item 1'}));
      menu.append(new gui.MenuItem({label : 'Item 2'}));
      assert.equal(menu.items.length, 2);
    })
  })

  describe('#insert()', function(){
    var menu = new gui.Menu();
    
    it('should adject .length', function(){
      menu.append(new gui.MenuItem({label : 'Item 1'}));
      menu.append(new gui.MenuItem({label : 'Item 2'}));
	  menu.insert(new gui.MenuItem({label : 'Item 0'}), 1);
      assert.equal(menu.items.length, 3);
    })

    it('new value should be added in', function(){
      assert.equal(menu.items[1].label, 'Item 0');
    })

    it('the origin value', function(){
      assert.equal(menu.items[2].label, 'Item 2');
    })
  })

  describe('#removeAt()', function(){
    var menu = new gui.Menu();
    it('should adject .length', function(){
      menu.append(new gui.MenuItem({label : 'Item 0'}));
      menu.append(new gui.MenuItem({label : 'Item 1'}));
      menu.append(new gui.MenuItem({label : 'Item 2'}));
      menu.removeAt(1);
      assert.equal(menu.items.length, 2);
    });

    it('the next value', function(){
      assert.equal(menu.items[1].label, 'Item 2');
    })
  })

  describe('#remove()', function(){
    var menu = new gui.Menu();
    menu.append(new gui.MenuItem({label : 'Item 0'}));
    menu.append(new gui.MenuItem({label : 'Item 1'}));
    var removedItem = new gui.MenuItem({label : 'Item Deleted'});
    menu.insert(removedItem, 1);
    it('before delete', function(){
      assert.equal(menu.items.length, 3);
      assert.equal(menu.items[1].label, 'Item Deleted');
    })

    it('after delete', function(){
      menu.remove(removedItem);
      assert.equal(menu.items.length, 2);
      assert.equal(menu.items[1].label, 'Item 1');

    })
  })

  describe('#popup(), not implentment',function(){
  })

})




<|start_filename|>tests/automation/snapshot/mocha_test.js<|end_filename|>
var path = require('path');
var os = require('os');
var fs = require('fs-extra');
var cp = require('child_process');
var curDir = fs.realpathSync('.');

var myTestJSPath = path.join(curDir, 'internal', 'mytest.js');
var myTestBinPath = path.join(curDir, 'internal', 'mytest.bin');

var snapshotPath;
var server;

describe('snapshot', function() {

/////////// 1

    describe('demo should work fine', function() {
	before(function(done) {
	    var snapshotExec;
	    if (os.platform() == 'darwin') {
		snapshotExec = '../../../../../../nwsnapshot';
	    }
	    if (os.platform() == 'linux') {
		snapshotExec = 'nwsnapshot';
	    }
	    if (os.platform() == 'win32') {
		snapshotExec = 'nwsnapshot.exe';
	    }

	    snapshotPath = path.join(process.execPath, '..', snapshotExec);
	    console.log("snapshotPath: " + snapshotPath);

	    cp.execFile(snapshotPath,
			['--extra_code', myTestJSPath, myTestBinPath],
			{cwd: curDir},
			function (error, stdout, stderr) {

                server = createTCPServer(13013);

			    done();
			}
        );

	});

	after(function() {
	    fs.unlink(myTestBinPath, function(err) {if(err && err.code !== 'ENOENT') throw err});
	    fs.unlink(path.join(curDir, 'internal', 'v8.log'), function(err) {if(err && err.code !== 'ENOENT') throw err});
        server.close();
	});

	it('the native code could be exectuted',
	   function(done) {
               this.timeout(0);
               var result = false;


            var child = spawnChildProcess(path.join(curDir, 'internal'));
    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        result = true;
        child.kill();
        done();
      });
    });


               setTimeout(function(){
		   if (!result) {
		       done('the native code does not been executed');
		       child.close();
		       //child.removeConnection();
		       //child.app.kill();
		   }
               }, 3000);
               //child.app.stderr.on('data', function(d){ console.log ('app' + d);});

	   });
    });


////////////////// 2


    describe('1266-snapshot-crash-start', function() {
    	before(function(done) {
    	    cp.execFile(snapshotPath,
    			['--extra_code', 'file_to_snapshot_to_app.bin.js', 'app.bin'],
    			{cwd: path.join(curDir, 'internal', '1266-snapshot-crash-start')},
    			function (error, stdout, stderr) {
    			    done();
    			}
			
    		       );
    	});
	
    	after(function() {
    	    fs.unlink(path.join(curDir, 'internal','1266-snapshot-crash-start', 'app.bin'), function(err) {if(err && err.code !== 'ENOENT') throw err});
    	    fs.unlink(path.join(curDir, 'internal','1266-snapshot-crash-start', 'v8.log'), function(err) {if(err && err.code !== 'ENOENT') throw err});
    	    fs.unlink(path.join(curDir, 'internal','1266-snapshot-crash-start','tmp'), function(err) {if(err && err.code !== 'ENOENT') throw err});
    	});
	
    	it('another demo should close nomally', function(done) {
    	    this.timeout(0);
    	    var ppath = process.execPath + " " + path.join(curDir, 'internal', '1266-snapshot-crash-start');
    	    cp.exec(ppath, function(err, stdout, stderr) {
    	    });
    	    setTimeout(function(){
		fs.exists(path.join(curDir, 'internal', '1266-snapshot-crash-start', 'tmp'), function(exists) {
		    if (exists)
			done();
		    else
			done('another demo fails');
		});
    	    }, 3000);
    	  });
    });



});




<|start_filename|>tests/automation/res/util.js<|end_filename|>
var div = document.createElement('div');
div.id = 'mocha';
//div.style.visibility = 'hidden';
document.body.appendChild(div);

// useful when need to keep app stay on window:
// $ quiet=false nw <app>
//
var g_quiet = process.env['quiet'] || true;
if (g_quiet === 'false') g_quiet = false;

if (!g_quiet) {
  var link = document.createElement('link');
  link.setAttribute('rel', 'stylesheet');
  link.setAttribute('type', 'text/css');
  link.setAttribute('href', '../res/mocha.css');
  document.getElementsByTagName('head')[0].appendChild(link);
}

var fs = require('fs');
var path = require('path');
var net = require('net');
var spawn = require('child_process').spawn;

var createTCPServer = function(port, autoClose) {
  var server = net.createServer();
  if (autoClose) {
    process.exit = function() {
      server.close();
      process.quit();
    };
  }
  port = port || 13013;
  server.on('error', function(e) {
    console.error('Failed to launch TCP server: '+ e.code);
  });
  server.listen(port);
  return server;
};

var connectToTCPServer = function(port, data, keepOpen) {
  port = port || 13013;
  var socket = net.connect({port: port});
  socket.setEncoding('utf8');
  if (data) {
    socket.write(JSON.stringify(data));
  }
  if (!keepOpen) {
    socket.end();
    socket = undefined;
  }
  return socket;
};

var spawnChildProcess = function(appPath) {
  var child = spawn(process.execPath, [appPath]);
  return child;
};

mocha.setup({ui:'bdd'});

var outputAsXML = function() {
  var outputDir = process.env['out_dir'];
  if (!outputDir) {
    outputDir = fs.realpathSync('.');
    console.log('====Test results will be at: ' + outputDir);
    //return;
  }
  var ret = 0;
  if (window.XMLSerializer) {
    var xmlParser = new XMLSerializer();
    var appName = process.cwd();
    appName = appName.substring(appName.lastIndexOf(path.sep) + 1);
    var outputPath = path.join(outputDir, appName + '.xml');
    var reportNode = document.getElementById('mocha-report');
    var mochaNode = document.getElementById('mocha');
    var data = xmlParser.serializeToString(mochaNode); //(reportNode);
    //data = data.replace('/', '//');
    //data = data.replace('%20', ' ');
    data = decodeURIComponent(data);
    fs.writeFileSync(outputPath, data);
  }

  // check failures
  var stats = document.getElementById('mocha-stats');
  var failureNodes = stats.getElementsByClassName('failures');
  var failureNumNode = undefined;
  var failures = '';

  if (failureNodes && failureNodes.length > 0) {
    failureNumNode = failureNodes[0].getElementsByTagName('em');
    if (failureNumNode && failureNumNode.length > 0) {
      failures = failureNumNode[0].innerText;
      if (failures !== '0') {
        ret = 1;
      }
    }
  }

  if (g_quiet)
    process.exit(ret);

  return 0;
};

window.assertRunningResult = function(result, errMsg) {

  describe('Assert test running result', function() {
    it('the test should succeed', function(done){
      if (result) {
        done();
      } else {
        done('Assertion failed: ' + errMsg);
      }
    });
  });
};

window.addEventListener('load', function(){
  mocha.run();
  mocha.suite.afterAll(function(){
    outputAsXML();
  });
});


<|start_filename|>tests/automation/website/mocha_test.js<|end_filename|>
var assert = require('assert');

describe('website', function() {
  describe('scores', function() {
    var gui = require('nw.gui');

    it('html5test.com should score high (long-to-run)', function(done) {
      this.timeout(0);
      var win = gui.Window.open('http://html5test.com', { show: false });
      win.on('loaded', function() {
        var results = win.window.document.getElementById('results');
        if (results == null){
          done('Can not connect to the web');
        } else {
		    try {
            var score = results.childNodes[0].childNodes[1].innerHTML;
            if (score >= 445) {
              done();
            } else {
              done('have a low score');
            }
            } catch (e) {
              done('failed to get score');
            }  // try-catch
            
        }
        win.close();
      });
    });
    
  
    it('should support WebGL at get.webgl.org', function(done) {
      this.timeout(0);
      var win = gui.Window.open('http://get.webgl.org', { show: false });
      win.on('loaded', function() {
        var results = win.window.document.getElementById('webgl-yes');
        if (results.classList.contains('webgl-hidden')) {
          done('do not support WebGL');
        } else {
          done();
        }
        win.close();
      });

    });
  
    
  });
});




<|start_filename|>tests/automatic_tests/quit_with_secondary_window_on_top/mocha_test.js<|end_filename|>
var assert = require('assert');
var path = require('path');
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
var os = require('os');
var result;

if (os.platform() != 'darwin')
  return;
describe('quit_with_secondary_window_on_top', function() {
    before(function(done) {
        this.timeout(0);
        var app_path = path.join(global.tests_dir, 'quit_with_secondary_window_on_top');
        var exec_path = process.execPath;
        exec_path = exec_path.replace(/ /g, '\\ ');
        exec(exec_path + ' ' + app_path, function(error, stdout, stderr) {
            result = error;
            done();
          });
      })
    it('should quit with secondary window on top without error', function() {
        assert.equal(result, null);
    });
});


<|start_filename|>tests/automation/chromium-args/internal/package2.json<|end_filename|>
{
  "name": "nw-chromium-args",
  "main": "index.html",
  "window": {
    "show": false
  },
  "chromium-args": "--app=http://www.baidu.com"
  
}


<|start_filename|>tests/automation/app/mocha_test.js<|end_filename|>
var gui = require('nw.gui');
var path = require('path');
var assert = require('assert');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');

describe('gui.App', function() {


  var server, child, result = false;

  before(function(done) {
    this.timeout(0);
    server = createTCPServer(13013);
    child = spawnChildProcess(path.join(curDir, 'internal'));
    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        result = true;
        child.kill();
        done();
      });
    });

    setTimeout(function() {
      if (!result) {
        child.kill();
        done('timeout');
      }
    }, 4500);

  });
    
  after(function () {
        server.close();
  });


    describe('manifest', function() {
	it('`gui.App.manifest` should equle to value of package.json', function() {
	    assert.equal(gui.App.manifest.name, 'nw-gui.App-test.wrapper');       
	});

	it('have main', function() {
	    assert.equal(typeof gui.App.manifest.main, 'string');
	    assert.equal(gui.App.manifest.main, 'index.html');
	});


	it('have window', function() {
        console.log('====have window:' + typeof gui.App.manifest.window);
	    assert.equal(typeof gui.App.manifest.window, 'object');       
	});

	it('have dependencies', function() {
	    assert.equal(typeof gui.App.manifest.dependencies, 'object');       
	});

    });

    describe('clearCache()', function(done) {
	it('should clear the HTTP cache in memory and the one on disk', function() {
	    var res_save = global.local_server.res_save;
	    
	    assert.equal(res_save[1].status, 304);
	    assert.equal(res_save[1].pathname, 'img.jpg');
	    assert.equal(res_save[2].status, 200);
	    assert.equal(res_save[2].pathname, 'img.jpg');
	});
    });

});




<|start_filename|>tests/automation/snapshot/internal/mytest.js<|end_filename|>
function mytest(a) {
  document.write(a + 42);
    
  var gui = require('nw.gui');
  var result = { ok: true };

    var socket = require('net').connect({port: 13013});
    socket.setEncoding('utf8');
    socket.end(JSON.stringify(result));
    
    
}


<|start_filename|>tests/automation/user-agent/mocha_test.js<|end_filename|>
var path = require('path');
var assert = require('assert');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');

describe('user-agent', function() {

  var server, child, results;

  before(function(done) {
    this.timeout(0);
    server = createTCPServer(13013);
    child = spawnChildProcess(path.join(curDir, 'internal'));
    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        results = JSON.parse(data);
        for (var i = 0, len = results.length; i < len; i++) {
            console.log('User agent['+i+']:' + results[i]);
        }
        child.kill();
        done();
      });
    });

  });
    
  after(function () {
        server.close();
  });

    
    describe('user-agent with child window opened', function() {
	it('should be same to the one in parent window', function() {
	    assert.equal(results[0], results[1]);
	});
    });
    
    describe('user-agent with reload', function() {
	it('should be same with all reload method', function() {
	    assert.equal(results[0], results[2]);
	    assert.equal(results[0], results[3]);
	    assert.equal(results[0], results[4]);
	    assert.equal(results[0], results[5]);
	});
    });
    
    describe('user-agent with package.json', function() {
	var user_agent = navigator.userAgent.split('/');
	var package_info = JSON.parse(fs.readFileSync(path.join(curDir, 'internal', 'package.json'), 'utf8'));
	it('name should be same to the one in package.json',
	   function() {
	       assert.equal(user_agent[0], package_info.name);
	   });
	
	it('version should be same to the one in package.json',
	   function() {
	       assert.equal(user_agent[2], package_info.version);
	   });
    });

});




<|start_filename|>tests/automatic_tests/buff_from_string/mocha_test.js<|end_filename|>
var assert = require('assert');
var func = require('./' + global.tests_dir + '/start_app/script.js');
var result = [];
var spawn = require('child_process').spawn;
var fs = require('fs-extra');
var is_chromedriver_exists = false;
var path = require('path');

describe("buff_from_string", function() {
	var results = [];
	var server = global.server;
	var getResult = function(socket){
		socket.on('data',function(data){
			results = JSON.parse(data.toString());
		});
	};
	before(function(done) {
		this.timeout(0);
		server.on('connection',getResult);
		func.copyExecFiles(function() {
			var src_files = [
				"automatic_tests/buff_from_string/index.html",
				"automatic_tests/buff_from_string/package.json",
				"automatic_tests/buff_from_string/test.py"
			];
			var dst_files = [
				"tmp-nw/index.html",
				"tmp-nw/package.json",
				"tmp-nw/test.py"
			];

			if (process.platform == 'win32'){
				src_files.push("automatic_tests/buff_from_string/chromedriver2_server.exe");
				dst_files.push("tmp-nw/chromedriver2_server.exe");
			} else {
				src_files.push("automatic_tests/buff_from_string/chromedriver2_server");
				dst_files.push("tmp-nw/chromedriver2_server");
			}

			for (var i=0;i<src_files.length;++i){
				fs.copySync(src_files[i],dst_files[i]);
			}
			if (process.platform != 'win32'){
				fs.chmodSync("tmp-nw/chromedriver2_server",365);
			}
			var test_file = path.join("tmp-nw","test.py");
			setTimeout(function(){
				var child = spawn('python',[test_file]);
				child.on('exit',function(code,signal){
					console.log(code,signal);
					done();
				});
				child.on('error',function(err){
					console.log(err);
				});
				child.stderr.on('data',function(data){
					console.log(data.toString());
				});
				child.stdout.on('data',function(data){
					console.log(data.toString());
				});
			},1000);
		});
	});

	it("string and buff.toString() should equal", function(done) {
		assert.equal(results.length,1);
		assert.equal(results[0],true);
		done();
	});

	after(function(done) {
		this.timeout(0);
		server.removeListener('connection',getResult);
		setTimeout(function(){
			fs.removeSync("tmp-nw");	
			done();
		},2000);
	});
});

<|start_filename|>tests/automation/source-maps/internal/scripts/script.typescript.js<|end_filename|>
document.getElementById("color").focus();
$(document).keydown(function (evt) {
    if(evt.keyCode == 13) {
        $("body").css("background-color", $("#color").val());
    }
});
//@ sourceMappingURL=script.typescript.js.map


<|start_filename|>tests/automatic_tests/plugin/mocha_test.js<|end_filename|>
var path = require('path');
var app_test = require('./nw_test_app');

describe('Plugin', function() {
  describe('flash', function(){
    it('should not crash', function(done) {
      var result = false;

      var child = app_test.createChildProcess({
        execPath: process.execPath,
        appPath: path.join(global.tests_dir, 'plugin', 'flash'),
        end: function(data, app) {        
          result = true;
          app.kill();
          done();
        }
      });

      setTimeout(function(){
        if (!result) {
          done('nw crash.');
          child.close();
          //child.removeConnection();
        }
      }, 2000);


    })
  })
})


<|start_filename|>tests/automatic_tests/datapath/mocha_test.js<|end_filename|>
var path = require('path');
var app_test = require('./nw_test_app');
var fs = require('fs-extra');
describe('data-path', function() {
	before(function(done){
		this.timeout(0);
	    fs.mkdirsSync('./data-cash');
	    fs.mkdirsSync('./dataPath');
	    fs.mkdirsSync('./dataPath/data-cash');
	    fs.mkdirsSync('./data-cash/dataPath');
	    done();
	  })

	  after(function() {
	    setTimeout(function() {
	      fs.remove('./data-cash');
	      fs.remove('./dataPath');
	      fs.remove('./dataPath/data-cash');
	      fs.remove('./data-cash/dataPath');
	    }, 1000);
	  })

  it('setting datapath as ./data-cash/ should pass',
    function(done) {
      this.timeout(0);
      var child = app_test.createChildProcess({
        execPath: process.execPath,
        appPath: path.join(global.tests_dir, 'datapath/datacash'),
        end: function(data, app) {
            app.kill();
            done();
        }
      });
  })
  it('setting datapath as ./dataPath/ should pass',
    function(done) {
      this.timeout(0);
      
      var child = app_test.createChildProcess({
        execPath: process.execPath,
        appPath: path.join(global.tests_dir, 'datapath/datapath'),
        end: function(data, app) {
            app.kill();
            done();
        }
      });
  })
  it('setting datapath as ./dataPath/data-cash/ should pass',
    function(done) {
      this.timeout(0);
      
      var child = app_test.createChildProcess({
        execPath: process.execPath,
        appPath: path.join(global.tests_dir, 'datapath/datapath-cash'),
        end: function(data, app) {
            app.kill();
            done();
        }
      });
  })
  it('setting datapath as ./data-cash/dataPath/ should pass',
    function(done) {
      this.timeout(0);
      
      var child = app_test.createChildProcess({
        execPath: process.execPath,
        appPath: path.join(global.tests_dir, 'datapath/datacash-path'),
        end: function(data, app) {
            app.kill();
            done();
        }
      });
  })
})


<|start_filename|>tests/automation/app_path_escape/mocha_test.js<|end_filename|>
var spawn = require('child_process').spawn;
var os = require('os');
var path = require('path');
var global = require('../globals');

describe('app_path_escaping',function(){
  it('app should start normally with directory named xdk',function(done){
    this.timeout(0);
    var opened = false;
    var app = spawn(process.execPath, [path.join(global.tests_dir,  'xdk')]);
    app.on('close',function(){
      opened = true;
      done();
    });

    setTimeout(function() {
      if(!opened){
        app.kill();
        done('the app is not executed');
      }
    }, 5000);

  });
});



<|start_filename|>tests/automatic_tests/reference_xhr_in_node_context/mocha_test.js<|end_filename|>
var path = require('path');
var assert = require('assert');
var spawn = require('child_process').spawn;
var server = global.server;
var port = global.port||13013;

describe('reference xhr from node context',function(){
	
	var crash = true;
	var child = undefined;
	var connection_handler_callback = undefined;
	var connection_handler = function(socket){
		socket.on('data',function(data){
			crash = false;
			connection_handler_callback();
		});
	};


	before(function(done){
		this.timeout(0);
		server.on('connection',connection_handler);
		var exec_path = path.join(global.tests_dir,'reference_xhr_in_node_context');
		var exec_argv = [exec_path,port]
		child = spawn(process.execPath,exec_argv);
		connection_handler_callback = done;
		child.on('exit',function(){
			if (crash){
				done();
			}
		});
	});

	after(function(done){
		server.removeListener('connection',connection_handler);
		child.kill();
		done();
	});

	it("reference xhr from node context should not crash",function(done){
		assert.equal(crash,false);
		done();
	});
});

<|start_filename|>tests/manual_tests/drag_window/package.json<|end_filename|>
{
	"name":"nw_drag_window",
	"main":"index.html",
	"window":{
		"toolbar":false,
		"frame":false
	}
}

<|start_filename|>tests/manual_tests/quit/app/close-handler.js<|end_filename|>
exports.init = function(win, nwGui) {
  console.log('Setting up close handler');
  win.on('close', function(how) {
    console.log('Got CLOSE event in close-handler.js with "' + how + '"');
    win.hide();
    var http = require('http');
    http.get("http://localhost:9000/close");
    setTimeout(function() {
      console.log('Quitting from close handler');
      nwGui.App.quit();
    }, 5000);
  });
};


<|start_filename|>tests/automation/reference_xhr_in_node_context/mocha_test.js<|end_filename|>
var path = require('path');
var assert = require('assert');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');

describe('reference xhr from node context',function(){

  var server, child, crash = true;

  before(function(done) {
    this.timeout(0);
    server = createTCPServer(13013);
    child = spawnChildProcess(path.join(curDir, 'internal'));
    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        crash = false;
        child.kill();
        done();
      });
    });

  });
    
  after(function () {
        server.close();
  });

	it("reference xhr from node context should not crash",function(done){
		assert.equal(crash,false);
		done();
	});
});



<|start_filename|>tests/automation/source-maps/internal/scripts/script.coffee.js<|end_filename|>
// Generated by CoffeeScript 1.4.0
(function() {

  document.getElementById("color").focus();

  $(document).keydown(function(evt) {
    if (evt.keyCode === 13) {
      return $("body").css("background-color", $("#color").val());
    }
  });

}).call(this);
//@ sourceMappingURL=script.coffee.js.map

<|start_filename|>tests/automatic_tests/snapshot/mocha_test.js<|end_filename|>
var path = require('path');
var app_test = require('./nw_test_app');
var os = require('os');
var fs = require('fs-extra');
var cp = require('child_process');
var snapshotPath;

describe('snapshot', function() {

    describe('demo should work fine', function() {
	before(function(done) {
	    var snapshotExec;
	    if (os.platform() == 'darwin') {
		snapshotExec = '../../../../../../nwsnapshot';
	    }
	    if (os.platform() == 'linux') {
		snapshotExec = 'nwsnapshot';
	    }
	    if (os.platform() == 'win32') {
		snapshotExec = 'nwsnapshot.exe';
	    }

	    snapshotPath = path.join(process.execPath, '..', snapshotExec);
	    console.log("snapshotPath: " + snapshotPath);

	    cp.execFile(snapshotPath,
			['--extra_code', 'mytest.js', 'mytest.bin'],
			{cwd:'./' + global.tests_dir + '/snapshot/'},
			function (error, stdout, stderr) {
			    done();
			}

		       );
	})

	after(function() {
	    fs.unlink(path.join(global.tests_dir, 'snapshot', 'mytest.bin'), function(err) {if(err && err.code !== 'ENOENT') throw err});
	    fs.unlink(path.join(global.tests_dir, 'snapshot', 'v8.log'), function(err) {if(err && err.code !== 'ENOENT') throw err});
	})

	it('the native code could be exectuted',
	   function(done) {
               this.timeout(0);
               var result = false;

               var child = app_test.createChildProcess({
		   execPath: process.execPath,
		   appPath: path.join(global.tests_dir, 'snapshot'),
		   end: function(data, app) {
		       done();
		       app.kill();
		       result = true;
		   }
               });

               setTimeout(function(){
		   if (!result) {
		       done('the native code does not been executed');
		       child.close();
		       //child.removeConnection();
		       //child.app.kill();
		   }
               }, 3000);
               //child.app.stderr.on('data', function(d){ console.log ('app' + d);});

	   })
    })

    describe('1266-snapshot-crash-start', function() {
    	before(function(done) {
    	    cp.execFile(snapshotPath,
    			['--extra_code', 'file_to_snapshot_to_app.bin.js', 'app.bin'],
    			{cwd:'./' + global.tests_dir + '/snapshot/1266-snapshot-crash-start/'},
    			function (error, stdout, stderr) {
    			    done();
    			}
			
    		       );
    	})
	
    	after(function() {
    	    fs.unlink(path.join(global.tests_dir, 'snapshot','1266-snapshot-crash-start', 'app.bin'), function(err) {if(err && err.code !== 'ENOENT') throw err});
    	    fs.unlink(path.join(global.tests_dir, 'snapshot','1266-snapshot-crash-start', 'v8.log'), function(err) {if(err && err.code !== 'ENOENT') throw err});
    	    fs.unlink(path.join(global.tests_dir, 'snapshot','1266-snapshot-crash-start','tmp'), function(err) {if(err && err.code !== 'ENOENT') throw err});
    	})
	
    	it('another demo should close nomally', function(done) {
    	    this.timeout(0);
    	    var ppath = process.execPath + " " + path.join(global.tests_dir, 'snapshot', '1266-snapshot-crash-start');
    	    cp.exec(ppath, function(err, stdout, stderr) {
    	    });
    	    setTimeout(function(){
		fs.exists(path.join(global.tests_dir, 'snapshot','1266-snapshot-crash-start', 'tmp'), function(exists) {
		    if (exists)
			done();
		    else
			done('another demo fails');
		});
    	    }, 3000);
    	  });
    });


})


<|start_filename|>tests/automation/fd-limit/mocha_test.js<|end_filename|>
var assert = require('assert');
var fs = require('fs');
var path = require('path');
var nw = require('./nw');

describe('fd-limit', function() {

    describe('file descriptor limit', function() {

        before(function(done) {
            this.timeout(5000);
            fs.mkdir('testfiles', function(err) {
                if (err) throw err;
                var n = 0;
                (function next() {
                    fs.writeFile('testfiles/' + n + '.json', JSON.stringify({i: n}), function(err) {
                        if (err) throw err;

                        if (++n === 2000) {
                            done();
                        } else {
                            next();
                        }
                    });
                }());
            });
        });

        after(function(done) {
            this.timeout(5000);
            var n = 0;
            (function next() {
                fs.unlink('testfiles/' + n + '.json', function(err) {
                    if (err) throw err;

                    if (++n === 2000) {
                        fs.rmdir('testfiles', function(err){
                            if (err) throw err;
                            done();
                        });
                    } else {
                        next();
                    }
                });
            }());
        });

        it('fetches 2k files via XHR should succeed with --file-descriptor-limit=8192', function(done) {
            if (process.platform === 'win32') {
                assert.equal(true, true);
                done();
            }

            this.timeout(5000);

            nw.spawn(['test_app', '--file-descriptor-limit=8192'], function(err, data) {
                if (err) throw err;
                assert.equal(data.ok, true);
                done();
            });
            
        });

        it('fetches 2k files via XHR should fail with --file-descriptor-limit=100', function(done) {
            if (process.platform === 'win32') {
                assert.equal(true, true);
                done();
            }

            this.timeout(5000);

            nw.spawn(['test_app', '--file-descriptor-limit=100'], function(err, data) {
                if (err) throw err;
                assert.equal(data.ok, false);
                done();
            });
            
        });

    });

});


<|start_filename|>tests/automation/proxy/mocha_test.js<|end_filename|>
var cp = require('child_process');
var os = require('os');
var path = require('path');
var assert = require('assert');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');

describe('proxy', function(){
  before(function(done){
    if (os.platform() == "win32"){
      this.timeout(0);
      var ex = cp.exec(path.join(curDir, 'export.bat'),
      function(error, stdout, stderr){
        console.log(stdout);
        done();
      });
    }
    else 
      done();
  })
  after(function(){
    this.timeout(0);
    if (os.platform() == "win32"){
      fs.unlink('c:/test.reg', function (err) {
        if (err) console.log(err);
      });
    }
  })
  it('the get proxyfor url should work fine', function(done) {
    if (os.platform() == "win32"){
      this.timeout(0);
      setTimeout(function(){
        var data = fs.readFileSync("c:/test.reg",'utf16le');
        var index = data.indexOf('ProxyServer');
        var right = data.substring(index+14);
        var array = right.split('"');
        var gui = require('nw.gui');
        var re = gui.App.getProxyForURL("https://www.google.com.hk");
        if (re == "PROXY "+array[0])
          done();
        else 
          done('the method getProxyForURL is not right');
      },1000);
    }
    else {
      done();
    }
 });

});



<|start_filename|>tests/automation/new-instance/mocha_test.js<|end_filename|>
var path = require('path');
var assert = require('assert');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');

describe('new-instance', function() {
  var server, child, result = false;

  before(function(done) {
    server = createTCPServer(13013);
    done();
  });
    
  after(function () {
        server.close();
  });

	it('new window has different pid', function(done) {
	    this.timeout(0);
	    var result = false;
	    var times = 0;
	    var pid1, pid2;

    child = spawnChildProcess(path.join(curDir, 'internal'));
    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
	        if (times == 0) {
	          pid1 = data;
	          times += 1;
	        } else {
	          pid2 = data;

	          if (pid1 != pid2) {
	            done();
	          } else {
	            done('they are in the same process');
	          }
              child.kill();
            }

      });
    });


	});


});




<|start_filename|>tests/automation/save_devtools_settings/mocha_test.js<|end_filename|>
var path = require('path');
var assert = require('assert');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');


var original;
var changed;
var ok = false;
var server, child;

var spawnChild = function(action) {
    return spawn(process.execPath, [path.join(curDir, 'internal'), action]);
};

function read_changed(done) {
    if (!ok) {
	  setTimeout(read_changed, 2000, done);
    } else {
      var tmpChild = spawnChild(0);
      server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        changed = data;
        tmpChild.kill();
        done();
        console.log("secnond");
      });
      });
      
    }
}

describe('save_devtools_settings', function() {

  before(function(done) {
    this.timeout(0);
    server = createTCPServer(13013);
    child = spawnChild(1);
    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        result = JSON.parse(data);
        original = data;
        ok = true;
        child.kill();
        done();
        console.log("first");
      });
    });

    setTimeout(read_changed, 2000, done);

  });
    
  after(function () {
        server.close();
  });

    
    it("should save devtools' settings", function() {
	var i = 0;
	// general
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.equal((original[i] + 1) % 4, changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;

	assert.equal((original[i] + 1) % 4, changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	if (!original[i - 1])
	    assert.equal((original[i] + 1) % 10, changed[i]);
	i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;

	// overrides
	assert.notEqual(original[i], changed[i]); i++;
	if (!original[i - 1])
	    // 0~21                                                                                               
	    assert.equal((original[i] + 1) % 22, changed[i]);
	i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	if (!original[i - 1]) {
	    assert.equal((original[i] + 1) % 10, changed[i]); i++;
	    assert.equal((original[i] + 1) % 10, changed[i]); i++;
	}
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	if (!original[i - 1]) {
	    assert.equal((original[i] + 1) % 10, changed[i]); i++;
	    assert.equal((original[i] + 1) % 10, changed[i]); i++;
	    assert.equal((original[i] + 1) % 10, changed[i]); i++;
	}
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	if (!original[i - 1])
	    assert.equal((original[i] + 1) % 9, changed[i]);
	i++;

    });
    
});




<|start_filename|>tests/automation/source-maps/internal/scripts/script.closure.js<|end_filename|>
document.getElementById("color").focus();$(document).keydown(function(a){13==a.keyCode&&$("body").css("background-color",$("#color").val())});
//@ sourceMappingURL=script.closure.js.map

<|start_filename|>tests/automation/plugin/mocha_test.js<|end_filename|>
var path = require('path');
var assert = require('assert');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');

describe('Plugin', function() {

  describe('flash', function(){

  var server, child, result = false;

  before(function(done) {
    server = createTCPServer(13013);
    child = spawnChildProcess(path.join(curDir, 'flash'));
    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        result = true;
        child.kill();
        done();
      });
    });

  });
    
  after(function () {
        server.close();
  });

    it('should not crash', function() {

      assert.equal(result, true);

    });

  });

});




<|start_filename|>tests/automatic_tests/crashonreload/mocha_test.js<|end_filename|>
var spawn = require('child_process').spawn;
var path = require('path');
var app_test = require('./nw_test_app');
describe('crash on reload',function(){
  it('nw should not crash when reloading with devtool opened',function(done){
    this.timeout(0);
    var result = false;
    var exec_argv = [path.join(global.tests_dir, 'crashonreload')];

    var app = spawn(process.execPath, exec_argv);
      app.on('exit', function (code){
      if (code != 0) return done('nw crashes');
        result = true;
        done();
      });
    setTimeout(function(){
        if (!result) {
          app.kill();
          done();
        }
    }, 7500);
  })
})

<|start_filename|>tests/automation/proxy/export.bat<|end_filename|>
reg export "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" c:\test.reg

<|start_filename|>tests/automatic_tests/node/node_modules/module3/test.js<|end_filename|>
exports.test = function() {
  return "module3";
}


<|start_filename|>tests/automation/crashonreload/mocha_test.js<|end_filename|>
var spawn = require('child_process').spawn;
var path = require('path');
var fs = require('fs');
var curDir = fs.realpathSync('.');

describe('crash on reload',function(){
  it('nw should not crash when reloading with devtool opened',function(done){
    this.timeout(0);
    var result = false;

    var child = spawnChildProcess(path.join(curDir, 'internal'));
    child.on('exit', function (code){
      result = true;
      if (code != 0) {
        done('nw crashes');
        child.kill();
      } else {
        done();
      }

    });

    setTimeout(function(){
        if (!result) {
          child.kill();
          done();
        }

    }, 4500);
  });
});


<|start_filename|>tests/automation/loaded_event/mocha_test.js<|end_filename|>
var path = require('path');
var assert = require('assert');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');

describe('loaded event', function() {

  var server, child, result = false;

  before(function(done) {
    server = createTCPServer(13013);
    done();
  });
    
  after(function () {
        server.close();
  });

    it('loaded event can been fired',
	  function(done) {
        this.timeout(0);

    child = spawnChildProcess(path.join(curDir, 'internal'));
    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        result = true;
        child.kill();
        done();
      });
    });

        setTimeout(function(){
          if (!result) {
            child.close();
            //child.app.kill();
            //child.removeConnection();
            done('loaded evenet does not been fired');
          }
        }, 3000);
        //child.app.stderr.on('data', function(d){ console.log ('app' + d);});

    })


})



<|start_filename|>tests/automation/nw_fork/mocha_test.js<|end_filename|>
var path = require('path');
var assert = require('assert');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');

var result = false;
describe('fork()',function(){

	var child, server, result;

	before(function(done){
		this.timeout(0);
        server = createTCPServer(13013);
        child = spawnChildProcess(path.join(curDir, 'internal'));

    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        result = JSON.parse(data+'');
      });
    });

		child.on('exit',function(){
			done();
		});


	});

	after(function(done){
		server.close();
		child.kill();
		done();
	});



	it("child_process.fork() should have a workaround solution",function(done){
		assert.equal(result,true);
		done();
	});
	
});



<|start_filename|>tests/automation/reload_application/mocha_test.js<|end_filename|>
var assert = require('assert');
var spawn = require('child_process').spawn;
var path = require('path');
var net = require('net');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');

var cb;

describe('AppTest', function(){

  describe('reload app (long-to-run)', function(){


  var server;

  before(function(done) {
    server = createTCPServer(13013);
	done();
  });
    
  after(function () {
        server.close();
  });

    afterEach(function(){
      try {
        server.removeAllListeners('connection');
      } catch (e) {
      }

    });



    var spawnChild = function(type) {
      return spawn(process.execPath, [path.join(curDir, 'internal'), type]);
    };


    it('close window after reload', function(done){
      this.timeout(0);
      var result = false;

      var app = spawnChild(0);
      app.on('exit', function (code){
      if (code != 0) return done('error');
        result = true;
        done();
      });

      setTimeout(function(){
        if (!result) {
          app.kill();
          done("Timeout, Can not close window.");
        }
      }, 30000);

    });



    it('quit app after reload', function(done){
      this.timeout(0);
      var result = false;
      var app = spawnChild(1);
      app.on('exit', function (code){
        if (code) {
          done('error: the error code is: ' + code);
        } else {
          result = true;
          done();
        }
      });

      setTimeout(function(){
        if (!result) {
          app.kill();
          done("Timeout, Can not quit App.");
        }
      }, 30000);


    });


    it('close window after reload dev', function(done){
      this.timeout(0);
      var times = 0;
      var result = false;

      server.on('connection', cb = function(socket){

        //console.log('client connect in 1');
        socket.setEncoding('utf8');
        socket.on('error', function(er) {
          //console.log(er);
        });
        socket.on('data', function(data){
          if (data == 'open'){
            if (times == 0){
              times += 1;
              socket.write('reload');
            } else if (times == 1){
              socket.write('quit');
            }

          }// if(data == 'open')

        });
      });

        var app = spawnChild(2);

        app.on('exit', function (code){
        if (code) {
          done('error: the error code is: ' + code);
        } else {
          result = true;
          done();
        }
        });


      setTimeout(function(){
        if (!result) {
          app.kill();
          done("Timeout, Can not close window.");
        }
      }, 30000);


    });


   it('quit app after reload dev', function(done){
      this.timeout(0);
      var times = 0;
      var result = false;

      server.on('connection', cb = function(socket){
        socket.on('error', function(er) {
          //console.log(er);
        });
        //console.log('client connect');
        socket.setEncoding('utf8');
        socket.on('data', function(data){
          if (data == 'open'){

            if (times == 0){
              times += 1;
              socket.write('reload');
            } else if (times == 1){
              socket.write('quit');
            }

          }// if(data == 'open')

        });
      });

        var app = spawnChild(3);

        app.on('exit', function (code){
          if (code != 0) return done('error');
          result = true;
          done();
        });


      setTimeout(function(){
        if (!result) {
          app.kill();
          done("Timeout, Can not quit App.");
        }
      }, 30000);


    });




  });

});





<|start_filename|>tests/automatic_tests/show_devtool_after_http_server_created_in_node_main/package.json<|end_filename|>
{
  "name": "server",
  "description": "server",
  "version": "0.1",
  "nodejs":true,
  "node-main": "main.js",
  "main": "index.html",
  "window": {
    "show": false,
    "toolbar": true,
    "fullscreen":false

    }
}

<|start_filename|>tests/automation/mocha_test.js<|end_filename|>
var fs = require('fs');
var path = require('path');
var child_process = require('child_process');
var colors = require('colors');
//var toMarkdown = require('to-markdown').toMarkdown;

var g_quiet = false;
var g_outputDir;
var g_outputLog;
var g_format;

function print(str, err) {
  if (!g_quiet) {
    if (err) {
      console.error(str);
    } else {
      console.log(str);
    }
  }
  if (g_outputLog) {
    fs.appendFile(g_outputLog, str + '\n');
  }
}

function preTest() {
  print(colors.green('==============='));
  print(colors.green('Begin testing'));
  print(colors.green('==============='));
}

function postTest() {
  print(colors.green('==============='));
  print(colors.green('End testing'));
  print(colors.green('==============='));

  if (g_format === 'markdown' && fs.existsSync(g_outputDir)) {
    // convert xml to md for better reading
    var subFiles = fs.readdirSync(g_outputDir);
    for (var i = 0, len = subFiles.length; i < len; i++) {
      var filePath = subFiles[i];
      if (path.extname(filePath) === '.xml') {
        var conent = fs.readFileSync(path.join(g_outputDir, filePath));
        content = encodeURIComponent(conent);
        var mdData = toMarkdown(content);
        fs.writeFileSync(path.join(g_outputDir, path.basename(filePath)+'.md'), mdData);
      }
    }
  }
}

function performTests(config) {

  g_quiet = config.quiet;

  var curPath = fs.realpathSync('.');
  if (!fs.existsSync('output'))
    fs.mkdirSync('output');
  g_outputDir = path.join(curPath, 'output', (new Date()).toUTCString());
  if (!fs.existsSync(g_outputDir))
    fs.mkdirSync(g_outputDir);
  g_outputLog = path.join(g_outputDir, 'summary.log');
  print('The test results will output to : ' + colors.underline(g_outputDir) + '\n');
 
  var subDirs = fs.readdirSync(curPath);
  var testSuites = [];
  var isExcluded = function(testsuite) {
    for (var i = 0, len = config.exclude.length; i < len; i++) {
      if (config.exclude[i] === testsuite)
        return true;
    }
    return false;
  };

  if (config.single && config.single !== '' && fs.existsSync(path.join(curPath, config.single))) {
    testSuites.push(config.single);
  } else {
    for (var i = 0, len = subDirs.length; i < len;  i++) {
      var subDir = subDirs[i];
      var status = fs.statSync(path.join(curPath, subDir));
      if (status && status.isDirectory() && !isExcluded(subDir)) {
        testSuites.push(subDir);
      }
    }
  }

  /* ============ running test cases ================ */
  if (testSuites.length === 0) {
    print('No test cases are found in ' + curPath);
    return;
  }
  preTest();
  g_format = config.format;
  var arg_timeout = config.timeout ? ['--timeout', config.timeout] : [];
  var arg_slow = config.slow ? ['--slow', config.slow] : [];
  var argv = undefined;
  var cmd = undefined;
  var child = undefined;
  var env = process.env;
  var timerId = undefined;
  var children = [];

  var timeout = parseInt(config.timeout);
  if (Number.isNaN(timeout) || timeout <= 0)
    timeout = 5000;

  env['out_dir'] = g_outputDir;

  var spawTestProcessByNW = function(testcase) {
    cmd = 'nw';
    argv = [testcase];
    print('Running: ' + colors.underline(testcase));
    child = child_process.spawn(cmd, argv, {env: env});
    child.testcase = testcase;
    return child;
  };

  var spawTestProcessByMocha = function(testcase) {
    cmd = 'mocha';
    argv = [testcase + path.sep + 'mocha_test'].concat(['-R', 'xunit-file'])
      .concat(arg_timeout).concat(arg_slow);
    env['XUNIT_FILE'] = path.join(g_outputDir, testcase + '.xml');
    print('Running:' + colors.underline(testcase));
    child = child_process.spawn(cmd, argv, {env: env});
    child.testcase = testcase;
    return child;
  };

  var curIdx = -1;
  var curChildProcess = undefined;
  var prefix;

//  for (var i =0, len = testSuites.length; i < len; i++ ) {
//    console.log('Test suite ' + i + ':' + testSuites[i]); 
//  }

  var runNextTestByNW = function() {
    curIdx += 1;
    if (curIdx < testSuites.length) {
      resetTimeout(curIdx);
      curChildProcess = spawTestProcessByNW(testSuites[curIdx]);
      children.push(curChildProcess);
      curChildProcess.on('exit', function(code, signal) {
        (function(p, c) {
          prefix = (code === 0 ? colors.green('[Success]') : colors.red('[Failure]'));
          print(prefix + ' : ' + colors.underline(p.testcase) + ' with exit code ' + c);
          clearTimeout(timerId);
          p.removeAllListeners('exit');
          p.kill('SIGKILL');
          runNextTestByNW();
        })(curChildProcess, code);
      });
    } else {
      if (timerId) {
        clearTimeout(timerId);
        timerId = undefined;
      }
      postTest();
    }
  };

  var resetTimeout = function(idx) {
    if (timerId)
      clearTimeout(timerId);
    (function(idx){

    timerId = setTimeout(function() {

      timerId = undefined;
      if (idx || idx >= 0) {
        var p = children[idx];
        print(colors.yellow('[Timeout]') + ' : ' + colors.underline(p.testcase));
        p.removeAllListeners('exit');
        p.kill('SIGKILL');  // 'SIGKILL', 'SIGTERM'
        p = undefined;
        runNextTestByNW();
      }
     }, timeout);

    })(idx);

  };

  runNextTestByNW();

}   // end of performTests()

var content = fs.readFileSync('./config.json');
if (content)
  performTests(JSON.parse(content));
else
  print('Failed to read configuration.', true);




<|start_filename|>tests/manual_tests/custom_tray_menu/package.json<|end_filename|>
{
  "main": "index.html",
  "name": "nw-test",
  "description": "test app",
  "window": {
    "title": "My Node-Webkit App",
    "icon": "icon.png",
    "toolbar": false,
    "frame": true,
    "width": 800,
    "height": 500,
    "always-on-top": false,
    "kiosk": false,
    "fullscreen": false,
    "show": false,
    "show_in_taskbar": false,
    "resizable": true
  },
  "webkit": {
    "plugin": false,
    "java": false,
    "page-cache": false
  }
}

<|start_filename|>tests/automatic_tests/user-agent/mocha_test.js<|end_filename|>
var assert = require('assert');
var fs = require('fs');
var app_test = require('./nw_test_app');
var path = require('path');
var results;
describe('user-agent', function() {
    before(function(done) {
	this.timeout(0);
	var child = app_test.createChildProcess({
	    execPath: process.execPath, 
	    appPath: path.join(global.tests_dir, 'user-agent'), 
	    end: function(data, app) {
		results = data;
		app.kill();
		done();
	    }
	});
    });
    
    describe('user-agent with child window opened', function() {
	it('should be same to the one in parent window', function() {
	    assert.equal(results[0], results[1]);
	});
    });
    
    describe('user-agent with reload', function() {
	it('should be same with all reload method', function() {
	    assert.equal(results[0], results[2]);
	    assert.equal(results[0], results[3]);
	    assert.equal(results[0], results[4]);
	    assert.equal(results[0], results[5]);
	});
    });
    
    describe('user-agent with package.json', function() {
	var user_agent = navigator.userAgent.split('/');
	var package_info = JSON.parse(fs.readFileSync('package.json', 'utf8'));
	it('name should be same to the one in package.json',
	   function() {
	       assert.equal(user_agent[0], package_info.name);
	   });
	
	it('version should be same to the one in package.json',
	   function() {
	       assert.equal(user_agent[2], package_info.version);
	   });
    });
})


<|start_filename|>tests/automation/remote-img/mocha_test.js<|end_filename|>
var path = require('path');
var spawn = require('child_process').spawn;
var fs = require('fs-extra');
var os = require('os');
var platform = os.platform();
var curDir = fs.realpathSync('.');

var result, app, exec_argv, timerId;

process.on('exit', function() {
  if (app) {
    app.kill('SIGKILL');
  }
});

describe('remote-file-access', function(){

	before(function(done){
		this.timeout(0);
		if(platform == "win32"){
			fs.copySync(path.join(curDir, 'star.jpg'),'/star.jpg');
		}
		else {
			fs.copySync(path.join(curDir, 'star.jpg'),'/tmp/star.jpg');
		}
		done();
	});

	after(function(done) {
		this.timeout(0);
		if (platform == "win32"){
			fs.unlinkSync('/star.jpg');
		}
		else {
			fs.unlinkSync('/tmp/star.jpg');
		}
        done();
	  });


	it ('remote img should work', function(done){
		this.timeout(0);
		exec_argv = [path.join(curDir, 'imgnotshown')];
		result  =false;
		app = spawn(process.execPath, exec_argv);
		app.on('exit', function(code){

            clearTimeout(timerId);
			result = true;
            app.kill('SIGKILL');
            app = undefined;
			done();
		});

		timerId = setTimeout(function(){
			if(!result){
                app.removeAllListeners('exit');
				app.kill('SIGKILL');
                app = undefined;
				done();
			}
		}, 2000);
	});


	it ('local img should work', function(done){
		this.timeout(0);
		exec_argv = [path.join(curDir, 'imgshown')];
		result = false;
		app = spawn(process.execPath, exec_argv);
		app.on('exit', function(code){
            clearTimeout(timerId);
			result = true;
            app.kill('SIGKILL');
            app = undefined;
			done();
		});

		timerId=setTimeout(function(){
			if(!result){
                app.removeAllListeners('exit');
				app.kill('SIGKILL');
                app = undefined;
				done();
		    }
		}, 2000);

	});


});




<|start_filename|>tests/automation/inject-js/mocha_test.js<|end_filename|>
var path = require('path');
var assert = require('assert');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');


describe('inject-js',function(){

  var server, child, result;

  before(function(done) {
    this.timeout(0);
    server = createTCPServer(13013);
    child = spawnChildProcess(path.join(curDir, 'internal'));
    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        result = JSON.parse(data);
        child.kill();
        done();
      });
    });

  });
    
  after(function () {
        server.close();
  });
	

	it('result.length should equal 4',function(done){
		assert.notEqual(result,null);
		assert.equal(result.length,4);
		done();
	});
	it('inject-js-start should run first',function(done){
		assert.equal(result[0],'inject-js-start');
		done();
	});
	it('document script should run after inject-js-start',function(done){
		assert.equal(result[1],'script-start');
		done();
	});
	it('inject-js-end should before window.onload',function(done){
		assert.equal(result[2],'inject-js-end');
		done();
	});
	it('inject-js-start should run last',function(done){
		assert.equal(result[3],'onload');
		done();
	});
});




<|start_filename|>tests/automation/after_close_previous_window_then_open_new/mocha_test.js<|end_filename|>
var path = require('path');
var app_test = require('../../nw_test_app');
var assert  =require('assert');
var fs = require('fs');
var fs_extra = require('fs-extra');
var spawn = require('child_process').spawn;
var global = require('../globals');
var result;

var dumpDir = path.join(global.tests_dir, 'internal', 'tmp');
console.log('dumpDir:' + dumpDir);

describe('after close previous window then open new', function() {
    after(function () {
    	fs_extra.remove(dumpDir, function (er) {
            if (er) throw er;
        });
    });

    before(function(done) {
      this.timeout(0);
      if (!fs.existsSync(dumpDir))
	    fs.mkdirSync(dumpDir);

      var appPath = path.join(global.tests_dir, 'internal');

	  var exec_argv = [appPath];
      app = spawn(process.execPath, exec_argv);
      setTimeout(function() {
        done();
      }, 2000);
    });

    it('should not crash', function() {
      result = fs.readdirSync(dumpDir);	
      assert.equal(result.length, 0);
    });

});


<|start_filename|>tests/automation/source-maps/internal/scripts/script.coffee.coffee<|end_filename|>
document.getElementById("color").focus()

$(document).keydown (evt) ->
  if evt.keyCode == 13
    $("body").css("background-color", $("#color").val())


<|start_filename|>tests/automation/chromedriver2_server/mocha_test.js<|end_filename|>
var assert = require('assert');
var exec = require('child_process').exec;
var fs = require('fs-extra');
var path = require('path');
var curDir = fs.realpathSync('.');
var func = require(path.join(curDir, '..', 'start_app', 'script.js'));
var is_chromedriver_exists = false;
var result = [];
var tmpnwPath = path.join(curDir, 'tmp-nw');

describe('chromedriver2_server', function() {
  this.timeout(0);

  before(function(done) {
    var srcFile;
    var dstFile;
    if (process.platform == 'win32'){
      srcFile = path.join(curDir, 'chromedriver2_server.exe');
      dstFile = path.join(curDir, 'tmp-nw', 'chromedriver2_server.exe');
    } else {
      srcFile = path.join(curDir, 'chromedriver2_server');
      dstFile = path.join(curDir, 'tmp-nw', 'chromedriver2_server');
    }
    if (!fs.existsSync(srcFile)) {
      is_chromedriver_exists = false;
      done();
    } else {
      func.copyExecFiles(function() {
        fs.copySync(srcFile, dstFile);
		exec('python ' + path.join(curDir, 'chromedriver2_server_test.py'),
		  function (error, stdout, stderr) {
			result.push(error);
			result.push(stdout);
			result.push(stderr);
			done();
		 });  // exec
      });  // copyExecfiles
    }

  });

  after(function () {
    if (fs.existsSync(tmpnwPath)) {
      fs.removeSync(tmpnwPath);
    }
  });

  it('should work' ,function(done) {
	if (!is_chromedriver_exists) {
	  done('chromedrier2_server does not exist');
    } else {
      assert.equal(result[0], null);
      assert.equal(result[1], 'pass\n');
      assert.equal(result[2], '');
      done();
	}
  });

});




<|start_filename|>tests/automatic_tests/crash_dump/mocha_test.js<|end_filename|>
var path = require('path');
var app_test = require('./nw_test_app');
var assert = require('assert');
var fs = require('fs');
var fs_extra = require('fs-extra');
var results;
describe('crash dump', function() {
    before(function(done) {
	fs.mkdirSync('./automatic_tests/crash_dump/tmp');
	done();
    });
    
    after(function () {
    	fs_extra.remove('./automatic_tests/crash_dump/tmp', function (er) {
            if (er) throw er;
    	});
    });

    describe('crashBrowser()', function() {
	before(function(done) {
	    this.timeout(0);
	    var child = app_test.createChildProcess({
		execPath: process.execPath,
		appPath: path.join(global.tests_dir, 'crash_dump'),
		args:[0],
		end: function(data, app) {
		    setTimeout(function() {
			result = fs.readdirSync('./automatic_tests/crash_dump/tmp');
			done();
		    }, 2000);
		}
	    });
	});

	it('should work fine', function() {
	    assert.equal(result.length, 1);
	    var r = result[0].indexOf("dmp");
	    assert.notEqual(r, -1);
	});
	
    })

    describe('crashRenderer()', function() {
	before(function(done) {
	    this.timeout(0);
	    var child = app_test.createChildProcess({
		execPath: process.execPath,
		appPath: path.join(global.tests_dir, 'crash_dump'),
		args:[1],
		end: function(data, app) {
		    setTimeout(function() {
			result = fs.readdirSync('./automatic_tests/crash_dump/tmp');
			done();
		    }, 2000);
		}
	    });
	});

	it('should work fine', function() {
	    assert.equal(result.length, 2);
	    var r = result[1].indexOf("dmp");
	    assert.notEqual(r, -1);
	});
    })

   describe('App.setCrashDumpDir(dir)', function() {
       	before(function(done) {
	    this.timeout(0);
	    result = fs.readdirSync('./automatic_tests/crash_dump/tmp');
            done();
	});

	it('should work fine', function() {
	    assert.equal(result.length, 2);
	});
    })
	

});


<|start_filename|>tests/automation/user-agent/internal/package.json<|end_filename|>
{
  "name": "nw-user-agent-test",
  "main": "index.html", 
  "user-agent": "%name/%nwver/%ver/%webkit_ver/%osinfo"	
}


<|start_filename|>tests/automation/quit_with_secondary_window_on_top/internal/index.html<|end_filename|>
<!DOCTYPE html>
<html>
  <head>
    <title>quit_with_secondary_window_on_top!</title>
  </head>
  <body>
    <h1>quit_with_secondary_window_on_top!</h1>
    with the created new window on top, hit CMD-Q or select Menu > Quit
    <script>
      var gui = require('nw.gui');
      var win1 = gui.Window.open('index1.html');
      setTimeout(function() {
         win1.focus();
      }, 1000);
    </script>.
  </body>
</html>


<|start_filename|>tests/automation/source-maps/internal/styles/style.css<|end_filename|>
@media -sass-debug-info{filename{font-family:file\:\/start\/styles\/style\.sass}line{font-family:\000034}}
body {
  background-color: #d9d9d9; }

@media -sass-debug-info{filename{font-family:file\:\/start\/styles\/style\.sass}line{font-family:\000037}}
input {
  background-color: rgba(255, 255, 255, 0.5);
  border: 0;
  display: block;
  font-size: 3em;
  margin: 15% auto;
  outline: none;
  padding: 0.4em;
  width: 20%; }

@media only screen and (max-width: 600px) {
@media -sass-debug-info{filename{font-family:file\:\/start\/styles\/style\.sass}line{font-family:\0000318}}
  input {
    font-size: 2em;
    width: 40%; } }


<|start_filename|>tests/automation/calls_across_window/mocha_test.js<|end_filename|>
var fs = require('fs');
var path = require('path');
var global = {tests_dir: fs.realpathSync('.')};

describe('AppTest', function(){
  describe('call across window', function(){
    var child;
    var server;
    var exec_argv;
    var socket;

    before(function(done){
      this.timeout(0);
      server = createTCPServer(13013);
      server.on('connection', function(theSocket) {
        socket = theSocket;
        socket.setEncoding('utf8');
        done();
      });
      exec_argv = path.join(global.tests_dir, 'internal');
      child = spawnChildProcess(exec_argv);
    });

    after(function(done){
      this.timeout(0);
      child.kill();
      server.close();
      done();
    });

    afterEach(function(){
      socket.removeAllListeners('data');
    });

    it ('nw window function call', function(done) {
      socket.on('data', function(data) {
        if (data == 'ok') {
          done();
        } else {
          done(data);
        }
      });
      socket.write('newWindow');
    });

    it ('brower window function call', function(done) {
      socket.on('data', function(data) {
        if (data == 'ok') {
          done();
        } else {
          done(data);
        }
      });
      socket.write('newBrowserWindow');
    });
  });
});




<|start_filename|>tests/automation/chromium-args/internal/package1.json<|end_filename|>
{
  "name": "nw-chromium-args",
  "main": "index.html",
  "window": {
    "show": false
  },
  "chromium-args": "--disable-javascript"
  
}


<|start_filename|>tests/automatic_tests/node/node_modules/module3/module2.js<|end_filename|>
exports.test = function() {
  return "module2";
}



<|start_filename|>tests/automatic_tests/temp_dir/mocha_test.js<|end_filename|>
var func = require('./' + global.tests_dir +'/start_app/script.js');
var execPath = func.getExecPath();
var fs = require('fs-extra');
var os = require('os');
var cp = require('child_process');
var app_test = require('./nw_test_app');
var current_path = process.cwd();
var mac_app_path = path.join('tmp-nw', 'node-webkit.app');
var assert = require('assert');
var temp_path;
var execPath;

if (os.platform() == 'win32') {
    execPath = path.join('tmp-nw', 'app.exe');
}
if (os.platform() == 'linux') {
    execPath = path.join('tmp-nw', 'app');
}
if (os.platform() == 'darwin') {
    execPath = path.join('tmp-nw', 'node-webkit.app', 'Contents', 'MacOS', 'node-webkit');
}

function make_execuable_file(folder_path, done) {
    func.copyExecFiles(function() {
	func.copySourceFiles(folder_path); 
	func.zipSourceFiles(function() {
	    func.makeExecuableFile();
	    if (os.platform() == 'darwin') {
		var app_path = 'tmp-nw/node-webkit.app/Contents/Resources/app.nw';
		fs.mkdir(app_path, function(err) {
		    if(err && err.code !== 'EEXIST') throw err
		    fs.copy('tmp-nw/index.html', path.join(app_path, 'index.html'));
		    fs.copy('tmp-nw/package.html', path.join(app_path, 'package.html'));
		    setTimeout(done, 3000);

		});
	    } else {
		setTimeout(function() {
		    var child = cp.spawn(execPath, [current_path]);
		    child.on('exit', function() {
			temp_path = path.dirname(fs.readFileSync(path.join('tmp-nw','path.org'))).substring(8);
			done();
		    });
		}, 3000);
	    }
	});
    });
}

describe('temp_dir', function() { 
    this.timeout(0);

    before(function(done) {
	make_execuable_file('temp_dir', done);
    });

    after(function() {
    	fs.remove('tmp-nw', function (er) {
            if (er) throw er;
        });
    });

    it('should be removed after app exit', function() {
	var exist = fs.existsSync(temp_path);
	assert.equal(exist, false);
    });
});


<|start_filename|>tests/automatic_tests/window/mocha_test.js<|end_filename|>
var path = require('path');
var app_test = require('./nw_test_app');
var assert = require('assert');
var window_counts = 3;
var results;

describe('window', function() {
    this.timeout(0);
    before(function(done) {
	this.timeout(0);
	var child = app_test.createChildProcess({
	    execPath: process.execPath,
	    appPath: path.join(global.tests_dir, 'window'),
	    end: function(data, app) {
		results = data;
                app.kill();
                done();
	    }
	});

    });
    describe('focus()', function() {
	it('should focus on the window', function() {
	    for (var i = 0; i < window_counts; i++)
		assert.notEqual(results[i], 0)
	});
    })
})
	 


<|start_filename|>tests/automation/reference_xhr_in_node_context/internal/test.js<|end_filename|>
exports.xhr = function () {
    global.xhr.onreadystatechange = function() {
        if (global.xhr.readyState === 4 && global.xhr.status === 200) {
        }
    }
    global.xhr.onload = function(e) {
        var uInt8Array = new Uint8Array(this.response); // this.response == uInt8Array.buffer                                                                                     
        // var byte3 = uInt8Array[4]; // byte at offset 4                                                                                                                         
    };

}

<|start_filename|>tests/manual_tests/autocomplete/index.html<|end_filename|>
<html>
    <body>
        <p>
            <h3>Test case for GitHub issue #434<br>(lack of autocomplete if "id" or "name" attribute is used for input tag)</h3>
        </p>
        <p>
            Please type letter "b" in this input field, it should present an autocomplete list with "Bart" entry in it. 
            <input name="element-name" id="element-id" type="text" list="characters" style="width:400px" autofocus>
            <datalist id="characters">
                <option value="<NAME>">
                <option value="Bart">
                <option value="<NAME>">
            </datalist>
        </p>
    </body>
</html>


<|start_filename|>tests/automatic_tests/remote-img/mocha_test.js<|end_filename|>
var path = require('path');
var spawn = require('child_process').spawn;
var fs = require('fs-extra');
describe('remote-file-access', function(){
	var os = require('os');
	var platform = os.platform();
	before(function(done){
		this.timeout(0);
		if(platform == "win32"){
			fs.copy(global.tests_dir+'/remote-img/star.jpg','/star.jpg');
		}
		else {
			fs.copy(global.tests_dir+'/remote-img/star.jpg','/tmp/star.jpg');
		}
		done();
	})
	after(function() {
		this.timeout(0);
		if (platform == "win32"){
			fs.remove('/star.jpg');
		}
		else {
			fs.remove('/tmp/star.jpg');
		}
	  })
	it ('remote img should work', function(done){
		this.timeout(0);
		var exec_argv = [path.join(global.tests_dir, 'remote-img/imgnotshown')]
		var result  =false;
		var app = spawn(process.execPath, exec_argv);
		app.on('exit', function(code){
			result = true;
			done();
		})
		setTimeout(function(){
			if(!result){
				app.kill();
				done();
			}
		}, 3000)
	})
	it ('local img should work', function(done){
		this.timeout(0);
		var exec_argv = [path.join(global.tests_dir, 'remote-img/imgshown')]
		var result = false;
		var app = spawn(process.execPath, exec_argv);
		app.on('exit', function(code){
			result = true;
			done();
		})
		setTimeout(function(){
			if(!result){
				app.kill();
				done();
				}
		}, 3000)
	})
})

<|start_filename|>tests/automation/window/mocha_test.js<|end_filename|>
var path = require('path');
var assert = require('assert');

describe('window', function() {
    this.timeout(0);
    before(function(done) {
	this.timeout(0);


    var checkDone = function() {
      if (test_done) {
        done();
      } else {
        setTimeout(function() {checkDone();}, 2000);;
      }
    };

    checkDone();

    });

    describe('focus()', function() {
	it('should focus on the window', function() {
	    for (var i = 0; i < 3; i++) {
          console.log('win_c['+i+'] = '+ win_c[i]);
          assert.notEqual(win_c[i], "0");
        }
	});
    });
});


<|start_filename|>tests/automation/globals.js<|end_filename|>
var fs = require('fs');

exports.tests_dir = fs.realpathSync('.');




<|start_filename|>tests/automation/user-agent-app/internal/package.json<|end_filename|>
{
  "name": "user agent app",
  "main": "index.html",
  "user-agent": "%name/%nwver/%ver/%webkit_ver/%osinfo"
}

<|start_filename|>tests/automation/filevalue/mocha_test.js<|end_filename|>

var path = require('path');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');

describe('file input',function(){
  describe('set value',function(){

  var server;

  before(function(done) {
    server = createTCPServer(13013);
	done();
  });
    
  after(function () {
        server.close();
  });

    it('the value should be set without exception',function(done){
      this.timeout(0);
      var child = spawnChildProcess(path.join(curDir, 'internal'));

    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        setTimeout(function() {
          child.kill();
          if (data == 'mytestfile')
            done();
          else 
            done('the value of the file input is not set correctly');
        }, 2000);
      });
    });

    });

  });

});




<|start_filename|>tests/manual_tests/visible_on_all_workspaces/package.json<|end_filename|>
{
    "name": "nw-always-on-visible-workspace-test",
    "main": "index.html",
    "window": {
        "visible-on-all-workspaces": true
    },
    "dependencies": {}
}


<|start_filename|>tests/automation/source-maps/internal/scripts/script2.js<|end_filename|>
// on load, put focus on the input
document.getElementById("color").focus();

$(document).keydown(function(evt) {

  // only if the user keypress is ENTER
  if (evt.keyCode == 13) {
    // css color names and hex code
    $("body").css("background-color", $("#color").val());
  }

});

<|start_filename|>tests/automation/single_instance/mocha_test.js<|end_filename|>
var path = require('path');
var os = require('os');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');

var func = require(path.join(curDir, '..', 'start_app', 'script.js'));
var execPath = func.getExecPath();

var spawn = require('child_process').spawn;
var exec = require('child_process').exec;

var app =  new Array();
var child1, child2;
var mac_app_path = path.join(curDir, 'tmp-nw', 'node-webkit.app');

function make_execuable_file(folder_path, done) {
    func.copyExecFiles(function() {
	func.copySourceFiles(folder_path); 
	func.zipSourceFiles(function() {
	    func.makeExecuableFile();
	    if (os.platform() == 'darwin') {
		var app_path = 'tmp-nw/node-webkit.app/Contents/Resources/app.nw';
		fs.mkdir(app_path, function(err) {
		    if(err && err.code !== 'EEXIST') throw err
		    fs.copy('tmp-nw/index.html', path.join(app_path, 'index.html'));
		    fs.copy('tmp-nw/package.html', path.join(app_path, 'package.html'));
		});
	    }
	    done();
	});
    });
}

function check_have(i, cmd, options, msg, last, done) {
    var result = false;
    app[i] = spawn(cmd, options);
    app[i].on('exit', function() {
	result = true;
    });
    
    if (last == 2) {
	setTimeout(function() {
	    if (result) {
		done();
	    } else {
		done(msg);
	    }
	    app[i].kill();
	    app[i - 1].kill();
	}, 3000);
    } else {
	setTimeout(function() {
	    if (result) {
		done(msg);
	    } else {
		done();
	    }
	    if (last == 1) {
		app[i].kill();
		app[i - 1].kill();
	    }
	}, 3000);
    }
}

describe('single-instance', function() { 
    this.timeout(0);

/////// 1 
    describe('single-instance false', function() {
	before(function(done) {
	    make_execuable_file(path.join(curDir, 'mul'), done);
	});

        after(function() {
	    fs.remove(path.join(curDir, 'tmp-nw'), function (er) {
                    if (er) throw er;
            });
        });

	it('should have a instance', function(done) {
	    check_have(0, execPath, "", 'not have a instance', 0, done);
	});

	it('should have a second instance', function(done) {
	    check_have(1, execPath, "", 'not have a second instance', 1, done);
	});
    });

//////////////// 2
    describe('single-instance default', function() {

	before(function(done) {
	    setTimeout(function() {
		make_execuable_file(path.join(curDir, 'single'), done);
	    }, 3000);
	});

        after(function() {
	    fs.remove(path.join(curDir, 'tmp-nw'), function (er) {
                    if (er) throw er;
            });
        });

	it('should have a instance', function(done) {
	    check_have(2, execPath, "", 'not have a instance', 0, done);
	});

	it('should not have a second instance', function(done) {
	    check_have(3, execPath, "", 'have a second instance', 2, done);
	});
    });

/////////////////////// 3
    if (os.platform() == 'darwin') {
        describe('single-instance false(open app)', function(){
                before(function(done) {
                        setTimeout(function() {
                                make_execuable_file('single_instance/open_mul', done);
                            }, 3000);
                });

                after(function() {
                        fs.remove('tmp-nw', function (er) {
                                if (er) throw er;
                            });
                });

                it('should have a instance (open app)', function(done) {
                        child1 = exec('open ' + mac_app_path);
                        setTimeout(function () {
                                var content = fs.readFileSync('tmp-nw/msg');
                                if (content + "" != "")
                                    done();
                                else
                                    done("not have a instance");
                            }, 6000);
                });
                
                it('should not have a second instance (open app)', function(done) {
                        child2 = exec('open ' + mac_app_path);
                        var content = fs.readFileSync('tmp-nw/msg');
                        if (content + "" == "11")
                            done("have a second instance");
                        else
                            done();
                });

        });

        describe('single-instance default(open app)', function(){
                before(function(done) {
                        setTimeout(function() {
                                make_execuable_file('single_instance/open_single', done);
                            }, 3000);
                });

                after(function() {
                        fs.remove('tmp-nw', function (er) {
                                if (er) throw er;
                            });
                });

                it('should have a instance (open app)', function(done) {
                        child1 = exec('open ' + mac_app_path);
                        setTimeout(function () {
                                var content = fs.readFileSync('tmp-nw/msg_s');
                                if (content + "" != "")
                                    done();
                                else
                                    done("not have a instance");
                            }, 6000);
                 });
                
                it('should not have a second instance (open app)', function(done) {
                        child2 = exec('open ' + mac_app_path);
                        var content = fs.readFileSync('tmp-nw/msg_s');
                        if (content + "" == "11")
                            done("have a second instance");
                        else
                            done();

                });
	    });
	}
});




<|start_filename|>tests/automation/source-maps/internal/scripts/script.jsmin-grunt.js<|end_filename|>

document.getElementById("color").focus();$(document).keydown(function(evt){if(evt.keyCode==13){$("body").css("background-color",$("#color").val());}});
//@ sourceMappingURL=script.jsmin-grunt.js.map

<|start_filename|>src/nw_package.h<|end_filename|>
// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy 
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef CONTENT_NW_SRC_NW_PACKAGE_H
#define CONTENT_NW_SRC_NW_PACKAGE_H

#include "base/basictypes.h"
#include "base/files/file_path.h"
#include "base/memory/scoped_ptr.h"
#include "base/files/scoped_temp_dir.h"

#include <string>

class GURL;

namespace base {
class DictionaryValue;
class FilePath;
}

namespace gfx {
class Image;
}

namespace nw {

using base::FilePath;
class Package {
 public:
  // Init package from command line parameters.
  Package();

  // Init package from specifed path.
  Package(FilePath path);
  ~Package();

  // Convert path to absoulte path.
  FilePath ConvertToAbsoutePath(const FilePath& path);

  // Get image from icon path.
  bool GetImage(const FilePath& path, gfx::Image* image);

  // Get startup url.
  GURL GetStartupURL();

  // Get app's name.
  std::string GetName();

  // Return if we enable node.js.
  bool GetUseNode();

  // Root path of package.
  FilePath path() const { return path_; }

  // If the package is extracting itself.
  bool self_extract() const { return self_extract_; }

  // Manifest root.
  base::DictionaryValue* root() { return root_.get(); }

  // Window field of manifest.
  base::DictionaryValue* window();

  // Manifest string.
  std::string package_string() { return package_string_; }

 private:
  bool InitFromPath();
  void InitWithDefault();
  bool ExtractPath();
  bool ExtractPackage(const FilePath& zip_file, FilePath* where);

  // Read chromium command line args from the package.json if specifed.
  void ReadChromiumArgs();

  // Read js flags from the package.json if specifed.
  void ReadJsFlags();

  // Convert error info into data url.
  void ReportError(const std::string& title, const std::string& content);

  // Root path of the package.
  FilePath path_;

  // Is it a standalone and self-extractable app?
  bool self_extract_;

  // The parsed package.json.
  scoped_ptr<base::DictionaryValue> root_;

  // The origin JSON string package.json.
  std::string package_string_;

  // Stored url for error page.
  std::string error_page_url_;

  // Auto clean our temporary directory
  base::ScopedTempDir scoped_temp_dir_;

  DISALLOW_COPY_AND_ASSIGN(Package);
};

}  // namespae nw

#endif  // CONTENT_NW_SRC_NW_PACKAGE_H


<|start_filename|>tests/automatic_tests/chromium-args/mocha_test.js<|end_filename|>
var assert = require('assert');
var cp = require('child_process');
var fs = require('fs');
var fs_extra = require('fs-extra');
var exec_path = process.execPath;
var app_path = path.join(global.tests_dir, 'chromium-args');
var app_test = require('./nw_test_app');

describe('chromium-args', function() {
    describe('--disable-javascript', function() {
    	before(function(done) {
    	    this.timeout(0);
	    fs_extra.copy(path.join(app_path, 'package1.json'), path.join(app_path, 'package.json'), function (err) {
		if (err) {
		    throw err;
		}
    		cp.exec(exec_path + " " + app_path, function(err, stdout, stderr) {
		})
    	    });
	    setTimeout(done, 2500);
    	});
	
    	it('javascript should not be executed', function() {
    	    var result = fs.existsSync(path.join(app_path, 'hi'));
    	    assert.equal(result, false);
    	});
	
    	after(function() {
    	    fs.unlink(path.join(app_path, 'hi'), function(err) {if(err && err.code !== 'ENOENT') throw err});
    	    fs.unlink(path.join(app_path, 'package.json'), function(err) {if(err && err.code !== 'ENOENT') throw err});
    	});
    });

    describe('--app=url', function() {
	var result2 = false;
    	before(function(done) {
    	    this.timeout(0);
	    fs_extra.copy(path.join(app_path, 'package2.json'), path.join(app_path, 'package.json'), function (err) {
		if (err) {
		    throw err;
		}
    		var child = app_test.createChildProcess({
		    execPath: exec_path,
		    appPath: app_path,
		    end: function(data, app) {
			result2 = data;
			app.kill();
			done()
		    }
		});
    	    });
    	});
	
    	it('website should be the url', function() {
    	    assert.equal(result2, true);
    	});
    
    	after(function() {
    	    fs.unlink(path.join(app_path, 'package.json'), function(err) {if(err && err.code !== 'ENOENT') throw err});
    	    fs.unlink(path.join(app_path, 'hi'), function(err) {if(err && err.code !== 'ENOENT') throw err});
    	});
    });

});


<|start_filename|>tests/automation/node/message_channel_test.js<|end_filename|>
exports.run = function(done) {
  var mc = new window.MessageChannel()
  mc.port1.onmessage = function(m) {
    done();
  }
  mc.port2.postMessage("HELLO");
}


<|start_filename|>tests/automation/window-eval/mocha_test.js<|end_filename|>
var path = require('path');
var assert = require('assert');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');


describe('Window.eval',function(){
  var server, child, result;

  before(function(done) {
    this.timeout(0);
    server = createTCPServer(13013);
    child = spawnChildProcess(path.join(curDir, 'internal'));
    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        result = (data.toString() == "success");
        child.kill();
        done();
      });
    });

  });
    
  after(function () {
        server.close();
  });

	it("Window.eval should works",function(done){
		assert.equal(result,true);
		done();
	});
});




<|start_filename|>tests/automatic_tests/app/mocha_test.js<|end_filename|>
var gui = require('nw.gui');
var assert = require('assert');
var app_test = require('./nw_test_app');

describe('gui.App', function() {
    before(function(done) {
	this.timeout(0);
	var child = app_test.createChildProcess({
	    execPath: process.execPath,
	    appPath: path.join(global.tests_dir, 'app'),
	    end: function(data, app) {
		app.kill();
		done();
	    }
	});
    });

    describe('manifest', function() {
	it('`gui.App.manifest` should equle to value of package.json', function() {
	    assert.equal(gui.App.manifest.name, 'nw-tests');       
	});
	
	it('have window', function() {
	    assert.equal(typeof gui.App.manifest.window, 'object');       
	});
	
	it('have main', function() {
	    assert.equal(typeof gui.App.manifest.main, 'string');
	    assert.equal(gui.App.manifest.main, 'index.html');
	});
	
	it('have dependencies', function() {
	    assert.equal(typeof gui.App.manifest.dependencies, 'object');       
	});
    });
    
    describe('clearCache()', function(done) {
	it('should clear the HTTP cache in memory and the one on disk', function() {
	    var res_save = global.local_server.res_save;
	    
	    assert.equal(res_save[1].status, 304);
	    assert.equal(res_save[1].pathname, 'img.jpg');
	    assert.equal(res_save[2].status, 200);
	    assert.equal(res_save[2].pathname, 'img.jpg');
	});
    });
})


<|start_filename|>tests/style.css<|end_filename|>
* {
  font-family: sans-serif;
}

div {
  margin-bottom: 3px;
}

button {
  height: 20px;
  margin-bottom: 5px;
}

.success {
  color: #AAA
}

.fail {
  color: black
}


<|start_filename|>tests/automation/sample/mocha_test.js<|end_filename|>
var assert = require('assert');

describe('sample-test', function() {

  beforeEach(function() {
    console.log('before each');
  });

  before(function() {
    console.log('before');
    //assert.ok(false);
  });

  describe('#indexOf()', function() {                                // unit test group 1
    it('should return -1 when value is not presenttt', function() {  // unit test 1.1
      assert.equal(-1, [1, 2, 3].indexOf(5));
      assert.equal(-1, [1, 2, 3].indexOf(6));
      assert.equal(1, [1, 2, 3].indexOf(2));
    });
  });

  describe('#length', function() {       // unit test group 2
    it('should return 3', function() {  // unit test 2.1
      assert.equal(3, [1,2,3].length);
    });
    it('should return 0', function() {  // unit test 2.2
      assert.equal(0, ''.length);
    });

  });
 
});


<|start_filename|>tests/automatic_tests/snapshot/mytest.js<|end_filename|>
function mytest(a) {
  document.write(a + 42);
    
  var gui = require('nw.gui');
  var result = { ok: true };
  
  var client = require('../../nw_test_app').createClient({
    argv: gui.App.argv,
    data: result,
  });
    
    
}

<|start_filename|>tests/automation/crash_dump/mocha_test.js<|end_filename|>
var path = require('path');
var assert = require('assert');
var fs = require('fs');
var fs_extra = require('fs-extra');
var curDir = fs.realpathSync('.');
var tmpDir = path.join(curDir, 'internal', 'tmp');

var results;

describe('crash dump', function() {

  var spawnChild = function(action) {
    return spawn(process.execPath, [path.join(curDir, 'internal'), action]);
  };

  var server;
  
  before(function(done) {

    var ready = function() {
    fs.mkdirSync(tmpDir);
    server = createTCPServer(13013);
	done();
    };

    if (fs.existsSync(tmpDir)) {
      fs_extra.remove(tmpDir, function() {
        ready();
      });
    } else {
      ready();
    }

  });
    
  after(function () {
        server.close();
    	fs_extra.remove(tmpDir, function (er) {
            if (er) throw er;
    	});
  });

////////// 1

  describe('crashBrowser()', function() {
	before(function(done) {
	    this.timeout(0);
        var child = spawnChild(0);

    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        setTimeout(function() {
          results = fs.readdirSync(tmpDir);
          //child.kill();
          done();
        }, 2000);
      });
    });

	});

    after(function() {
      server.removeAllListeners('connection');
    });

	it('should work fine', function() {
	    assert.equal(results.length, 1);
	    var r = results[0].indexOf("dmp");
	    assert.notEqual(r, -1);
	});
	
    });


///// 2 

    describe('crashRenderer()', function() {
	before(function(done) {
	    this.timeout(0);
        var child = spawnChild(1);

    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        setTimeout(function() {
          results = fs.readdirSync(tmpDir);
          //child.kill();
          done();
        }, 2000);
      });
	});
      });

    after(function() {
      server.removeAllListeners('connection');
    });

	it('should work fine', function() {
	    assert.equal(results.length, 2);
	    var r = results[1].indexOf("dmp");
	    assert.notEqual(r, -1);
	});
    });

//// 3,
   describe('App.setCrashDumpDir(dir)', function() {
       	before(function(done) {
	    this.timeout(0);
	    results = fs.readdirSync(tmpDir);
            done();
	});

	it('should work fine', function() {
	    assert.equal(results.length, 2);
	});
    });


});





<|start_filename|>tests/automatic_tests/source-maps/mocha_test.js<|end_filename|>
var path = require('path');
var app_test = require('./nw_test_app');
var assert = require('assert');
var results;

describe('source maps', function() {
    before(function(done) {
        this.timeout(0);
        var child = app_test.createChildProcess({
            execPath: process.execPath,
            appPath: path.join(global.tests_dir, 'source-maps'),
            end: function(data, app) {
                results = data;
                app.kill();
                done();
            }
        });
    });

    it('should support Closure Compile', function() {
	assert.equal("script.closure.js", results[0]);
	assert.equal("script1.js", results[8]);
    });
    
    it('should support JSMin and Grunt', function() {
	assert.equal("script.jsmin-grunt.js", results[4]);
	assert.equal("script2.js", results[9]);
    });
    
    it('should support Uglifyjs', function() {
	assert.equal('script.uglify.js', results[7]);
	assert.equal('script.js', results[3]);
    });
    
    it('should support CoffeeScript', function() {
	assert.equal('script.coffee.min.js', results[2]);
	assert.equal('script.coffee.coffee', results[1]);
    });
    
    it('should support TypeScript', function() {
	assert.equal('script.typescript.min.js', results[5]);
	assert.equal('script.typescript.ts', results[6]);
    });
});


<|start_filename|>tests/automatic_tests/app-single-instance/mocha_test.js<|end_filename|>
var child_process = require('child_process')
var server = global.server;
var server_port = global.port;
var assert = require('assert');
var path = require('path');

describe('Single Instance APP', function() {
	var counter = 0;
    var pushData = function(socket) {
        socket.on('data', function(data) {
        	counter += 1;
        })
    };
    var runApp = function(path){
    	var spawn = child_process.spawn;
    	var child = spawn(process.execPath,[path,server_port]);
    	return child;
    };

    before(function(done) {
        server.on('connection',pushData);
        var app_path = path.join(global.tests_dir,'app-single-instance/app');
        console.log(app_path);
        console.log(process.cwd());
        var child1 = runApp(app_path);
        var child2 = runApp(app_path);
        var child3 = runApp(app_path);
        setTimeout(function(){
        	child1.kill();
        	child2.kill();
        	child3.kill();
        	done();
        },1000);
    });

    it('app should be single instance', function(done) {
        assert.equal(counter,1);
        done();
    });

    after(function(done) {
        server.removeListener('connection',pushData);
        done();
    });
});

<|start_filename|>tests/automation/nwfaketop/mocha_test.js<|end_filename|>
var path = require('path');
var assert = require('assert');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');


describe('nwfaketop',function(){

	var child, server, result;

	before(function(done){
		this.timeout(0);
        server = createTCPServer(13013);
        child = spawnChildProcess(path.join(curDir, 'internal'));

    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        result = JSON.parse(data+'');
        done();
      });
    });

	});

	after(function(done){
		server.close();
		child.kill();
		done();
	});

	it("nwfaketop attribute set",function(done){
		assert(result[0],true);
		done();
	});
	it("nwfaketop attribute default",function(done){
		assert(result[1],true);
		done();
	});


});




<|start_filename|>tests/automation/reference-node-main/index.js<|end_filename|>
exports.message = "hello world";
exports.port = 10000;
exports.ready = false;

var server = require('net').createServer();
server.on('connection',function(socket){
	socket.on('data',function(data){
		socket.write(data);
	});
});

server.on('error',function(){
	try{
		server.close();
	}catch(e){
		exports.port += 1;
		setTimeout(function(){
			server.listen(exports.port);
		},0);
	}
});
server.listen(exports.port,function(){
	exports.ready = true;
});


<|start_filename|>tests/manual_tests/notification/package.json<|end_filename|>
{
    "name": "nw-notification-test",
    "main": "index.html",
	"app-id": "com.node.webkit.notification.test"
}


<|start_filename|>tests/nw_test_app/app_test.js<|end_filename|>
/**
 * console module for app test
 */

var spawn = require('child_process').spawn;
var net = require('net');
var server = global.server;
var port = global.port;
var program = require('commander');


/*
 * options:
 *   argv: the argv of nw
 *   data: (string|json) data to be sended to control
 *         
 *
 */
exports.createClient = function(options) {
  var
      argv = options.argv;
      
  
  //command line arguments.
  program
    .option('--auto', 'run app automatic')
    .option('-p, --port <port>', "set port used by socket")
    .parse([ 'node-webkit', 'nw-test' ].concat(argv));
  
  var client_prot = 13013;
  if (program.port)
    client_prot = program.port;
  
  
  if (options.port) client_prot = options.port;
  
  if (program.auto) {
    var client = net.connect({port: client_prot});
    client.setEncoding('utf8');   
   
    if (options.data != null) {
    if (options.delay) {
      setTimeout(function(){        
        client.end(JSON.stringify(options.data));
      }, options.delay);
      
    } else {
      client.end(JSON.stringify(options.data));
    }
    
    }
    
  }
  return {'auto': program.auto, 'socket': client};
}

exports.init = function(arg1, arg2) {
  server = arg1;
  port =  arg2;
}

function childProcess() {
  this.socket = null;
  this.app = null;
  this.server_connection_cb = null;
}

childProcess.prototype.removeConnection = function() {
  try {
    server.removeListener('connection', this.server_connection_cb); 
  } catch (e) {
  }
}

childProcess.prototype.close = function() {
  try {
    this.app.kill();
    server.removeListener('connection', this.server_connection_cb); 
  } catch (e) {
    console.log('error');
  }
}

/*
 * options: 
 *   execPath: (string)the path of nw.
 *   appPath: (string)the path of app.
 *   args: (array)the args of the app.
 *   end:  (function)we should do the report here, after get child process's result.    
 *           data: JSON object
 *           app: nodejs childProcess.spawn 
 *   no_connect: (bool) whether listen the connection event
 *
 * notices:
 *   now we can only receive data one time. 
 *   if your client exists error then crash, and casue the data can not been
 *   sended, please call `removeConnection()`. otherwise there would be problem. 
 *
 */
exports.createChildProcess = function(options) {
  
  if (options.port) prot = options.port;
  
  var 
      execPath = options.execPath,
      path = options.appPath,
      exec_argv, 
      app, cb,
      no_connect = options.no_connect || false,
      child = new childProcess();
  
    if (!options.args)
	exec_argv = [path, '--port', port, '--auto'];
    else
	exec_argv = [path].concat(options.args).concat(['--port', port, '--auto']);

  if (!no_connect) {
  
    server.on('connection', cb = function(socket){
      socket.setEncoding('utf8');
      console.log('in app connect');
      child.socket = socket;
      
      socket.on('data', function(data) {
        options.end(JSON.parse(data), app);              
      });
      socket.on('end', function() {
        //console.log('in app end');
        server.removeListener('connection', cb); 
      });
      socket.on('error', function(e) {
        //console.log(e);
      });
      child.server_connection_cb = cb;
    }); //server.on()   
  } //if (no_conect)
  
  app = spawn(execPath, exec_argv);
  child.app = app;
  
  return child;
}



<|start_filename|>tests/automation/cookies_api/mocha_test.js<|end_filename|>
var path = require('path');
var assert = require('assert');
var spawn = require('child_process').spawn;
var fs = require('fs');
var curDir = fs.realpathSync('.');

var changed;

describe('Window.cookies', function() {

  var server;

  var spawnChild = function(action) {
    return spawn(process.execPath, [path.join(curDir, 'internal'), action]);
  };

  before(function(done){
    server = createTCPServer(13013);
    done();
  });

  after(function(done) {
    this.timeout(0);
    server.close();
    done();
  });

//// 1 
    describe("get, getAll", function() {

    var child;
    var results;

	before(function(done) {
	    this.timeout(0);
    child = spawnChild(1);
    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        results = JSON.parse(data);
        child.kill();
        done();
      });
    });
	});

    after(function() {
      server.removeAllListeners('connection');
    });

	it('should get cookies', function() {
	    assert.equal(results[0], true);
	    assert.equal(results[1], true);
	});
    });


/////////// 2
    describe("set", function() {
    	describe("set lang en", function() {
    	    before(function(done) {
    		this.timeout(0);
            child = spawnChild(2);
    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        results = JSON.parse(data);
        changed = results[1];
        child.kill();
        done();
      });
    });
    	    });

    after(function() {
      server.removeAllListeners('connection');
    });

    	    it('should get cookies', function() {
    		assert.equal(results[0], true);
    	    })
    	});

	describe("set lang zh", function() {
	    before(function(done) {
		this.timeout(0);
            child = spawnChild(3);
    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        results = JSON.parse(data);
        changed = results[1];
        child.kill();
        done();
      });
    });
	    });

    after(function() {
      server.removeAllListeners('connection');
    });

	    it('should get cookies', function() {
		assert.equal(results[0], true);
	    })
	});

    });
    
//// 3, 
    describe('remove', function() {
    	before(function(done) {
    	    this.timeout(0);
            child = spawnChild(4);
    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        results = JSON.parse(data);
        //changed = results[1];
        child.kill();
        done();
      });
    });
    	});

    after(function() {
      server.removeAllListeners('connection');
    });

    	it('should remove lang', function() {
    	    assert.equal(results[1], false);
    	});
    });
    
///////// 4, 
    describe('onChanged', function() {
    	it('should be called when changed', function() {
    	    assert.equal(changed, true);
    	})
    });


});
	 


<|start_filename|>tests/automatic_tests/new-instance/mocha_test.js<|end_filename|>

var path = require('path');
var app_test = require('./nw_test_app');
var server = global.server;
var cb;

describe('new-instance', function() {

  after(function() {
     server.removeListener('connection', cb);
  });

	it('new window has different pid', function(done) {
	    this.timeout(0);
	    var result = false;
	    var times = 0;
	    var pid1, pid2;

	    var child = app_test.createChildProcess({
	      execPath: process.execPath,
	      appPath: path.join(global.tests_dir, 'new-instance'),
	      no_connect: true,

	    });


	    server.on('connection', cb = function(socket){
	      socket.setEncoding('utf8');
          socket.on('error', function(er) {
            console.log(er);
          })
	      socket.on('data', function(data) {

	        if (times == 0) {
	          pid1 = data;
	          times += 1;
	        } else {
	          pid2 = data;

	          if (pid1 != pid2) {
	            done();
	          } else {
	            done('they are in the same process');
	          }

	          child.app.kill();
	        } // if (times == 0)
	      });
	    }); // server.on('connection', cb = function(socket)


	})


})



<|start_filename|>tests/automation/chromium-args/mocha_test.js<|end_filename|>
var assert = require('assert');
var cp = require('child_process');
var fs = require('fs');
var fs_extra = require('fs-extra');
var curDir = fs.realpathSync('.');
var exec_path = process.execPath;
var app_path = path.join(curDir, 'internal');

describe('chromium-args', function() {


    describe('--disable-javascript', function() {

        var child;

    	before(function(done) {
          this.timeout(0);
          fs_extra.copy(path.join(app_path, 'package1.json'), path.join(app_path, 'package.json'), function (err) {
            if (err) {
              throw err;
            }
            child = spawnChildProcess(path.join(curDir, 'internal'));
          });

          setTimeout(function(){done();}, 2500);
    	});

    	after(function() {
          if (child)
            child.kill();
    	  fs.unlink(path.join(app_path, 'hi'), function(err) {if(err && err.code !== 'ENOENT') throw err});
    	  fs.unlink(path.join(app_path, 'package.json'), function(err) {if(err && err.code !== 'ENOENT') throw err});
    	});
	
    	it('javascript should not be executed', function() {
    	    var result = fs.existsSync(path.join(app_path, 'hi'));
    	    assert.equal(result, false);
    	});

    });


    describe('--app=url', function() {
	  var result = false, result2 = false;

      var child, server;

      before(function(done) {
        this.timeout(0);
        fs_extra.copy(path.join(app_path, 'package2.json'), path.join(app_path, 'package.json'), function (err) {
          if (err) {
            throw err;
          }

          server = createTCPServer(13013);
          server.on('connection', function(socket) {
            socket.setEncoding('utf8');
            socket.on('data', function(data) {
              result2 = data;
              result = true;
              done();
            });
          });

          child = spawnChildProcess(path.join(curDir, 'internal'));

          setTimeout(function() {
            if (!result) {
              child.kill();
              done('timeout');
            }
          }, 4500);

        });
      });

    	after(function(done) {
          this.timeout(0);
          child.kill();
          server.close();
          fs.unlink(path.join(app_path, 'package.json'), function(err) {if(err && err.code !== 'ENOENT') throw err});
          fs.unlink(path.join(app_path, 'hi'), function(err) {if(err && err.code !== 'ENOENT') throw err});
          done();
    	});
	
    	it('website should be the url', function() {
    	    assert.equal(result2, true);
    	});
    

    });

});


<|start_filename|>tests/automation/buff_from_string/mocha_test.js<|end_filename|>
var assert = require('assert');
var spawn = require('child_process').spawn;
var fs = require('fs-extra');
var path = require('path');
var curDir = fs.realpathSync('.');
var func = require(path.join(curDir, '..', 'start_app', 'script.js'));

var is_chromedriver_exists = false;

describe("buff_from_string", function() {
  var results = [];
  var onConnection = function(socket) {
    socket.on('data', function(data) {
      results = JSON.parse(data.toString());
    });
  };

  var server = undefined;
  var tmpnwPath = path.join(curDir, 'tmp-nw');

  before(function(done) {
    this.timeout(0);

    server = createTCPServer(13013);
    server.on('connection', onConnection);

    if (is_chromedriver_exists) {
      func.copyExecFiles(function() {
        var src_files = [
          path.join(curDir, 'internal', 'index.html'),
          path.join(curDir, 'internal', 'package.json'),
          path.join(curDir, 'internal', 'test.py')
        ];
        var dst_files = [
          path.join(curDir, 'tmp-nw', 'index.html'),
          path.join(curDir, 'tmp-nw', 'package.json'),
          path.join(curDir, 'tmp-nw', 'test.py')
        ];

        if (process.platform == 'win32'){
          src_files.push(path.join(curDir, 'chromedriver2_server.exe'));
          dst_files.push(path.join(curDir, 'tmp-nw', 'chromedriver2_server.exe'));
        } else {
          src_files.push(path.join(curDir, 'chromedriver2_server'));
          dst_files.push(path.join(curDir, 'tmp-nw', 'chromedriver2_server'));
        }

        for (var i=0;i<src_files.length;++i){
          fs.copySync(src_files[i],dst_files[i]);
        }
        if (process.platform != 'win32'){
          fs.chmodSync(path.join(curDir, 'tmp-nw', 'chromedriver2_server'),365);
        }

        var test_file = path.join(curDir, 'tmp-nw', 'test.py');
        setTimeout(function(){
          var child = spawn('python',[test_file]);
          child.on('exit',function(code,signal){
            console.log(code,signal);
            done();
          });
          child.on('error',function(err){
            console.error(err);
          });
          child.stderr.on('data',function(data){
            console.error(data.toString());
          });
          child.stdout.on('data',function(data){
            console.log(data.toString());
          });
        },1000);  // setTimeout
		});
    } else {
      var originMsg = 'Hello 上海';
      var bufMsg = new Buffer(originMsg, 'utf8');
      if (bufMsg == originMsg)
        results.push(true);
      else
        results.push(false);
      done();
    }

  });


  after(function(done) {
    this.timeout(0);
    if (server) {
      server.removeListener('connection', onConnection);
      server.close();
    }
    setTimeout(function(){
      if (fs.existsSync(tmpnwPath)) {
        fs.removeSync(tmpnwPath);
      }
      done();
    },2000);

  });

  it("string and buff.toString() should equal", function() {
    assert.equal(results.length,1);
    assert.equal(results[0],true);
  });


});


<|start_filename|>tests/automation/user-agent-app/mocha_test.js<|end_filename|>
var path = require('path');
var assert = require('assert');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');


describe('user-agent-app', function() {

  var result = false, package_name, package_info;

  before(function(done) {
    this.timeout(0);
    server = createTCPServer(13013);
    child = spawnChildProcess(path.join(curDir, 'internal'));
    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        result = true;
        package_name = data;
        package_info = JSON.parse(fs.readFileSync(path.join(curDir, 'internal', 'package.json'), 'utf8'));
        child.kill();
        done();
      });
    });

      setTimeout(function(){
          if (!result) {
            child.kill();
            done('loaded event does not been fired');
          }
        }, 7000);
    
  });
    
  after(function () {
        server.close();
  });

  it('user agent shoud be the same when open a new window',
    function() {
      assert.equal(result, true);
      assert.equal(package_name, package_info.name);
  });


});



<|start_filename|>tests/automatic_tests/after_close_previous_window_then_open_new/mocha_test.js<|end_filename|>
var path = require('path');
var app_test = require('./nw_test_app');
var assert  =require('assert');
var fs = require('fs');
var fs_extra = require('fs-extra');
var spawn = require('child_process').spawn;
var result;

describe('after close previous window then open new', function() {
    after(function () {
    	fs_extra.remove('./automatic_tests/after_close_previous_window_then_open_new/tmp', function (er) {
            if (er) throw er;
        });
    });

    before(function(done) {
        this.timeout(0);
	fs.mkdirSync('./automatic_tests/after_close_previous_window_then_open_new/tmp');

        var appPath = path.join(global.tests_dir, 'after_close_previous_window_then_open_new');

	var exec_argv = [appPath];
	app = spawn(process.execPath, exec_argv);
	setTimeout(function() {
	    done();
	}, 2000);
    });

    it('should not crash', function() {
	result = fs.readdirSync('./automatic_tests/after_close_previous_window_then_open_new/tmp');	
	assert.equal(result.length, 0);
    });

});


<|start_filename|>tests/automation/temp_dir/mocha_test.js<|end_filename|>
var path = require('path');
var os = require('os');
var cp = require('child_process');
var assert = require('assert');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');

var func = require(path.join(curDir, '..', 'start_app', 'script.js'));
var execPath = func.getExecPath();


var mac_app_path = path.join(curDir, 'tmp-nw', 'node-webkit.app');

var temp_path;

if (os.platform() == 'win32') {
    execPath = path.join(curDir, 'tmp-nw', 'app.exe');
} else if (os.platform() == 'linux') {
    execPath = path.join(curDir, 'tmp-nw', 'app');
} else if (os.platform() == 'darwin') {
    execPath = path.join(curDir, 'tmp-nw', 'node-webkit.app', 'Contents', 'MacOS', 'node-webkit');
}

function make_execuable_file(folder_path, done) {
    func.copyExecFiles(function() {
	func.copySourceFiles(folder_path); 
	func.zipSourceFiles(function() {
	    func.makeExecuableFile();
	    if (os.platform() == 'darwin') {
		var app_path = 'tmp-nw/node-webkit.app/Contents/Resources/app.nw';
		fs.mkdir(app_path, function(err) {
		    if(err && err.code !== 'EEXIST') throw err
		    fs.copy('tmp-nw/index.html', path.join(app_path, 'index.html'));
		    fs.copy('tmp-nw/package.html', path.join(app_path, 'package.html'));
		    setTimeout(done, 3000);

		});
	    } else {
		setTimeout(function() {
		    var child = cp.spawn(execPath, curDir); // [path.join(curDir, 'internal')]);
		    child.on('exit', function() {
			temp_path = path.dirname(fs.readFileSync(path.join(curDir, 'tmp-nw','path.org'))).substring(8);
			done();
		    });
		}, 3000);
	    }
	});
    });
}

describe('temp_dir', function() { 
    this.timeout(0);

    before(function(done) {
	make_execuable_file('internal', done);
    });

    after(function() {
    	fs.remove('tmp-nw', function (er) {
            if (er) throw er;
        });
    });

    it('should be removed after app exit', function() {
	var exist = fs.existsSync(temp_path);
	assert.equal(exist, false);
    });
});




<|start_filename|>tests/automatic_tests/loaded_event/mocha_test.js<|end_filename|>

var path = require('path');
var app_test = require('./nw_test_app');

describe('loaded event', function() {

    it('loaded event can been fired',
	  function(done) {
        this.timeout(0);
        var result = false;

        var child = app_test.createChildProcess({
          execPath: process.execPath,
          appPath: path.join(global.tests_dir, 'loaded_event'),
          end: function(data, app) {
            result = true;
            done();
            app.kill();
          }
        });


        setTimeout(function(){
          if (!result) {
            child.close();
            //child.app.kill();
            //child.removeConnection();
            done('loaded evenet does not been fired');
          }
        }, 3000);
        //child.app.stderr.on('data', function(d){ console.log ('app' + d);});

    })


})



<|start_filename|>tests/automation/app-single-instance/mocha_test.js<|end_filename|>
var assert = require('assert');
var path = require('path');
var global = require('../globals');

describe('Single Instance APP', function() {

  var count = 0;
  var onConnection = function(socket) {
    socket.on('data', function(data) {
      count += 1;
    });
  };

  var server = undefined;

  before(function(done) {
    server = createTCPServer(13013);
    server.on('connection', onConnection);

    var appPath = path.join(global.tests_dir, 'app');
    var child_1 = spawnChildProcess(appPath);
    var child_2 = spawnChildProcess(appPath);
    var child_3 = spawnChildProcess(appPath);
    setTimeout(function() {
      child_1.kill();
      child_2.kill();
      child_3.kill();
      done();
    }, 1000);
  });

  after(function() {
    if (server) {
      server.removeListener('connection',onConnection);
      server.close();
    }
  });

  it('app should be single instance', function() {
    assert.equal(count,1);
  });
});


<|start_filename|>tests/automation/inject-js/internal/start.js<|end_filename|>
var result = result ||[];
result.push('inject-js-start');

window.onload = function(){
	result.push('onload')
};

<|start_filename|>tests/automation/source-maps/mocha_test.js<|end_filename|>
var path = require('path');
var assert = require('assert');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');


describe('source maps', function() {

  var server, child, results, ok = false;

  before(function(done) {
    this.timeout(0);
    server = createTCPServer(13013);
    child = spawnChildProcess(path.join(curDir, 'internal'));
    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        ok = true;
        results = JSON.parse(data);
        child.kill();
        done();
      });
    });

    setTimeout(function() {
      if (!ok) {
        child.kill();
        done('timeout');
      }
    }, 4500);

  });
    
  after(function () {
        server.close();
  });

    it('should support Closure Compile', function() {
	assert.equal("script.closure.js", results[0]);
	assert.equal("script1.js", results[8]);
    });
    
    it('should support JSMin and Grunt', function() {
	assert.equal("script.jsmin-grunt.js", results[4]);
	assert.equal("script2.js", results[9]);
    });
    
    it('should support Uglifyjs', function() {
	assert.equal('script.uglify.js', results[7]);
	assert.equal('script.js', results[3]);
    });
    
    it('should support CoffeeScript', function() {
	assert.equal('script.coffee.min.js', results[2]);
	assert.equal('script.coffee.coffee', results[1]);
    });
    
    it('should support TypeScript', function() {
	assert.equal('script.typescript.min.js', results[5]);
	assert.equal('script.typescript.ts', results[6]);
    });


});




<|start_filename|>tests/automation/window-document-event/mocha_test.js<|end_filename|>
var path = require('path');
var assert = require('assert');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');

describe('document-start/end',function(){

  var server, child, results;

  before(function(done) {
    this.timeout(0);
    server = createTCPServer(13013);
    child = spawnChildProcess(path.join(curDir, 'internal'));
    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        results = JSON.parse(''+data);
        child.kill();
        done();
      });
    });

  });
    
  after(function () {
        server.close();
  });


	it('results should not equal undefined',function(done){
		assert.notEqual(results,undefined);
		done();
	})

	it('new window document-start run first',function(done){
		assert.equal(results[0]['flag'],true)
		assert.equal(results[0]['name'],'top-window-document-start')
		done();
	});
	it('new window script run between document-start and document-end',function(done){
		assert.equal(results[1],'new-window-script');
		done();
	});
	it('new window document-end should run before onload event',function(done){
		assert.equal(results[2]['flag'],true)
		assert.equal(results[2]['name'],'top-window-document-end')
		done();
	});
	it('new window onload should run last',function(done){
		assert.equal(results[3],'onload-from-new-window');
		done();
	});

	it('iframe document-start should run first',function(done){
		assert.equal(results[4]['flag'],true)
		assert.equal(results[4]['name'],'iframe-document-start')
		done();
	});
	it('iframe script run between document-start and document-end',function(done){
		assert.equal(results[5],'iframe-script');
		done();
	});
	it('iframe document-end should run later',function(done){
		assert.equal(results[6]['flag'],true)
		assert.equal(results[6]['name'],'iframe-document-end')
		done();
	});
	it('iframe onload should run last',function(done){
		assert.equal(results[7],'onload-from-iframe');
		done();
	});
});




<|start_filename|>tests/automation/nw_fork/internal/fork_module.js<|end_filename|>
process.on("message",function(m){
	process.send(m);
});

<|start_filename|>tests/automation/remote-img/imgnotshown/package.json<|end_filename|>
{
	"name": "remote file access",
	"main": "http://localhost:8123/index.html",
	"node-remote": "localhost"
}

<|start_filename|>tests/automation/datapath/datacash-path/package.json<|end_filename|>
{
  "name": "data path",
  "main": "index.html",
  "chromium-args": "--data-path='./data-cash/dataPath/'"
}


<|start_filename|>tests/automatic_tests/app_path_escape/mocha_test.js<|end_filename|>
var spawn = require('child_process').spawn;
var os = require('os');
describe('app_path_escaping',function(){
  it('app should start normally with directory named xdk',function(done){
    this.timeout(0);
    var opened = false;
    if(os.platform() == "win32"){
      var app = spawn(process.execPath, [path.join(global.tests_dir, 'app_path_escape/xdk')]);
      app.on('close',function(){
        opened = true;
        done();
      })
      setTimeout(function() {
        if(!opened){
          app.kill();
          done('the app is not executed');
        }
      }, 5000);
    }
    else
      done();
  })
})


<|start_filename|>tests/automatic_tests/nwfaketop/mocha_test.js<|end_filename|>
var path = require('path');
var assert = require('assert');
var spawn = require('child_process').spawn;
var server = global.server;
var server_port = global.port;


describe('nwfaketop',function(){

	var results = [];
	var connection_handler_callback = undefined;
	var connection_handler = function(socket){
		socket.on('data',function(data){
			results = JSON.parse(data+"");
			connection_handler_callback();
		});
	};
	var child = undefined;

	before(function(done){
		this.timeout(0);
		server.on('connection',connection_handler);
		var app_path = path.join(global.tests_dir,'nwfaketop');
		var exec_argv = [app_path,server_port];
		child = spawn(process.execPath,exec_argv);
		connection_handler_callback = done;
	});

	after(function(done){
		server.removeListener('connection',connection_handler);
		child.kill();
		done();
	});

	it("nwfaketop attribute set",function(done){
		assert(results[0],true);
		done();
	});
	it("nwfaketop attribute default",function(done){
		assert(results[1],true);
		done();
	});


});

<|start_filename|>tests/automation/snapshot/internal/1266-snapshot-crash-start/file_to_snapshot_to_app.bin.js<|end_filename|>
var sampleFunction;

(function()
{
	var privateVar = 'private';
	
	sampleFunction = function()
	{
		return privateVar+'67868';
	};
})();


<|start_filename|>tests/assert.js<|end_filename|>
function assert() {
  var str = '';
  str += ('<span class="description">' + arguments[arguments.length - 1] + ': </span>');

  var result = true;
  for (var i = 0; i < arguments.length - 1; ++i) {
    if (!arguments[i]) {
      result = false;
      str += ('<span style="color:red">FAILED</span>');
      str += ('<span style="color:grey"> at condition ' + (i + 1) + ' </span>');
    }
  }

  if (result) {
    str = '<div class="success test">' + str + '<span style="color:green">PASSED</span>';
  } else {
    str = '<div class="fail test">' + str;
  }

  str += '</div>';

  $(document.body).append(str);
}



<|start_filename|>tests/manual_tests/new_win_policy/index.html<|end_filename|>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf8">
    <title>test</title>
    <style type="text/css">
      div#from-top-window{
        width: 45%;
        float: left;
      }

      div#from-iframe{
        width: 45%;
        margin-left: 5%;
        float: left;
      }

    </style>
  </head>
  <body>
    <script type="text/javascript">
      var path = require('path');
      var spawn = require('child_process').spawn;
      var child = undefined;
      var RunApp = function(type,policy){
        if (child != undefined){
          child.kill();
        }
        var app_path = './app';
        var exec_argv = [app_path,type+"_"+policy];
        child = spawn(process.execPath,exec_argv);
      };

      process.on('exit',function(){
        if (child){
          child.kill();
        }
      })
    </script>

    <div>
      <ul>
        <li>ignore() =&gt; ignore the request, navigation won't happen.</li>
        <li>forceCurrent() =&gt; force the link to be opened in the same frame.</li>
        <li>forceDownload() =&gt; force the link to be a downloadable, or open by external program.</li>
        <li>forceNewWindow() =&gt; force the link to be opened in a new window.</li>
        <li>forceNewPopup() =&gt; force the link to be opened in a new popup window</li>
        <li style="color:red;">Please make sure there are no overlapping windows when running this case</li>
      </ul>
    </div>

    <div id="from-top-window">
      <div><h2>From Top Window</h2></div>
      <div><button onclick="RunApp('window','ignore')">ignore()</button></div>
      <div><button onclick="RunApp('window','forceNewPopup')">forceNewPopup()</button></div>
      <div><button onclick="RunApp('window','forceNewWindow')">forceNewWindow()</button></div>
      <div><button onclick="RunApp('window','forceDownload')">forceDownload()</button></div>
      <div><button onclick="RunApp('window','forceDownload-manually')">forceDownload() manually</button></div>
      <div><button onclick="RunApp('window','forceCurrent')">forceCurrent()</button></div>
    </div>

    <div id="from-iframe">
      <div><h2>From Iframe</h2></div>
      <div><button onclick="RunApp('iframe','ignore')">ignore()</button></div>
      <div><button onclick="RunApp('iframe','forceNewPopup')">forceNewPopup()</button></div>
      <div><button onclick="RunApp('iframe','forceNewWindow')">forceNewWindow()</button></div>
      <div><button onclick="RunApp('iframe','forceDownload')">forceDownload()</button></div>
      <div><button onclick="RunApp('iframe','forceDownload-manually')">forceDownload() manually</button></div>
      <div><button onclick="RunApp('iframe','forceCurrent')">forceCurrent()</button></div>
    </div>

  </body>
</html>
    

<|start_filename|>tests/automation/fd-limit/nw.js<|end_filename|>
var spawn = require('child_process').spawn;
var net = require('net');

exports.port = 13030;

exports.spawn = function(args, cb) {
    var shutdown = function (err, data) {
        shutdown = function(){};
        server.close(function(){
            if (err) {
                cb(err);
            } else {
                cb(null, JSON.parse(data));
            }
        });
    };

    var server = net.createServer();
    server.on('connection', function(con) {
        con.on('data', function(data) {
            shutdown(null, data);
        });
        con.on('error', function(err){
            shutdown(err);
        });
        con.on('close', function(){
            shutdown(new Error('not-receive'));
        });
    });
    server.listen(exports.port);

    return spawn(process.execPath, args);

};

exports.send = function(data) {
    var client = net.connect(exports.port);
    client.end(JSON.stringify(data));
    require('nw.gui').App.quit();
};


<|start_filename|>tests/automation/node/module1.js<|end_filename|>
exports.test = function() {
  return "module1";
}


<|start_filename|>tests/automation/node-main/mocha_test.js<|end_filename|>
var path = require('path');
var assert = require('assert');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');

describe('node-main', function() {

  var server;

  before(function(done) {
    server = createTCPServer(13013);
    done();
  });
    
  after(function () {
        server.close();
  });

  describe('create http server in node-main', function() {
    it('nw should not close by itself after show devtool',
	  function(done) {
        this.timeout(0);
        var result = false;

        var child = spawnChildProcess(path.join(curDir, '..', 'show_devtool_after_http_server_created_in_node_main'));

    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        result = JSON.parse(data);
        child.kill();
        if (result.success) done();
        else done('error');
        result = true;
        server.removeAllListeners('connection');
      });
    });


        setTimeout(function(){
          if (!result) {
            done('nw close by itself')
          }
        }, 3000);
        //child.app.stderr.on('data', function(d){ console.log ('app' + d);});

    });
  });



  describe('call require() in app', function() {
    it('nw should can require modules', function(done){
      this.timeout(0);
      var result = false;
        var child = spawnChildProcess(path.join(curDir, '..', 'call_require_with_node-main_set'));

    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        result = JSON.parse(data);
        child.kill();
        if (result.ok) done();
        else done('error:'+result.error);
        result = true;
        server.removeAllListeners('connection');
      });
    });

    });
  });

  describe('reference node-main module',function(){
    it('nw should be able to reference node-main module',function(done){
      this.timeout(0);

      var result = false;
        var child = spawnChildProcess(path.join(curDir, '..', 'reference-node-main'));

    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        result = JSON.parse(data);
        child.kill();
        assert.equal(result,true);
        done();
        server.removeAllListeners('connection');
      });
    });

    });
  });



});




<|start_filename|>tests/manual_tests/tooltip/index.html<|end_filename|>
<html>
<body>
    <h3 title="this is a tooltip">Testing tooltips - please place your mouse pointer onto this text. If you see a tooltip, the test is passed.</h3>
</body>
</html>


<|start_filename|>tests/automatic_tests/filevalue/mocha_test.js<|end_filename|>
var app_test = require('./nw_test_app');
var path = require('path');

describe('file input',function(){
  describe('set value',function(){
    it('the value should be set without exception',function(done){
      this.timeout(0);
      var child = app_test.createChildProcess({
        execPath : process.execPath,
        appPath : path.join(global.tests_dir, 'filevalue'),
        end: function(data, app){
          app.kill();
          if (data == 'mytestfile')
            done();
          else 
            done('the value of the file input is not set correctly');
        }
      })
    })
  })
})

<|start_filename|>tests/automatic_tests/node/mocha_test.js<|end_filename|>
var assert = require('assert');

describe('require', function() {
  describe('type', function() {
    it('is function', function() {
      assert.equal(typeof global.require, 'function');
    });
  });

  describe('members', function() {
    it('have resolve', function() {
      assert.equal(typeof global.require.resolve, 'function');
    });

    it('have main', function() {
      assert.equal(typeof global.require.main, 'object');
    });

    it('have extensions', function() {
      assert.equal(typeof global.require.extensions, 'object');
    });

    it('have registerExtension', function() {
      assert.equal(typeof global.require.registerExtension, 'function');
    });

    it('have cache', function() {
      assert.equal(typeof global.require.cache, 'object');
    });
  });
});

describe('node', function() {

  var mocha_callback = null;
  before(function() {
    mocha_callback = process.listeners('uncaughtException')[1];
    process.removeListener('uncaughtException', mocha_callback);
  });
  after(function(){
    process.on('uncaughtException',mocha_callback);
  })

  describe('process', function() {
    it('uncaughtException should have a default listener', function() {
      assert.equal(process.listeners('uncaughtException').length, 1);
    });

    it('throwing uncaughtException should not show error page when having listener', function(done) {
      var empty = function(e) {
        process.removeListener('uncaughtException', empty);
        done();
      };
      process.on('uncaughtException', empty);
      process.nextTick(function() {
        throw new String('If you see this then uncaughtException test failed');
      });
    });
  });
});

describe('module', function() {
  describe('javascript modules', function() {
    var path = require('path');

    it('require by path', function() {
      assert.equal(require('./automatic_tests/node/module1.js').test(), 'module1');
    });

    it('simple file module', function() {
      assert.equal(require('./automatic_tests/node/node_modules/module3').test(), 'module3');
    });

    it('space in path', function() {
      assert.equal(require('./automatic_tests/node/node_modules/module4 space').test(), 'module4');
    });
  });

  describe('built-in modules', function() {
    var fs = require('fs');
    var http = require('http');
    var path = require('path');
    var exec = require('child_process').exec;

    it('read self', function() {
      var path1 = 'automatic_tests/node/mocha_test.js';
      var path2 = path.join(process.cwd(), 'automatic_tests', 'node', 'mocha_test.js');
      var content = fs.readFileSync(path1, 'utf8');
      fs.readFile(path2, 'utf8', function(err, data) {
        assert.equal(err, null);
        assert.equal(content, data);
      });
    });

    it('execute child process', function(done) {
      var child = exec('echo echo back', function (error, stdout, stderr) {
        assert.equal(error, null);
        assert.equal(stdout, process.platform == 'win32' ? 'echo back\r\n' : 'echo back\n');
        assert.equal(stderr, '');
        done();
      });
    });

    it('Buffer', function() {
      assert.equal(String(Buffer('test')), 'test');
    });

    it('http server and client', function(done) {
      var server = http.createServer(function (req, res) {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('hello');
      }).listen(10086);
      process.nextTick(function() {
        var count = 0;
        for (var i = 0; i < 5; ++i) {
          http.get("http://127.0.0.1:10086", function(res) {
            var data = '';
            res.on('end', function(e) {
              if (data == 'hello')
                ++count;
            }).on('data', function(chunk) {
              data += chunk;
            });
          }).on('error', function() {
            assert.equal(true, false);
          });
        }
        setTimeout(function() {
          assert.equal(count, 5);
          server.close();
          done();
        }, 50);
      });
    });
  });

  describe('native modules (long-to-run)', function() {
    it('bignum should work on posix environment', function() {
      if (process.platform != 'win32') {
        var bignum = require('./node_modules/bignum');
        assert.equal(bignum('782910138827292261791972728324982').sub('182373273283402171237474774728373').div(8), '75067108192986261319312244199576');
      }
    });

    it('native modules without handle scope', function() {
	require('./node_modules/nw_test_loop_without_handle');
    });
     
    it('native modules should work', function() {
	var nativeModules = new Array("dtrace-provider", "ref", "lame");
	for (var i = 0; i < nativeModules.length; i++)
	    assert.equal((typeof require(nativeModules[i])),  "object");
    });
  });
});

describe('performance', function() {
  describe('timers', function() {
    it('setTimeout in webkit and node.js should be accurate', function(done) {
      var flag1, flag2;
      global.setTimeout(function() { flag1 = true; }, 10);
      window.setTimeout(function() { flag2 = true; }, 10);

      setTimeout(function() {
        assert.equal(flag1, true);
        assert.equal(flag2, true);
        done();
      }, 50);
    });

    it('setInterval int webkit and node.js should be accurate', function(done) {
      var count1 = 0;
      var count2 = 0;;
      global.setInterval(function() { ++count1; }, 10);
      window.setInterval(function() { ++count2; }, 10);

      setTimeout(function() {
        assert.equal(count1 > 3, true);
        assert.equal(count2 > 3, true);
        done();
      }, 50);
    });
  });

  describe('IO', function() {
    var fs = require('fs');
    var path = require('path');
    var exec = require('child_process').exec;
    var tar = require('tar');

    it('file reading should be quick even when we have a child process running', function(done) {
      this.timeout(100);
      exec('sleep 1000', function () { });
      fs.readFile('automatic_tests/node/mocha_test.js', 'utf8', function(err, data) {
        done();
      });
    });

    it('untar a file should be quick', function(done) {
      this.timeout(100);
      fs.createReadStream('automatic_tests/node/test.tar')
      .pipe(tar.Extract({ path: 'tmp' }))
      .on('error', function (er) {
        assert.equal(false, true);
      })
      .on('end', function () {
        var content = fs.readFileSync('tmp/text', 'utf8');
        assert.equal(content, 'I love luyao\n');
        fs.unlinkSync('tmp/text');
        fs.rmdirSync('tmp');
        done();
      });
    });
  });
});

describe('browser', function() {
  describe('security', function() {
    it('cross domain call in file:// should succeed', function(done) {
      window.$.get('http://baidu.com', function(data, status) {
        assert.equal(status, 'success');
        assert.notEqual(data, null);
        done();
      });
    });
  });

  describe('render crashes', function() {
    it('MessageChannel should not crash', function(done) {
      var test = require('./automatic_tests/node/message_channel_test.js');
      test.run(done); // force to run in node context.
    });
  });
});


<|start_filename|>tests/automatic_tests/save_devtools_settings/mocha_test.js<|end_filename|>
var path = require('path');
var app_test = require('./nw_test_app');
var assert = require('assert');
var original;
var changed;
var ok = false;

function read_changed(done) {
    if (!ok)
	setTimeout(read_changed, 2000, done);
    else {
	var child = app_test.createChildProcess({
	    execPath: process.execPath,
	    appPath: path.join(global.tests_dir, 'save_devtools_settings'),
	    args: [0],
	    end: function(data, app) {
		changed = data;
		app.kill();
		done();
		console.log("secnond");
	    }
	});
    }
}

describe('save_devtools_settings', function() {
    
    before(function(done) {
	this.timeout(0);
	var child = app_test.createChildProcess({
	    execPath: process.execPath,
	    appPath: path.join(global.tests_dir, 'save_devtools_settings'),
	    args: [1],
	    end: function(data, app) {
		original = data;
		app.kill();
		ok = true;
		console.log("first");
	    }
	});
	setTimeout(read_changed, 2000, done);
    });
    
    it("should save devtools' settings", function() {
	var i = 0;
	// general
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.equal((original[i] + 1) % 4, changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;

	assert.equal((original[i] + 1) % 4, changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	if (!original[i - 1])
	    assert.equal((original[i] + 1) % 10, changed[i]);
	i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;

	// overrides
	assert.notEqual(original[i], changed[i]); i++;
	if (!original[i - 1])
	    // 0~21                                                                                               
	    assert.equal((original[i] + 1) % 22, changed[i]);
	i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	if (!original[i - 1]) {
	    assert.equal((original[i] + 1) % 10, changed[i]); i++;
	    assert.equal((original[i] + 1) % 10, changed[i]); i++;
	}
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	if (!original[i - 1]) {
	    assert.equal((original[i] + 1) % 10, changed[i]); i++;
	    assert.equal((original[i] + 1) % 10, changed[i]); i++;
	    assert.equal((original[i] + 1) % 10, changed[i]); i++;
	}
	assert.notEqual(original[i], changed[i]); i++;
	assert.notEqual(original[i], changed[i]); i++;
	if (!original[i - 1])
	    assert.equal((original[i] + 1) % 9, changed[i]);
	i++;

    });
    
});


<|start_filename|>tests/automation/document_cookies/mocha_test.js<|end_filename|>
var path = require('path');
var assert = require('assert');
var gui = require('nw.gui');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');
var results = new Array();
describe('document.cookies', function() {

var server;

  before(function(done) {
    server = createTCPServer(13013);
    results.push('dump');  // should be remove when the first test case is ready
	done();
  });
    
  after(function () {
        server.close();
  });

/*
    describe('http', function() {
	before(function(done) {
	    this.timeout(0);
	    var url = "http://127.0.0.1:8123/document_cookies.html";
	    var win = gui.Window.open(url);

	    setTimeout(function() {
		results.push(win.window.msg.textContent);
		done();
		win.window.close();
	    }, 1000);
	});
	it('should be set', function() {
	    assert.equal(results[0], '123');
	});
    });
*/

    describe('file', function() {
	before(function(done) {
	    this.timeout(0);
        var child = spawnChildProcess(path.join(curDir, 'file'));

    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        setTimeout(function() {
          results.push(data);
          child.kill();
          done();
        }, 1000);
      });
    });
	    setTimeout(done, 10000);
	});

    after(function() {
      server.removeAllListeners('connection');
    });

	it ('should be set', function() {
	    assert.equal(results[1], '123');
	});
    });

    describe('app', function() {
	before(function(done) {
	    this.timeout(0);
        var child = spawnChildProcess(path.join(curDir, 'app'));

    server.on('connection', function(socket) {
      socket.setEncoding('utf8');
      socket.on('data', function(data) {
        setTimeout(function() {
          results.push(data);
          child.kill();
          done();
        }, 1000);
      });
    });

	    setTimeout(done, 10000);
	});

    after(function() {
      server.removeAllListeners('connection');
    });

	it ('should be set', function() {
	    assert.equal(results[2], '123');
	});
    });

});


<|start_filename|>tests/automation/snapshot/internal/1266-snapshot-crash-start/script.js<|end_filename|>
$(document).ready(function()
{
	$('#content').html(sampleFunction()); 
});

<|start_filename|>tests/automatic_tests/window-eval/mocha_test.js<|end_filename|>
var server = global.server;
var server_port = global.port;
var result = false;
var assert = require('assert');
var spawn = require('child_process').spawn;
var path = require('path');

var connection_handler_callback = undefined;
var connection_handler = function(socket){
	socket.on('data',function(data){
		if (data.toString() == "success"){
			result = true;
		}
		if (typeof connection_handler_callback === 'function'){
			(connection_handler_callback)();
		}
	})
};

describe('Window.eval',function(){
	var child = null;
	
	before(function(done){
		this.timeout(0);
		server.on('connection',connection_handler);
		var app_path = path.join(global.tests_dir,'window-eval');
		var exec_args = [app_path,server_port];
		child = spawn(process.execPath,exec_args);
		connection_handler_callback = done;
	});

	after(function(done){
		server.removeListener('connection',connection_handler);
		child.kill();
		done();
	});

	it("Window.eval should works",function(done){
		assert.equal(result,true);
		done();
	});
})

<|start_filename|>tests/automation/nw-in-mem/mocha_test.js<|end_filename|>
var os = require('os');
var path = require('path');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');

var exec = require('child_process').exec;
var spawn = require('child_process').spawn;

describe('nw in memory after quiting',function(){

  it('nw.exe should not be in memory after gui.App.quit is called on windows',function(done){
    this.timeout(0);
    if(os.platform() == "win32") {
      var app = spawn(process.execPath, [path.join(curDir,'package')])
      app.on('close',function(){
        var nwname = "nw.exe";
        var nwcount = 0;
        setTimeout(function() {
          exec("tasklist", function(err, stdout, stderr) {
            if(err){ return console.log(err); }
            stdout.split('\n').filter(function(line){
              var p=line.trim().split(/\s+/),pname=p[0];
              if(pname.toLowerCase().indexOf(nwname)>=0)
                  nwcount++;
            });

            if(nwcount == 2)
              done();
            else if(nwcount > 2)
              done('nw.exe is still in memory after the quit of app');
          })
        }, 500);
      });
    }
    else 
      done();
  });


});




<|start_filename|>tests/automatic_tests/window-document-event/mocha_test.js<|end_filename|>
var path = require('path');
var spawn = require('child_process').spawn;
var server = global.server;
var server_port = global.port;
var assert = require('assert');

describe('document-start/end',function(){

	var results = undefined;
	var connection_handler_callback = undefined;
	var connection_handler = function(socket){
		socket.on('data',function(data){
			results = JSON.parse(data+"");
			if (typeof connection_handler_callback == 'function'){
				(connection_handler_callback)();
			}
		})
	};
	var child = null;
	before(function(done){
		this.timeout(0);
		server.on('connection',connection_handler);
		var app_path = path.join(global.tests_dir,'window-document-event');
		var exec_argv = [app_path,server_port];
		child = spawn(process.execPath,exec_argv);
		connection_handler_callback = done;
		//we call done when we receive data from child
	});
	after(function(done){
		server.removeListener('connection',connection_handler);
		child.kill();
		done();
	});

	it('results should not equal undefined',function(done){
		assert.notEqual(results,undefined);
		done();
	})

	it('new window document-start run first',function(done){
		assert.equal(results[0]['flag'],true)
		assert.equal(results[0]['name'],'top-window-document-start')
		done();
	});
	it('new window script run between document-start and document-end',function(done){
		assert.equal(results[1],'new-window-script');
		done();
	});
	it('new window document-end should run before onload event',function(done){
		assert.equal(results[2]['flag'],true)
		assert.equal(results[2]['name'],'top-window-document-end')
		done();
	});
	it('new window onload should run last',function(done){
		assert.equal(results[3],'onload-from-new-window');
		done();
	});

	it('iframe document-start should run first',function(done){
		assert.equal(results[4]['flag'],true)
		assert.equal(results[4]['name'],'iframe-document-start')
		done();
	});
	it('iframe script run between document-start and document-end',function(done){
		assert.equal(results[5],'iframe-script');
		done();
	});
	it('iframe document-end should run later',function(done){
		assert.equal(results[6]['flag'],true)
		assert.equal(results[6]['name'],'iframe-document-end')
		done();
	});
	it('iframe onload should run last',function(done){
		assert.equal(results[7],'onload-from-iframe');
		done();
	});
});

<|start_filename|>tests/automation/fast_open_and_close_devtools/mocha_test.js<|end_filename|>
var path = require('path');
var assert = require('assert');
var fs = require('fs-extra');
var curDir = fs.realpathSync('.');

var result = false;
describe('Fast open&close devtools from #1391', function() {
        before(function(done) {
                this.timeout(0);
                var app = spawnChildProcess(path.join(curDir, 'internal'));
                app.on('exit', function(code) {
                        if (code != null)
                           result = true;
                        done();
                });
        });

        it('should not crash', function() {
                assert.equal(result, true);
        });
});


<|start_filename|>src/resources/pages/nw_blank.html<|end_filename|>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>node-webkit</title>
</head>
<body>
<div style="width: 100%; height: 100%; display: table;">
<pre style="text-align: center; margin: 0 auto; display: table-cell; vertical-align: middle">
    .__   __.   ______    _______   _______         
    |  \ |  |  /  __  \  |       \ |   ____|        
    |   \|  | |  |  |  | |  .--.  ||  |__    ______ 
    |  . `  | |  |  |  | |  |  |  ||   __|  |______|
    |  |\   | |  `--'  | |  '--'  ||  |____         
    |__| \__|  \______/  |_______/ |_______|        
                                                        
____    __    ____  _______ .______    __  ___  __  .___________.
\   \  /  \  /   / |   ____||   _  \  |  |/  / |  | |           |
 \   \/    \/   /  |  |__   |  |_)  | |  '  /  |  | `---|  |----`
  \            /   |   __|  |   _  &lt;  |    &lt;   |  |     |  |     
   \    /\    /    |  |____ |  |_)  | |  .  \  |  |     |  |     
    \__/  \__/     |_______||______/  |__|\__\ |__|     |__|     
</pre>
</div>
</body>
</html>
