How to use writefile method in Cypress

Best JavaScript code snippet using cypress

thrusterCheck-utils.js

Source:thrusterCheck-utils.js Github

copy

Full Screen

12import {getIdByCompanyName, getIdBySiteName, getSiteNEidByName} from '../utils/basic-utils'3import {exec_cmd_on_local} from '../utils/consulCheck-utils'4import {testCPEGlobalConfigBody} from '../utils/variables-utils'5const pythonLogPath = "cypress/results/pythoncmd.log"6const genFilesPath = "/tmp/"78export function checkAiwanJson(token, companyName, siteName, sn){9 let tmpFile = 'aiwan.json'10 getIdByCompanyName(token, companyName)11 cy.get('@companyId').then(companyId => {12 expect(companyId).to.not.equal("")13 getSiteNEidByName(token,companyId, siteName)14 cy.get('@neId').then(neId => {15 getIdBySiteName(token, companyId, siteName)16 cy.get('@siteId').then(siteId => {17 expect(neId).to.not.equal("")18 cy.writeFile(genFilesPath + tmpFile, "{\n\t\"neId\": " + neId + "\n}")19 let cmd = "diff " + genFilesPath + tmpFile + ' ' + genFilesPath + sn + "/" + tmpFile20 exec_cmd_on_local(cmd)21 })22 })23 })24}2526export function checkInfoJson(token, companyName, siteName, sn){27 let tmpFile = 'info.json'28 getIdByCompanyName(token, companyName)29 cy.get('@companyId').then(companyId => {30 expect(companyId).to.not.equal("")31 getSiteNEidByName(token,companyId, siteName)32 cy.get('@neId').then(neId => {33 getIdBySiteName(token, companyId, siteName)34 cy.get('@siteId').then(siteId => {35 expect(neId).to.not.equal("")36 var infoCheck = {}37 infoCheck.company = companyId38 infoCheck.siteId = siteId39 infoCheck.siteName = siteName40 infoCheck.companyName = companyName41 cy.log(JSON.stringify(infoCheck))42 cy.writeFile(genFilesPath + tmpFile, JSON.stringify(infoCheck))43 let cmd = "export PYTHONPATH=../erlang;python cypress/integration/utils/python-util/CheckConsul.py \"['checkJsonFile']\" " + genFilesPath + tmpFile + ' ' + genFilesPath + sn + "/" + tmpFile44 exec_cmd_on_local(cmd)45 })46 })47 })48}4950export function checkNeJson(sn){51 let tmpFile = 'ne.json'52 let neBody = JSON.parse(JSON.stringify(testCPEGlobalConfigBody.ST))53 neBody.controllers[0].mode = "gateway"54 neBody.controllers[1].mode = "parallel"55 neBody.controllers[2].mode = "series"56 cy.log(neBody.controllers[2].mode)57 cy.writeFile(genFilesPath + tmpFile, neBody)58 let cmd = "diff --suppress-common-lines -wy " + genFilesPath + tmpFile + ' ' + genFilesPath + sn + "/" + tmpFile59 exec_cmd_on_local(cmd)60}6162export function checkStartupJson(site, sn, master=true){63 let tmpFile = 'startup_cpe.json'64 var siteCheck = {}65 let mode = ""66 switch (site.type) {67 case "网关":68 mode = "gateway"69 break;70 case "串联":71 mode = "series"72 break;73 case "旁挂":74 mode = "parallel"75 break;76 default:77 cy.log("Unknown type: " + site.type)78 }79 siteCheck.mode = mode80 siteCheck.tunnelPort = parseInt(site.tunnelNum)81 var interfaces = new Array()82 if (mode != "parallel") {83 var i84 for (i=0;i<site.wans.length;i++){85 var interfaceWan = {}86 interfaceWan.name = site.wans[i].ifname87 interfaceWan.type = "WAN"88 interfaceWan.mode = site.wans[i].ip_mode89 interfaceWan.proxy = site.wans[i].proxy90 interfaceWan.usage = "normal"91 if (site.wans[i].hasOwnProperty('gatewayMac')) {92 interfaceWan["gw-mac"] = site.wans[i].gatewayMac93 }94 if (site.wans[i].hasOwnProperty('staticIp') && site.wans[i].staticIp != "") {95 interfaceWan["static-ip"] = site.wans[i].staticIp96 }97 interfaces.push(interfaceWan)98 }99 if (site.lans[0].IDC == true) {100 var interfaceLan = {}101 interfaceLan.name = site.lans[0].ifname102 interfaceLan.type = "LAN"103 interfaceLan.mode = site.lans[0].ip_mode104 interfaceLan.pair = site.lans[0].pair105 interfaces.push(interfaceLan)106 }107 if (site.hasOwnProperty('enablePrivate') && site.enablePrivate == true) {108 var interfaceDIA = {"name":"enp1s0f2","type":"LAN","mode":"DIA"}109 interfaces.push(interfaceDIA)110 }111 } else {112 // WAN113 var interfaceWan = {}114 interfaceWan.name = site.wans[0].ifname115 interfaceWan.type = "WAN"116 interfaceWan.mode = site.wans[0].ip_mode117 interfaceWan.proxy = true118 interfaceWan.usage = "normal"119 interfaceWan["parallel-gateway"] = site.wans[0].gateway120 var wanIps = new Array()121 for (i=0;i<site.wans.length;i++) {122 var wanIp = {}123 wanIp["parallel-ip"] = site.wans[i].ip124 wanIp["parallel-netmask"] = site.wans[i].mask125 wanIp["ip-mode"] = site.wans[i].ip_mode126 wanIps.push(wanIp)127 }128 interfaceWan.ips = wanIps129 if (site.HA == true) {130 if (master == true) {131 interfaceWan["static-ip"] = site.HAaddress.master_wanip132 } else {133 interfaceWan["static-ip"] = site.HAaddress.standby_wanip134 }135 }136 interfaces.push(interfaceWan)137 // LAN138 var interfaceLan = {}139 interfaceLan.name = site.lans[0].ifname140 interfaceLan.type = "LAN"141 interfaceLan.mode = "FIA"142 interfaceLan.pair = site.wans[0].ifname143 interfaceLan["parallel-gateway"] = site.lans[0].gateway144 var lanIps = new Array()145 var lanIp = {}146 lanIp["parallel-ip"] = site.lans[0].ip_addr147 lanIp["parallel-netmask"] = site.lans[0].mask148 lanIp["ip-mode"] = "FIA"149 lanIps.push(lanIp)150 interfaceLan.ips = lanIps151 if (site.HA == true) {152 if (master == true) {153 interfaceLan["static-ip"] = site.HAaddress.master_lanip154 } else {155 interfaceLan["static-ip"] = site.HAaddress.master_lanip156 }157 }158 interfaces.push(interfaceLan)159 }160 siteCheck.interface = interfaces161 if (site.hasOwnProperty('natNet')) {162 siteCheck.natNet = site.natNet163 }164 siteCheck.reportInterval = parseInt(site.reportInterval)165 siteCheck.scoreInterval = parseInt(site.scoreInterval)166 cy.log(JSON.stringify(siteCheck))167 cy.writeFile(genFilesPath + tmpFile, JSON.stringify(siteCheck))168 let cmd = "export PYTHONPATH=../erlang;python cypress/integration/utils/python-util/CheckConsul.py \"['checkJsonFile']\" " + genFilesPath + tmpFile + ' ' + genFilesPath + site.sn + "/" + tmpFile169 exec_cmd_on_local(cmd)170}171172export function checkWirelessJson(site, sn) {173 let tmpFile = 'wireless'174 cy.writeFile(genFilesPath + tmpFile, "##s\n")175 if (site.type == '网关') {176 cy.writeFile(genFilesPath + tmpFile, "config wifi-iface 'default_radio0'\n", {flag: 'a+'})177 cy.writeFile(genFilesPath + tmpFile, "\toption ssid '" + site.wifi.ssid + "'\n", {flag: 'a+'})178 cy.writeFile(genFilesPath + tmpFile, "\toption encryption '" + site.wifi.encryption + "'\n", {flag: 'a+'})179 cy.writeFile(genFilesPath + tmpFile, "\toption key '" + site.wifi.key + "'\n", {flag: 'a+'})180 var net_name = (site.wifi.network == 'lan1')?"lan":site.wifi.network.toLowerCase()181 cy.writeFile(genFilesPath + tmpFile, "\toption network '" + net_name + "'\n", {flag: 'a+'})182 cy.writeFile(genFilesPath + tmpFile, "\toption macfilter '" + site.wifi.macfilter + "'\n", {flag: 'a+'})183 var i184 for (i=0;i<site.wifi.mac_list.length;i++) {185 cy.writeFile(genFilesPath + tmpFile, "\tlist maclist '" + site.wifi.mac_list[i] + "'\n", {flag: 'a+'})186 }187 cy.writeFile(genFilesPath + tmpFile, "\toption device 'radio0'\n", {flag: 'a+'})188 cy.writeFile(genFilesPath + tmpFile, "\toption mode 'ap'\n", {flag: 'a+'})189 cy.writeFile(genFilesPath + tmpFile, "\toption disabled '0'\n\n", {flag: 'a+'})190 }191 cy.writeFile(genFilesPath + tmpFile, "\n##e\n\n", {flag: 'a+'})192 let cmd = "diff " + genFilesPath + tmpFile + ' ' + genFilesPath + site.sn + "/" + tmpFile193 exec_cmd_on_local(cmd)194}195196export function checkFirewallJson(site, sn) {197 let tmpFile = 'firewall'198 cy.writeFile(genFilesPath + tmpFile, "##s\n")199 if (site.type == '网关') {200 if (site.hasOwnProperty('natPort')) {201 cy.writeFile(genFilesPath + tmpFile, "config rule\n", {flag: 'a+'})202 cy.writeFile(genFilesPath + tmpFile, "\toption name 'Allow-Aiwan-Link'\n", {flag: 'a+'})203 cy.writeFile(genFilesPath + tmpFile, "\toption src 'wan'\n", {flag: 'a+'})204 cy.writeFile(genFilesPath + tmpFile, "\toption proto 'udp'\n", {flag: 'a+'})205 cy.writeFile(genFilesPath + tmpFile, "\toption dest_port '" + site.natPort + "'\n", {flag: 'a+'})206 cy.writeFile(genFilesPath + tmpFile, "\toption target 'ACCEPT'\n", {flag: 'a+'})207 cy.writeFile(genFilesPath + tmpFile, "\t option family 'ipv4'\n", {flag: 'a+'})208 }209 var i210 for (i=0;i<site.lans.length;i++) {211 cy.writeFile(genFilesPath + tmpFile, "config zone\n", {flag: 'a+'})212 var lan_name = (site.lans[i].name == 'LAN1')?"lan":'aiwanlan2'213 cy.writeFile(genFilesPath + tmpFile, "\toption name '" + lan_name + "'\n", {flag: 'a+'})214 cy.writeFile(genFilesPath + tmpFile, "\tlist network '" + lan_name + "'\n", {flag: 'a+'})215 cy.writeFile(genFilesPath + tmpFile, "\toption input 'ACCEPT'\n", {flag: 'a+'})216 cy.writeFile(genFilesPath + tmpFile, "\toption output 'ACCEPT'\n", {flag: 'a+'})217 cy.writeFile(genFilesPath + tmpFile, "\toption forward 'REJECT'\n", {flag: 'a+'})218 if (site.lans[i].IDC) {219 cy.writeFile(genFilesPath + tmpFile, "config forwarding\n", {flag: 'a+'})220 cy.writeFile(genFilesPath + tmpFile, "\toption src '" + lan_name + "'\n", {flag: 'a+'})221 cy.writeFile(genFilesPath + tmpFile, "\toption dest 'aiwan_tun'\n\n", {flag: 'a+'})222 cy.writeFile(genFilesPath + tmpFile, "config forwarding\n", {flag: 'a+'})223 cy.writeFile(genFilesPath + tmpFile, "\toption src 'aiwan_tun'\n", {flag: 'a+'})224 cy.writeFile(genFilesPath + tmpFile, "\toption dest '" + lan_name + "'\n\n", {flag: 'a+'})225 }226 if (site.lans[i].internet) {227 cy.writeFile(genFilesPath + tmpFile, "config forwarding\n", {flag: 'a+'})228 cy.writeFile(genFilesPath + tmpFile, "\toption src '" + lan_name + "'\n", {flag: 'a+'})229 cy.writeFile(genFilesPath + tmpFile, "\toption dest 'wan'\n\n", {flag: 'a+'})230 }231 }232 }233 cy.writeFile(genFilesPath + tmpFile, "\n##e\n\n", {flag: 'a+'})234 let cmd = "diff " + genFilesPath + tmpFile + ' ' + genFilesPath + site.sn + "/" + tmpFile235 exec_cmd_on_local(cmd)236}237238export function checkNetworkJson(site, sn) {239 let tmpFile = 'network'240 cy.writeFile(genFilesPath + tmpFile, "##s\n")241 if (site.type == '网关') {242 var i243 for (i=0;i<site.wans.length;i++) {244 cy.writeFile(genFilesPath + tmpFile, "config interface '", {flag: 'a+'})245 var wan_name = (site.wans[i].name == 'WAN1')?"wan":site.wans[i].name.toLowerCase()246 cy.writeFile(genFilesPath + tmpFile, wan_name + "'\n", {flag: 'a+'})247 cy.writeFile(genFilesPath + tmpFile, "\toption ifname '" + site.wans[i].ifname + "'\n", {flag: 'a+'})248 cy.writeFile(genFilesPath + tmpFile, "\toption proto '", {flag: 'a+'})249 switch (site.wans[i].ip_type) {250 case "静态ip地址":251 cy.writeFile(genFilesPath + tmpFile, "static'\n\toption ipaddr '" + site.wans[i].ip + "'\n", {flag: 'a+'})252 var maskStr=ipv4PrefixLen2MaskStr(site.wans[i].mask)253 cy.writeFile(genFilesPath + tmpFile, "\toption netmask '" + maskStr + "'\n\n", {flag: 'a+'})254 break255 case "PPPOE":256 cy.writeFile(genFilesPath + tmpFile, "pppoe'\n\toption username '" + site.wans[i].account + "'\n", {flag: 'a+'})257 cy.writeFile(genFilesPath + tmpFile, "\toption password '" + site.wans[i].password + "'\n", {flag: 'a+'})258 cy.writeFile(genFilesPath + tmpFile, "\toption metric '100'\n\n", {flag: 'a+'})259 break260 case "DHCP":261 cy.writeFile(genFilesPath + tmpFile, "dhcp'\n\n", {flag: 'a+'})262 break263 default:264 cy.log("Unknown ip_type: " + site.wans[i].ip_type)265 }266 }267 for (i=0;i<site.lans.length;i++) {268 cy.writeFile(genFilesPath + tmpFile, "config interface '", {flag: 'a+'})269 var lan_name = (site.lans[i].name == 'LAN1')?"lan":"aiwanlan2"270 cy.writeFile(genFilesPath + tmpFile, lan_name + "'\n", {flag: 'a+'})271 cy.writeFile(genFilesPath + tmpFile, "\toption ifname '" + site.lans[i].phy_ifname + "'\n", {flag: 'a+'})272 cy.writeFile(genFilesPath + tmpFile, "\toption proto '", {flag: 'a+'})273 cy.writeFile(genFilesPath + tmpFile, "static'\n\toption ipaddr '" + site.lans[i].ip_addr + "'\n", {flag: 'a+'})274 var maskStr=ipv4PrefixLen2MaskStr(site.lans[i].mask)275 cy.writeFile(genFilesPath + tmpFile, "\toption netmask '" + maskStr + "'\n", {flag: 'a+'})276 cy.writeFile(genFilesPath + tmpFile, "\toption type 'bridge'\n\n", {flag: 'a+'})277 }278 }279 // wan2 static280 for (i=1;i<site.wans.length;i++) {281 if (site.wans[i].ip_type == '静态ip地址') {282 cy.writeFile(genFilesPath + tmpFile, "config route 'to_gateway_default_", {flag: 'a+'})283 var wan_name = (site.wans[i].name == 'WAN1')?"wan":site.wans[i].name.toLowerCase()284 cy.writeFile(genFilesPath + tmpFile, wan_name + "'\n", {flag: 'a+'})285 cy.writeFile(genFilesPath + tmpFile, "\toption interface '" + wan_name + "'\n", {flag: 'a+'})286 cy.writeFile(genFilesPath + tmpFile, "\toption table '20'\n", {flag: 'a+'})287 cy.writeFile(genFilesPath + tmpFile, "\toption netmask '0.0.0.0'\n", {flag: 'a+'})288 cy.writeFile(genFilesPath + tmpFile, "\toption target '0.0.0.0'\n", {flag: 'a+'})289 cy.writeFile(genFilesPath + tmpFile, "\toption gateway '" + site.wans[i].gateway + "'\n\n", {flag: 'a+'})290 cy.writeFile(genFilesPath + tmpFile, "config route 'to_gateway_default_main_" + wan_name + "'\n", {flag: 'a+'})291 cy.writeFile(genFilesPath + tmpFile, "\toption interface '" + wan_name + "'\n", {flag: 'a+'})292 cy.writeFile(genFilesPath + tmpFile, "\toption table 'main'\n", {flag: 'a+'})293 cy.writeFile(genFilesPath + tmpFile, "\toption netmask '0.0.0.0'\n", {flag: 'a+'})294 cy.writeFile(genFilesPath + tmpFile, "\toption target '0.0.0.0'\n", {flag: 'a+'})295 cy.writeFile(genFilesPath + tmpFile, "\toption gateway '" + site.wans[i].gateway + "'\n", {flag: 'a+'})296 cy.writeFile(genFilesPath + tmpFile, "\toption metric '100'\n\n", {flag: 'a+'})297 }298 }299 cy.writeFile(genFilesPath + tmpFile, "\n##e\n", {flag: 'a+'})300 cy.writeFile(genFilesPath + tmpFile, "\n##rs\n", {flag: 'a+'})301 if (site.hasOwnProperty('natNet')) {302 cy.writeFile(genFilesPath + tmpFile, "config route\n", {flag: 'a+'})303 cy.writeFile(genFilesPath + tmpFile, "\toption interface 'tun'\n", {flag: 'a+'})304 var natNet = site.natNet.split('/')305 cy.writeFile(genFilesPath + tmpFile, "\toption target '" + natNet[0] + "'\n", {flag: 'a+'})306 cy.writeFile(genFilesPath + tmpFile, "\toption netmask '" + ipv4PrefixLen2MaskStr(natNet[1]) + "'\n\n", {flag: 'a+'})307 }308 cy.writeFile(genFilesPath + tmpFile, "\n##re\n", {flag: 'a+'})309 let cmd = "diff " + genFilesPath + tmpFile + ' ' + genFilesPath + site.sn + "/" + tmpFile310 exec_cmd_on_local(cmd)311}312313export function checkDhcpJson(site, sn) {314 let tmpFile = 'dhcp'315 cy.writeFile(genFilesPath + tmpFile, "##s\n")316 var i317 for (i=0;i<site.lans.length;i++) {318 var if_name = (site.lans[i].name == 'LAN1')?"lan":site.lans[i].name.toLowerCase()319 var lan_name = (site.lans[i].name == 'LAN1')?"lan":"aiwanlan2"320 cy.writeFile(genFilesPath + tmpFile, "config dhcp '" + if_name + "'\n", {flag: 'a+'})321 if (site.lans[i].DHCP==false) {322 cy.writeFile(genFilesPath + tmpFile, "\toption dhcpv4 'disable'\n\n", {flag: 'a+'})323 } else {324 cy.writeFile(genFilesPath + tmpFile, "\toption interface '" + lan_name + "'\n", {flag: 'a+'})325 cy.writeFile(genFilesPath + tmpFile, "\toption start '" + site.lans[i].ip_start.split('.').pop() + "'\n", {flag: 'a+'})326 var count=site.lans[i].ip_end.split('.').pop()-site.lans[i].ip_start.split('.').pop()327 cy.writeFile(genFilesPath + tmpFile, "\toption limit '" + count + "'\n", {flag: 'a+'})328 cy.writeFile(genFilesPath + tmpFile, "\toption leasetime '12h'\n", {flag: 'a+'})329 cy.writeFile(genFilesPath + tmpFile, "\toption dhcpv6 'server'\n", {flag: 'a+'})330 cy.writeFile(genFilesPath + tmpFile, "\toption ra 'server'\n\n", {flag: 'a+'})331 }332 }333 cy.writeFile(genFilesPath + tmpFile, "\n##e\n\n", {flag: 'a+'})334 let cmd = "diff " + genFilesPath + tmpFile + ' ' + genFilesPath + site.sn + "/" + tmpFile335 exec_cmd_on_local(cmd)336}337338export function ipv4PrefixLen2MaskStr (prefixLen) {339 if (prefixLen > 32) {340 return '255.255.255.255'341 }342 var x=prefixLen/8343 var y=prefixLen%8344 var z=4-x-1345 var res=""346 var i347 for (i=0;i<x;i++) {348 res=res.concat('255.')349 }350 var tmp=0351 for (i=0;i<y;i++) {352 tmp=tmp*2+1353 }354 for (i=0;i<8-y;i++) {355 tmp=tmp*2356 }357 res=res.concat(tmp + '.')358 for (i=0;i<z;i++) {359 res=res.concat('0.')360 }361 return res.substring(0,res.length-1)362}363364export function exec_cmd_on_local_ignoreErr(cmd){365 cy.log(cmd)366 cy.exec(cmd,{ failOnNonZeroExit: false }).then(result => {367 cy.writeFile(pythonLogPath,cmd + "\ncmdError:\n" + result.stderr + "\n" + result.stdout + "\n", {flag: 'a+'})368 cy.log(result.stderr)369 cy.log(result.stdout)370 cy.log(result.code)371 }) ...

Full Screen

Full Screen

OrgWriter.test.js

Source:OrgWriter.test.js Github

copy

Full Screen

1/* eslint-disable max-lines */2const writeFile = ORG.Writer.writeFile;3QUnit.module("OrgWriter Tests", () => {4 QUnit.test("should return empty string for non-array input", (assert) => {5 assert.equal(writeFile(), "");6 assert.equal(writeFile("test"), "");7 assert.equal(writeFile({}), "");8 assert.equal(writeFile(Object.assign([], {"TEXT": ""})), "");9 });10 QUnit.test("should return null if string is given as parameter", (assert) => {11 assert.equal(writeFile("test"), "");12 });13 QUnit.test("should return null if object is given as parameter", (assert) => {14 assert.equal(writeFile({}), "");15 });16 QUnit.test("should return null given empty nodes", (assert) => {17 assert.equal(writeFile([]), "");18 });19 QUnit.test("should return empty string if nodes has empty objects", (assert) => {20 assert.equal(writeFile([{"TEXT": [], "PROPS": {}}]), "");21 assert.equal(writeFile([{"TEXT": [], "PROPS": {}}, {"TEXT": [], "PROPS": {}}]), "");22 assert.equal(writeFile([{"TEXT": [], "PROPS": {}}, {"TEXT": [], "PROPS": {}}, {"TEXT": [], "PROPS": {}}]), "");23 });24 QUnit.test("should return as expected only first node", (assert) => {25 assert.equal(writeFile(Object.assign([], {"TEXT": ""})), "");26 assert.equal(writeFile(Object.assign([], {"TEXT": null})), "");27 assert.equal(writeFile(Object.assign([], {"TEXT": "test"})), "test");28 assert.equal(writeFile(Object.assign([], {"CATEGORY": "cat1", "TEXT": "#+CATEGORY: cat1\ntest"})), "#+CATEGORY: cat1\ntest");29 assert.equal(writeFile(Object.assign([], {"CATEGORY": "", "TEXT": "test"})), "test");30 });31 QUnit.test("writeFile should return as expected", (assert) => {32 assert.equal(writeFile([{33 "LVL": "1",34 "TODO": "",35 "TITLE": "test",36 "TEXT": [],37 "PROPS": {}38 }]), "* test");39 assert.equal(writeFile([{40 "LVL": "1",41 "TODO": "SMTH",42 "TITLE": "test",43 "TEXT": [],44 "PROPS": {}45 }]), "* SMTH test");46 assert.equal(writeFile([{47 "LVL": "1",48 "TITLE": "test",49 "TEXT": [],50 "PROPS": {}51 }]), "* test");52 assert.equal(writeFile([{53 "LVL": "1",54 "TODO": "SMTH",55 "PRI": "A",56 "TEXT": [],57 "PROPS": {}58 }]), "* SMTH [#A]");59 assert.equal(writeFile([{60 "LVL": "2",61 "TODO": "SMTH",62 "PRI": "A",63 "TITLE": "test",64 "TEXT": [],65 "PROPS": {}66 }]), "** SMTH [#A] test");67 assert.equal(writeFile(Object.assign([{68 "LVL": "1",69 "TODO": "",70 "TITLE": "test",71 "TEXT": [],72 "PROPS": {}73 }], {"TEXT": "settings"})), "settings\n* test");74 assert.equal(writeFile([{75 "LVL": "1",76 "TODO": "SMTH",77 "PRI": "A",78 "TITLE": "test",79 "TAGS": ":tag1:",80 "TEXT": [],81 "PROPS": {}82 }]), "* SMTH [#A] test\t\t:tag1:");83 assert.equal(writeFile([{84 "LVL": "1",85 "PRI": "A",86 "TITLE": "test",87 "TAGS": ":tag1:",88 "TEXT": [],89 "PROPS": {}90 }]), "* [#A] test\t\t:tag1:");91 assert.equal(writeFile([{92 "LVL": "1",93 "TODO": "SMTH",94 "TITLE": "test",95 "TAGS": ":tag1:",96 "TEXT": [],97 "PROPS": {}98 }]), "* SMTH test\t\t:tag1:");99 assert.equal(writeFile([{100 "LVL": "1",101 "TODO": "SMTH",102 "PRI": "A",103 "TAGS": ":tag1:",104 "TEXT": [],105 "PROPS": {}106 }]), "* SMTH [#A]\t\t:tag1:");107 assert.equal(writeFile([{108 "LVL": "1",109 "TODO": "SMTH",110 "PRI": "A",111 "TITLE": "test",112 "TAGS": ":tag1:",113 "TEXT": [],114 "PROPS": {}115 }]), "* SMTH [#A] test\t\t:tag1:");116 });117 QUnit.test("writeFile should return as expected with schedule", (assert) => {118 assert.equal(writeFile([{119 "LVL": "1",120 "TODO": "SMTH",121 "PRI": "A",122 "TITLE": "test",123 "TAGS": ":tag1:",124 "TEXT": [],125 "SCHEDULED": {126 "ml": 1525294800000,127 },128 "PROPS": {}129 }]), "* SMTH [#A] test\t\t:tag1:\nSCHEDULED: <2018-05-03 Thu>");130 });131 QUnit.test("should return as expected with schedule with hours", (assert) => {132 assert.equal(writeFile([{133 "LVL": "1",134 "TITLE": "test",135 "TEXT": [],136 "SCHEDULED": {137 "ml": 1525294800000,138 "hs": "12:00",139 },140 "PROPS": {}141 }]), "* test\nSCHEDULED: <2018-05-03 Thu 12:00>");142 assert.equal(writeFile([{143 "LVL": "1",144 "TITLE": "test",145 "TEXT": [],146 "SCHEDULED": {147 "ml": 1525294800000,148 "he": "12:00",149 },150 "PROPS": {}151 }]), "* test\nSCHEDULED: <2018-05-03 Thu>");152 assert.equal(writeFile([{153 "LVL": "1",154 "TITLE": "test",155 "TEXT": [],156 "SCHEDULED": {157 "ml": 1525294800000,158 "hs": "12:00",159 "he": "14:00",160 },161 "PROPS": {}162 }]), "* test\nSCHEDULED: <2018-05-03 Thu 12:00-14:00>");163 });164 QUnit.test("should return as expected with schedule with repeater", (assert) => {165 assert.equal(writeFile([{166 "LVL": "1",167 "TITLE": "test",168 "TEXT": [],169 "SCHEDULED": {170 "ml": 1525294800000,171 "r": "+",172 "rmin": "1d",173 },174 "PROPS": {}175 }]), "* test\nSCHEDULED: <2018-05-03 Thu +1d>");176 assert.equal(writeFile([{177 "LVL": "1",178 "TITLE": "test",179 "TEXT": [],180 "SCHEDULED": {181 "ml": 1525294800000,182 "rmin": "1d",183 },184 "PROPS": {}185 }]), "* test\nSCHEDULED: <2018-05-03 Thu>");186 assert.equal(writeFile([{187 "LVL": "1",188 "TITLE": "test",189 "TEXT": [],190 "SCHEDULED": {191 "ml": 1525294800000,192 "r": "+",193 "rmin": "1d",194 "rmax": "2d",195 },196 "PROPS": {}197 }]), "* test\nSCHEDULED: <2018-05-03 Thu +1d/2d>");198 assert.equal(writeFile([{199 "LVL": "1",200 "TITLE": "test",201 "TEXT": [],202 "SCHEDULED": {203 "ml": 1525294800000,204 "hs": "12:00",205 "he": "14:00",206 "r": "+",207 "rmin": "1d",208 "rmax": "2d",209 },210 "PROPS": {}211 }]), "* test\nSCHEDULED: <2018-05-03 Thu 12:00-14:00 +1d/2d>");212 });213 QUnit.test("should return as expected with schedule with warning", (assert) => {214 assert.equal(writeFile([{215 "LVL": "1",216 "TITLE": "test",217 "TEXT": [],218 "SCHEDULED": {219 "ml": 1525294800000,220 "w": "1w",221 },222 "PROPS": {}223 }]), "* test\nSCHEDULED: <2018-05-03 Thu -1w>");224 assert.equal(writeFile([{225 "LVL": "1",226 "TITLE": "test",227 "TEXT": [],228 "SCHEDULED": {229 "ml": 1525294800000,230 "hs": "12:00",231 "he": "14:00",232 "w": "1w",233 },234 "PROPS": {}235 }]), "* test\nSCHEDULED: <2018-05-03 Thu 12:00-14:00 -1w>");236 assert.equal(writeFile([{237 "LVL": "1",238 "TITLE": "test",239 "TEXT": [],240 "SCHEDULED": {241 "ml": 1525294800000,242 "r": "+",243 "rmin": "1d",244 "rmax": "2d",245 "w": "1w",246 },247 "PROPS": {}248 }]), "* test\nSCHEDULED: <2018-05-03 Thu +1d/2d -1w>");249 assert.equal(writeFile([{250 "LVL": "1",251 "TITLE": "test",252 "TEXT": [],253 "SCHEDULED": {254 "ml": 1525294800000,255 "r": "+",256 "rmin": "1d",257 "w": "1w",258 },259 "PROPS": {}260 }]), "* test\nSCHEDULED: <2018-05-03 Thu +1d -1w>");261 assert.equal(writeFile([{262 "LVL": "1",263 "TITLE": "test",264 "TEXT": [],265 "SCHEDULED": {266 "ml": 1525294800000,267 "hs": "12:00",268 "he": "14:00",269 "r": "+",270 "rmin": "1d",271 "rmax": "2d",272 "w": "1w",273 },274 "PROPS": {}275 }]), "* test\nSCHEDULED: <2018-05-03 Thu 12:00-14:00 +1d/2d -1w>");276 });277 QUnit.test("should return as expected with schedule with next timestamp", (assert) => {278 assert.equal(writeFile([{279 "LVL": "1",280 "TITLE": "test",281 "TEXT": [],282 "SCHEDULED": {283 "ml": 1525294800000,284 "n": "",285 },286 "PROPS": {}287 }]), "* test\nSCHEDULED: <2018-05-03 Thu>");288 assert.equal(writeFile([{289 "LVL": "1",290 "TITLE": "test",291 "TEXT": [],292 "SCHEDULED": {293 "ml": 1525294800000,294 "n": "test",295 },296 "PROPS": {}297 }]), "* test\nSCHEDULED: <2018-05-03 Thu>");298 assert.equal(writeFile([{299 "LVL": "1",300 "TITLE": "test",301 "TEXT": [],302 "SCHEDULED": {303 "ml": 1525294800000,304 "n": null,305 },306 "PROPS": {}307 }]), "* test\nSCHEDULED: <2018-05-03 Thu>");308 assert.equal(writeFile([{309 "LVL": "1",310 "TITLE": "test",311 "TEXT": [],312 "SCHEDULED": {313 "ml": 1525294800000,314 "n": {"ml": 1525381200000},315 },316 "PROPS": {}317 }]), "* test\nSCHEDULED: <2018-05-03 Thu>-<2018-05-04 Fri>");318 });319 QUnit.test("should return as expected with deadline", (assert) => {320 assert.equal(writeFile([{321 "LVL": "1",322 "TITLE": "test",323 "DEADLINE": {"ml": 1525294800000},324 "TEXT": [],325 "PROPS": {}326 }]), "* test\nDEADLINE: <2018-05-03 Thu>");327 assert.equal(writeFile([{328 "LVL": "1",329 "TITLE": "test",330 "SCHEDULED": {"ml": 1525294800000},331 "DEADLINE": {"ml": 1525294800000},332 "TEXT": [],333 "PROPS": {}334 }]), "* test\nSCHEDULED: <2018-05-03 Thu> DEADLINE: <2018-05-03 Thu>");335 });336 QUnit.test("should return as expected with properties", (assert) => {337 assert.equal(writeFile([{338 "LVL": "1",339 "TITLE": "test",340 "TEXT": [],341 "PROPS": {}342 }]), "* test");343 assert.equal(writeFile([{344 "LVL": "1",345 "TITLE": "test",346 "TEXT": [],347 "PROPS": {"prop1": "val1"}348 }]), "* test\n:PROPERTIES:\n:prop1: val1\n:END:");349 assert.equal(writeFile([{350 "LVL": "1",351 "TITLE": "test",352 "TEXT": [],353 "PROPS": {"prop1": "val1", "prop2": "val2"}354 }]), "* test\n:PROPERTIES:\n:prop1: val1\n:prop2: val2\n:END:");355 assert.equal(writeFile([{356 "LVL": "1",357 "TITLE": "test",358 "TEXT": [],359 "SCHEDULED": {360 "ml": 1525294800000,361 "n": {"ml": 1525381200000},362 },363 "PROPS": {"prop1": "val1", "prop2": "val2"},364 }]), "* test\nSCHEDULED: <2018-05-03 Thu>-<2018-05-04 Fri>\n:PROPERTIES:\n:prop1: val1\n:prop2: val2\n:END:");365 assert.equal(writeFile([{366 "LVL": "1",367 "TITLE": "test",368 "TEXT": [],369 "DEADLINE": {"ml": 1525294800000},370 "SCHEDULED": {371 "ml": 1525294800000,372 "n": {"ml": 1525381200000},373 },374 "PROPS": {"prop1": "val1", "prop2": "val2"},375 }]), "* test\nSCHEDULED: <2018-05-03 Thu>-<2018-05-04 Fri> DEADLINE: <2018-05-03 Thu>\n:PROPERTIES:\n:prop1: val1\n:prop2: val2\n:END:");376 });377 QUnit.test("should return as expected with text", (assert) => {378 assert.equal(writeFile([{379 "LVL": "1",380 "TITLE": "test",381 "TEXT": ["log1"],382 "PROPS": {}383 }]), "* test\nlog1");384 assert.equal(writeFile([{385 "LVL": "1",386 "TITLE": "test",387 "TEXT": ["log1", "log2"],388 "PROPS": {}389 }]), "* test\nlog1\nlog2");390 assert.equal(writeFile([{391 "LVL": "1",392 "TITLE": "test",393 "TEXT": ["log1", "log2"],394 "PROPS": {"prop1": "val1", "prop2": "val2"},395 }]), "* test\n:PROPERTIES:\n:prop1: val1\n:prop2: val2\n:END:\nlog1\nlog2");396 assert.equal(writeFile([{397 "LVL": "1",398 "TITLE": "test",399 "DEADLINE": {"ml": 1525294800000},400 "SCHEDULED": {401 "ml": 1525294800000,402 "n": {"ml": 1525381200000},403 },404 "TEXT": ["log1", "log2"],405 "PROPS": {"prop1": "val1", "prop2": "val2"},406 }]), "* test\nSCHEDULED: <2018-05-03 Thu>-<2018-05-04 Fri> DEADLINE: <2018-05-03 Thu>\n:PROPERTIES:\n:prop1: val1\n:prop2: val2\n:END:\nlog1\nlog2");407 });408 QUnit.test("should return as expected with multiple nodes", (assert) => {409 assert.equal(writeFile(Object.assign([410 {"LVL": "1", "TITLE": "test1", "TEXT": [], "PROPS": {}},411 {"LVL": "2", "TITLE": "test2", "TEXT": [], "PROPS": {}}], {"TEXT": "setting"})),412 "setting\n* test1\n** test2");413 assert.equal(writeFile(Object.assign([414 {"LVL": "1", "TITLE": "test1", "DEADLINE": {"ml": 1525294800000}, "TEXT": [""], "PROPS": {}},415 {"LVL": "2", "TITLE": "test2", "PROPS": {"prop1": "val1", "prop2": "val2"}, "TEXT": ["text1"]}], {"TEXT": "setting"})),416 "setting\n* test1\nDEADLINE: <2018-05-03 Thu>\n\n** test2\n:PROPERTIES:\n:prop1: val1\n:prop2: val2\n:END:\ntext1");417 });418 QUnit.test("write proper CLOSED", (assert) => {419 assert.equal(writeFile([{420 "LVL": "1",421 "TITLE": "test",422 "TEXT": [],423 "CLOSED": {424 "ml": 1532693134504,425 "hs": "15:05",426 },427 "PROPS": {}428 }]), "* test\nCLOSED: [2018-07-27 Fri 15:05]");429 });430 QUnit.test("write time should be at least 100k nodes/sec @i7-6700HQ", (assert) => {431 var done = assert.async();432 $.get("./OrgParser.test.1000nodes.org", (orgFileTxt) => {433 const nodes = ORG.Parser.parseFile("", orgFileTxt, ORG.defaults);434 const p0 = performance.now();435 writeFile(nodes);436 assert.ok(performance.now() - p0 < 10);437 done();438 }).fail(() => {439 assert.ok(1);440 done();441 });442 });...

Full Screen

Full Screen

actions.js

Source:actions.js Github

copy

Full Screen

1const fs = require('fs');2const path = require('path');3const chalk = require('chalk');4const lignator = require('lignator');5function writeFile(fileName, fileNameTemp, dir = '.') {6 if (!fs.existsSync(`${dir}/${fileName}`)) {7 const tempPath = path.join(__dirname, '../templates');8 const lastPath = dir.substring(dir.indexOf('/') + 1);9 const fileTemp = fs.readFileSync(`${tempPath}/${dir === '.' ? fileNameTemp : lastPath + '/' + fileNameTemp}`);10 const indent = dir === '.' ? '' : ' ';11 fs.writeFileSync(`${dir}/${fileName}`, fileTemp);12 console.log(chalk.green(`${indent}✔ Create ${dir === '.' ? fileName : dir + '/' + fileName} successful`));13 } else console.log(chalk.red(`✖ File ${fileName} already exists!`));14}15function makeDir(dir) {16 if (!fs.existsSync(`./${dir}`)) {17 fs.mkdirSync(`./${dir}`, { recursive: true });18 console.log(chalk.green(`✔ Make directory ${dir} successful`));19 return true;20 } else {21 console.log(chalk.red(`✖ Directory ${dir} already exists!`));22 return false;23 }24}25var actions = {};26actions.init = path => {27 var initSuccess = true;28 var startTime = process.hrtime();29 /** make directory if path defined */30 if (path) {31 makeDir(path);32 } else path = '.';33 const expExists = fs.existsSync(`${path}/app.js`) || fs.existsSync(`${path}/package.json`);34 if (!expExists) {35 /** create package.json */36 writeFile(`${path}/package.json`, 'packageTemp.json');37 /** create app.js */38 writeFile(`${path}/app.js`, 'appTemp.js');39 /** create module apidoc */40 const apiDocDir = `${path}/apidoc`;41 if (makeDir(apiDocDir)) {42 writeFile('apidoc.html', 'apiDocTemp.html', apiDocDir);43 writeFile('favicon.ico', 'faviconTemp.ico', apiDocDir);44 writeFile('icon.png', 'iconTemp.png', apiDocDir);45 }46 /** create module config */47 const configDir = `${path}/config`;48 if (makeDir(configDir)) {49 writeFile('config.js', 'configTemp.js', configDir);50 writeFile('graphql.js', 'graphqlTemp.js', configDir);51 writeFile('swagger.js', 'swaggerTemp.js', configDir);52 }53 /** create module docs */54 const docsDir = `${path}/docs`;55 if (makeDir(docsDir)) {56 writeFile('1-introduction.js', '1-introductionTemp.js', docsDir);57 writeFile('meta.js', 'metaTemp.js', docsDir);58 }59 /** create module graphql */60 const graphqlDir = `${path}/graphql`;61 if (makeDir(graphqlDir)) {62 const graphqlResloversDir = `${graphqlDir}/resolvers`;63 if (makeDir(graphqlResloversDir)) {64 writeFile('ExampleResolvers.js', 'ExampleResolversTemp.js', graphqlResloversDir);65 writeFile('index.js', 'indexTemp.js', graphqlResloversDir);66 }67 const graphqlSchemaDir = `${graphqlDir}/schema`;68 if (makeDir(graphqlSchemaDir)) {69 writeFile('schemagraphql.js', 'schemagraphqlTemp.js', graphqlSchemaDir);70 }71 }72 /** create module logs */73 const logsDir = `${path}/logs`;74 if (makeDir(logsDir)) {75 fs.writeFileSync(`${logsDir}/.keep`);76 }77 /** create module models */78 const modelsDir = `${path}/models`;79 if (makeDir(modelsDir)) {80 writeFile('Example.js', 'ExampleTemp.js', modelsDir);81 writeFile('index.js', 'indexTemp.js', modelsDir);82 }83 /** create module restapi */84 const restapiDir = `${path}/restapi`;85 if (makeDir(restapiDir)) {86 const restapiControllersDir = `${restapiDir}/controllers`;87 if (makeDir(restapiControllersDir)) {88 writeFile('BaseController.js', 'BaseControllerTemp.js', restapiControllersDir);89 writeFile('ExampleController.js', 'ExampleControllerTemp.js', restapiControllersDir);90 writeFile('HandleError.js', 'HandleErrorTemp.js', restapiControllersDir);91 writeFile('index.js', 'indexTemp.js', restapiControllersDir);92 }93 const restapiRoutesDir = `${restapiDir}/routes`;94 if (makeDir(restapiRoutesDir)) {95 writeFile('example.js', 'exampleTemp.js', restapiRoutesDir);96 }97 const restapiServicesDir = `${restapiDir}/services`;98 if (makeDir(restapiServicesDir)) {99 writeFile('BaseService.js', 'BaseServiceTemp.js', restapiServicesDir);100 writeFile('ExampleService.js', 'ExampleServiceTemp.js', restapiServicesDir);101 writeFile('index.js', 'indexTemp.js', restapiServicesDir);102 }103 }104 /** create module server */105 const serverDir = `${path}/server`;106 if (makeDir(serverDir)) {107 writeFile('apiLimiter.js', 'apiLimiterTemp.js', serverDir);108 writeFile('cluster.js', 'clusterTemp.js', serverDir);109 writeFile('compression.js', 'compressionTemp.js', serverDir);110 writeFile('cors.js', 'corsTemp.js', serverDir);111 writeFile('graphql.js', 'graphqlTemp.js', serverDir);112 writeFile('log.js', 'logTemp.js', serverDir);113 writeFile('routes.js', 'routesTemp.js', serverDir);114 writeFile('swagger.js', 'swaggerTemp.js', serverDir);115 }116 /** create module utils */117 const utilsDir = `${path}/utils`;118 if (makeDir(utilsDir)) {119 writeFile('index.js', 'indexTemp.js', utilsDir);120 writeFile('ResponseBuilder.js', 'ResponseBuilderTemp.js', utilsDir);121 }122 } else initSuccess = false;123 if (initSuccess) {124 console.log(chalk.green(`\n✨ Initialization done in ${process.hrtime(startTime)}s`));125 return true;126 } else {127 console.log(chalk.red('✖ Application server already exists!'));128 return false;129 }130};131actions.clean = async path => {132 const pathExists = await fs.existsSync(path);133 if (path !== undefined && pathExists) {134 const startTime = process.hrtime();135 lignator.remove(path);136 console.log(chalk.green(`\n✨ Clean Directory ${path} done in ${process.hrtime(startTime)}s`));137 return true;138 } else {139 console.log(chalk.red('✖ Please insert directory name to delete!'));140 return false;141 }142};...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1/*!2 * write <https://github.com/jonschlinkert/write>3 *4 * Copyright (c) 2014-2017, Jon Schlinkert.5 * Released under the MIT License.6 */7'use strict';8var fs = require('fs');9var path = require('path');10var mkdirp = require('mkdirp');11/**12 * Asynchronously writes data to a file, replacing the file if it already13 * exists and creating any intermediate directories if they don't already14 * exist. Data can be a string or a buffer. Returns a promise if a callback15 * function is not passed.16 *17 * ```js18 * var writeFile = require('write');19 * writeFile('foo.txt', 'This is content...', function(err) {20 * if (err) console.log(err);21 * });22 *23 * // promise24 * writeFile('foo.txt', 'This is content...')25 * .then(function() {26 * // do stuff27 * });28 * ```29 * @name writeFile30 * @param {string|Buffer|integer} `filepath` filepath or file descriptor.31 * @param {string|Buffer|Uint8Array} `data` String to write to disk.32 * @param {object} `options` Options to pass to [fs.writeFile][fs]{#fs_fs_writefile_file_data_options_callback} and/or [mkdirp][]33 * @param {Function} `callback` (optional) If no callback is provided, a promise is returned.34 * @api public35 */36function writeFile(filepath, data, options, cb) {37 if (typeof options === 'function') {38 cb = options;39 options = {};40 }41 if (typeof cb !== 'function') {42 return writeFile.promise.apply(null, arguments);43 }44 if (typeof filepath !== 'string') {45 cb(new TypeError('expected filepath to be a string'));46 return;47 }48 mkdirp(path.dirname(filepath), options, function(err) {49 if (err) {50 cb(err);51 return;52 }53 fs.writeFile(filepath, data, options, cb);54 });55};56/**57 * The promise version of [writeFile](#writefile). Returns a promise.58 *59 * ```js60 * var writeFile = require('write');61 * writeFile.promise('foo.txt', 'This is content...')62 * .then(function() {63 * // do stuff64 * });65 * ```66 * @name .promise67 * @param {string|Buffer|integer} `filepath` filepath or file descriptor.68 * @param {string|Buffer|Uint8Array} `val` String or buffer to write to disk.69 * @param {object} `options` Options to pass to [fs.writeFile][fs]{#fs_fs_writefile_file_data_options_callback} and/or [mkdirp][]70 * @return {Promise}71 * @api public72 */73writeFile.promise = function(filepath, val, options) {74 if (typeof filepath !== 'string') {75 return Promise.reject(new TypeError('expected filepath to be a string'));76 }77 return new Promise(function(resolve, reject) {78 mkdirp(path.dirname(filepath), options, function(err) {79 if (err) {80 reject(err);81 return;82 }83 fs.writeFile(filepath, val, options, function(err) {84 if (err) {85 reject(err);86 return;87 }88 resolve(val);89 });90 });91 });92};93/**94 * The synchronous version of [writeFile](#writefile). Returns undefined.95 *96 * ```js97 * var writeFile = require('write');98 * writeFile.sync('foo.txt', 'This is content...');99 * ```100 * @name .sync101 * @param {string|Buffer|integer} `filepath` filepath or file descriptor.102 * @param {string|Buffer|Uint8Array} `data` String or buffer to write to disk.103 * @param {object} `options` Options to pass to [fs.writeFileSync][fs]{#fs_fs_writefilesync_file_data_options} and/or [mkdirp][]104 * @return {undefined}105 * @api public106 */107writeFile.sync = function(filepath, data, options) {108 if (typeof filepath !== 'string') {109 throw new TypeError('expected filepath to be a string');110 }111 mkdirp.sync(path.dirname(filepath), options);112 fs.writeFileSync(filepath, data, options);113};114/**115 * Uses `fs.createWriteStream` to write data to a file, replacing the116 * file if it already exists and creating any intermediate directories117 * if they don't already exist. Data can be a string or a buffer. Returns118 * a new [WriteStream](https://nodejs.org/api/fs.html#fs_class_fs_writestream)119 * object.120 *121 * ```js122 * var fs = require('fs');123 * var writeFile = require('write');124 * fs.createReadStream('README.md')125 * .pipe(writeFile.stream('a/b/c/other-file.md'))126 * .on('close', function() {127 * // do stuff128 * });129 * ```130 * @name .stream131 * @param {string|Buffer|integer} `filepath` filepath or file descriptor.132 * @param {object} `options` Options to pass to [mkdirp][] and [fs.createWriteStream][fs]{#fs_fs_createwritestream_path_options}133 * @return {Stream} Returns a new [WriteStream](https://nodejs.org/api/fs.html#fs_class_fs_writestream) object. (See [Writable Stream](https://nodejs.org/api/stream.html#stream_class_stream_writable)).134 * @api public135 */136writeFile.stream = function(filepath, options) {137 mkdirp.sync(path.dirname(filepath), options);138 return fs.createWriteStream(filepath, options);139};140/**141 * Expose `writeFile`142 */...

Full Screen

Full Screen

init.js

Source:init.js Github

copy

Full Screen

1#!/usr/bin/env node2const process = require("process");3const fs = require("fs");4const http = require("https");5const readline = require("readline");6let inSrc = false;7let inApp = false;8let inAssets = false;9let inEnv = false;10function writeFile(fileName) {11 console.log(`Creating ${fileName} ...`);12 let url;13 if (!inSrc) {14 url =15 "https://raw.githubusercontent.com/RocketCommunicationsInc/astro/main/packages/starter-kits/angular-starter/" +16 fileName;17 } else if (inSrc && !inApp && !inAssets && !inEnv) {18 url =19 "https://raw.githubusercontent.com/RocketCommunicationsInc/astro/main/packages/starter-kits/angular-starter/src/" +20 fileName;21 } else if (inSrc && inApp) {22 url =23 "https://raw.githubusercontent.com/RocketCommunicationsInc/astro/main/packages/starter-kits/angular-starter/src/app/" +24 fileName;25 } else if (inSrc && inAssets) {26 url =27 "https://raw.githubusercontent.com/RocketCommunicationsInc/astro/main/packages/starter-kits/angular-starter/src/assets/" +28 fileName;29 } else if (inSrc && inEnv) {30 url =31 "https://raw.githubusercontent.com/RocketCommunicationsInc/astro/main/packages/starter-kits/angular-starter/src/environments/" +32 fileName;33 }34 const file = fs.createWriteStream(`${fileName}`);35 const request = http.get(url, (res) => {36 res.on("error", (err) => {37 console.log(err);38 process.exit(1);39 });40 res.pipe(file);41 });42}43function changeDir(dir) {44 if (!fs.existsSync(dir)) {45 fs.mkdirSync(dir);46 process.chdir(dir);47 } else {48 process.chdir(dir);49 }50 console.log(`Now working in ${process.cwd()}`);51}52function getAppName(query) {53 const rl = readline.createInterface({54 input: process.stdin,55 output: process.stdout,56 });57 return new Promise((resolve) =>58 rl.question(query, (ans) => {59 rl.close();60 resolve(ans);61 })62 );63}64async function init() {65 let appName = process.argv[2];66 if (!appName) {67 appName = await getAppName("Please enter a root directory name: ");68 }69 console.log("***** Instializing Astro angular starter kit *****");70 changeDir(`./${appName}`);71 console.log(`Root directory ${appName} created!`);72 writeFile("package.json");73 writeFile(".browserslistrc");74 writeFile(".editorconfig");75 writeFile(".gitignore");76 writeFile("angular.json");77 writeFile("karma.conf.js");78 writeFile("README.md");79 writeFile("tsconfig.app.json");80 writeFile("tsconfig.json");81 writeFile("tsconfig.spec.json");82 //create src dir, or change into it if it exists83 changeDir("./src");84 inSrc = true;85 writeFile("favicon.ico");86 writeFile("index.html");87 writeFile("main.ts");88 writeFile("polyfills.ts");89 writeFile("styles.scss");90 writeFile("test.ts");91 console.log(`/src directory created in ${process.cwd()}`);92 //create public dir or change into it if already exists93 changeDir("./app");94 inApp = true;95 writeFile("app.component.html");96 writeFile("app.component.scss");97 writeFile("app.component.spec.ts");98 writeFile("app.component.ts");99 writeFile("app.module.ts");100 console.log(`./app directory created in ${process.cwd()}`);101 //create assets dir102 changeDir("../");103 inApp = false;104 changeDir("./assets");105 inAssets = true;106 writeFile(".gitkeep");107 console.log(`./assets directory created in ${process.cwd()}`);108 changeDir("../");109 inAssets = false;110 changeDir("./environments");111 inEnv = true;112 writeFile("environment.prod.ts");113 writeFile("environment.ts");114 console.log(`./environments directory created in ${process.cwd()}`);115 console.log(`Finished!`);116 console.log(`******************`);117 console.log(`Please run: `);118 console.log(`cd ${appName}`);119 console.log(`npm install`);120 console.log(`npm start`);121 console.log(`Thanks for using AstroUXDS!`);122 console.log(`******************`);123}...

Full Screen

Full Screen

rafinder.txt

Source:rafinder.txt Github

copy

Full Screen

1#!/usr/bin/env node23var fs = require('fs');4var path = '/sys/class/gpio/';5var Blynk = require('blynk-library');6var AUTH = '941c0bde9dfe43df9f5c334ae792a64f';7var blynk = new Blynk.Blynk(AUTH);8var pins = [2, 3, 4, 5, 30, 31, 48, 50, 51, 60];9var delay = 500;1011// Virtual pins for Blynk12var v0 = new blynk.VirtualPin(0);13var v1 = new blynk.VirtualPin(1);14var v2 = new blynk.VirtualPin(2);15var v3 = new blynk.VirtualPin(3);16var v4 = new blynk.VirtualPin(4);17var v5 = new blynk.VirtualPin(5);18var v6 = new blynk.VirtualPin(6);19var v7 = new blynk.VirtualPin(7);20var v8 = new blynk.VirtualPin(8);21var v9 = new blynk.VirtualPin(9);2223// Setting GPIOs up as outputs24for(var i in pins) {25 setTimeout(function() {fs.writeFile(path + 'export', i, done);26 }, delay);27 setTimeout(function() {fs.writeFile(path + 'gpio' + i.toString() + '/direction', 'out', done);28 }, delay);29 }303132// fs.writeFile(path + 'export', 30, done); // v0 - domke33// fs.writeFile(path + 'export', 60, done); // v1 - gabbi34// fs.writeFile(path + 'export', 31, done); // v2 - cole 35// fs.writeFile(path + 'export', 50, done); // v3 - vibha36// fs.writeFile(path + 'export', 48, done); // v4 - bailey37// fs.writeFile(path + 'export', 51, done); // v5 - randy38// fs.writeFile(path + 'export', 5, done); // v6 - off campus39// fs.writeFile(path + 'export', 4, done); // v7 - around campus40// fs.writeFile(path + 'export', 3, done); // v8 - class41// fs.writeFile(path + 'export', 2, done); // v9 - apartments4243// fs.writeFile(path + 'gpio30/direction', 'out', done);44// fs.writeFile(path + 'gpio60/direction', 'out', done);45// fs.writeFile(path + 'gpio31/direction', 'out', done);46// fs.writeFile(path + 'gpio50/direction', 'out', done);47// fs.writeFile(path + 'gpio48/direction', 'out', done);48// fs.writeFile(path + 'gpio51/direction', 'out', done);49// fs.writeFile(path + 'gpio5/direction', 'out', done);50// fs.writeFile(path + 'gpio4/direction', 'out', done);51// fs.writeFile(path + 'gpio3/direction', 'out', done);52// fs.writeFile(path + 'gpio2/direction', 'out', done);535455// DUTY56v0.on('write', function(param) { // domke57 console.log('V0:', param[0]);58 fs.writeFile(path + 'gpio30/value', param[0], done);59});6061v1.on('write', function(param) { // gabbi62 console.log('V1:', param[0]); 63 fs.writeFile(path + 'gpio60/value', param[0], done);64});6566v2.on('write', function(param) { // cole 67 console.log('V2:', param[0]);68 fs.writeFile(path + 'gpio31/value', param[0], done);69});7071v3.on('write', function(param) { // vibha72 console.log('V3:', param[0]);73 fs.writeFile(path + 'gpio50/value', param[0], done);74});7576v4.on('write', function(param) { // bailey77 console.log('V4:', param[0]);78 fs.writeFile(path + 'gpio48/value', param[0], done);79});8081v5.on('write', function(param) { // randy82 console.log('V5:', param[0]);83 fs.writeFile(path + 'gpio51/value', param[0], done);84});8586// LOCATION87v6.on('write', function(param) { // off campus88 console.log('V6:', param[0]);89 fs.writeFile(path + 'gpio5/value', param[0], done);90});9192v7.on('write', function(param) { // around campus93 console.log('V7:', param[0]);94 fs.writeFile(path + 'gpio4/value', param[0], done);95});9697v8.on('write', function(param) { // class98 console.log('V8:', param[0]);99 fs.writeFile(path + 'gpio3/value', param[0], done);100});101102v9.on('write', function(param) { // apartments103 console.log('V9:', param[0]);104 fs.writeFile(path + 'gpio2/value', param[0], done);105});106107function done() {108 console.log("Done"); ...

Full Screen

Full Screen

encoder.test.js

Source:encoder.test.js Github

copy

Full Screen

1const fs = require('fs')2const test = require('ava')3const td = require('testdouble')4const yaml = require('js-yaml')5const encoder = require('../lib/encoder')6test.afterEach(t => td.reset()) // eslint-disable-line no-unused-vars7test('for() should return encoder for yaml', t => {8 const encoders = ['Yaml', 'yaml', 'yml'].map(encoder.for)9 const allEncodersAreValid = encoders.every(p => p === yaml.safeDump)10 t.true(allEncodersAreValid)11})12test('for() should return encoder for json', t => {13 const encoders = ['Json', 'json', 'JSON'].map(encoder.for)14 const allEncodersAreValid = encoders.every(p => p === JSON.stringify)15 t.true(allEncodersAreValid)16})17test('for() should return null for unsupported format', t => {18 t.is(encoder.for('txt'), null)19})20test('save() should reject format not supported', async t => {21 const err = await t.throwsAsync(encoder.save({}, 'test.txt', 'txt'))22 t.is(err.message, 'Unsupported format \'txt\'')23})24test('save() should reject if file cannot be written', async t => {25 const writeFile = td.function()26 td.when(writeFile(td.matchers.anything(), td.matchers.anything()))27 .thenCallback(new Error('no such file or directory'))28 td.replace(fs, 'writeFile', writeFile)29 const err = await t.throwsAsync(encoder.save({}, 'write-test.json', 'json'))30 t.regex(err.message, /no such file or directory/)31})32test('save() should write JSON file', async t => {33 const writeFile = td.function()34 td.when(writeFile(td.matchers.anything(), td.matchers.anything())).thenCallback()35 td.replace(fs, 'writeFile', writeFile)36 await t.notThrowsAsync(encoder.save({foo: 'bar'}, 'write-test.json', 'json'))37 td.verify(writeFile('write-test.json', '{"foo":"bar"}', td.matchers.isA(Function)))38})39test('save() should write YAML file', async t => {40 const writeFile = td.function()41 td.when(writeFile(td.matchers.anything(), td.matchers.anything())).thenCallback()42 td.replace(fs, 'writeFile', writeFile)43 await t.notThrowsAsync(encoder.save({foo: 'bar'}, 'write-test.yaml', 'yaml'))44 td.verify(writeFile('write-test.yaml', 'foo: bar\n', td.matchers.isA(Function)))...

Full Screen

Full Screen

write-file.js

Source:write-file.js Github

copy

Full Screen

1var test = require('./helpers/test');2test('writeFile', function(fs, t) {3 fs.writeFile('/test.txt', 'hello', function(err) {4 t.notOk(err);5 fs.readFile('/test.txt', function(err, data) {6 t.same(data.toString(), 'hello');7 fs.stat('/test.txt', function(err, stat) {8 t.same(stat.mode, 0666);9 t.same(stat.size, 5);10 t.ok(stat.isFile());11 t.end();12 });13 });14 });15});16test('writeFile + encoding', function(fs, t) {17 fs.writeFile('/foo', new Buffer('foo'), function(err) {18 t.notOk(err);19 fs.readFile('/foo', function(err, data) {20 t.same(data.toString(), 'foo');21 fs.writeFile('/foo', '68656c6c6f', 'hex', function(err) {22 t.notOk(err);23 fs.readFile('/foo', function(err, data) {24 t.same(data.toString(), 'hello');25 t.end();26 });27 });28 });29 });30});31test('multiple writeFile', function(fs, t) {32 fs.writeFile('/foo', new Buffer('foo'), function(err) {33 t.notOk(err);34 fs.writeFile('/foo', new Buffer('bar'), function(err) {35 t.notOk(err);36 fs.writeFile('/foo', new Buffer('baz'), function(err) {37 t.notOk(err);38 fs.readFile('/foo', function(err, data) {39 t.same(data.toString(), 'baz');40 t.end();41 });42 });43 });44 });45});46test('writeFile + mode', function(fs, t) {47 fs.writeFile('/foo', new Buffer('foo'), {mode:0644}, function(err) {48 t.notOk(err);49 fs.stat('/foo', function(err, stat) {50 t.same(stat.mode, 0644);51 t.end();52 });53 });54});55test('overwrite file', function(fs, t) {56 fs.writeFile('/test.txt', 'foo', function(err) {57 t.notOk(err);58 fs.writeFile('/test.txt', 'bar', function(err) {59 t.notOk(err);60 fs.readFile('/test.txt', function(err, data) {61 t.same(data.toString(), 'bar');62 t.end();63 });64 });65 });66});67test('cannot writeFile to dir', function(fs, t) {68 fs.mkdir('/test', function() {69 fs.writeFile('/test', 'hello', function(err) {70 t.ok(err);71 t.same(err.code, 'EISDIR');72 t.end();73 });74 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.contains('type').click()4 cy.writeFile('cypress/fixtures/example.json', {name: 'Jane', age: 20})5 })6})7{8}9describe('My First Test', function() {10 it('Does not do much!', function() {11 cy.contains('type').click()12 cy.readFile('cypress/fixtures/example.json').its('name').should('eq', 'Jane')13 })14})15describe('My First Test', function() {16 it('Does not do much!', function() {17 cy.contains('type').click()18 cy.writeFile('cypress/fixtures/example.json', {name: 'Jane', age: 20})19 })20})21describe('My First Test', function() {22 it('Does not do much!', function() {23 cy.contains('type').click()24 cy.readFile('cypress/fixtures/example.json').its('name').should('eq', 'Jane')25 })26})27cy.writeFile()28cy.readFile()

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Writefile', function() {2 it('Writefile', function() {3 cy.writeFile('cypress/fixtures/test.json', {name: 'testname'})4 })5})6describe('Readfile', function() {7 it('Readfile', function() {8 cy.readFile('cypress/fixtures/test.json').then((data) => {9 expect(data.name).to.equal('testname')10 })11 })12})13describe('Readfile', function() {14 it('Readfile', function() {15 cy.readFile('cypress/fixtures/test.json').then((data) => {16 expect(data.name).to.equal('testname')17 })18 })19})20describe('Readfile', function() {21 it('Readfile', function() {22 cy.readFile('cypress/fixtures/test.json').then((data) => {23 expect(data.name).to.equal('testname')24 })25 })26})27describe('Readfile', function() {28 it('Readfile', function() {29 cy.readFile('cypress/fixtures/test.json').then((data) => {30 expect(data.name).to.equal('testname')31 })32 })33})34describe('Readfile', function() {35 it('Readfile', function() {36 cy.readFile('cypress/fixtures/test.json').then((data) => {37 expect(data.name).to.equal('testname')38 })39 })40})41describe('Readfile', function() {42 it('Readfile', function() {43 cy.readFile('cypress/fixtures/test.json').then((data) => {44 expect(data.name).to.equal('testname')45 })46 })47})48describe('Readfile', function() {49 it('Readfile', function() {50 cy.readFile('cypress/fixtures/test.json').then((data) => {51 expect(data.name).to.equal('testname')52 })53 })54})

Full Screen

Using AI Code Generation

copy

Full Screen

1import { writeFile } from "cypress/types/lodash";2const data = "Hello world";3writeFile("cypress/fixtures/test.txt", data);4const data = "Hello world";5cy.writeFile("cypress/fixtures/test.txt", data);6const data = "Hello world";7cy.writeFile("cypress/fixtures/test.txt", data);8const data = "Hello world";9cy.writeFile("cypress/fixtures/test.txt", data);10const data = "Hello world";11cy.writeFile("cypress/fixtures/test.txt", data);12const data = "Hello world";13cy.writeFile("cypress/fixtures/test.txt", data);14const data = "Hello world";15cy.writeFile("cypress/fixtures/test.txt", data);

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.writeFile('cypress/fixtures/fileName.json', {name: 'John Doe'})2cy.readFile('cypress/fixtures/fileName.json').its('name').should('eq', 'John Doe')3cy.readFile('cypress/fixtures/fileName.json').its('name').should('eq', 'John Doe')4cy.readFile('cypress/fixtures/fileName.json').its('name').should('eq', 'John Doe')5cy.readFile('cypress/fixtures/fileName.json').its('name').should('eq', 'John Doe')6cy.readFile('cypress/fixtures/fileName.json').its('name').should('eq', 'John Doe')7cy.readFile('cypress/fixtures/fileName.json').its('name').should('eq', 'John Doe')8cy.readFile('cypress/fixtures/fileName.json').its('name').should('eq', 'John Doe')9cy.readFile('cypress/fixtures/fileName.json').its('name').should('eq', 'John Doe')10cy.readFile('cypress/fixtures/fileName.json').its('name').should('eq',

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful