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

Issue 579 fix unit testing #593

Merged
merged 10 commits into from
Oct 18, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
20 changes: 10 additions & 10 deletions bot/validations.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const {
isIso4217,
isDisputeSolver,
removeLightningPrefix,
isOrderCreator,
} = require('../util');
const { existLightningAddress } = require('../lnurl/lnurl-pay');
const { logger } = require('../logger');
Expand Down Expand Up @@ -82,6 +83,7 @@ const validateAdmin = async (ctx, id) => {

const isSolver = isDisputeSolver(community, user);

// TODO this validation does not return anything
if (!user.admin && !isSolver)
return await messages.notAuthorized(ctx, tgUserId);

Expand Down Expand Up @@ -169,6 +171,7 @@ const validateSellOrder = async ctx => {
return false;
}

// TODO, this validation could be amount > 0?
if (amount !== 0 && amount < process.env.MIN_PAYMENT_AMT) {
await messages.mustBeGreatherEqThan(
ctx,
Expand Down Expand Up @@ -319,7 +322,9 @@ const validateInvoice = async (ctx, lnInvoice) => {
return false;
}

if (new Date(invoice.expires_at) < latestDate) {
// This is a bug discovered by the test, new Date(invoice.expires_at) was an Object
// and latestDate is a string
if (new Date(invoice.expires_at).toISOString() < latestDate) {
await messages.minimunExpirationTimeInvoiceMessage(ctx);
return false;
}
Expand Down Expand Up @@ -361,7 +366,9 @@ const isValidInvoice = async (ctx, lnInvoice) => {
};
}

if (new Date(invoice.expires_at) < latestDate) {
// This is a bug discovered by the test, new Date(invoice.expires_at) was an Object
// and latestDate is a string
if (new Date(invoice.expires_at).toISOString() < latestDate) {
await messages.invoiceExpiryTooShortMessage(ctx);
return {
success: false,
Expand Down Expand Up @@ -401,14 +408,7 @@ const isValidInvoice = async (ctx, lnInvoice) => {
}
};

const isOrderCreator = (user, order) => {
try {
return user._id == order.creator_id;
} catch (error) {
logger.error(error);
return false;
}
};


const validateTakeSellOrder = async (ctx, bot, user, order) => {
try {
Expand Down
1,050 changes: 514 additions & 536 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"lint": "eslint .",
"format": "prettier --write '**/*.js'",
"pretest": "npx tsc",
"test": "export NODE_ENV=test && mocha --exit 'tests/**/*.js'"
"test": "export NODE_ENV=test && mocha --exit tests/**/*.spec.js"
},
"license": "MIT",
"dependencies": {
Expand Down
180 changes: 180 additions & 0 deletions tests/bot/bot.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
const path = require('path');
const fs = require('fs');
const sinon = require('sinon');
const { expect } = require('chai');
const { initialize } = require('../../bot');
const { User, Order } = require('../../models');
const { getCurrenciesWithPrice } = require('../../util');
const { mockUpdatesResponseForCurrencies } = require('./mocks/currenciesResponse');
const { mockUpdatesResponseForLanguages } = require('./mocks/languagesResponse');

describe('Telegram bot', () => {
const token = '123456';
let server;
let sandbox;
let order, user;

beforeEach(() => {
user = {
lang: 'ESP',
trades_completed: 7,
admin: false,
banned: false,
disputes: 0,
_id: '61006f0e85ad4f96cde94141',
balance: 0,
tg_id: '1',
username: 'negrunch',
created_at: '2021-07-27T20:39:42.403Z',
};
order = {
buyer_dispute: false,
seller_dispute: false,
buyer_cooperativecancel: false,
seller_cooperativecancel: false,
_id: '612d451148df8353e387eeff',
description:
'Vendiendo 111 sats\n' +
'Por ves 111\n' +
'Pago por Pagomovil\n' +
'Tiene 7 operaciones exitosas',
amount: 111,
fee: 0.111,
creator_id: '61006f0e85ad4f96cde94141',
seller_id: '61006f0e85ad4f96cde94141',
type: 'sell',
status: 'PENDING',
fiat_amount: 111,
fiat_code: 'ves',
payment_method: 'Pagomovil',
tg_chat_id: '1',
tg_order_message: '1',
created_at: '2021-08-30T20:52:33.870Z',
};
sandbox = sinon.createSandbox();
// Mock process.env
sandbox.stub(process, 'env').value({
CHANNEL: '@testChannel',
MIN_PAYMENT_AMT: 100,
NODE_ENV: 'test',
INVOICE_EXPIRATION_WINDOW: 3600000,
LND_GRPC_HOST: '127.0.0.1:10005',
});

// Mock TelegramServer
server = {
getClient: sandbox.stub().returns({
makeCommand: sandbox.stub().returns({}),
sendCommand: sandbox.stub().resolves({ ok: true }),
getUpdates: sandbox.stub().resolves({
ok: true,
result: [{
update_id: 1,
message: {
message_id: 1,
from: {
id: 1,
is_bot: false,
first_name: 'Test',
username: 'testuser',
language_code: 'en',
},
chat: {
id: 1,
first_name: 'Test',
username: 'testuser',
type: 'private',
},
date: 1678888888,
text: '/start',
entities: [{
offset: 0,
length: 6,
type: 'bot_command',
}],
},
}],
}),
sendMessage: sandbox.stub().resolves({ ok: true }),
}),
ApiURL: 'http://localhost:9001',
};

// Mock mongo connection and models
sandbox.stub(User, 'findOne').resolves(user);
sandbox.stub(Order, 'findOne').resolves(null);
sandbox.stub(Order.prototype, 'save').resolves(order);

// Initialize the bot
initialize(token, { telegram: { apiRoot: server.ApiURL } });
});

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

it('should start', async () => {
const client = server.getClient(token, { timeout: 5000 });
const command = client.makeCommand('/start');
const res = await client.sendCommand(command);
expect(res.ok).to.be.equal(true);
const updates = await client.getUpdates();
expect(updates.ok).to.be.equal(true);
expect(updates.result.length).to.be.equal(1);
});

it('should return /sell help', async () => {
const client = server.getClient(token, { timeout: 5000 });
const command = client.makeCommand('/sell help');
const res = await client.sendCommand(command);
expect(res.ok).to.be.equal(true);
});

it('should create a /sell', async () => {
const client = server.getClient(token, { timeout: 5000 });
const command = client.makeCommand('/sell 100 1 ves Pagomovil');
grunch marked this conversation as resolved.
Show resolved Hide resolved
const res = await client.sendCommand(command);
expect(res.ok).to.be.equal(true);
});

it('should return /buy help', async () => {
const client = server.getClient(token, { timeout: 5000 });
const command = client.makeCommand('/buy help');
const res = await client.sendCommand(command);
expect(res.ok).to.be.equal(true);
});

it('should return the list of supported currencies', async () => {
const client = server.getClient(token, { timeout: 5000 });
const command = client.makeCommand('/listcurrencies');
client.getUpdates.onCall(0).resolves(mockUpdatesResponseForCurrencies);

const res = await client.sendCommand(command);
expect(res.ok).to.be.equal(true);
const updates = await client.getUpdates();
expect(updates.ok).to.be.equal(true);
expect(
(updates.result[0].message.text.match(/\n/g) || []).length - 1
).to.be.equal(getCurrenciesWithPrice().length);
});

it('should return flags of langs supported', async () => {
const client = server.getClient(token, { timeout: 5000 });
const command = client.makeCommand('/setlang');
client.getUpdates.onCall(0).resolves(mockUpdatesResponseForLanguages);

const res = await client.sendCommand(command);
expect(res.ok).to.be.equal(true);
const updates = await client.getUpdates();
expect(updates.ok).to.be.equal(true);
let flags = 0;
updates.result[0].message.reply_markup.inline_keyboard.forEach(flag => {
flags += flag.length;
});
let langs = 0;
fs.readdirSync(path.join(__dirname, '../../locales')).forEach(file => {
langs++;
});
expect(flags).to.be.equal(langs);
});
});
117 changes: 117 additions & 0 deletions tests/bot/mocks/currenciesResponse.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
const mockUpdatesResponseForCurrencies = {
ok: true,
result: [
{
time: 1726511559928,
botToken: '123456',
message: {
chat_id: 1,
text: 'Code | Name |\n' +
'AED | United Arab Emirates Dirham | 🇦🇪\n' +
'ANG | Netherlands Antillean Guilder | 🇧🇶\n' +
'AOA | Angolan Kwanza | 🇦🇴\n' +
'ARS | Peso argentino | 🇦🇷\n' +
'AUD | Australian Dollar | 🇦🇺\n' +
'AZN | Azerbaijani Manat | 🇦🇿\n' +
'BDT | Bangladeshi Taka | 🇧🇩\n' +
'BHD | Bahraini Dinar | 🇧🇭\n' +
'BIF | Burundian Franc | 🇧🇮\n' +
'BMD | Bermudan Dollar | 🇧🇲\n' +
'BOB | Boliviano | 🇧🇴\n' +
'BRL | Brazilian Real | 🇧🇷\n' +
'BWP | Botswanan Pula | 🇧🇼\n' +
'BYN | Belarusian Ruble | 🇧🇾\n' +
'CAD | Canadian Dollar | 🇨🇦\n' +
'CDF | Congolese Franc | 🇨🇩\n' +
'CHF | Swiss Franc | 🇨🇭\n' +
'CLP | Peso chileno | 🇨🇱\n' +
'CNY | Chinese Yuan | 🇨🇳\n' +
'COP | Peso colombiano | 🇨🇴\n' +
'CRC | Colón | 🇨🇷\n' +
'CUP | Peso cubano | 🇨🇺\n' +
'CZK | Czech Republic Koruna | 🇨🇿\n' +
'DJF | Djiboutian Franc | 🇩🇯\n' +
'DKK | Danish Krone | 🇩🇰\n' +
'DOP | Peso dominicano | 🇩🇴\n' +
'DZD | Algerian Dinar | 🇩🇿\n' +
'EGP | Egyptian Pound | 🇪🇬\n' +
'ETB | Ethiopian Birr | 🇪🇹\n' +
'EUR | Euro | 🇪🇺\n' +
'GBP | British Pound Sterling | 🇬🇧\n' +
'GEL | Georgian Lari | 🇬🇪\n' +
'GHS | Ghanaian Cedi | 🇬🇭\n' +
'GNF | Guinean Franc | 🇬🇳\n' +
'GTQ | Quetzal | 🇬🇹\n' +
'HKD | Hong Kong Dollar | 🇭🇰\n' +
'HNL | Lempira | 🇭🇳\n' +
'HUF | Hungarian Forint | 🇭🇺\n' +
'IDR | Indonesian Rupiah | 🇮🇩\n' +
'ILS | Israeli New Sheqel | 🇮🇱\n' +
'INR | Indian Rupee | 🇮🇳\n' +
'IRR | Iranian Rial | 🇮🇷\n' +
'IRT | Iranian Tomen | 🇮🇷\n' +
'JMD | Jamaican Dollar | 🇯🇲\n' +
'JOD | Jordanian Dinar | 🇯🇴\n' +
'JPY | Japanese Yen | 🇯🇵\n' +
'KES | Kenyan Shilling | 🇰🇪\n' +
'KGS | Kyrgystani Som | 🇰🇬\n' +
'KRW | South Korean Won | 🇰🇷\n' +
'KZT | Kazakhstani Tenge | 🇰🇿\n' +
'LBP | Lebanese Pound | 🇱🇧\n' +
'LKR | Sri Lankan Rupee | 🇱🇰\n' +
'MAD | Moroccan Dirham | 🇲🇦\n' +
'MGA | Malagasy Ariary | 🇲🇬\n' +
'MLC | Moneda Libremente Convertible | 🇨🇺\n' +
'MXN | Peso mexicano | 🇲🇽\n' +
'MWK | Malawian Kwacha | 🇲🇼\n' +
'MYR | Malaysian Ringgit | 🇲🇾\n' +
'NAD | Namibian Dollar | 🇳🇦\n' +
'NGN | Nigerian Naira | 🇳🇬\n' +
'NIO | Nicaraguan Córdoba | 🇳🇮\n' +
'NOK | Norwegian Krone | 🇳🇴\n' +
'NPR | Nepalese Rupee | 🇳🇵\n' +
'NZD | New Zealand Dollar | 🇳🇿\n' +
'PAB | Panamanian Balboa | 🇵🇦\n' +
'PEN | Peruvian Nuevo Sol | 🇵🇪\n' +
'PHP | Philippine Peso | 🇵🇭\n' +
'PKR | Pakistani Rupee | 🇵🇰\n' +
'PLN | Polish Zloty | 🇵🇱\n' +
'PYG | Paraguayan Guarani | 🇵🇾\n' +
'QAR | Qatari Rial | 🇶🇦\n' +
'RON | Romanian Leu | 🇷🇴\n' +
'RSD | Serbian Dinar | 🇷🇸\n' +
'RUB | руб | 🇷🇺\n' +
'RWF | Rwandan Franc | 🇷🇼\n' +
'SAR | Saudi Riyal | 🇸🇦\n' +
'SEK | Swedish Krona | 🇸🇪\n' +
'SGD | Singapore Dollar | 🇸🇬\n' +
'THB | Thai Baht | 🇹🇭\n' +
'TND | Tunisian Dinar | 🇹🇳\n' +
'TRY | Turkish Lira | 🇹🇷\n' +
'TTD | Trinidad and Tobago Dollar | 🇹🇹\n' +
'TWD | New Taiwan Dollar | 🇹🇼\n' +
'TZS | Tanzanian Shilling | 🇹🇿\n' +
'UAH | Ukrainian Hryvnia | 🇺🇦\n' +
'UGX | Ugandan Shilling | 🇺🇬\n' +
'USD | US Dollar | 🇺🇸\n' +
'USDSV | USD en El Salvador | 🇺🇸🇸🇻\n' +
'USDVE | USD en Bs | 🇺🇸🇻🇪\n' +
'USDUY | USD en Uruguay | 🇺🇸🇺🇾\n' +
'UYU | Peso uruguayo | 🇺🇾\n' +
'UZS | Uzbekistan Som | 🇺🇿\n' +
'VES | Bolívar | 🇻🇪\n' +
'VND | Vietnamese Dong | 🇻🇳\n' +
'XAF | CFA Franc BEAC | 🇨🇲 🇨🇫 🇹🇩 🇬🇶 🇬🇦 🇨🇬\n' +
'XOF | CFA Franc BCEAO | 🇧🇯 🇧🇫 🇨🇮 🇬🇼 🇲🇱 🇳🇪 🇸🇳 🇹🇬\n' +
'ZAR | South African Rand | 🇿🇦\n'
},
updateId: 2,
messageId: 2,
isRead: true
}
]
};

module.exports = {
mockUpdatesResponseForCurrencies,
};
Loading
Loading