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

Open
wants to merge 7 commits into
base: main
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
20 changes: 7 additions & 13 deletions bot/validations.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { MainContext, OrderQuery, ctxUpdateAssertMsg } from "./start";
import { ICommunity } from "../models/community";
import { ICommunity, IUsernameId } from "../models/community";
import { FilterQuery } from "mongoose";
import { UserDocument } from "../models/user";
import { IOrder } from "../models/order";
Expand All @@ -9,7 +9,7 @@ const { parsePaymentRequest } = require('invoices');
const { ObjectId } = require('mongoose').Types;
import * as messages from './messages';
import { Order, User, Community } from '../models';
import { isIso4217, isDisputeSolver, removeLightningPrefix } from '../util';
import { isIso4217, isDisputeSolver, removeLightningPrefix, isOrderCreator } from '../util';
const { existLightningAddress } = require('../lnurl/lnurl-pay');
import { logger } from '../logger';

Expand Down Expand Up @@ -106,6 +106,7 @@ const validateAdmin = async (ctx: MainContext, id?: string) => {

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 @@ -192,7 +193,8 @@ const validateSellOrder = async (ctx: MainContext) => {
await messages.mustBeANumberOrRange(ctx);
return false;
}


// TODO, this validation could be amount > 0?
if (amount !== 0 && amount < Number(process.env.MIN_PAYMENT_AMT)) {
await messages.mustBeGreatherEqThan(
ctx,
Expand Down Expand Up @@ -338,7 +340,7 @@ const validateInvoice = async (ctx: MainContext, lnInvoice: string) => {
const latestDate = new Date(
Date.now() + Number(process.env.INVOICE_EXPIRATION_WINDOW)
);
if (!("MAIN_PAYMENT_AMT" in process.env)) throw Error("MIN_PAYMENT_AMT not found, please check .env file");
if (!("MIN_PAYMENT_AMT" in process.env)) throw Error("MIN_PAYMENT_AMT not found, please check .env file");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@danfercf1 this looks like an unrelated change that should go in a separate PR?

Copy link
Contributor Author

@danfercf1 danfercf1 Oct 3, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, you are right the problem is that the test related to this implementation will not work. I've reported that problem in this issue #594

if (!!invoice.tokens && invoice.tokens < Number(process.env.MIN_PAYMENT_AMT)) {
await messages.minimunAmountInvoiceMessage(ctx);
return false;
Expand Down Expand Up @@ -429,14 +431,6 @@ const isValidInvoice = async (ctx: MainContext, lnInvoice: string) => {
}
};

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

const validateTakeSellOrder = async (ctx: MainContext, bot: Telegraf<MainContext>, user: UserDocument, order: IOrder) => {
try {
Expand Down Expand Up @@ -688,7 +682,7 @@ const isBannedFromCommunity = async (user: UserDocument, communityId: string) =>
if (!communityId) return false;
const community = await Community.findOne({ _id: communityId });
if (!community) return false;
return community.banned_users.toObject().some((buser: ICommunity) => buser.id == user._id);
return community.banned_users.some((buser: IUsernameId) => buser.id == user._id);
} catch (error) {
logger.error(error);
return false;
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');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have a doubt about this test, if I change the commando to a wrong command, let's say client.makeCommand('/sello 100 1 ves Pagomovil'); the test still passes, what are we testing here? can we make the test fails if the command is wrong?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will add the fail tests, the reason is that the telegram api is mocked with a certain response, for the fails tests it's necessary to add the mocks for the failed tests

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The unit tests have a controlled environment, we need to add all the mocked data to makes the test run every possible scenario

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it possible to add some mocked data on this PR? not necessary all data but something to start

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I'm working on that

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