Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added tests for batch-create-wallet, batch-transfer, and event endpoints #450

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions server/handlers/eventHandler.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
const request = require('supertest');
const express = require('express');
const sinon = require('sinon');
const chai = require('chai');
const sinonChai = require('sinon-chai');
const uuid = require('uuid');
const eventRouter = require('../routes/eventRouter');
const { errorHandler } = require('../utils/utils');

chai.use(sinonChai);
const { expect } = chai;
const ApiKeyService = require('../services/ApiKeyService');
const JWTService = require('../services/JWTService');
const EventService = require('../services/EventService');
const EventEnums = require('../utils/event-enum');


describe ('eventRouter', () => {
let app;
const authenticatedWalletId = uuid.v4();

beforeEach(() => {
sinon.stub(ApiKeyService.prototype, 'check');
sinon.stub(JWTService, 'verify').returns({
id: authenticatedWalletId,
});
app = express();
app.use(express.urlencoded({extended: false}));
app.use(express.json());
app.use(eventRouter);
app.use(errorHandler);
})

afterEach(() => {
sinon.restore();
});

describe('GET /events', () => {
it('missing parameters -- no limit parameter', async() => {
const res = await request(app).get('/events');
expect(res).property('statusCode').eq(422);
expect(res.body.message).match(/limit.*required/);
})

it('wrong parameters -- wrong date format', async() => {
const res = await request(app).get('/events?limit=10&since=test');
expect(res).property('statusCode').eq(422);
expect(res.body.message).match(/since.*format/);
})

it('get all events sucessfully', async() => {
const mockEvents = [
{
id: 'event1Id',
wallet_id: 'walletId',
type: EventEnums.AUTH.login,
payload: {}
},

{
id: 'event2Id',
wallet_id: 'walletId',
type: EventEnums.TRANSFER.transfer_completed,
payload: {}
}
];

const getAllEventsStub = sinon
.stub(EventService.prototype, 'getAllEvents')
.resolves(mockEvents);

const res = await request(app).get(
'/events?limit=10&since=2021-10-05T14:48:00.000Z&wallet=wallet1');

expect(res).property('statusCode').eql(200);
expect(res.body.events).lengthOf(2);
expect(res.body.events).eql(mockEvents);
expect(getAllEventsStub.calledOnceWithExactly({
wallet: 'wallet1',
limit: '10',
since: '2021-10-05T14:48:00.000Z',
walletLoginId: authenticatedWalletId
})).eql(true);

})
})
})
125 changes: 125 additions & 0 deletions server/handlers/walletHandler.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,4 +177,129 @@ describe('walletRouter', () => {
expect(res.body.message).match(/wallet.*required/);
});
});

describe('post /wallet/batch-create-wallet', () => {

const mockCsvContent = `wallet_name,token_transfer_amount_overwrite,extra_wallet_data_about,extra_wallet_data_cover_url,extra_wallet_data_logo_url
wallet1,5,about wallet1,,
wallet2,,about wallet2,wallet2 cover url,wallet2 logo url`;
const mock_file_path = "mockfile.csv";
const mock_sender_wallet = "wallet";
const token_transfer_amount_default = 10;

it('successfully creates wallets', async () => {

const mockCsvJson = [
{ wallet_name: "wallet1",
token_transfer_amount_overwrite: 5,
extra_wallet_data_about: "about wallet1",
extra_wallet_data_cover_url: '',
extra_wallet_data_logo_url: ''
},
{ wallet_name: "wallet2",
token_transfer_amount_overwrite: '',
extra_wallet_data_about: "about wallet2",
extra_wallet_data_cover_url: "wallet2 cover url",
extra_wallet_data_logo_url: "wallet2 logo url"
},
];

const walletBatchCreateStub = sinon
.stub(WalletService.prototype, 'batchCreateWallet')
.resolves({
wallets_created: 2,
wallets_already_exists: [],
wallet_other_failure_count: 0,
extra_wallet_information_saved: 0,
extra_wallet_information_not_saved: [],
});

const res = await request(app)
.post('/wallets/batch-create-wallet')
.field('sender_wallet', mock_sender_wallet)
.field('token_transfer_amount_default', token_transfer_amount_default)
.attach('csv', Buffer.from(mockCsvContent), mock_file_path);

expect(res).property('statusCode').eq(201);
expect(walletBatchCreateStub.calledOnce).eql(true);
expect(walletBatchCreateStub.args[0].slice(0,-1)).eql([
mock_sender_wallet,
token_transfer_amount_default,
authenticatedWalletId,
mockCsvJson
]);


})

it('missing parameter', async () => {

const res = await request(app)
.post('/wallets/batch-create-wallet')
.field('token_transfer_amount_default', token_transfer_amount_default)
.attach('csv', Buffer.from(mockCsvContent), mock_file_path);

expect(res).property('statusCode').eq(422);
expect(res.body.message).match(/required/);
})
})

describe('post /wallet/batch-transfer', () => {

const mockCsvContent = `wallet_name,token_transfer_amount_overwrite
wallet1,5
wallet2,
wallet3,7`;
const mock_file_path = "mockfile.csv";
const mock_sender_wallet = "wallet";
const token_transfer_amount_default = 10;


it('successfully transfer all tokens', async () => {

const mockCsvJson = [
{ wallet_name: "wallet1",
token_transfer_amount_overwrite: 5
},
{ wallet_name: "wallet2",
token_transfer_amount_overwrite: ''
},
{ wallet_name: "wallet3",
token_transfer_amount_overwrite: 7
}
];

const walletBatchTransferWalletStub = sinon
.stub(WalletService.prototype, 'batchTransferWallet')
.resolves();

const res = await request(app)
.post('/wallets/batch-transfer')
.field('sender_wallet', mock_sender_wallet)
.field('token_transfer_amount_default', token_transfer_amount_default)
.attach('csv', Buffer.from(mockCsvContent), mock_file_path);

expect(res).property('statusCode').eq(200);
expect(walletBatchTransferWalletStub.calledOnce).eql(true);
expect(walletBatchTransferWalletStub.args[0].slice(0,-1)).eql([
mock_sender_wallet,
token_transfer_amount_default,
authenticatedWalletId,
mockCsvJson
]);


})

it('missing parameter', async () => {

const res = await request(app)
.post('/wallets/batch-transfer')
.field('token_transfer_amount_default', token_transfer_amount_default)
.attach('csv', Buffer.from(mockCsvContent), mock_file_path);

expect(res).property('statusCode').eq(422);
expect(res.body.message).match(/required/);
})
})
});
2 changes: 1 addition & 1 deletion server/handlers/walletHandler/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ const walletBatchCreate = async (req, res) => {
const { sender_wallet, token_transfer_amount_default } = validatedBody;
const { wallet_id } = req;
const walletService = new WalletService();

const result = await walletService.batchCreateWallet(
sender_wallet,
token_transfer_amount_default,
Expand Down
2 changes: 1 addition & 1 deletion server/handlers/walletHandler/schemas.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ const csvValidationSchema = Joi.array()
Joi.string().valid(''),
],
extra_wallet_data_about: Joi.string(),
}),
}).options({ allowUnknown: true }),
)
.unique('wallet_name')
.min(1)
Expand Down
102 changes: 102 additions & 0 deletions server/models/Event.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
const sinon = require('sinon');
const chai = require('chai');
const sinonChai = require('sinon-chai');
const uuid = require('uuid');
const Event = require('./Event');
const Session = require('../infra/database/Session');
const EventRepository = require('../repositories/EventRepository');
const EventEnums = require('../utils/event-enum');

chai.use(sinonChai);
const { expect } = chai;

describe('Event Model', () => {
let eventModel;
let eventRepositoryStub;

beforeEach(() => {
const session = new Session();
eventModel = new Event(session);
eventRepositoryStub = sinon.stub(EventRepository.prototype);
});

afterEach(() => {
sinon.restore();
});

describe('getAllEvents function', () => {
const walletId = uuid.v4();
const filter = {
and: [],
};
filter.and.push({ wallet_id: walletId });

const mockEvents = [
{
id: 'event1Id',
wallet_id: 'walletId',
type: EventEnums.AUTH.login,
payload: {}
},

{
id: 'event2Id',
wallet_id: 'walletId',
type: EventEnums.TRANSFER.transfer_completed,
payload: {}
}
];

it('should get events', async () => {

eventRepositoryStub.getAllEvents.resolves(mockEvents);
const result = await eventModel.getAllEvents(walletId, 10);

expect(result).eql(mockEvents.map(event => ({ ...event})));
expect(eventRepositoryStub.getAllEvents
.calledOnceWithExactly(filter, 10)).eql(true);

});

it('should get events -- since', async () => {

const mockSince = '2021-10-05T15:00:00.000Z';
const filterCopy = JSON.parse(JSON.stringify(filter));
filterCopy.and.push({ after: { 'wallet_event.created_at': mockSince } });

eventRepositoryStub.getAllEvents.resolves(mockEvents);
const result = await eventModel.getAllEvents(walletId, 10, mockSince);

expect(result).eql(mockEvents.map(event => ({ ...event})));
expect(eventRepositoryStub.getAllEvents
.calledOnceWithExactly(filterCopy, 10)).eql(true);

});
});

it('should log event', async () => {
const walletId = uuid.v4();
const mockEvent = {
id: 'eventId',
wallet_id: 'walletId',
type: EventEnums.AUTH.login,
payload: {}
};

eventRepositoryStub.create.resolves(mockEvent)

const result = await eventModel.logEvent({
wallet_id: walletId,
type: EventEnums.TRANSFER.transfer_completed,
payload: {}
});

expect(result).eql(mockEvent);
expect(eventRepositoryStub.create.calledOnceWithExactly({
wallet_id: walletId,
type: EventEnums.TRANSFER.transfer_completed,
payload: {}
})).eql(true);

})
});
35 changes: 35 additions & 0 deletions server/repositories/EventRepository.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const { expect } = require('chai');
const mockKnex = require('mock-knex');
const EventRepository = require('./EventRepository');
const knex = require('../infra/database/knex');

const tracker = mockKnex.getTracker();
const Session = require('../infra/database/Session');


describe('EventRepository', () => {
let eventRepository;

beforeEach(() => {
mockKnex.mock(knex);
tracker.install();
eventRepository = new EventRepository(new Session());
});

afterEach(() => {
tracker.uninstall();
mockKnex.unmock(knex);
});

it('getAllEvents', async () => {
tracker.on('query', (query) => {
expect(query.sql).match(
/select.*wallet_event.*/,
);
query.response([{}]);
});
await eventRepository.getByFilter({});
});


});
Loading
Loading