it("should call a method of an obj in his context", function() { return async(function* () { var myClass = new MyClass('PREFIX-'); var result = yield ninvoke(myClass, 'myNodeStyleMethod', '-SUFIX'); h.expect(result).to.equal('PREFIX-INNER_PROPERTY-SUFIX'); }); });
it("should support bind ports", function() { var script = 'socat TCP-LISTEN:1500,fork SYSTEM:\'echo -e "HTTP/1.1\\n\\n $(date)"\''; var cmd = ["/bin/bash", "-c", script]; var opts = { daemon: true, ports: {} }; opts.ports["1500/tcp"] = [{ HostIp: "0.0.0.0" }]; return async(function* () { // Run http server var container = yield h.docker.run(default_img, cmd, opts); var data = yield container.inspect(); var name = data.NetworkSettings.Access["1500"].name; var host = data.NetworkSettings.Access["1500"].gateway; var port = data.NetworkSettings.Access["1500"].port; var protocol = data.NetworkSettings.Access["1500"].protocol; h.expect(name).to.equal("1500"); h.expect(protocol).to.equal("tcp"); // Request var _cmd = ["/bin/bash", "-c", `exec 3<>/dev/tcp/${host}/${port}; echo -e "" >&3; cat <&3`]; yield h.docker.run(default_img, _cmd, { stdout: mocks.stdout }); h.expect(outputs.stdout).to.match(/HTTP\/1\.1/); var container_info = yield container.inspect(); yield container.inspect(); if (container_info.State.Running) { return container.kill(); } else { return promiseResolve(); } }); });
return thenAll(_.map(system.syncs || {}, (sync_data, host_folder) => { return async(this, function* () { if (daemon && sync_data.options.daemon === false || !daemon && sync_data.options.shell !== true) { return promiseResolve(); } if (config('agent:requires_vm')) { sync_data.options = _.defaults(sync_data.options, { use_vm: true, ssh: lazy.Client.ssh_opts() }); } var clean_sync_folder = yield this._clean_sync_folder(system, host_folder); if (clean_sync_folder !== 0) { // TODO: throw proper error throw new NotBeenImplementedError('SyncError'); } var pub_data = { system : system.name, host_folder : host_folder, guest_folder: sync_data.guest_folder, options : sync_data.options }; publish(topic, _.assign({ type : "sync_start" }, pub_data)); return lazy.Client .watch(host_folder, sync_data.guest_folder, sync_data.options) .then(() => { publish(topic, _.assign({ type : "sync_done" }, pub_data)); }); }); }));
index(opts) { return async(this, function* () { // Get agent status var agent = yield lazy.Client.status(); var require_vm = config("agent:requires_vm"); // Load configs from agent if (agent.agent) { yield Helpers.requireAgent(this.ui); } // Mount data to render var data = { version: Azk.version, docker: require_vm && !agent.agent ? { Version: this.ui.c.red("down") } : yield this.docker.version(), use_vm: require_vm ? this.ui.c.green("yes") : this.ui.c.yellow("no"), agent_running: agent.agent ? this.ui.c.green("up") : this.ui.c.red("down"), }; if (require_vm && agent.agent) { var ip = config('agent:vm:ip'); data.use_vm = data.use_vm + ', ip: ' + this.ui.c.yellow(ip); } var render = opts.logo ? this.render_with_logo : this.render_normal; this.ui.output(render.apply(this, [data])); return 0; }); }
function config_net_interfaces(name, ip, use_dhcp) { return async(function* () { var result = yield exec("hostonlyif", "create"); var inter = result.match(/Interface '(.*)?'/)[1]; yield modifyvm(name, [ "--nic1", "hostonly", "--nictype1", "virtio", "--cableconnected1", "on", "--hostonlyadapter1", inter ]); // Configure dhcp server var gateway = Utils.net.calculateGatewayIp(ip); var network = Utils.net.calculateNetIp(ip); var netmask = "255.255.255.0"; // nat interfance yield config_nat_interface(name); yield hostonly.configure_if(inter, gateway, netmask); // dhcp server if (use_dhcp) { yield config_dhcp(inter, gateway, netmask, ip); } else { var key_base = "/VirtualBox/D2D/eth0"; return thenAll([ guestproperty.set(name, `${key_base}/address`, ip), guestproperty.set(name, `${key_base}/netmask`, netmask), guestproperty.set(name, `${key_base}/network`, network), ]); } }); }
it("should add system to event object", function() { return async(function* () { // force azk to think that the image is builded system.image.builded = true; // mock check to return null system.image.check = function () { return defer((resolve) => { process.nextTick(() => { publish("image.check.status", { type: "action", context: "image", action: "check_image" }); resolve(system.image); }); }); }; _subscription2 = subscribe('system.run.image.check.status', (event) => { events.push(event); }); yield system.runDaemon() .catch(() => {}); _subscription2.unsubscribe(); h.expect(events).to.have.deep.property("[0]").and.eql( { type: 'action', context: 'image', action: 'check_image', system: system } ); }); });
it("should wait for server running in a host:port", function() { var _subscription; var connect = () => { return net_utils.waitService("tcp://localhost:" + port, { timeout: 1000 }); }; return async(function* () { // not listening to utils.net.waitService.status yield h.expect(connect()).to.eventually.equal(false); // listening to utils.net.waitService.status var serverRunning = false; _subscription = subscribe('utils.net.waitService.status', (event) => { // Start server after first connection attempt if (event.type == "try_connect" && !serverRunning) { serverRunning = true; runServer(port); } }); yield h.expect(connect()).to.eventually.equal(true); _subscription.unsubscribe(); }) .catch(function (err) { if (_subscription) { _subscription.unsubscribe(); } throw err; }); });
_check_for_except_from(origin, opts) { return async(this, function* () { // Find from exceptions in files opts = _.clone(opts); opts.except = _.flatten([opts.except || []]); var exists, file, file_content = ''; var candidates = opts.except_from ? [opts.except_from] : []; candidates = candidates.concat([ path.join(origin, ".syncignore"), path.join(origin, ".gitignore"), ]); delete opts.except_from; for (var i = 0; i < candidates.length; i++) { file = candidates[i]; exists = yield fsAsync.exists(file); if (exists) { opts.except_from = file; file_content = yield fsAsync.readFile(file); file_content = file_content.toString(); break; } } opts.except = opts.except.concat( _.without(file_content.split('\n'), '') ); return opts; }); }
index(options={}) { if (!config('agent:requires_vm')) { this.ui.fail('commands.vm.not_required'); return promiseResolve(1); } return async(this, function* () { var action = _.head((this.route && this.route.actions)) || options.action; var vm_name = config("agent:vm:name"); var vm_info = yield lazy.VM.info(vm_name); var promise = this[`action_${action}`](vm_info, options); var _subscription = subscribe('vm.action.status', (data) => { Helpers.vmStartProgress(this.ui)(data); }); return promise .then(function (result) { _subscription.unsubscribe(); return result; }) .catch(options.fail || ((error) => { if (error instanceof RequiredError) { this.ui.fail(error.key); return 1; } _subscription.unsubscribe(); throw error; })); }); }
watch(origin, destination, opts = {}) { this.unwatch(); log.debug('[sync] call to watch and sync: %s => %s', origin, destination); return async(this, function* () { try { var exists = yield fsAsync.exists(origin); if (!exists) { throw { err: 'Sync: origin path not exist', code: 101 }; } var stats = yield fsAsync.stat(origin); if (!(stats.isDirectory || stats.isFile() || stats.isSymbolicLink())) { throw new Error(`The type of the file ${origin} is not supported for synchronization`); } if (stats.isDirectory()) { opts = yield this._check_for_except_from(origin, opts); } yield lazy.Sync.sync(origin, destination, opts); this._send('sync', 'done'); yield this._start_watcher(origin, destination, opts); this._send('watch', 'ready'); } catch (err) { log.error('[sync] fail', (err.stack ? err.stack : err.toString())); this._send('sync', 'fail', { err }); throw err; } }); }
it("should genereate a new screenshot file", function() { return async(this, function* () { var file = yield lazy.VM.saveScreenShot(name); yield h.expect(fsAsync.exists(file)).to.eventually.fulfilled; yield fsAsync.remove(file); }); });
it("should add/remove hostonly network without dhcp server", function() { return async(this, function* () { // Install vm and get infos var info = yield aux_tools.install_vm.apply(this); var data = yield aux_tools.netinfo(); // Check for vmbox networking var net = aux_tools.filter_hostonly(data[0], info.hostonlyadapter1); h.expect(net).to.have.property('Name', info.hostonlyadapter1); h.expect(net).to.have.property('IPAddress' , net_opts.gateway); h.expect(net).to.have.property('NetworkMask', net_opts.netmask); // Networking configure guest ip var result, key_base = "/VirtualBox/D2D/eth0"; result = yield lazy.VM.getProperty(opts.name, `${key_base}/address`); h.expect(result).to.eql({ Value: net_opts.ip }); result = yield lazy.VM.getProperty(opts.name, `${key_base}/netmask`); h.expect(result).to.eql({ Value: net_opts.netmask }); result = yield lazy.VM.getProperty(opts.name, `${key_base}/network`); h.expect(result).to.eql({ Value: net_opts.network }); // Check if dhcp server is disabled var VBoxNetworkName = net.VBoxNetworkName; h.expect(aux_tools.filter_dhcp(data[1], VBoxNetworkName)).to.empty; // Removing vm and network interface var msgs, wait_msgs = h.wait_msgs("agent.#", (msg, msgs) => msgs.length >= 2); yield remove.apply(this); data = yield aux_tools.netinfo(); msgs = yield wait_msgs; h.expect(aux_tools.filter_hostonly(data[0], info.hostonlyadapter1)).to.empty; h.expect(msgs).to.length(2); }); });
it("should add and remove dhcp server and hostonly network", function() { return async(this, function* () { // Install vm and get infos var info = yield aux_tools.install_vm.apply(this, [{ dhcp: true }]); var data = yield aux_tools.netinfo(); // Check for vmbox networking var net = aux_tools.filter_hostonly(data[0], info.hostonlyadapter1); h.expect(net).to.have.property('Name', info.hostonlyadapter1); h.expect(net).to.have.property('IPAddress' , net_opts.gateway); h.expect(net).to.have.property('NetworkMask', net_opts.netmask); // Check for dhcp server var VBoxNetworkName = net.VBoxNetworkName; var server = aux_tools.filter_dhcp(data[1], VBoxNetworkName); h.expect(server).to.have.property('lowerIPAddress', opts.ip); h.expect(server).to.have.property('upperIPAddress', opts.ip); // Removing vm, network and dhcp server yield remove.apply(this); data = yield aux_tools.netinfo(); h.expect(aux_tools.filter_hostonly(data[0], info.hostonlyadapter1)).to.empty; h.expect(aux_tools.filter_dhcp(data[1], VBoxNetworkName)).to.empty; }); });
function config_dhcp(net, getway, net_mask, ip) { return async(function* () { var lower_ip = ip; var upper_ip = ip; yield dhcp.ensure_hostonly_server(net, getway, net_mask, lower_ip, upper_ip); yield dhcp.enable_hostonly_server(net); }); }
it("should run and stop daemon with system options", function() { return async(function* () { var container = yield system.runDaemon(); var data = yield container.inspect(); yield system.stop([data]); return h.expect(container.inspect().catch(() => {})).to.reject; }); });
pull(options, stdout) { return async(this, function* () { // split docker namespace and docker repository var namespace = ''; var repository = ''; var splited = this.repository.split('\/'); if (splited.length === 2) { namespace = splited[0]; repository = splited[1]; } else { namespace = 'library'; repository = this.repository; } // check if exists local image this.repository = namespace + '/' + repository; var image = yield this.check(); // check official docker image without "library/" namespace if (isBlank(image) && namespace === 'library') { this.repository = repository; image = yield this.check(); } // download from registry if (isBlank(image) || options.build_force) { this.repository = namespace + '/' + repository; publish("image.pull.status", { type: "action", context: "image", action: "pull_image", data: this }); var registry_result; var output; var currentOnline = yield net.isOnlineCheck(); if ( !currentOnline ) { throw new NoInternetConnection(); } // get size and layers count try { registry_result = yield this.getDownloadInfo( lazy.docker.modem, namespace, repository, this.tag); output = _.isObject(stdout) && stdout; // docker pull image = yield lazy.docker.pull(this.repository, this.tag, output, registry_result); } catch (err) { output = (err || '').toString(); throw new LostInternetConnection(' ' + output); } yield this._track('pull'); } return this.check(); }); }
it("should run a daemon with system options", function() { return async(function* () { var container = yield system.runDaemon(); var data = yield container.inspect(); h.expect(data).to.have.deep.property('Annotations.azk.sys', system.name); h.expect(data).to.have.deep.property('State.ExitCode', 0); h.expect(data).to.have.deep.property('State.Running').and.ok; }); });
it("should call a \'binded\' node function", function() { var myClass = new MyClass('PREFIX-'); return async(function* () { return yield nfcall(myClass.myNodeStyleMethod.bind(myClass), '-SUFIX'); }) .then(function (result) { h.expect(result).to.equal('PREFIX-INNER_PROPERTY-SUFIX'); }); });
it("should sync two folders", function() { return async(function* () { var [origin, dest] = yield make_copy(); var code = yield lazy.Sync.sync(origin, dest); var result = yield h.diff(origin, dest); h.expect(code).to.eql(0); h.expect(result).to.have.property('deviation', 0); }); });
it("should support a sync with bind", function() { this.var = 'onevalue'; /* jshint ignore:start */ return h.expect(async(this, function* () { h.expect(this.var).to.equal('onevalue'); return true; })).to.eventually.ok; /* jshint ignore:end */ });
it("should not sync an invalid folder", function() { return async(function* () { var origin = invalid_fixtures; var dest = yield h.tmp_dir(); var promise = lazy.Sync.sync(origin, dest); return h.expect(promise).to.be.rejected.and.eventually.have.property('code', 23); }); });
action_remove(vm_info, opts) { return async(this, function* () { this.require_installed(vm_info); if (vm_info.running) { yield lazy.VM.stop(vm_info.name, opts.force); } yield lazy.VM.remove(vm_info.name); }); }
relevantFiles = yield mapPromises(projectFiles, function(fullpath) { return async(this, function* () { var content = yield fsAsync.readFile(fullpath); return { fullpath: fullpath, content: content.toString() }; }); });
action_start(vm_info/*, _opts*/) { return async(this, function* () { if (vm_info.running) { this.ui.fail("commands.vm.already_running"); return 1; } this.require_installed(vm_info); yield lazy.Server.installVM(true, false); }); }
it("should run a command in a shell for a system", function() { return async(function* () { var exitResult = yield system.runShell({ command: ["ls -ls; exit"], stdout: mocks.stdout, stderr: mocks.stderr }); h.expect(exitResult).to.have.property("code", 0); h.expect(outputs).to.have.property("stdout").match(/.*src/); }); });
it("should start, stop and return vm status", function() { return async(this, function* () { this.timeout(15000); h.expect(yield lazy.VM.start(opts.name)).to.ok; h.expect(yield lazy.VM.start(opts.name)).to.fail; h.expect(yield lazy.VM.isRunnig(opts.name)).to.ok; h.expect(yield lazy.VM.stop(opts.name, true)).to.ok; h.expect(yield lazy.VM.isRunnig(opts.name)).to.fail; h.expect(yield lazy.VM.stop(opts.name)).to.fail; }); });
it("should support a async alias", function() { var promise = async(function* () { var number = yield will_solve(); h.expect(number).to.equal(1); return true; }); return promise.then((result) => { h.expect(result).to.equal(true); }); });
it("should wait for server runing in a unix socket", function() { var connect = () => { return net_utils.waitService("unix://" + unix, { timeout: 500 }); }; return async(function* () { yield h.expect(connect()).to.eventually.equal(false); yield runServer(unix); yield h.expect(connect()).to.eventually.equal(true); }); });
it("should support create with a name", function() { return async(function* () { var name = `/${namespace}.azk-test-cont-name`; var cmd = ["/bin/true"]; var opts = { name: name, rm: false, stdout: mocks.stdout }; var cont = yield h.docker.run(default_img, cmd, opts); var data = yield cont.inspect(); h.expect(data).to.have.property('Name', name); }); });
it("should support remove container after ended run", function() { return async(function* () { var exitResult = yield system.runShell({ command: ["exit"], remove: true, stdout: mocks.stdout, stderr: mocks.stderr }); h.expect(exitResult).to.have.property("code", 0); var container = h.docker.findContainer(exitResult.containerId); return h.expect(container).to.eventually.null; }); });