How to use getBaseHostname method in Appium

Best JavaScript code snippet using appium

Run Appium automation tests on LambdaTest cloud grid

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

parse.js

Source: parse.js Github

copy
1import path from 'path';
2import yaml from 'yaml-js';
3import { fs, mkdirp, util } from 'appium-support';
4import validate from 'validate.js';
5import Handlebars from 'handlebars';
6import _ from 'lodash';
7import { asyncify } from 'asyncbox';
8import { validator, CLIENT_URL_TYPES } from './validator';
9import url from 'url';
10import log from 'fancy-log';
11import findRoot from 'find-root';
12
13
14// What range of platforms do the driver's support
15const platformRanges = {
16  xcuitest: ['9.3'],
17  uiautomation: ['8.0', '9.3'],
18  espresso: ['?'],
19  uiautomator2: ['?'],
20  uiautomator: ['4.3'],
21  windows: ['10'],
22  mac: ['?'], // TODO
23};
24
25// When was the driver supported in Appium?
26const appiumRanges = {
27  xcuitest: ['1.6.0'],
28  uiautomator2: ['1.6.0'],
29  espresso: ['1.9.0'],
30  windows: ['1.6.0'],
31  mac: ['1.6.4'],
32};
33
34const rootFolder = findRoot(__dirname);
35
36// Create Handlebars helper that shows a version range
37Handlebars.registerHelper('versions', function versionHelper (object, name, driverName) {
38  if (!object) {
39    return 'None';
40  }
41
42  if (!_.isObject(object)) {
43    object = {};
44  }
45
46  let min = object[name ? `${name}_min` : 'min'];
47  let max = object[name ? `${name}_max` : 'max'];
48
49  if (!min) {
50    if (name === 'appium' && _.isArray(appiumRanges[driverName])) {
51      min = appiumRanges[driverName][0];
52    } else if (name === 'platform' && _.isArray(platformRanges[driverName])) {
53      min = platformRanges[driverName][0];
54    }
55  }
56
57  if (!max) {
58    if (name === 'appium' && appiumRanges[driverName]) {
59      max = appiumRanges[driverName][1];
60    } else if (name === 'platform' && platformRanges[driverName]) {
61      max = platformRanges[driverName][1];
62    }
63  }
64
65  if (!min && !max) {
66    return 'All';
67  } else if (!max) {
68    return `${min}+`;
69  } else if (!min) {
70    return `<= ${max}`;
71  }
72
73  return `${min} to ${max}`;
74});
75
76Handlebars.registerHelper('hyphenate', (str) => str.replace('_', '-'));
77Handlebars.registerHelper('uppercase', (str) => str.toUpperCase());
78
79Handlebars.registerHelper('capitalize', function capitalizeDriver (driverName) {
80  switch (driverName.toLowerCase()) {
81    case 'xcuitest':
82      return 'XCUITest';
83    case 'uiautomation':
84      return 'UIAutomation';
85    case 'uiautomator2':
86      return 'UiAutomator2';
87    case 'uiautomator':
88      return 'UiAutomator';
89    case 'espresso':
90      return 'Espresso';
91    default:
92      return driverName.length === 0 ? driverName : driverName[0].toUpperCase() + driverName.substr(1);
93  }
94});
95
96Handlebars.registerHelper('if_eq', function ifEq (a, b, opts) {
97  if (a === b) {
98    return opts.fn(this);
99  } else {
100    return opts.inverse(this);
101  }
102});
103
104function getBaseHostname (fullUrl) {
105  const baseUrl = url.parse(fullUrl);
106  return baseUrl.hostname;
107}
108
109Handlebars.registerHelper('base_url', function baseUrl (fullUrl) {
110  return getBaseHostname(fullUrl);
111});
112
113Handlebars.registerHelper('client_url', function clientUrl (clientUrl) {
114  if (!clientUrl) {
115    return;
116  }
117
118  const createUrlString = function createUrlString (clientUrl, name = getBaseHostname(clientUrl)) {
119    return `[${name}](${clientUrl})`;
120  };
121
122  if (!_.isArray(clientUrl)) {
123    return createUrlString(clientUrl);
124  }
125
126  let urlStrings = [];
127  for (const item of clientUrl) {
128    for (let [key, value] of _.toPairs(item)) {
129      key = key.toLowerCase();
130      const urlStr = CLIENT_URL_TYPES[key] === 'hostname'
131        ? createUrlString(value)
132        : createUrlString(value, CLIENT_URL_TYPES[key]);
133      urlStrings.push(urlStr);
134    }
135  }
136  return urlStrings.join(' ');
137});
138
139async function registerSpecUrlHelper () {
140  const routesFile = await fs.readFile(path.resolve(rootFolder, 'node_modules', 'appium-base-driver', 'lib', 'protocol', 'routes.js'), 'utf8');
141  const routesFileLines = routesFile.split('\n');
142
143  Handlebars.registerHelper('spec_url', function specUrl (specUrl, endpoint) {
144    // return the url if it is not a link to our routes doc
145    if (!specUrl.includes('routes.js')) {
146      return specUrl;
147    }
148    // make sure it is a full url
149    if (specUrl.startsWith('routes.js')) {
150      specUrl = `https://github.com/appium/appium-base-driver/blob/master/lib/protocol/${specUrl}`;
151    }
152
153    // strip off any line numbers
154    specUrl = specUrl.split('#L')[0];
155
156    // the endpoint here is often `session_id` and we need `sessionId`
157    endpoint = endpoint.replace('session_id', 'sessionId');
158    // and `element_id` and we need `elementId`
159    endpoint = endpoint.replace('element_id', 'elementId');
160
161    // find the line number for this endpoint
162    let index;
163    for (const i in routesFileLines) {
164      if (routesFileLines[i].includes(endpoint)) {
165        // line numbers are 1-indexed
166        index = parseInt(i, 10) + 1;
167        break;
168      }
169    }
170    if (_.isUndefined(index)) {
171      throw new Error(`Unable to find entry in 'appium-base-driver#routes' for endpoint '${endpoint}'`);
172    }
173
174    return `${specUrl}#L${index}`;
175  });
176}
177
178async function generateCommands () {
179  await registerSpecUrlHelper();
180
181  const commands = path.resolve(rootFolder, 'commands-yml', 'commands/**/*.yml');
182  log('Traversing YML files', commands);
183  await fs.rimraf(path.resolve(rootFolder, 'docs', 'en', 'commands'));
184
185  // get the template from which the md files will be created
186  const template = Handlebars.compile(await fs.readFile(path.resolve(rootFolder, 'commands-yml', 'template.md'), 'utf8'), {noEscape: true, strict: true});
187
188  let fileCount = 0;
189  for (const filename of await fs.glob(commands)) {
190    const relativeFilename = path.relative(path.resolve(rootFolder, 'commands-yml'), filename);
191    log(`Rendering file: ${filename} ${relativeFilename}`);
192
193    // Translate the YML specs to JSON
194    const inputYML = await fs.readFile(filename, 'utf8');
195    const inputJSON = yaml.load(inputYML);
196    inputJSON.ymlFileName = `/${path.relative(rootFolder, filename)}`;
197    const validationErrors = validate(inputJSON, validator);
198    if (validationErrors) {
199      throw new Error(`Data validation error for ${filename}: ${JSON.stringify(validationErrors)}`);
200    }
201
202    // Pass the inputJS into our Handlebars template
203    const markdown = template(inputJSON);
204
205    // Write the markdown to its right place
206    const ext = path.extname(relativeFilename);
207    const markdownPath = `${relativeFilename.substring(0, relativeFilename.length - ext.length)}.md`;
208    const outfile = path.resolve(rootFolder, 'docs', 'en', markdownPath);
209    log(`    Writing to: ${outfile}`);
210    await mkdirp(path.dirname(outfile));
211    await fs.writeFile(outfile, markdown, 'utf8');
212
213    fileCount++;
214  }
215  log(`Done writing ${fileCount} command documents`);
216}
217
218async function generateCommandIndex () {
219  function getTree (element, path) {
220    let node = {
221      name: element[0],
222    };
223    if (!_.isArray(element[1])) {
224      node.path = `${path}/${element[1]}`;
225    } else {
226      node.path = `${path}/${element[1][0]}`;
227      const name = element[1].shift();
228      node.commands = [];
229      for (let subElement of element[1]) {
230        node.commands.push(getTree(subElement, `${path}/${name}`));
231      }
232    }
233    return node;
234  }
235
236  // parse the toc.js file and get the commands into the form of
237  //   {commands: [{name: '', path: ''}, {name: '', commands: [...]}]}
238  const toc = require(path.resolve(rootFolder, 'docs', 'toc.js'));
239  const commandToc = _.find(toc.en, (value) => value.indexOf('Commands') === 0);
240  const commands = [];
241  for (let el of commandToc[1].slice(1)) {
242    commands.push(getTree(el, '/docs/en/commands'));
243  }
244
245  const commandTemplate = Handlebars.compile(await fs.readFile(path.resolve(rootFolder, 'commands-yml', 'api-template.md'), 'utf8'), {noEscape: true, strict: true});
246
247  async function writeIndex (index, commands, indexPath) {
248    log(`Creating API index '${index}'`);
249    const commandMarkdown = commandTemplate({
250      commands,
251      path: indexPath,
252    });
253    await fs.writeFile(index, commandMarkdown, 'utf8');
254  }
255
256  const apiIndex = path.resolve(rootFolder, 'docs', 'en', 'about-appium', 'api.md');
257  await writeIndex(apiIndex, commands);
258  log(`Done writing main API index`);
259
260  async function writeIndividualIndexes (command) {
261    if (!util.hasValue(command.commands)) {
262      // this is a leaf, so end
263      return;
264    }
265
266    // write this node
267    const relPath = command.path.startsWith(path.sep) ? command.path.substring(1) : command.path;
268    const index = path.resolve(rootFolder, relPath, 'README.md');
269    await writeIndex(index, command.commands, command.path);
270
271    // go through all the sub-commands
272    for (const el of command.commands) {
273      await writeIndividualIndexes(el);
274    }
275  }
276
277  // go through the full tree and generate readme files
278  const index = path.resolve(rootFolder, 'docs', 'en', 'commands', 'README.md');
279  await writeIndex(index, commands);
280  for (const el of commands) {
281    await writeIndividualIndexes(el);
282  }
283}
284
285async function main () {
286  await generateCommands();
287  await generateCommandIndex();
288}
289
290asyncify(main);
291
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Appium on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)