How to use convertCookie method in Appium Xcuitest Driver

Best JavaScript code snippet using appium-xcuitest-driver

ext-cookies.js

Source:ext-cookies.js Github

copy

Full Screen

...255 normalizeFirstPartyDomain(details);256 // FIXME: We don't sort by length of path and creation time.257 let allowed = ["url", "name", "storeId", "firstPartyDomain"];258 for (let cookie of query(details, allowed, context)) {259 return Promise.resolve(convertCookie(cookie));260 }261 // Found no match.262 return Promise.resolve(null);263 },264 getAll: function(details) {265 if (!("firstPartyDomain" in details)) {266 normalizeFirstPartyDomain(details);267 }268 let allowed = ["url", "name", "domain", "path", "secure", "session", "storeId"];269 // firstPartyDomain may be set to null or undefined to not filter by FPD.270 if (details.firstPartyDomain != null) {271 allowed.push("firstPartyDomain");272 }273 let result = Array.from(query(details, allowed, context), convertCookie);274 return Promise.resolve(result);275 },276 set: function(details) {277 normalizeFirstPartyDomain(details);278 let uri = Services.io.newURI(details.url).QueryInterface(Ci.nsIURL);279 let path;280 if (details.path !== null) {281 path = details.path;282 } else {283 // This interface essentially emulates the behavior of the284 // Set-Cookie header. In the case of an omitted path, the cookie285 // service uses the directory path of the requesting URL, ignoring286 // any filename or query parameters.287 path = uri.directory;288 }289 let name = details.name !== null ? details.name : "";290 let value = details.value !== null ? details.value : "";291 let secure = details.secure !== null ? details.secure : false;292 let httpOnly = details.httpOnly !== null ? details.httpOnly : false;293 let isSession = details.expirationDate === null;294 let expiry = isSession ? Number.MAX_SAFE_INTEGER : details.expirationDate;295 let isPrivate = context.incognito;296 let userContextId = 0;297 if (isDefaultCookieStoreId(details.storeId)) {298 isPrivate = false;299 } else if (isPrivateCookieStoreId(details.storeId)) {300 isPrivate = true;301 } else if (isContainerCookieStoreId(details.storeId)) {302 let containerId = getContainerForCookieStoreId(details.storeId);303 if (containerId === null) {304 return Promise.reject({message: `Illegal storeId: ${details.storeId}`});305 }306 isPrivate = false;307 userContextId = containerId;308 } else if (details.storeId !== null) {309 return Promise.reject({message: "Unknown storeId"});310 }311 let cookieAttrs = {host: details.domain, path: path, isSecure: secure};312 if (!checkSetCookiePermissions(extension, uri, cookieAttrs)) {313 return Promise.reject({message: `Permission denied to set cookie ${JSON.stringify(details)}`});314 }315 let originAttributes = {316 userContextId,317 privateBrowsingId: isPrivate ? 1 : 0,318 firstPartyDomain: details.firstPartyDomain,319 };320 // The permission check may have modified the domain, so use321 // the new value instead.322 Services.cookies.add(cookieAttrs.host, path, name, value,323 secure, httpOnly, isSession, expiry, originAttributes);324 return self.cookies.get(details);325 },326 remove: function(details) {327 normalizeFirstPartyDomain(details);328 let allowed = ["url", "name", "storeId", "firstPartyDomain"];329 for (let {cookie, storeId} of query(details, allowed, context)) {330 Services.cookies.remove(cookie.host, cookie.name, cookie.path, false, cookie.originAttributes);331 // Todo: could there be multiple per subdomain?332 return Promise.resolve({333 url: details.url,334 name: details.name,335 storeId,336 firstPartyDomain: details.firstPartyDomain,337 });338 }339 return Promise.resolve(null);340 },341 getAllCookieStores: function() {342 let data = {};343 for (let tab of extension.tabManager.query()) {344 if (!(tab.cookieStoreId in data)) {345 data[tab.cookieStoreId] = [];346 }347 data[tab.cookieStoreId].push(tab.id);348 }349 let result = [];350 for (let key in data) {351 result.push({id: key, tabIds: data[key], incognito: key == PRIVATE_STORE});352 }353 return Promise.resolve(result);354 },355 onChanged: new EventManager(context, "cookies.onChanged", fire => {356 let observer = (subject, topic, data) => {357 let notify = (removed, cookie, cause) => {358 cookie.QueryInterface(Ci.nsICookie2);359 if (extension.whiteListedHosts.matchesCookie(cookie)) {360 fire.async({removed, cookie: convertCookie({cookie, isPrivate: topic == "private-cookie-changed"}), cause});361 }362 };363 // We do our best effort here to map the incompatible states.364 switch (data) {365 case "deleted":366 notify(true, subject, "explicit");367 break;368 case "added":369 notify(false, subject, "explicit");370 break;371 case "changed":372 notify(true, subject, "overwrite");373 notify(false, subject, "explicit");374 break;...

Full Screen

Full Screen

http.js

Source:http.js Github

copy

Full Screen

...12const agent = `${remote.getCurrentWebContents().userAgent}`;13function getAgent(extended) {14 return extended ? `${agent} PostyBirb/${remote.app.getVersion()}` : agent;15}16function convertCookie(cookie) {17 const url = `${cookie.secure ? 'https' : 'http'}://${cookie.domain}${cookie.path || ''}`;18 const expirationDate = new Date();19 const details = {20 domain: cookie.domain,21 httpOnly: cookie.httpOnly || false,22 name: cookie.name,23 secure: cookie.secure || false,24 url: url.replace('://.', '://'),25 value: cookie.value,26 expirationDate: expirationDate.setMonth(expirationDate.getMonth() + 4)27 };28 return details;29}30function setCookie(session, cookie) {31 return session.cookies.set(cookie)32 .catch(function(err) {33 if (err) {34 console.warn(err, this);35 }36 }.bind(cookie));37}38function appendFormValue(form, key, value) {39 if (value && value.hasOwnProperty('value') && value.hasOwnProperty('options')) {40 form.append(key, value.value, value.options);41 } else {42 form.append(key, value);43 }44}45exports.get = (url, partitionId, options) => {46 options = options || {};47 options.headers = options.headers || {};48 return new Promise((resolve, reject) => {49 const {50 headers51 } = options;52 const _session = session.fromPartition(`persist:${partitionId}`);53 if (!headers['User-Agent']) headers['User-Agent'] = getAgent(options.extendedAgent);54 if (options.cookies) headers['Cookie'] = options.cookies.map(c => `${c.name}=${c.value}`).join('; ')55 const request = net.request({56 headers,57 redirect: 'follow',58 session: _session,59 url,60 });61 request.end();62 request.on('response', async (response) => {63 const res = {64 body: (response.data || []).filter(d => !!d).map(d => d.toString()).join(),65 headers: response.headers,66 statusCode: response.statusCode,67 statusMessage: response.statusMessage,68 };69 if (options.updateCookies && response.headers['set-cookie']) {70 const cookies = cookieParser.parse(response.headers['set-cookie']);71 for (let i = 0; i < cookies.length; i++) {72 await setCookie(_session, convertCookie(cookies[i]));73 }74 }75 resolve(res);76 });77 request.on('error', (error) => {78 reject(error);79 });80 });81};82exports.post = (url, partitionId, body, options) => {83 options = options || {};84 options.headers = options.headers || {};85 return new Promise((resolve, reject) => {86 const {87 headers88 } = options;89 const _session = session.fromPartition(`persist:${partitionId}`);90 if (!headers['User-Agent']) headers['User-Agent'] = getAgent(options.extendedAgent);91 if (options.cookies) headers['cookie'] = options.cookies.map(c => `${c.name}=${c.value}`).join('; ');92 const request = net.request({93 headers,94 method: options.method || 'POST',95 redirect: 'manual',96 session: _session,97 url,98 });99 request.chunkedEncoding = true;100 request.on('error', (error) => {101 reject(error);102 });103 Object.entries(headers).forEach(([key, value]) => request.setHeader(key, value));104 if (options.json) {105 const data = JSON.stringify(body);106 // request.setHeader('Content-Length', data.length);107 if (!headers['Content-Type']) request.setHeader('Content-Type', 'application/json');108 request.write(Buffer.from(data));109 } else if (options.multipart) {110 const form = new FormData();111 const keys = Object.keys(body);112 for (var i = 0; i < keys.length; i++) {113 const key = keys[i];114 const val = body[key];115 try {116 if (val instanceof Array) {117 for (let i = 0; i < val.length; i++) {118 appendFormValue(form, key, val[i]);119 }120 } else {121 appendFormValue(form, key, val);122 }123 } catch (err) {124 throw new Error(`${url}\nUnable to append form value ${key}=${val}\n${err.message}`);125 }126 }127 request.setHeader('Content-Type', `multipart/form-data; boundary=${form.getBoundary()}`);128 request.setHeader('Content-Length', form.getLengthSync());129 request.write(form.getBuffer());130 } else {131 const encoded = UrlEncoded(body);132 if (!headers['Content-Type']) request.setHeader('Content-Type', 'application/x-www-form-urlencoded');133 request.setHeader('Content-Length', (encoded || '').length);134 request.write(encoded);135 }136 request.end();137 let lastRedirect = '';138 request.on('redirect', (statusCode, method, redirectUrl, responseHeaders) => {139 lastRedirect = redirectUrl;140 request.followRedirect();141 });142 let response;143 request.on('response', (r) => {144 response = r;145 });146 request.on('close', async () => {147 const res = {148 body: (response.data || []).filter(d => !!d).map(d => d.toString()).join(),149 headers: response.headers,150 href: lastRedirect,151 statusCode: response.statusCode,152 statusMessage: response.statusMessage,153 success: response.statusCode <= 330, // assumed success154 };155 if (options.updateCookies && response.headers['set-cookie']) {156 const cookies = cookieParser.parse(response.headers['set-cookie']);157 for (let i = 0; i < cookies.length; i++) {158 await setCookie(_session, convertCookie(cookies[i]));159 }160 }161 resolve(res);162 });163 });164};165exports.browserPost = (url, partition, headers, data) => {166 return new Promise((resolve, reject) => {167 const bw = new BrowserWindow({168 show: false,169 webPreferences: {170 partition: `persist:${partition}`171 }172 });...

Full Screen

Full Screen

cookies.js

Source:cookies.js Github

copy

Full Screen

...53 // if name is key, this is the central element of the cookie, so add as `name`54 // otherwise it is an optional element55 if (key && key === name) {56 result.name = key;57 result.value = convertCookie(val, converter);58 } else {59 result[name] = convertCookie(val, converter);60 }61 }62 return result;63}64// takes a JavaScript cookiestring and parses it for the value given the key65function getValue (key, cookieString, converter = null) {66 let result = createJWPCookie(key, cookieString, converter);67 // if `key` is undefined we want the entire cookie68 return _.isUndefined(key) ? result : result.value;69}70// returns a cookie that expires on 01 Jan 197071// assign the returned cookie to an existing cookie to delete that cookie72function expireCookie (key, options) {73 // override `expires` in `options`, and then make the cookie...

Full Screen

Full Screen

cookie.js

Source:cookie.js Github

copy

Full Screen

...45 // if name is key, this is the central element of the cookie, so add as `name`46 // otherwise it is an optional element47 if (key && key === name) {48 result.name = key;49 result.value = convertCookie(val, converter);50 } else {51 result[name] = convertCookie(val, converter);52 }53 }54 return result;55}56// takes a JavaScript cookiestring and parses it for the value given the key57function getValue (key, cookieString, converter = null) {58 let result = createJWPCookie(key, cookieString, converter);59 // if `key` is undefined we want the entire cookie60 return _.isUndefined(key) ? result : result.value;61}62// returns a cookie that expires on 01 Jan 197063// assign the returned cookie to an existing cookie to delete that cookie64function expireCookie (key, options) {65 // override `expires` in `options`, and then make the cookie...

Full Screen

Full Screen

SendWeiboInformation.js

Source:SendWeiboInformation.js Github

copy

Full Screen

...8 response: '',9 header: {}10 }11 }12 convertCookie(cookies) {13 let tmp = {}14 cookies.split(';').forEach(d => {15 let [key, value] = d.split('=')16 tmp[key.trim()] = value17 })18 return tmp19 }20 onClick = () => {21 const cookie = this.convertCookie(document.cookie)22 const url = window.location.href23 const message = {24 type: 'WEIBO_SCRAPY',25 cookie,26 url27 }28 chrome.runtime.sendMessage(message, (response) => {29 this.setState({30 response: 'response'31 })32 })33 }34 render () {35 return (...

Full Screen

Full Screen

parseCookie.js

Source:parseCookie.js Github

copy

Full Screen

1const trim = (str) => {2 return str.replace(/(^\s*)|(\s*$)/g, '');3}4export const convertCookie = (cookie) => {5 const cookieArr = cookie.split(";");6 let cookieParams = [];7 for (const item of cookieArr) {8 const s = item.split("=");9 cookieParams.push({10 name: trim(s[0]),11 value: s[1],12 path: '/',13 domain: '.weibo.com'14 })15 }16 return cookieParams;...

Full Screen

Full Screen

util.js

Source:util.js Github

copy

Full Screen

1const convertCookie = str => {2 let cookieData = { }3 let kvPairs = str.split(/[,;]/)4 for (let i = 0; i < kvPairs.length; i++) {5 let kv = kvPairs[i].trim()6 if (kv === '') { continue }7 const kvSplit = kv.split('=')8 cookieData[kvSplit[0]] = kvSplit[1]9 };10 return cookieData11}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const XCUITestDriver = require('appium-xcuitest-driver');3const opts = {4};5 .init(opts)6 .then(() => driver.setCookies([7 {name: 'foo', value: 'bar'},8 {name: 'baz', value: 'qux'}9 .then(() => driver.getCookies())10 .then((cookies) => console.log(cookies))11 .fin(() => driver.quit());12[ { name: 'foo', value: 'bar' },13 { name: 'baz', value: 'qux' } ]14const wd = require('wd');15const XCUITestDriver = require('appium-xcuitest-driver');16const opts = {17};18 .init(opts)19 .then(() => driver.setCookies([20 {name: 'foo', value: 'bar'},21 {name: 'baz', value: 'qux'}22 .then(() => driver.getCookies())23 .then((cookies) => console.log(cookies))24 .fin(() => driver.quit());25[ { name: 'foo', value: 'bar' },26 { name: 'baz', value: 'qux' } ]27const wd = require('wd');28const XCUITestDriver = require('appium-xcuitest-driver');

Full Screen

Using AI Code Generation

copy

Full Screen

1var convertCookie = require('appium-xcuitest-driver').convertCookie;2var cookie = {3};4var convertedCookie = convertCookie(cookie);5console.log(convertedCookie);6Your name to display (optional):7Your name to display (optional):8Your name to display (optional):

Full Screen

Using AI Code Generation

copy

Full Screen

1const { convertCookie } = require('appium-xcuitest-driver').utils;2const cookie = {name: 'cookie_name', value: 'cookie_value', domain: 'google.com', path: '/', expiry: 1505958000};3const convertedCookie = convertCookie(cookie);4console.log(convertedCookie);5const { convertCookie } = require('appium-xcuitest-driver').utils;6const cookie = {name: 'cookie_name', value: 'cookie_value', domain: 'google.com', path: '/', expiry: 1505958000};7const convertedCookie = convertCookie(cookie, true);8console.log(convertedCookie);9const { convertCookie } = require('appium-xcuitest-driver').utils;10const cookie = {name: 'cookie_name', value: 'cookie_value', domain: 'google.com', path: '/', expiry: 1505958000};11const convertedCookie = convertCookie(cookie, true, true);12console.log(convertedCookie);

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