Best JavaScript code snippet using devicefarmer-stf
tokens.test.ts
Source:tokens.test.ts
1/*2 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one3 * or more contributor license agreements. Licensed under the Elastic License;4 * you may not use this file except in compliance with the Elastic License.5 */6import { errors } from 'elasticsearch';7import { elasticsearchServiceMock, loggingSystemMock } from '../../../../../src/core/server/mocks';8import { mockAuthenticatedUser } from '../../common/model/authenticated_user.mock';9import {10 ILegacyClusterClient,11 LegacyElasticsearchErrorHelpers,12} from '../../../../../src/core/server';13import { Tokens } from './tokens';14describe('Tokens', () => {15 let tokens: Tokens;16 let mockClusterClient: jest.Mocked<ILegacyClusterClient>;17 beforeEach(() => {18 mockClusterClient = elasticsearchServiceMock.createLegacyClusterClient();19 const tokensOptions = {20 client: mockClusterClient,21 logger: loggingSystemMock.create().get(),22 };23 tokens = new Tokens(tokensOptions);24 });25 it('isAccessTokenExpiredError() returns `true` only if token expired', () => {26 const nonExpirationErrors = [27 {},28 new Error(),29 new errors.InternalServerError(),30 new errors.Forbidden(),31 { statusCode: 500, body: { error: { reason: 'some unknown reason' } } },32 ];33 for (const error of nonExpirationErrors) {34 expect(Tokens.isAccessTokenExpiredError(error)).toBe(false);35 }36 const expirationErrors = [37 { statusCode: 401 },38 LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()),39 new errors.AuthenticationException(),40 ];41 for (const error of expirationErrors) {42 expect(Tokens.isAccessTokenExpiredError(error)).toBe(true);43 }44 });45 describe('refresh()', () => {46 const refreshToken = 'some-refresh-token';47 it('throws if API call fails with unknown reason', async () => {48 const refreshFailureReason = new errors.ServiceUnavailable('Server is not available');49 mockClusterClient.callAsInternalUser.mockRejectedValue(refreshFailureReason);50 await expect(tokens.refresh(refreshToken)).rejects.toBe(refreshFailureReason);51 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(1);52 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith('shield.getAccessToken', {53 body: { grant_type: 'refresh_token', refresh_token: refreshToken },54 });55 });56 it('returns `null` if refresh token is not valid', async () => {57 const refreshFailureReason = new errors.BadRequest();58 mockClusterClient.callAsInternalUser.mockRejectedValue(refreshFailureReason);59 await expect(tokens.refresh(refreshToken)).resolves.toBe(null);60 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(1);61 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith('shield.getAccessToken', {62 body: { grant_type: 'refresh_token', refresh_token: refreshToken },63 });64 });65 it('returns token pair if refresh API call succeeds', async () => {66 const authenticationInfo = mockAuthenticatedUser();67 const tokenPair = { accessToken: 'access-token', refreshToken: 'refresh-token' };68 mockClusterClient.callAsInternalUser.mockResolvedValue({69 access_token: tokenPair.accessToken,70 refresh_token: tokenPair.refreshToken,71 authentication: authenticationInfo,72 });73 await expect(tokens.refresh(refreshToken)).resolves.toEqual({74 authenticationInfo,75 ...tokenPair,76 });77 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(1);78 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith('shield.getAccessToken', {79 body: { grant_type: 'refresh_token', refresh_token: refreshToken },80 });81 });82 });83 describe('invalidate()', () => {84 for (const [description, failureReason] of [85 ['an unknown error', new Error('failed to delete token')],86 ['a 404 error without body', { statusCode: 404 }],87 ] as Array<[string, object]>) {88 it(`throws if call to delete access token responds with ${description}`, async () => {89 const tokenPair = { accessToken: 'foo', refreshToken: 'bar' };90 mockClusterClient.callAsInternalUser.mockImplementation((methodName, args: any) => {91 if (args && args.body && args.body.token) {92 return Promise.reject(failureReason);93 }94 return Promise.resolve({ invalidated_tokens: 1 });95 });96 await expect(tokens.invalidate(tokenPair)).rejects.toBe(failureReason);97 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(2);98 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith(99 'shield.deleteAccessToken',100 {101 body: { token: tokenPair.accessToken },102 }103 );104 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith(105 'shield.deleteAccessToken',106 {107 body: { refresh_token: tokenPair.refreshToken },108 }109 );110 });111 it(`throws if call to delete refresh token responds with ${description}`, async () => {112 const tokenPair = { accessToken: 'foo', refreshToken: 'bar' };113 mockClusterClient.callAsInternalUser.mockImplementation((methodName, args: any) => {114 if (args && args.body && args.body.refresh_token) {115 return Promise.reject(failureReason);116 }117 return Promise.resolve({ invalidated_tokens: 1 });118 });119 await expect(tokens.invalidate(tokenPair)).rejects.toBe(failureReason);120 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(2);121 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith(122 'shield.deleteAccessToken',123 {124 body: { token: tokenPair.accessToken },125 }126 );127 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith(128 'shield.deleteAccessToken',129 {130 body: { refresh_token: tokenPair.refreshToken },131 }132 );133 });134 }135 it('invalidates all provided tokens', async () => {136 const tokenPair = { accessToken: 'foo', refreshToken: 'bar' };137 mockClusterClient.callAsInternalUser.mockResolvedValue({ invalidated_tokens: 1 });138 await expect(tokens.invalidate(tokenPair)).resolves.toBe(undefined);139 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(2);140 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith(141 'shield.deleteAccessToken',142 { body: { token: tokenPair.accessToken } }143 );144 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith(145 'shield.deleteAccessToken',146 { body: { refresh_token: tokenPair.refreshToken } }147 );148 });149 it('invalidates only access token if only access token is provided', async () => {150 const tokenPair = { accessToken: 'foo' };151 mockClusterClient.callAsInternalUser.mockResolvedValue({ invalidated_tokens: 1 });152 await expect(tokens.invalidate(tokenPair)).resolves.toBe(undefined);153 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(1);154 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith(155 'shield.deleteAccessToken',156 { body: { token: tokenPair.accessToken } }157 );158 });159 it('invalidates only refresh token if only refresh token is provided', async () => {160 const tokenPair = { refreshToken: 'foo' };161 mockClusterClient.callAsInternalUser.mockResolvedValue({ invalidated_tokens: 1 });162 await expect(tokens.invalidate(tokenPair)).resolves.toBe(undefined);163 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(1);164 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith(165 'shield.deleteAccessToken',166 { body: { refresh_token: tokenPair.refreshToken } }167 );168 });169 for (const [description, response] of [170 ['none of the tokens were invalidated', Promise.resolve({ invalidated_tokens: 0 })],171 [172 '404 error is returned',173 Promise.reject({ statusCode: 404, body: { invalidated_tokens: 0 } }),174 ],175 ] as Array<[string, Promise<any>]>) {176 it(`does not fail if ${description}`, async () => {177 const tokenPair = { accessToken: 'foo', refreshToken: 'bar' };178 mockClusterClient.callAsInternalUser.mockImplementation(() => response);179 await expect(tokens.invalidate(tokenPair)).resolves.toBe(undefined);180 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(2);181 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith(182 'shield.deleteAccessToken',183 {184 body: { token: tokenPair.accessToken },185 }186 );187 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith(188 'shield.deleteAccessToken',189 {190 body: { refresh_token: tokenPair.refreshToken },191 }192 );193 });194 }195 it('does not fail if more than one token per access or refresh token were invalidated', async () => {196 const tokenPair = { accessToken: 'foo', refreshToken: 'bar' };197 mockClusterClient.callAsInternalUser.mockResolvedValue({ invalidated_tokens: 5 });198 await expect(tokens.invalidate(tokenPair)).resolves.toBe(undefined);199 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(2);200 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith(201 'shield.deleteAccessToken',202 { body: { token: tokenPair.accessToken } }203 );204 expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith(205 'shield.deleteAccessToken',206 { body: { refresh_token: tokenPair.refreshToken } }207 );208 });209 });...
Using AI Code Generation
1var client = require('devicefarmer-stf-client');2client.deleteAccessToken('yourAccessToken');3var client = require('devicefarmer-stf-client');4client.getDevices(function(error, response, body) {5 if (!error && response.statusCode == 200) {6 console.log(body);7 }8});9var client = require('devicefarmer-stf-client');10client.getDevices(function(error, response, body) {11 if (!error && response.statusCode == 200) {12 console.log(body);13 }14});15var client = require('devicefarmer-stf-client');16client.getDevice('yourDeviceId', function(error, response, body) {17 if (!error && response.statusCode == 200) {18 console.log(body);19 }20});21var client = require('devicefarmer-stf-client');22client.getDevice('yourDeviceId', function(error, response, body) {23 if (!error && response.statusCode == 200) {24 console.log(body);25 }26});27var client = require('devicefarmer-stf-client');28client.getDevice('yourDeviceId', function(error, response, body) {29 if (!error && response.statusCode == 200) {30 console.log(body);31 }32});33var client = require('devicefarmer-stf-client');34client.getDevice('yourDeviceId', function(error, response, body) {35 if (!error && response.statusCode == 200) {36 console.log(body);37 }38});39var client = require('devicefarmer-stf-client');40client.getDevice('yourDeviceId', function(error, response, body) {41 if (!error && response.statusCode == 200) {42 console.log(body);43 }44});
Using AI Code Generation
1var stf = require('devicefarmer-stf');2client.deleteAccessToken('12345', function(err, res) {3 if (err) {4 console.log(err);5 } else {6 console.log(res);7 }8});9var stf = require('devicefarmer-stf');10client.getDevices(function(err, res) {11 if (err) {12 console.log(err);13 } else {14 console.log(res);15 }16});17var stf = require('devicefarmer-stf');18client.getDevices(function(err, res) {19 if (err) {20 console.log(err);21 } else {22 console.log(res);23 }24});25var stf = require('devicefarmer-stf');26client.getDevices(function(err, res) {27 if (err) {28 console.log(err);29 } else {30 console.log(res);31 }32});33var stf = require('devicefarmer-stf');34client.getDevices(function(err, res) {35 if (err) {36 console.log(err);37 } else {38 console.log(res);39 }40});41var stf = require('devicefarmer-stf');42client.getDevices(function(err, res) {43 if (err) {44 console.log(err);45 } else {46 console.log(res);47 }48});49var stf = require('devicefarmer-stf');
Using AI Code Generation
1var DeviceFarmer = require('devicefarmer-stf-client');2var deviceFarmer = new DeviceFarmer();3deviceFarmer.deleteAccessToken("access_token", function(error, response) {4 if (error) {5 console.log(error);6 } else {7 console.log(response);8 }9});
Using AI Code Generation
1var stf = require('devicefarmer-stf-client');2client.deleteAccessToken('xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxx').then(function(token) {3 console.log(token);4}).catch(function(err) {5 console.log(err);6});7deleteAccessToken(accessToken, callback)8var stf = require('devicefarmer-stf-client');9client.deleteAccessToken('xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxx').then(function(token) {10 console.log(token);11}).catch(function(err) {12 console.log(err);13});14deleteDevice(deviceId, callback)15var stf = require('devicefarmer-stf-client');16client.deleteDevice('xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxx').then(function(device) {17 console.log(device);18}).catch(function(err) {19 console.log(err);20});21deleteUser(userId, callback)
Using AI Code Generation
1var devicefarmer = require('devicefarmer-stf-client');2var client = devicefarmer.createClient({3});4client.deleteAccessToken('your token', function (err, result) {5 if (err) {6 console.log(err);7 }8 else {9 console.log(result);10 }11});12{ success: true }13var devicefarmer = require('devicefarmer-stf-client');14var client = devicefarmer.createClient({15});16client.deleteUser('username', function (err, result) {17 if (err) {18 console.log(err);19 }20 else {21 console.log(result);22 }23});24{ success: true }25var devicefarmer = require('devicefarmer-stf-client');26var client = devicefarmer.createClient({27});28client.deleteDevice('serial number', function (err, result) {29 if (err) {30 console.log(err);31 }32 else {33 console.log(result);34 }35});36{ success: true }37var devicefarmer = require('devicefarmer-stf-client');38var client = devicefarmer.createClient({39});40client.deleteGroup('group name', function (err, result) {41 if (err) {42 console.log(err);43 }44 else {45 console.log(result);46 }47});48{ success: true }
Using AI Code Generation
1var stf = require('devicefarmer-stf');2var util = require('util');3var config = {4};5var api = stf.connect(config);6var accessToken = 'abc123';7api.deleteAccessToken(accessToken).then(function (result) {8 console.log('Result: ', util.inspect(result, { depth: null }));9}).catch(function (err) {10 console.error('Error: ', err);11});12var stf = require('devicefarmer-stf');13var util = require('util');14var config = {15};16var api = stf.connect(config);17var serial = 'abc123';18api.deleteDevice(serial).then(function (result) {19 console.log('Result: ', util.inspect(result, { depth: null }));20}).catch(function (err) {21 console.error('Error: ', err);22});23var stf = require('devicefarmer-stf');24var util = require('util');25var config = {26};27var api = stf.connect(config);28var groupName = 'abc123';29api.deleteGroup(groupName).then(function (result) {30 console.log('Result: ', util.inspect(result, { depth: null }));31}).catch(function (err) {32 console.error('Error: ', err);33});34var stf = require('devicefarmer-stf');35var util = require('util');36var config = {37};38var api = stf.connect(config);39var keyName = 'abc123';40api.deleteKey(keyName).then(function (result) {41 console.log('Result: ', util.inspect(result, { depth: null }));42}).catch(function (err) {43 console.error('Error: ', err);44});45var stf = require('devicefarmer-stf');46var util = require('util');47var config = {
Using AI Code Generation
1var stf = require('devicefarmer-stf');2stf.deleteAccessToken('your token', function(err, res) {3 console.log(err, res);4});5stf.deleteAccessToken(token, callback)6var stf = require('devicefarmer-stf');7stf.deleteAccessToken('your token', function(err, res) {8 console.log(err, res);9});10{11}12stf.getDevices(callback)13var stf = require('devicefarmer-stf');14stf.getDevices(function(err, res) {15 console.log(err, res);16});17stf.getDevices(callback)18var stf = require('devicefarmer-stf');19stf.getDevices(function(err, res) {20 console.log(err, res);21});22{23 "devices": [{24 "provider": {
Using AI Code Generation
1const { Client } = require('devicefarmer-stf-client')2const client = new Client()3client.deleteAccessToken('token')4.then(() => {5console.log('Token Deleted')6})7.catch((err) => {8console.log('Error:', err)9})10const { Client } = require('devicefarmer-stf-client')11const client = new Client()12client.deleteAccessToken('token')13.then(() => {14console.log('Token Deleted')15})16.catch((err) => {17console.log('Error:', err)18})19const { Client } = require('devicefarmer-stf-client')20const client = new Client()21client.deleteAccessToken('token')22.then(() => {23console.log('Token Deleted')24})25.catch((err) => {26console.log('Error:', err)27})28const { Client } = require('devicefarmer-stf-client')29const client = new Client()30client.deleteAccessToken('token')31.then(() => {32console.log('Token Deleted')33})34.catch((err) => {35console.log('Error:', err)36})37const { Client } = require('devicefarmer-stf-client')38const client = new Client()39client.deleteAccessToken('token')40.then(() => {41console.log('Token Deleted')42})43.catch((err) => {44console.log('Error:', err)45})46const { Client } = require('devicefarmer-stf-client')47const client = new Client()48client.deleteAccessToken('token')49.then(() => {50console.log('Token Deleted')51})52.catch((err) => {53console.log('Error:', err)54})55const { Client } = require('devicefarmer-stf-client')56const client = new Client()57client.deleteAccessToken('token')58.then(() => {59console.log('Token Deleted')60})61.catch((err) => {62console.log('Error:', err)63})
Using AI Code Generation
1var stf = require('devicefarmer-stf-client');2var device = client.getDevice('deviceID');3device.deleteAccessToken('accessTokenID');4var stf = require('devicefarmer-stf-client');5var device = client.getDevice('deviceID');6device.deleteAccessToken('accessTokenID');7var stf = require('devicefarmer-stf-client');8var device = client.getDevice('deviceID');9device.deleteAccessToken('accessTokenID');10var stf = require('devicefarmer-stf-client');11var device = client.getDevice('deviceID');12device.deleteAccessToken('accessTokenID');13var stf = require('devicefarmer-stf-client');14var device = client.getDevice('deviceID');15device.deleteAccessToken('accessTokenID');16var stf = require('devicefarmer-stf-client');17var device = client.getDevice('deviceID');18device.deleteAccessToken('accessTokenID');19var stf = require('devicefarmer-stf-client');20var device = client.getDevice('deviceID');21device.deleteAccessToken('accessTokenID');22var stf = require('devicefarmer-stf-client');23var device = client.getDevice('deviceID');24device.deleteAccessToken('
Using AI Code Generation
1var stf = require('devicefarmer-stf-client');2client.deleteAccessToken('user', 'token', function(err, res) {3 if (err) {4 console.log(err);5 } else {6 console.log(res);7 }8});9var stf = require('devicefarmer-stf-client');10client.getAccessToken('user', function(err, res) {11 if (err) {12 console.log(err);13 } else {14 console.log(res);15 }16});17var stf = require('devicefarmer-stf-client');18client.getDevices('user', function(err, res) {19 if (err) {20 console.log(err);21 } else {22 console.log(res);23 }24});25var stf = require('devicefarmer-stf-client');26client.getDevicesForUser('user', function(err, res) {27 if (err) {28 console.log(err);29 } else {30 console.log(res);31 }32});33var stf = require('devicefarmer-stf-client');34client.getDevicesForUser('user', function(err, res) {35 if (err) {36 console.log(err);37 } else {38 console.log(res);39 }40});41var stf = require('devicefarmer-stf-client');
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!