How to use driver.close method in Appium Xcuitest Driver

Best JavaScript code snippet using appium-xcuitest-driver

testSL.js

Source:testSL.js Github

copy

Full Screen

...26    var title = await driver.getTitle();27    console.log('\nTitle is:',title,searchString);28    console.log("Swag Labs Standard Login - Test Passed\n")29    //Driver.close , closes the browser remaining from the test.30    await driver.close();31}32Swaglabs_standard_login();33//Test to login with locked user34async function Swaglabs_locked_login() {35    let driver = await new Builder().forBrowser("chrome").build();36    await driver.get("https://www.saucedemo.com/");37    await driver.findElement(By.id("user-name")).click();38    await driver.findElement(By.id("user-name")).sendKeys("locked_out_user");39    await driver.findElement(By.id("password")).sendKeys("secret_sauce",Key.RETURN)40    //Verify that locked out login popped up41    await driver.findElement(By.xpath("//*[contains(text(), 'Epic sadface')]"));42    var title = await driver.getTitle();43    console.log('Title is:',title,searchString);44    console.log("Swag Labs Locked Login - Passed Test\n")45    //Driver.close , closes the browser remaining from the test.46    await driver.close();47}48Swaglabs_locked_login();49//Test to login with Problem user50async function Swaglabs_problem_login() {51    let driver = await new Builder().forBrowser("chrome").build();52    await driver.get("https://www.saucedemo.com/");53    await driver.findElement(By.id("user-name")).click();54    await driver.findElement(By.id("user-name")).sendKeys("problem_user");55    await driver.findElement(By.id("password")).sendKeys("secret_sauce",Key.RETURN)56    //added interaction on successful login to check that it worked57    await driver.findElement(By.name("add-to-cart-sauce-labs-backpack")).click();58    var title = await driver.getTitle();59    console.log('Title is:',title,searchString);60    console.log("Swag Labs Problem Login - Test Passed\n")61    //Driver.close , closes the browser remaining from the test.62    await driver.close();63}64Swaglabs_problem_login();65//Test to login with gliched user66async function Swaglabs_glitch_login() {67    let driver = await new Builder().forBrowser("chrome").build();68    await driver.get("https://www.saucedemo.com/");69    await driver.findElement(By.id("user-name")).click();70    await driver.findElement(By.id("user-name")).sendKeys("performance_glitch_user");71    await driver.findElement(By.id("password")).sendKeys("secret_sauce",Key.RETURN)72    //added interaction on successful login to check that it worked73    await driver.findElement(By.name("add-to-cart-sauce-labs-backpack")).click();74    var title = await driver.getTitle();75    console.log('Title is:',title,searchString);76    console.log("Swag Labs Glitched Login - Test Passed\n")77   //Driver.close , closes the browser remaining from the test.78    await driver.close();79}80Swaglabs_glitch_login();81//Test to login and logoff with standard_user82async function Swaglabs_standard_login_logoff() {83    let driver = await new Builder().forBrowser("chrome").build();84    await driver.get("https://www.saucedemo.com/");85    await driver.findElement(By.id("user-name")).click();86    await driver.findElement(By.id("user-name")).sendKeys("standard_user");87    await driver.findElement(By.id("password")).sendKeys("secret_sauce",Key.RETURN)88    await driver.findElement(By.id("react-burger-menu-btn")).click();89    async function awaitCss(){90        await driver.findElement(By.id("logout_sidebar_link")).click();91        //Verify that we are back at the login-screen by pressing the login-button92        await driver.findElement(By.id("login-button")).click();93        let title = await driver.getTitle();94        console.log('Title is:',title,searchString);95        console.log("Swag Labs Standard login - logoff - Test Passed\n")96       //Driver.close , closes the browser remaining from the test.97        await driver.close();98    }99    setTimeout(awaitCss,1000)100};101Swaglabs_standard_login_logoff();102// UI functionality test (Standrad_user)103//Test to add all shoppingcart items104async function Swaglabs_standard_login_add() {105    let driver = await new Builder().forBrowser("chrome").build();106    await driver.get("https://www.saucedemo.com/");107    await driver.findElement(By.id("user-name")).click();108    await driver.findElement(By.id("user-name")).sendKeys("standard_user");109    await driver.findElement(By.id("password")).sendKeys("secret_sauce",Key.RETURN)110    await driver.findElement(By.name("add-to-cart-sauce-labs-backpack")).click();111    await driver.findElement(By.name("add-to-cart-sauce-labs-bike-light")).click();112    await driver.findElement(By.name("add-to-cart-sauce-labs-bolt-t-shirt")).click();113    await driver.findElement(By.name("add-to-cart-sauce-labs-fleece-jacket")).click();114    await driver.findElement(By.name("add-to-cart-sauce-labs-onesie")).click();115    await driver.findElement(By.name("add-to-cart-test\.allthethings\(\)-t-shirt-\(red\)")).click();116    var title = await driver.getTitle();117    console.log('Title is:',title,searchString);118    console.log("Swag Labs Standard Login - Add all items - Test Passed\n")119    //Driver.close , closes the browser remaining from the test.120    await driver.close();121}122Swaglabs_standard_login_add();123//Test to add and remove all Shoppingcart items124async function Swaglabs_standard_login_add_remove() {125    let driver = await new Builder().forBrowser("chrome").build();126    await driver.get("https://www.saucedemo.com/");127    await driver.findElement(By.id("user-name")).click();128    await driver.findElement(By.id("user-name")).sendKeys("standard_user");129    await driver.findElement(By.id("password")).sendKeys("secret_sauce",Key.RETURN)130    await driver.findElement(By.name("add-to-cart-sauce-labs-backpack")).click();131    await driver.findElement(By.name("remove-sauce-labs-backpack")).click();132    await driver.findElement(By.name("add-to-cart-sauce-labs-bike-light")).click();133    await driver.findElement(By.name("remove-sauce-labs-bike-light")).click();134    await driver.findElement(By.name("add-to-cart-sauce-labs-bolt-t-shirt")).click();135    await driver.findElement(By.name("remove-sauce-labs-bolt-t-shirt")).click();136    await driver.findElement(By.name("add-to-cart-sauce-labs-fleece-jacket")).click();137    await driver.findElement(By.name("remove-sauce-labs-fleece-jacket")).click();138    await driver.findElement(By.name("add-to-cart-sauce-labs-onesie")).click();139    await driver.findElement(By.name("remove-sauce-labs-onesie")).click();140    await driver.findElement(By.name("add-to-cart-test\.allthethings\(\)-t-shirt-\(red\)")).click();141    await driver.findElement(By.name("remove-test\.allthethings\(\)-t-shirt-\(red\)")).click();142    var title = await driver.getTitle();143    console.log('Title is:',title,searchString);144    console.log("Swag Labs Standard Login - Add and remove all items - Test Passed\n")145    //Driver.close , closes the browser remaining from the test.146    await driver.close();147}148Swaglabs_standard_login_add_remove();149//Test to press the About button in the sidebar/burger menu and verify that it landed on that page.150async function Swaglabs_standard_login_about() {151    let driver = await new Builder().forBrowser("chrome").build();152    await driver.get("https://www.saucedemo.com/");153    await driver.findElement(By.id("user-name")).click();154    await driver.findElement(By.id("user-name")).sendKeys("standard_user");155    await driver.findElement(By.id("password")).sendKeys("secret_sauce",Key.RETURN)156    await driver.findElement(By.id("react-burger-menu-btn")).click();157    async function awaitCss(){158        await driver.findElement(By.id("about_sidebar_link")).click();159        //Verify that we are arrived on the about page.160        await driver.findElement(By.className("nav-image-link")).click();161        let title = await driver.getTitle();162        console.log('Title is:',title,searchString);163        console.log("Swag Labs Standard Login - Pressing About in sidebar - Test Passed\n")164        //Driver.close , closes the browser remaining from the test.165        await driver.close();166    }167    setTimeout(awaitCss,1000)168}169Swaglabs_standard_login_about();170//Test to press the "Inventory" button in the burger,sidebar171async function Swaglabs_standard_login_inventory() {172    let driver = await new Builder().forBrowser("chrome").build();173    await driver.get("https://www.saucedemo.com/");174    await driver.findElement(By.id("user-name")).click();175    await driver.findElement(By.id("user-name")).sendKeys("standard_user");176    await driver.findElement(By.id("password")).sendKeys("secret_sauce",Key.RETURN)177    await driver.findElement(By.id("shopping_cart_container")).click();178    await driver.findElement(By.id("react-burger-menu-btn")).click();179    async function awaitCss(){180        await driver.findElement(By.id("inventory_sidebar_link")).click();181        //Verify that we are arrived on the select item page.182        await driver.findElement(By.name("add-to-cart-sauce-labs-backpack")).click();183        await driver.findElement(By.name("remove-sauce-labs-backpack")).click();184        let title = await driver.getTitle();185        console.log('Title is:',title,searchString);186        console.log("Swag Labs Standard Login - Pressing All Items in sidebar - Test Passed\n")187        //Driver.close , closes the browser remaining from the test.188        await driver.close();189    }190    setTimeout(awaitCss,1000)191}192Swaglabs_standard_login_inventory();193//Test to press the "Reset app state" button in the burger,sidebar194async function Swaglabs_standard_login_reset_app() {195    let driver = await new Builder().forBrowser("chrome").build();196    await driver.get("https://www.saucedemo.com/");197    await driver.findElement(By.id("user-name")).click();198    await driver.findElement(By.id("user-name")).sendKeys("standard_user");199    await driver.findElement(By.id("password")).sendKeys("secret_sauce",Key.RETURN)200    await driver.findElement(By.id("react-burger-menu-btn")).click();201    async function awaitCss(){202        await driver.findElement(By.id("reset_sidebar_link")).click();203        //Verify that we are arrived on the select item page.204        await driver.findElement(By.name("add-to-cart-sauce-labs-backpack")).click();205        await driver.findElement(By.name("remove-sauce-labs-backpack")).click();206        let title = await driver.getTitle();207        console.log('Title is:',title,searchString);208        console.log("Swag Labs Standard Login - Pressing Reset app state in sidebar - Test Passed\n")209       //Driver.close , closes the browser remaining from the test.210        await driver.close();211    }212    setTimeout(awaitCss,1000)213}214Swaglabs_standard_login_reset_app();215async function Swaglabs_standard_login_sort_first() {216    let driver = await new Builder().forBrowser("chrome").build();217    await driver.get("https://www.saucedemo.com/");218    await driver.findElement(By.id("user-name")).click();219    await driver.findElement(By.id("user-name")).sendKeys("standard_user");220    await driver.findElement(By.id("password")).sendKeys("secret_sauce",Key.RETURN)221    await driver.findElement(By.xpath('//*[@id="header_container"]/div[2]/div[2]/span/select/option[1]')).click();222    await driver.takeScreenshot().then(223        function(image, err) {224            require('fs').writeFile('Screenshots/Selenium/SortingInventoryFirstImg.png', image, 'base64', function(err) {225                //console.log(err);226            });227        228        }229    );230    var title = await driver.getTitle();231    console.log('\nTitle is:',title,searchString);232    console.log("Swag Labs Standard Login - click first Inventory sorter + save screenshot - Test Passed\n")233    //Driver.close , closes the browser remaining from the test.234    await driver.close();235}236Swaglabs_standard_login_sort_first();237async function Swaglabs_standard_login_sort_second() {238    let driver = await new Builder().forBrowser("chrome").build();239    await driver.get("https://www.saucedemo.com/");240    await driver.findElement(By.id("user-name")).click();241    await driver.findElement(By.id("user-name")).sendKeys("standard_user");242    await driver.findElement(By.id("password")).sendKeys("secret_sauce",Key.RETURN)243    await driver.findElement(By.xpath('//*[@id="header_container"]/div[2]/div[2]/span/select/option[2]')).click();244    await driver.takeScreenshot().then(245    function(image, err) {246        require('fs').writeFile('Screenshots/Selenium/SortingInventorySecondImg.png', image, 'base64', function(err) {247            //console.log(err);248        });249    250    }251);252    var title = await driver.getTitle();253    console.log('\nTitle is:',title,searchString);254    console.log("Swag Labs Standard Login - click second Inventory sorter + save screenshot - Test Passed\n")255    //Driver.close , closes the browser remaining from the test.256    await driver.close();257}258Swaglabs_standard_login_sort_second();259async function Swaglabs_standard_login_sort_third() {260    let driver = await new Builder().forBrowser("chrome").build();261    await driver.get("https://www.saucedemo.com/");262    await driver.findElement(By.id("user-name")).click();263    await driver.findElement(By.id("user-name")).sendKeys("standard_user");264    await driver.findElement(By.id("password")).sendKeys("secret_sauce",Key.RETURN)265    await driver.findElement(By.xpath('//*[@id="header_container"]/div[2]/div[2]/span/select/option[3]')).click();266    await driver.takeScreenshot().then(267        function(image, err) {268            require('fs').writeFile('Screenshots/Selenium/SortingInventoryThirdImg.png', image, 'base64', function(err) {269                //console.log(err);270            });271        272        }273    );274    var title = await driver.getTitle();275    console.log('\nTitle is:',title,searchString);276    console.log("Swag Labs Standard Login - click third Inventory sorter + save screenshot - Test Passed\n")277    //Driver.close , closes the browser remaining from the test.278    await driver.close();279}280Swaglabs_standard_login_sort_third();281async function Swaglabs_standard_login_sort_fourth() {282    let driver = await new Builder().forBrowser("chrome").build();283    await driver.get("https://www.saucedemo.com/");284    await driver.findElement(By.id("user-name")).click();285    await driver.findElement(By.id("user-name")).sendKeys("standard_user");286    await driver.findElement(By.id("password")).sendKeys("secret_sauce",Key.RETURN)287    await driver.findElement(By.xpath('//*[@id="header_container"]/div[2]/div[2]/span/select/option[4]')).click();288    await driver.takeScreenshot().then(289        function(image, err) {290            require('fs').writeFile('Screenshots/Selenium/SortingInventoryFourthImg.png', image, 'base64', function(err) {291                //console.log(err);292            });293        294        }295    );296    var title = await driver.getTitle();297    console.log('\nTitle is:',title,searchString);298    console.log("Swag Labs Standard Login - click fourth Inventory sorter + save screenshot - Test Passed\n")299    //Driver.close , closes the browser remaining from the test.300    await driver.close();301}302Swaglabs_standard_login_sort_fourth();303async function Swaglabs_standard_login_continue_shopping() {304    let driver = await new Builder().forBrowser("chrome").build();305    await driver.get("https://www.saucedemo.com/");306    await driver.findElement(By.id("user-name")).click();307    await driver.findElement(By.id("user-name")).sendKeys("standard_user");308    await driver.findElement(By.id("password")).sendKeys("secret_sauce",Key.RETURN)309    await driver.findElement(By.id('shopping_cart_container')).click();310    await driver.findElement(By.id('continue-shopping')).click();311    //Added interaction on item page to verify that we landed there correctly312    await driver.findElement(By.name("add-to-cart-sauce-labs-backpack")).click();313    var title = await driver.getTitle();314    console.log('\nTitle is:',title,searchString);315    console.log("Swag Labs Standard Login - Testing Shopping cart + Continue shopping button - Test Passed\n")316    //Driver.close , closes the browser remaining from the test.317    await driver.close();318}319Swaglabs_standard_login_continue_shopping();320async function Swaglabs_standard_login_checkout() {321    let driver = await new Builder().forBrowser("chrome").build();322    await driver.get("https://www.saucedemo.com/");323    await driver.findElement(By.id("user-name")).click();324    await driver.findElement(By.id("user-name")).sendKeys("standard_user");325    await driver.findElement(By.id("password")).sendKeys("secret_sauce",Key.RETURN)326    await driver.findElement(By.id('shopping_cart_container')).click();327    await driver.findElement(By.id('checkout')).click();328    //Added interaction on item page to verify that we landed there correctly329    let getText = await driver.findElement(By.xpath('//*[@id="header_container"]/div[2]/span')).getText();330    let shouldBe = "CHECKOUT: YOUR INFORMATIONT"331    if(getText !== shouldBe) {332        console.log("Text does not match! Test FAILED");333        await driver.close();334    }335    else {336        var title = await driver.getTitle();337        console.log('\nTitle is:',title,searchString);338        console.log("Swag Labs Standard Login - Testing the checkout button in the cart menu - Test Passed\n")339        //Driver.close , closes the browser remaining from the test.340        await driver.close();341    }342}343Swaglabs_standard_login_checkout();344async function Swaglabs_standard_login_cancel_checkout() {345    let driver = await new Builder().forBrowser("chrome").build();346    await driver.get("https://www.saucedemo.com/");347    await driver.findElement(By.id("user-name")).click();348    await driver.findElement(By.id("user-name")).sendKeys("standard_user");349    await driver.findElement(By.id("password")).sendKeys("secret_sauce",Key.RETURN)350    await driver.findElement(By.id('shopping_cart_container')).click();351    await driver.findElement(By.id('checkout')).click();352    await driver.findElement(By.id('cancel')).click();353    //Added interaction on item page to verify that we landed there correctly354    let getText = await driver.findElement(By.xpath('//*[@id="header_container"]/div[2]/span')).getText();355    let shouldBe = "YOUR CART"356    if(getText !== shouldBe) {357        console.log("Text does not match! Test FAILED");358        await driver.close();359    }360    else {361        var title = await driver.getTitle();362        console.log('\nTitle is:',title,searchString);363        console.log("Swag Labs Standard Login - Testing the cancel button in the checkout menu - Test Passed\n")364        //Driver.close , closes the browser remaining from the test.365        await driver.close();366    }367}368Swaglabs_standard_login_cancel_checkout();369async function Swaglabs_standard_login_cancel_finish() {370    let driver = await new Builder().forBrowser("chrome").build();371    await driver.get("https://www.saucedemo.com/");372    await driver.findElement(By.id("user-name")).click();373    await driver.findElement(By.id("user-name")).sendKeys("standard_user");374    await driver.findElement(By.id("password")).sendKeys("secret_sauce",Key.RETURN)375    await driver.findElement(By.id('shopping_cart_container')).click();376    await driver.findElement(By.id('checkout')).click();377    await driver.findElement(By.id('continue')).click();378    //checking if error when you enter nothing379    await driver.findElement(By.xpath("//*[contains(text(), 'Error: First Name is required')]"));380    await driver.findElement(By.id('first-name')).sendKeys("Tester_firstName");381    await driver.findElement(By.id('last-name')).sendKeys("Tester_lastName");382    await driver.findElement(By.id('postal-code')).sendKeys("Tester_ZipCode");383    await driver.findElement(By.id('continue')).click();384    await driver.findElement(By.xpath("//*[contains(text(), 'FREE PONY EXPRESS DELIVERY!')]"));385    await driver.findElement(By.id('cancel')).click();386    //Verify that we are arrived on the select item page.387    await driver.findElement(By.name("add-to-cart-sauce-labs-backpack")).click();388    var title = await driver.getTitle();389    console.log('\nTitle is:',title,searchString);390    console.log("Swag Labs Standard Login - Testing the cancel button in the checkout menu - Test Passed\n")391    //Driver.close , closes the browser remaining from the test.392     await driver.close();393}394Swaglabs_standard_login_cancel_finish();395async function Swaglabs_standard_login_finish() {396    let driver = await new Builder().forBrowser("chrome").build();397    await driver.get("https://www.saucedemo.com/");398    await driver.findElement(By.id("user-name")).click();399    await driver.findElement(By.id("user-name")).sendKeys("standard_user");400    await driver.findElement(By.id("password")).sendKeys("secret_sauce",Key.RETURN)401    await driver.findElement(By.id('shopping_cart_container')).click();402    await driver.findElement(By.id('checkout')).click();403    await driver.findElement(By.id('continue')).click();404    //checking if error when you enter nothing405    await driver.findElement(By.xpath("//*[contains(text(), 'Error: First Name is required')]"));406    await driver.findElement(By.id('first-name')).sendKeys("Tester_firstName");407    await driver.findElement(By.id('last-name')).sendKeys("Tester_lastName");408    await driver.findElement(By.id('postal-code')).sendKeys("Tester_ZipCode");409    await driver.findElement(By.id('continue')).click();410    await driver.findElement(By.xpath("//*[contains(text(), 'FREE PONY EXPRESS DELIVERY!')]"));411    await driver.findElement(By.id('finish')).click();412    await driver.findElement(By.xpath("//*[contains(text(), 'THANK YOU FOR YOUR ORDER')]"));413    await driver.findElement(By.id("back-to-products")).click();414    //Verify that we are arrived on the select item page.415    await driver.findElement(By.id("add-to-cart-sauce-labs-backpack")).click();416    var title = await driver.getTitle();417    console.log('\nTitle is:',title,searchString);418    console.log("Swag Labs Standard Login - Testing the cancel button in the checkout menu - Test Passed\n")419    //Driver.close , closes the browser remaining from the test.420     await driver.close();421}...

Full Screen

Full Screen

neo4j-query.js

Source:neo4j-query.js Github

copy

Full Screen

...22                  })23                  .catch(err =>{console.log(err.message)})24                )}25            finally { await session.close() }  26            await driver.close()27    28    }29    ////FUNCTION - GET ID30    async MaxId(){31        var output = [];32        var neo4j = require('neo4j-driver');                           33            var driver = neo4j.driver(34                'bolt://localhost:7687',35                neo4j.auth.basic('neo4j', 'bookmarks')  36            )37            var session = driver.session()38            try {   39                const result = await session.writeTransaction(tx =>40                  tx.run('match (n) where exists(n.id) return n.id as maxid order by n.date desc limit 1')41                  .then(res => {42                    output.push(res.records[0].get('maxid'))                      43                  })44                  .catch(err =>{ console.log(err)})45                )}46            finally { await session.close() }  47            await driver.close()48            return output49    }50    ////FUNCTION - SIMILAR BOOKMARKS51    async SimilarBookmarks(id){52        var output = [];53        var neo4j = require('neo4j-driver');54            var driver = neo4j.driver(55                'bolt://localhost:7687',56                neo4j.auth.basic('neo4j', 'bookmarks')  57            )58            var session = driver.session()59            try {    60                const result = await session.writeTransaction(tx =>61                  tx.run('MATCH(b:Bookmark)<-[:KEYOF]-(k1:Keyword)-[:KEYOF *0..]->(b1:Bookmark) WHERE b.id=$id RETURN b1',{id:id})62                  .then(res => {63                      res.records.forEach(record=>{64                          output.push(record.get(0).properties)})65                      })66                  .catch(err =>{console.log(err.message)})67                )      68            }     69            finally { await session.close() }  70            await driver.close()71            return output72    }73    ////FUNCTION -SEARCH RECENTS74    async RecentBookmarks(n){75        var output = [];76        var driver = neo4j.driver(77            'bolt://localhost:7687',78            neo4j.auth.basic('neo4j', 'bookmarks')  79        )80        var session = driver.session()81        try {    82            const result = await session.writeTransaction(tx =>83              tx.run('MATCH(b:Bookmark) RETURN b ORDER BY b.date DESC LIMIT $n',{n: n})84              .then(res => {85                  res.records.forEach(record=>{86                      output.push(record.get(0).properties)})87                  })88              .catch(err =>{console.log(err.message)})89            )      90        }     91        finally { await session.close() }  92        await driver.close()93        return output94    }95    ////FUNCTION - SEARCH READ LATER96    async RLBookmarks(n){97        var output = [];98        var driver = neo4j.driver(99            'bolt://localhost:7687',100            neo4j.auth.basic('neo4j', 'bookmarks')  101        )102        var session = driver.session()103        try {    104            const result = await session.writeTransaction(tx =>105              tx.run('MATCH(b:Bookmark) WHERE b.rl = true RETURN b ORDER BY b.date DESC LIMIT $n',{n: n})106              .then(res => {107                  res.records.forEach(record=>{108                      output.push(record.get(0).properties)})109                  })110              .catch(err =>{console.log(err.message)})111            )      112        }     113        finally { await session.close() }  114        await driver.close()115        return output116    }117    ////FUNCTION -SEARCH BY TITLE118    async SearchByTitle(title){119        var op = []120        var driver = neo4j.driver(121            'bolt://localhost:7687',122            neo4j.auth.basic('neo4j', 'bookmarks')  123        )124        var session = driver.session()125        try {    126            const result = await session.writeTransaction(tx =>127              tx.run('MATCH (b: Bookmark) WHERE b.title CONTAINS $title return b',{title:title})128              .then(res => {129                  res.records.forEach(record=>{130                      //console.log(record.get(0).properties)131                      op.push(record.get(0).properties)})132                 //console.log(op)133                  })134              .catch(err =>{console.log(err.message)})135            )      136        }     137        finally { await session.close() }  138        await driver.close()139        return op140    }141    ////FUNCTION -SEARCH BY DOMAIN142    async SearchByDomain(domain){143        var op = []144        var driver = neo4j.driver(145            'bolt://localhost:7687',146            neo4j.auth.basic('neo4j', 'bookmarks')  147        )148        var session = driver.session()149        try {    150            const result = await session.writeTransaction(tx =>151                tx.run('MATCH (b: Bookmark) WHERE b.url CONTAINS $domain return b',{domain:domain})152                .then(res => {153                    res.records.forEach(record=>{154                        op.push(record.get(0).properties)})155                        //console.log(op)156                    })157                .catch(err =>{console.log(err.message)})158            )      159        }     160        finally { await session.close() }  161        await driver.close()162        return op163    }164    ////FUNCTION -SEARCH BY TAG165    async SearchByTag(tag){166        var op = [];167        var driver = neo4j.driver(168            'bolt://localhost:7687',169            neo4j.auth.basic('neo4j', 'bookmarks')  170        )171        var session = driver.session()172        try {    173            const result = await session.writeTransaction(tx =>174                tx.run('MATCH (key: Keyword)-[keyof:KEYOF]->(book:Bookmark) WHERE key.phrase CONTAINS $tag return book',{tag:tag})175                .then(res => {176                    res.records.forEach(record=>{177                        op.push(record.get(0).properties)})                178                })179                .catch(err =>{console.log(err.message)})180            )      181        }     182        finally { await session.close() }  183        await driver.close()184        return op185    }186    ////FUNCTION - ADD KEYS NODE TO DB187    async addKeys(keys){188        var driver = neo4j.driver(189            'bolt://localhost:7687',190            neo4j.auth.basic('neo4j', 'bookmarks')  191        )192        var session = driver.session()193        try {194            keys.term = keys.term.toLowerCase()    195            const result0 = await session.writeTransaction(tx =>196                tx.run(`merge(n:Keyword{phrase:$term})`,197                {term: keys.term})198                .then(res => {console.log('added: KEYWORD - ',keys.term )})199                .catch(err =>{console.log(err.message)})200            )   201            const result = await session.writeTransaction(tx =>202                tx.run(`match(n:Keyword),(b:Bookmark) where n.phrase=$term and b.id=$id merge (n)-[r:KEYOF {tf: $tf}]->(b)`,203                keys)204            .then(res => {console.log('added: KEYWORD RELATIONSHIP - ',keys.id,keys.term)})205            .catch(err =>{console.log(err.message)})206            )      207        }     208        finally { await session.close() }  209        await driver.close()210    }211    ////FUNCTION - ADD RELATIONS NODE TO DB212    async addRelations(){213        var driver = neo4j.driver(214            'bolt://localhost:7687',215            neo4j.auth.basic('neo4j', 'bookmarks')  216        )217        var session = driver.session()218        try {    219            const result = await session.writeTransaction(tx =>220            tx.run('match (n),(p:Folder) where n.parent = p.id merge (n)-[r:CHILDOF]->(p) return n')221            .then(res => {console.log('added: RELATIONSHIPS')})222            .catch(err =>{console.log(err.message)})223            )      224        }     225        finally { await session.close() }  226        await driver.close()227    }228    //FUNCTION - ADD BOOKMARK NODE TO DB229    async addBookmark(bookmark){230        var driver = neo4j.driver(231            'bolt://localhost:7687',232            neo4j.auth.basic('neo4j', 'bookmarks')  233        )234        var session = driver.session()235        try {    236            const result = await session.writeTransaction(tx =>237            tx.run('MERGE (b: Bookmark {id:$id,title:$title,index:$index,url:$url,parent:$parent,date:timestamp(),visits:$visits,rl:$readlater}) return b',bookmark)238            .then(res => {console.log('added: ',bookmark.title)})239            .catch(err =>{console.log(err.message)})240            )      241        }     242        finally { await session.close() }  243        await driver.close()244    }245    //FUNCTION - ADD FOLDER NODE TO DB246    async addFolder(bookmark){247        var driver = neo4j.driver(248            'bolt://localhost:7687',249            neo4j.auth.basic('neo4j', 'bookmarks')  250        )251        var session = driver.session()252        try {    253            const result = await session.writeTransaction(tx =>254            tx.run('MERGE (b: Folder {id:$id,title:$title,index:$index,parent:$parent,date:timestamp()}) return b',bookmark)255            .then(res => {console.log('added: ',bookmark.title)})256            .catch(err =>{console.log(err.message)})257            )       258        }     259        finally { await session.close() }  260        await driver.close()261    }262    //FUNCTION - ADD NEW PAGE263    async addNewBookmark(bookmark){264        var driver = neo4j.driver(265            'bolt://localhost:7687',266            neo4j.auth.basic('neo4j', 'bookmarks')  267        )268        var session = driver.session()269        try {    270            const result = await session.writeTransaction(tx =>271            tx.run(`merge (n:Bookmark {id:$id,parent:$parent,url:$url,title:$title,rl:$rl})`,bookmark)272            .then(res => {console.log('added BM node: ',bookmark.title)})273            .catch(err =>{console.log(err.message)})274            )275            await session.writeTransaction(tx =>276                tx.run(`match (n:Bookmark),(f:Folder) where n.id = $id and n.parent=f.id merge (n)-[r:CHILDOF]->(f)`,bookmark)277                .then(res => {console.log('added rel to parent: ',bookmark.title)})278                .catch(err =>{console.log(err.message)})279            )    280        }     281        finally { await session.close() }  282        await driver.close()283    }284    ////GET FOLDERS285    async DisplayFolder(){286        var output = [];287        var neo4j = require('neo4j-driver');288            var driver = neo4j.driver(289                'bolt://localhost:7687',290                neo4j.auth.basic('neo4j', 'bookmarks')  291            )292            var session = driver.session()293            try {    294                const result = await session.writeTransaction(tx =>295                  tx.run('MATCH(f:Folder) RETURN f')296                  .then(res => {297                      res.records.forEach(record=>{298                          output.push(record.get(0).properties)})299                      })300                  .catch(err =>{console.log(err.message)})301                )      302            }     303            finally { await session.close() }  304            await driver.close()305            return output306    }307    308    //NAVIGATION DISPLAY309    async DisplayBookmarksUnderFolder(id){310        var output = [];311        var neo4j = require('neo4j-driver');312        var driver = neo4j.driver(313            'bolt://localhost:7687',314            neo4j.auth.basic('neo4j', 'bookmarks')  315        )316        var session = driver.session()317            try {    318                const result = await session.writeTransaction(tx =>319                    tx.run(`match (n) where n.parent = $id return n`,{id:id})320                    .then(r=>{321                        //console.log(r.reco)322                        r.records.forEach(record=>{output.push(record.get(0).properties)323                        })})324                    .catch(e=>{}))325            }     326            finally { await session.close() }  327            await driver.close()328            console.log('sent no. of children:',output.length)329            return output330    }331    //DELETE FOLDER332    async DeleteFolder(id){333        var neo4j = require('neo4j-driver');334        var driver = neo4j.driver(335            'bolt://localhost:7687',336            neo4j.auth.basic('neo4j', 'bookmarks')  337        )338        var session = driver.session()339        try { 340            const result = await session.writeTransaction(tx =>341              tx.run('Match((n)-[c:CHILDOF *0..]->(f:Folder)) WHERE f.id=$id DETACH DELETE n,f',{id:id})342              .then(res => {343              })344              .catch(err =>{console.log(err.message)})345            )  346        }     347        finally { await session.close() }  348        await driver.close()349        350    }351    async DeleteBookmark(id){352        var neo4j = require('neo4j-driver');353        var driver = neo4j.driver(354            'bolt://localhost:7687',355            neo4j.auth.basic('neo4j', 'bookmarks')  356        )357        var session = driver.session()358        try { 359            const result = await session.writeTransaction(tx =>360              tx.run('MATCH((b:Bookmark) WHERE b.id=$id DETACH DELETE b ',{id:id})361              .then(res => {362              })363              .catch(err =>{console.log(err.message)})364            )  365               366        }     367        finally { await session.close() }  368        await driver.close()369    }370    //atempt 2371    async ADDFolder2(new_title,old_title,id){372        var neo4j = require('neo4j-driver');373        var driver = neo4j.driver(374            'bolt://localhost:7687',375            neo4j.auth.basic('neo4j', 'bookmarks')  376        )377        var output=[]378        var session = driver.session()379        try {    380            const result = await session.writeTransaction(tx =>381              tx.run('MERGE(f:Folder{title:$new_title,id:$id}) set f.date=timestamp() MERGE(f1:Folder {title:$old_title})  MERGE((f)-[:CHILDOF]->(f1)) RETURN f1',{new_title:new_title,old_title:old_title,id:id})382              .then(res => {383                  console.log(res.records[0].get(0).properties.id);384                  output.push(res.records[0].get(0).properties.id)385              })386              .catch(err =>{console.log(err.message)})387            )      388        }     389        finally { await session.close() }  390        await driver.close()391        return output[0]392    }393    394    async findParent(pname){395        var op = []396        var neo4j = require('neo4j-driver');397            var driver = neo4j.driver(398                'bolt://localhost:7687',399                neo4j.auth.basic('neo4j', 'bookmarks')  400            )401            var session = driver.session()402            try {    403                const result = await session.writeTransaction(tx =>404                  tx.run('match (p:Folder) where p.title = $pname return p.id',{pname:pname})405                  .then(res => {406                      res.records.forEach(record=>{407                        op.push(record.get(0))})408                  })409                  .catch(err =>{console.log(err.message)})410                )      411            }     412            finally { await session.close() }  413        await driver.close()414        return op415    }416}417exports.neo4jQueries = neo4jQueries418/**419res => {420                    res.records.forEach(record=>{421                        op.push(record.get(0).properties)})422                        //console.log(op)423                    }...

Full Screen

Full Screen

SqlPrettyPrinter.js

Source:SqlPrettyPrinter.js Github

copy

Full Screen

1var SqlPrettyPrinter = {2  keywords: {groupBy: 'GROUP BY',3             having: 'HAVING',4             orderBy: 'ORDER BY'},5  strFunctions: {6    toUpper: function(s) {7      return s.toUpperCase()8    },9    toLower: function(s) {10      return s.toLowerCase()11    },12    toTitle: function(s) {13      return s.toLowerCase().replace(/((^)|(\s+)|(\.)|_)[a-zA-Z0-9]/g,14      	                             function(t) { return t.toUpperCase() })15    },16    toEqual: function(s) {17      return s18    }19  },20  format: function(query, settings) {21    var ast = null22    try {23      ast = parser.parse(query)24    } catch(e) {25      return e26    }27    28    settings = settings || {}29    var driver = {30      settings: settings,31      buffer: '',32      prevChar: '',33      linePositions: [],34      appendToBuffer: function(s) {35          this.buffer = this.buffer + s36          SqlPrettyPrinter.buffer = this.buffer37      },38      write: function(st, suppressPrepend) {39        var prepend = ' '40        if (st == ',' || st == '' || st == ')' || st == 'SELECT') prepend = ''41        if (this.prevChar =='(') prepend = ''42        if (suppressPrepend) prepend = ''43        this.appendToBuffer(prepend + st)44        this.prevChar = st45      },46      writeUsingSettingsCase: function(st, kase) {47        var caseSetting = this.settings[kase + 'Case']48      	49        if (caseSetting) this.write(SqlPrettyPrinter.strFunctions[caseSetting](st))50      	else this.write(st)51      },52      curLineLength: function() {53        return this.buffer.length - Math.max(0, this.buffer.lastIndexOf('\n') + 1)54      },55      lastLinePositionElem: function() {56        return this.linePositions[this.linePositions.length - 1]57      },58      openParen: function(suppressPrepend) {59        this.write('(', suppressPrepend)60      },61      closeParen: function() {62        this.write(')')63      },64      writeKeyword: function(st) {65        this.write(st.toUpperCase())66      },67      writeIndent: function() {68        this.appendToBuffer('    ')69      },70      wrapToRight: function() {71        this.appendToBuffer('\n')72        var elem = this.lastLinePositionElem()73        for (var i = 0; i < (elem.margin - 1); i++) this.appendToBuffer(' ')74      },75      writeLeftKeyword: function(st) {76        var beforeSpace = '\n'77        var cntWhite78        if (st.toUpperCase() == 'SELECT') {79          beforeSpace = ''80          cntWhite = this.lastLinePositionElem().leftSize - st.length81        } else {82          cntWhite = this.lastLinePositionElem().margin - st.length - 183        }84         85        this.appendToBuffer(beforeSpace)86        for (var i = 0; i < cntWhite; i++) this.appendToBuffer(' ')87        this.appendToBuffer(st.toUpperCase())88        this.prevChar = st89      },90      saveCurrentPos: function(prefixSize) {91        this.linePositions.push({leftSize: prefixSize, margin:this.curLineLength() + prefixSize + 1})92      },93      restoreCurrentPos: function() {94        this.linePositions.pop()95      }96    }97    98    this.formatSelect(ast.value, driver)99    return SqlPrettyPrinter.buffer100  },101  formatSelect: function(node, driver) {102    this.formatExpressionPlus(node, driver)103  },104  formatSelectItem: function(node, driver) {105    var leftSize = 6106    for (var keyword in SqlPrettyPrinter.keywords) {107      if (node[keyword]) leftSize = Math.max(leftSize, SqlPrettyPrinter.keywords[keyword].length)108    }109    110    driver.saveCurrentPos(leftSize)111    driver.writeLeftKeyword('SELECT')112    if (node.distinct) {113        driver.writeKeyword('DISTINCT');114    }115    if (node.top) {116        driver.writeKeyword('TOP');117        driver.write(node.top);118    }119    for (var i = 0; i < node.columns.length; i++) {120      this.formatColumn(node.columns[i], driver)121      if (node.columns.length > 1 && i != (node.columns.length - 1)) {122        driver.write(',')123        driver.wrapToRight()124      }125    }126    if (node.from.length) {127      driver.writeLeftKeyword('FROM')128      for (var i = 0; i < node.from.length; i++) {129        this.formatFrom(node.from[i], driver)130        if (node.from.length > 1 && i != (node.from.length - 1)) {131          driver.write(',')132          driver.wrapToRight()133        }            134      }135    }136    if (node.where) this.formatWhere(node.where, driver)137    if (node.groupBy) this.formatGroupBy(node.groupBy, driver)138    if (node.having) this.formatHaving(node.having, driver)139    if (node.orderBy) this.formatOrderBy(node.orderBy, driver)140    if (node.queryHints) this.formatQueryHints(node.queryHints, driver)141    142    driver.restoreCurrentPos()143  },144  formatColumn: function(node, driver) {145    if (typeof node.value == 'string') {146      driver.write(node.value)147    } else {148      this.formatExpression(node.value, driver)149    }150    this.formatAlias(node, driver)151  },152  formatAlias: function(node, driver) {153    if (node.alias) {154      if (node.alias.includeAs) driver.writeKeyword('AS')155      driver.write(node.alias.value)156    }157  },158  formatAndChain: function(node, driver) {159      for (var i = 0; i < node.length; i++) {160      	if (i != 0) driver.writeLeftKeyword('AND')161      	this.formatCondition(node[i], driver)162      }163  },164  formatExpressionPlus: function(node, driver) {165    driver.saveCurrentPos(0)166    for (var i = 0; i < node.length; i++) {167      if (node[i].nodeType === 'Select') {168        this.formatSelectItem(node[i], driver);169      } else if (node[i].nodeType === 'SetOperator') {170        driver.wrapToRight()171        driver.writeKeyword(node[i].value)172        driver.wrapToRight()173      } else {174        this.formatExpression(node[i], driver)175      }176    }177    driver.restoreCurrentPos()178  },179  formatExpression: function(node, driver) {180    if (node.nodeType === 'Select') {181      this.formatSelectItem(node, driver);182    } else if (node.nodeType == 'AndCondition') {183      this.formatAndChain(node.value, driver)184    } else {185      /* OrCondition */186      this.formatExpression(node.left, driver)187      driver.writeLeftKeyword('OR')188      this.formatAndChain(node.right, driver)189    }190  },191  formatFrom: function(node, driver) {192    for (var i = 0; i < node.value.length; i++) {193      this.formatTableFrom(node.value[i], driver)194    }195  },196  formatTableFrom: function(node, driver) {197    if (node.nodeType) {198      driver.writeLeftKeyword('')199      driver.write(node.modifier)200      driver.writeKeyword('JOIN')201      this.formatTableFrom(node.value, driver)202      if (node.expression) {203        driver.writeKeyword('ON')204        this.formatExpression(node.expression, driver)205      }206      return207    }208    if (typeof node.exprName == 'string') {209      driver.writeUsingSettingsCase(node.exprName, 'table')210    } else {211      /* Sub select expression */212      driver.openParen()213      this.formatSelect(node.exprName, driver)214      driver.closeParen()215    }216    this.formatAlias(node, driver)217    if (node.tableHints) {218      driver.writeKeyword('WITH')219      driver.openParen()220      for (var i = 0; i < node.tableHints.length; i++) {221        driver.writeKeyword(node.tableHints[i])222        if (i != (node.tableHints.length - 1)) { 223          driver.write(',')224        }225      }226      driver.closeParen()227    }228  },229  formatWhere: function(node, driver) {230    driver.writeLeftKeyword('WHERE')231    this.formatExpression(node, driver)232  },233  formatGroupBy: function(node, driver) {234    driver.writeLeftKeyword('GROUP BY')235    for (var i = 0; i < node.length; i++) {236      this.formatExpression(node[i], driver)237      if (i != (node.length - 1)) { 238        driver.write(',')239        driver.wrapToRight()240      }241    }242  },243  formatHaving: function(node, driver) {244    driver.writeLeftKeyword('HAVING')245    this.formatExpression(node, driver)246  },247  formatOrderBy: function(node, driver) {248    driver.writeLeftKeyword('ORDER BY')249    for (var i = 0; i < node.length; i++) {250      var elem = node[i]251      this.formatExpression(elem.expression, driver)252      driver.writeKeyword(elem.orderByOrder)253      driver.writeKeyword(elem.orderByNulls)254      if (i != (node.length - 1)) {255        driver.write(',')256        driver.wrapToRight()257      }258    }259  },260  formatCondition: function(node, driver) {261    if (node.nodeType == 'Condition') {262      this.formatOperand(node.value, driver)263    } else if (node.nodeType == 'BinaryCondition') {264      this.formatOperand(node.left, driver)265      this.formatRhs(node.right, driver)266    } else if (node.nodeType == 'ExistsCondition') {267      driver.writeKeyword('EXISTS')268      driver.openParen()269      this.formatSelect(node.value, driver)270      driver.closeParen()271    } else if (node.nodeType == 'NotCondition') {272      driver.writeKeyword('NOT')273      this.formatCondition(node.value, driver)274    }275  },276  formatOperand: function(node, driver) {277    if (node.nodeType == 'Term') {278      if (typeof node.value == 'string') {279        driver.writeUsingSettingsCase(node.value, 'identifier')280      } else {281        /* Sub expression */282        driver.openParen()283        this.formatExpressionPlus(node.value, driver);284        driver.closeParen()285      }286    } else if (node.nodeType == 'Operand'287            || node.nodeType == 'Factor'288            || node.nodeType == 'Summand') {289      this.formatOperand(node.left, driver)290      driver.write(node.op)291      this.formatOperand(node.right, driver)292    } else if (node.nodeType == 'FunctionCall') {293      driver.writeUsingSettingsCase(node.name, 'function')294      driver.openParen()295      if (node.args) {296        for (var i = 0; i < node.args.length; i++) {297          var elem = node.args[i]298          if (typeof elem == 'string') {299            /* Element is STAR or QUALIFIED_STAR */300            driver.write(elem)301          } else {302            this.formatExpression(node.args[i], driver)  303          }304          if (i != (node.args.length - 1)) driver.write(',')305        }306      }307      driver.closeParen()308    } else if (node.nodeType == 'Case') {309      driver.saveCurrentPos(4)310      driver.writeKeyword('CASE')311      driver.saveCurrentPos(5)312      for (var i = 0; i < node.clauses.length; i++) {313        if (i == 0) {314          driver.writeKeyword('WHEN')315        } else {316          driver.writeLeftKeyword('WHEN')317        }318        this.formatExpression(node.clauses[i].when, driver)319        driver.writeKeyword('THEN')320        this.formatExpression(node.clauses[i].then, driver)321      }322      if (node.else) {323        driver.writeLeftKeyword('ELSE')324        this.formatExpression(node.else, driver)325      }326      driver.restoreCurrentPos()327      driver.writeLeftKeyword('END')328      driver.restoreCurrentPos()329    } else if (node.nodeType == 'Select') {330      this.formatSelectItem(node.value, driver)331    } else if (node.nodeType == 'Cast') {332      driver.writeKeyword('CAST')333      driver.openParen(true)334      this.formatExpression(node.expression, driver)335      driver.writeKeyword('AS')336      driver.writeKeyword(node.dataType.name)337      if (node.dataType.len !== null) {338        driver.openParen(true)339        driver.writeKeyword(node.dataType.len)340        driver.closeParen()341      }342      driver.closeParen()343    }344  },345  formatRhs: function(node, driver) {346    if (node.nodeType == 'RhsCompare') {347      driver.write(node.op)348      this.formatOperand(node.value, driver)349    } else if (node.nodeType == 'RhsCompareSub') {350      driver.write(node.op)351      driver.writeKeyword(node.kind)352      driver.openParen()353      this.formatSelect(node.value, driver)354      driver.closeParen()355    } else if (node.nodeType == 'RhsIs') {356      driver.writeKeyword('IS')357      if (node.not) driver.writeKeyword('NOT')358      if (node.distinctFrom) {359        driver.writeKeyword('DISTINCT')360        driver.writeKeyword('FROM')361      }362      this.formatOperand(node.value, driver)363    } else if (node.nodeType == 'RhsInSelect') {364      driver.writeKeyword('IN')365      driver.openParen()366      this.formatSelect(node.value, driver)367      driver.closeParen()368    } else if (node.nodeType == 'RhsInExpressionList') {369      driver.writeKeyword('IN')370      driver.openParen()371      for (var i = 0; i < node.value.length; i++) {372        this.formatExpression(node.value[i], driver)373        if (i != (node.value.length - 1)) driver.write(',')374      }375      driver.closeParen()376    } else if (node.nodeType == 'RhsBetween') {377      if (node.not) driver.writeKeyword('NOT')378      driver.writeKeyword('BETWEEN')379      this.formatOperand(node.left, driver)380      driver.writeKeyword('AND')381      this.formatOperand(node.right, driver) 382    } else if (node.nodeType == 'RhsLike') {383      if (node.not) driver.writeKeyword('NOT')384      driver.writeKeyword('LIKE')385      this.formatOperand(node.value, driver)386    }387  },388  formatQueryHints: function(node, driver) {389    driver.writeLeftKeyword('OPTION')390    driver.openParen()391    for (var i = 0; i < node.length; i++) {392      var elem = node[i]393      for (var j = 0; j < elem.length; j++) {394        driver.writeUsingSettingsCase(elem[j], 'identifier')395      }396      if (i != (node.length - 1)) {397        driver.write(',')398      }399    }400    driver.closeParen()401  }...

Full Screen

Full Screen

query.js

Source:query.js Github

copy

Full Screen

...62                                                }63                                            }).catch(err  =>  {64                                                console.log(err)65                                                session.close()66                                                driver.close()67                                            })68                                        }).catch(err  =>  {69                                            console.log(err)70                                            session.close()71                                            driver.close()72                                        })73                                    }).catch(err  =>  {74                                        console.log(err)75                                        session.close()76                                        driver.close()77                                    })78                                }).catch(err  =>  {79                                    console.log(err)80                                    session.close()81                                    driver.close()82                                })83                            }).catch(err  =>  {84                                console.log(err)85                                session.close()86                                driver.close()87                            })88                        })89                        .catch(err  =>  {90                            console.log(err)91                            session.close()92                            driver.close()93                        })94                    .catch(err  =>  {95                        console.log(err)96                        session.close()97                        driver.close()98                    })99                })100                .catch(err  =>  {101                    console.log(err)102                    session.close()103                    driver.close()104                })105            }   else    {106                let collectionId = Number(comic.resourceURI.slice(comic.resourceURI.indexOf('comics/')).replace('comics/', ''))107                return match(session, driver, "Collection", 'marvelId', collectionId)108                .then(res   =>  {109                    if(res.records.length === 0)    {110                        return addCollection(session, driver, {name: comic.title}, collectionId)111                    }   else    {112                        return generalMatch(session, driver)113                    }114                })115                .then(()    =>  {116                    if(newComics.length > 0)    {117                        return query(session, driver, newComics, number+1)...

Full Screen

Full Screen

test.js

Source:test.js Github

copy

Full Screen

...20    }, 30 * 1000);21  })22  .then(function() {23    t.pass('got candidates');24    driver.close();25    driver.quit();26    t.end();27  })28  .then(null, function(err) {29    t.fail(err);30    driver.close();31    driver.quit();32    t.end();33  });34});35test('Loading server data', function(t) {36  var driver = seleniumHelpers.buildDriver();37  driver.get('file://' + process.cwd() +38      '/src/content/peerconnection/trickle-ice/index.html')39  .then(function() {40    t.pass('page loaded');41    return driver.findElement(webdriver.By.css('#servers>option'));42  })43  .then(function(element) {44    return new webdriver.ActionSequence(driver).45        doubleClick(element).perform();46  })47  .then(function() {48    return driver.findElement(webdriver.By.id('url')).getAttribute('value');49  })50  .then(function(value) {51    t.ok(value !== '', 'doubleclick loads server data');52    driver.close();53    driver.quit();54    t.end();55  })56  .then(null, function(err) {57    t.fail(err);58    driver.close();59    driver.quit();60    t.end();61  });62});63test('Adding a server', function(t) {64  var driver = seleniumHelpers.buildDriver();65  driver.get('file://' + process.cwd() +66      '/src/content/peerconnection/trickle-ice/index.html')67  .then(function() {68    t.pass('page loaded');69    return driver.findElement(webdriver.By.id('url'))70        .sendKeys('stun:stun.l.google.com:19302');71  })72  .then(function() {73    t.pass('url input worked');74    return driver.findElement(webdriver.By.id('add')).click();75  })76  .then(function() {77    return driver.findElement(webdriver.By.css('#servers'))78        .getAttribute('length');79  })80  .then(function(length) {81    t.ok(length === '2', 'server added');82    driver.close();83    driver.quit();84    t.end();85  })86  .then(null, function(err) {87    t.fail(err);88    driver.close();89    driver.quit();90    t.end();91  });92});93test('Removing a server', function(t) {94  var driver = seleniumHelpers.buildDriver();95  driver.get('file://' + process.cwd() +96      '/src/content/peerconnection/trickle-ice/index.html')97  .then(function() {98    t.pass('page loaded');99    return driver.findElement(webdriver.By.css('#servers>option')).click();100  })101  .then(function() {102    return driver.findElement(webdriver.By.id('remove')).click();103  })104  .then(function() {105    return driver.findElement(webdriver.By.css('#servers'))106        .getAttribute('length');107  })108  .then(function(length) {109    t.ok(length === '0', 'server removed');110    driver.close();111    driver.quit();112    t.end();113    driver = null;114  })115  .then(null, function(err) {116    t.fail(err);117    if (driver) {118      driver.close();119      driver.quit();120      driver = null;121    }122    t.end();123  });...

Full Screen

Full Screen

insertQuestions.js

Source:insertQuestions.js Github

copy

Full Screen

...25                 merge (q:question{value:'${linearr[4]}'}) merge (q)-[:${linearr[3]}]->(n)26                 merge (i:image{value:'${linearr[8]}'}) merge (q)-[:answer{rating:0}]->(i)`;27                session.run(query).then(function(result) {28                    session.close();29                    driver.close();30                }).catch(function(error) {31                    driver.close();32                });33            } else {34                if (linearr[5].length > 1) {35                    let query = `match (n:${linearr[0]} {id:${linearr[1]}})36                    merge (q:question{value:'${linearr[4]}'}) merge (q)-[:${linearr[3]}]->(n)37                    merge (t:text{value:'${linearr[5]}'}) merge (q)-[:answer{rating:0}]->(t)`;38                    session.run(query).then(function(result) {39                        session.close();40                        driver.close();41                    }).catch(function(error) {42                        driver.close();43                    });44                }45                if (linearr[6].length > 1) {46                    let query = `match (n:${linearr[0]} {id:${linearr[1]}})47                    merge (q:question{value:'${linearr[4]}'}) merge (q)-[:${linearr[3]}]->(n)48                    merge (b:blog{value:'${linearr[6]}'}) merge (q)-[:answer{rating:0}]->(b)`;49                    session.run(query).then(function(result) {50                        session.close();51                        driver.close();52                    }).catch(function(error) {53                        driver.close();54                    });55                }56                if (linearr[7].length > 1) {57                    let query = `match (n:${linearr[0]} {id:${linearr[1]}})58                    merge (q:question{value:'${linearr[4]}'})   merge (q)-[:${linearr[3]}]->(n)59                    merge (v:video{value:'${linearr[7]}'}) merge (q)-[:answer{rating:0}]->(v)`;60                    session.run(query).then(function(result) {61                        session.close();62                        driver.close();63                    }).catch(function(error) {64                        driver.close();65                    });66                }67            }68        }69    });7071    rd.on('close', function() {});
...

Full Screen

Full Screen

verifyTestSL.js

Source:verifyTestSL.js Github

copy

Full Screen

...8    let placeholder_username = await driver.findElement(By.id('user-name')).getAttribute('placeholder');9    let placeholder_password = await driver.findElement(By.id('password')).getAttribute('placeholder');10    if (placeholder_username !== 'Username' || placeholder_password !== 'Password'){11        console.log("Username or Password - placeholder missmatch")12        await driver.close();13    }14    else {15    var title = await driver.getTitle();16    console.log('\nTitle is:',title,searchString);17    console.log("Swag Labs login screen - Both placeholders are correct - Test Passed\n")18    //Driver.close , closes the browser remaining from the test.19    await driver.close();20    }21}22Swaglabs_standard_login_placeholder_check();23async function Swaglabs_standard_login_creds_check() {24    let driver = await new Builder().forBrowser("chrome").build();25    await driver.get("https://www.saucedemo.com/");26    let acceptText = await driver.findElement(By.xpath('//*[@id="login_credentials"]/h4')).getText();27    let passwordText = await driver.findElement(By.xpath('//*[@id="root"]/div/div[2]/div[2]/div/div[2]/h4')).getText();28    await driver.findElement(By.xpath('//*[text()="standard_user"]'))29    await driver.findElement(By.xpath('//*[text()="locked_out_user"]'))30    await driver.findElement(By.xpath('//*[text()="problem_user"]'))31    await driver.findElement(By.xpath('//*[text()="performance_glitch_user"]'))32    await driver.findElement(By.xpath('//*[text()="secret_sauce"]'))33    if (acceptText !== "Accepted usernames are:"){34        console.log("Accepted users text missmatch")35        await driver.close();36    }37    else if (passwordText !== "Password for all users:"){38        console.log("Password for all users text missmatch")39        await driver.close();40    }41    else {42        var title = await driver.getTitle();43        console.log('\nTitle is:',title,searchString);44        console.log("Swag Labs login screen - All login Credential texts are correct - Test Passed\n")45        //Driver.close , closes the browser remaining from the test.46        await driver.close();47    }48}49Swaglabs_standard_login_creds_check();50*/51async function Swaglabs_standard_login() {52    let driver = await new Builder().forBrowser("chrome").build();53    await driver.get("https://www.saucedemo.com/");54    await driver.findElement(By.id("user-name")).click();55    await driver.findElement(By.id("user-name")).sendKeys("standard_user");56    await driver.findElement(By.id("password")).sendKeys("secret_sauce",Key.RETURN)57    //added interaction on successful login to check that it worked58    await driver.findElement(By.name("add-to-cart-sauce-labs-backpack")).click();59    var title = await driver.getTitle();60    console.log('\nTitle is:',title,searchString);61    console.log("Swag Labs Standard Login - Test Passed\n")62    //Driver.close , closes the browser remaining from the test.63    await driver.close();64}...

Full Screen

Full Screen

tweets.js

Source:tweets.js Github

copy

Full Screen

1var dbDriver = require("../module/db.js");2exports.list = function(req, res){3	dbDriver.openAndAuthDatabase(dbDriver,function(err,db){4		if(err)5		{6			console.log(err);7			res.end();8		}9		else {10			var tweet = require("../module/tweet.js");11			tweet.getAll(db,1,function(err,list) {12				dbDriver.closeDatabase();13				if(!err)14				{15					res.send(list);16				}17				18				res.end();19			});20		}21	});// end of dbDriver22};23exports.newtweet = function(req, res){24	dbDriver.openAndAuthDatabase(dbDriver,function(err,db){25		if(err)26		{27			dbDriver.closeDatabase();28			console.log(err);29			res.end();30		}31		else {32			var username = req.body.username;33			if(req.body.username== null || username =="")34			{35				dbDriver.closeDatabase();36				res.status(400);37				res.end("Username is required");38			}39			var avatar_url = req.body.avatar_url;40			if(req.body.avatar_url== null || avatar_url =="")41			{42				avatar_url = "http://localhost:3000/images/redpanda.png";43			}44			45			var message = req.body.message;46			if(req.body.message== null || message =="")47			{48				dbDriver.closeDatabase();49				res.status(400);50				res.end("message is required");51			}52			var tweet = require("../module/tweet.js");53			var user = {54				username : username,55				avatar_url:avatar_url56			}57			tweet.newtweet(user,message,db,function(err,docs){58				dbDriver.closeDatabase();59				if(err)60				{61					console.log(err);62					res.end();63				}64				else {65					res.send(docs[0]);66					res.end();67				}68			});69			res.end();70		}71	});//close open and auth database72}73exports.deletetweet = function(req, res){74	dbDriver.openAndAuthDatabase(dbDriver,function(err,db){75		var tweet_id = req.params.id;76		if(req.params.id == null || tweet_id =="")77		{78			dbDriver.closeDatabase();79			res.status(400);80			res.end("id is required");81		}82		else if(tweet_id != null && tweet_id.length != 24)83		{84			dbDriver.closeDatabase();85			res.status(400);86			res.end("id is not correct");87		}88		else {89			var tweet = require("../module/tweet.js");90			tweet.delete(tweet_id,db,function(err,removed) {91			dbDriver.closeDatabase();92			if(err)93			{94				console.log(err);95				res.end();96			}97			else {98				console.log("removed");99				res.end();100			}101		});102		}103		104		105		106	});...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const chai = require('chai');3const chaiAsPromised = require('chai-as-promised');4const { exec } = require('child_process');5chai.use(chaiAsPromised);6chai.should();7async function main() {8  await driver.init({9  });10  await driver.quit();11}12main();13info: [debug] [BaseDriver] Event 'quitSessionRequested' logged at 1518145840227 (13:50:40 GMT+0530 (IST))14info: [debug] [BaseDriver] Event 'quitSessionFinished' logged at 1518145840228 (13:50:40 GMT+0530 (IST))

Full Screen

Using AI Code Generation

copy

Full Screen

1driver.closeApp();2driver.terminateApp();3driver.activateApp();4driver.resetApp();5driver.installApp();6driver.removeApp();7driver.launchApp();8driver.isAppInstalled();9driver.terminateApp();10driver.activateApp();11driver.resetApp();12driver.installApp();13driver.removeApp();14driver.launchApp();15driver.isAppInstalled();16driver.terminateApp();17driver.activateApp();18driver.resetApp();19driver.installApp();20driver.removeApp();21driver.launchApp();22driver.isAppInstalled();23driver.terminateApp();

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test Native App', () => {2  it('should close the app', async () => {3    await driver.closeApp();4  });5});6describe('Test Native App', () => {7  it('should launch the app', async () => {8    await driver.launchApp();9  });10});11describe('Test Native App', () => {12  it('should reset the app', async () => {13    await driver.resetApp();14  });15});16describe('Test Native App', () => {17  it('should check if the app is installed', async () => {18    await driver.isAppInstalled('com.example.app');19  });20});21describe('Test Native App', () => {22  it('should install the app', async () => {23    await driver.installApp('path/to/app.ipa');24  });25});26describe('Test Native App', () => {27  it('should remove the app', async () => {28    await driver.removeApp('com.example.app');29  });30});31describe('Test Native App', () => {32  it('should activate the app', async () => {33    await driver.activateApp('com.example.app');34  });35});36describe('Test Native App', () => {37  it('should terminate the app', async () => {38    await driver.terminateApp('com.example.app');

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const assert = require('assert');3const {exec} = require('child_process');4const argv = require('minimist')(process.argv.slice(2));5const username = argv.username;6const accessKey = argv.accessKey;7const device = argv.device;8const platform = argv.platform;9const platformVersion = argv.platformVersion;10const app = argv.app;11const appPackage = argv.appPackage;12const appActivity = argv.appActivity;13const appiumVersion = argv.appiumVersion;14const udid = argv.udid;15const deviceName = argv.deviceName;16const automationName = argv.automationName;17const browserName = argv.browserName;18const platformName = argv.platformName;19const newCommandTimeout = argv.newCommandTimeout;20const browserstackLocal = argv.browserstackLocal;21const browserstackLocalIdentifier = argv.browserstackLocalIdentifier;22const browserstackDebug = argv.browserstackDebug;23const browserstackNetworkLogs = argv.browserstackNetworkLogs;24const browserstackConsole = argv.browserstackConsole;25const browserstackAppiumLogs = argv.browserstackAppiumLogs;26const browserstackVideo = argv.browserstackVideo;27const browserstackDeviceLogs = argv.browserstackDeviceLogs;28const browserstackUseFirstMatchingApp = argv.browserstackUseFirstMatchingApp;29const browserstackForceAppInstall = argv.browserstackForceAppInstall;30const browserstackForceDevice = argv.browserstackForceDevice;31const browserstackForceOrientation = argv.browserstackForceOrientation;32const browserstackGeoLocation = argv.browserstackGeoLocation;33const browserstackLocalProxyHost = argv.browserstackLocalProxyHost;34const browserstackLocalProxyPort = argv.browserstackLocalProxyPort;35const browserstackLocalProxyUser = argv.browserstackLocalProxyUser;36const browserstackLocalProxyPass = argv.browserstackLocalProxyPass;37const browserstackLocalBinary = argv.browserstackLocalBinary;38const browserstackLocalForcedKill = argv.browserstackLocalForcedKill;39const browserstackLocalOnly = argv.browserstackLocalOnly;40const browserstackLocalLogLevel = argv.browserstackLocalLogLevel;41const browserstackLocalUseBeta = argv.browserstackLocalUseBeta;42const browserstackLocalDebug = argv.browserstackLocalDebug;43const browserstackLocalIdentifierFile = argv.browserstackLocalIdentifierFile;44const browserstackLocalLogFile = argv.browserstackLocalLogFile;

Full Screen

Using AI Code Generation

copy

Full Screen

1driver.close();2var isAppRunning = driver.isAppInstalled("com.testapp");3console.log("isAppRunning: " + isAppRunning);4driver.launchApp();5isAppRunning = driver.isAppInstalled("com.testapp");6console.log("isAppRunning: " + isAppRunning);7driver.close();8isAppRunning = driver.isAppInstalled("com.testapp");9console.log("isAppRunning: " + isAppRunning);10driver.launchApp();11isAppRunning = driver.isAppInstalled("com.testapp");12console.log("isAppRunning: " + isAppRunning);13driver.close();14isAppRunning = driver.isAppInstalled("com.testapp");15console.log("isAppRunning: " + isAppRunning);16driver.launchApp();17isAppRunning = driver.isAppInstalled("com.testapp");18console.log("isAppRunning: " + isAppRunning);19driver.close();20isAppRunning = driver.isAppInstalled("com.testapp");21console.log("isApp

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium Xcuitest Driver automation tests on LambdaTest cloud grid

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

Sign up Free
_

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful