-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.test.js
More file actions
1799 lines (1426 loc) · 65.8 KB
/
index.test.js
File metadata and controls
1799 lines (1426 loc) · 65.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const { Pool } = require('pg');
const bcrypt = require('bcryptjs');
const cron = require('node-cron');
const ErrsolePostgres = require('../lib/index'); // Adjust the path as needed
const { describe } = require('@jest/globals');
/* globals expect, jest, beforeEach, it, afterEach, describe, afterAll */
jest.mock('pg', () => {
const mClient = {
query: jest.fn(),
release: jest.fn()
};
const mPool = {
connect: jest.fn().mockResolvedValue(mClient),
query: jest.fn().mockResolvedValue({ rows: [{ work_mem: '8192kB' }] })
};
return { Pool: jest.fn(() => mPool) };
});
jest.mock('bcryptjs', () => ({
hash: jest.fn(),
compare: jest.fn()
}));
describe('ErrsolePostgres', () => {
let errsolePostgres;
let poolMock;
let clientMock;
let originalConsoleError;
let cronJob;
beforeEach(() => {
clientMock = {
query: jest.fn().mockResolvedValue({ rows: [{ work_mem: '8192kB' }] }),
release: jest.fn()
};
poolMock = {
connect: jest.fn().mockResolvedValue(clientMock),
query: jest.fn().mockImplementation((query, values) => {
if (query.includes('SHOW work_mem')) {
return Promise.resolve({ rows: [{ work_mem: '8192kB' }] }); // Mock for getWorkMem
}
if (query.includes('INSERT INTO')) {
return Promise.resolve({ rows: [{ id: 1 }] }); // Mock for createUser
}
return Promise.resolve({ rows: [] });
})
};
Pool.mockImplementation(() => poolMock);
errsolePostgres = new ErrsolePostgres({
host: 'localhost',
user: 'root',
password: 'password',
database: 'dbname'
});
// Mock setInterval and cron.schedule
jest.useFakeTimers();
jest.spyOn(global, 'setInterval');
cronJob = { stop: jest.fn() };
jest.spyOn(cron, 'schedule').mockReturnValue(cronJob);
// Suppress console.error
originalConsoleError = console.error;
console.error = jest.fn();
});
afterEach(() => {
jest.clearAllMocks();
jest.useRealTimers();
// Restore console.error
console.error = originalConsoleError;
});
describe('#initialize', () => {
it('should initialize properly', async () => {
await errsolePostgres.initialize();
expect(poolMock.connect).toHaveBeenCalled();
expect(poolMock.query).toHaveBeenCalledWith(expect.any(String));
expect(errsolePostgres.isConnectionInProgress).toBe(false);
// Check if setInterval and cron.schedule were called
expect(setInterval).toHaveBeenCalled();
expect(cron.schedule).toHaveBeenCalled();
});
});
describe('#getWorkMem', () => {
let poolQuerySpy;
beforeEach(() => {
poolQuerySpy = jest.spyOn(poolMock, 'query');
poolMock.query.mockClear(); // Clear any previous calls
});
afterEach(() => {
jest.clearAllMocks();
});
it('should return the current work_mem value', async () => {
poolMock.query.mockResolvedValueOnce({ rows: [{ work_mem: '8192kB' }] });
const result = await errsolePostgres.getWorkMem();
expect(poolQuerySpy).toHaveBeenCalledWith('SHOW work_mem');
expect(result).toBe(8192);
});
it('should handle errors during the query execution', async () => {
const error = new Error('Query error');
poolQuerySpy.mockRejectedValueOnce(error);
await expect(errsolePostgres.getWorkMem()).rejects.toThrow('Query error');
expect(poolQuerySpy).toHaveBeenCalledWith('SHOW work_mem');
});
it('should return NaN if work_mem value is not a number', async () => {
poolMock.query.mockResolvedValueOnce({ rows: [{ work_mem: 'not_a_number' }] });
const result = await errsolePostgres.getWorkMem();
expect(poolQuerySpy).toHaveBeenCalledWith('SHOW work_mem');
expect(result).toBeNaN();
});
});
describe('#checkConnection', () => {
it('should successfully check the database connection', async () => {
await expect(errsolePostgres.checkConnection()).resolves.not.toThrow();
expect(poolMock.connect).toHaveBeenCalled();
expect(clientMock.query).toHaveBeenCalledWith('SELECT NOW()');
expect(clientMock.release).toHaveBeenCalled();
});
it('should throw an error if query fails', async () => {
clientMock.query.mockRejectedValueOnce(new Error('Query error'));
await expect(errsolePostgres.checkConnection()).rejects.toThrow('Query error');
expect(poolMock.connect).toHaveBeenCalled();
expect(clientMock.query).toHaveBeenCalledWith('SELECT NOW()');
expect(clientMock.release).toHaveBeenCalled();
});
it('should release the client even if the query fails', async () => {
clientMock.query.mockRejectedValueOnce(new Error('Query error'));
try {
await errsolePostgres.checkConnection();
} catch (error) {
expect(error.message).toBe('Query error');
}
expect(clientMock.release).toHaveBeenCalled();
});
});
describe('#setWorkMem', () => {
let poolQuerySpy;
let getWorkMemSpy;
beforeEach(() => {
poolQuerySpy = jest.spyOn(poolMock, 'query');
getWorkMemSpy = jest.spyOn(errsolePostgres, 'getWorkMem');
});
afterEach(() => {
jest.clearAllMocks();
});
it('should set work_mem if current size is less than desired', async () => {
getWorkMemSpy.mockResolvedValueOnce(4096); // Current size less than desired
await expect(errsolePostgres.setWorkMem()).resolves.not.toThrow();
expect(getWorkMemSpy).toHaveBeenCalled();
expect(poolQuerySpy).toHaveBeenCalledWith("SET work_mem = '8192kB'");
});
it('should handle errors during setting work_mem', async () => {
const error = new Error('Query error');
getWorkMemSpy.mockResolvedValueOnce(4096); // Current size less than desired
poolQuerySpy.mockRejectedValueOnce(error);
await expect(errsolePostgres.setWorkMem()).rejects.toThrow('Query error');
expect(getWorkMemSpy).toHaveBeenCalled();
expect(poolQuerySpy).toHaveBeenCalledWith("SET work_mem = '8192kB'");
});
});
describe('#createTables', () => {
it('should create necessary tables', async () => {
// Mock the query method to resolve for all calls
poolMock.query.mockResolvedValue({});
// Call the function
await errsolePostgres.createTables();
// Capture all queries executed
const executedQueries = poolMock.query.mock.calls.map(call => call[0]);
// Define expected table creation queries
const expectedQueries = [
/CREATE TABLE IF NOT EXISTS errsole_logs_v3/,
/CREATE INDEX IF NOT EXISTS .*errsole_logs_v3.*hostname.*source.*level.*timestamp.*id/,
/CREATE INDEX IF NOT EXISTS .*errsole_logs_v3.*hostname.*timestamp.*id/,
/CREATE INDEX IF NOT EXISTS .*errsole_logs_v3.*hostname/,
/CREATE INDEX IF NOT EXISTS .*errsole_logs_v3.*timestamp.*id/,
/CREATE INDEX IF NOT EXISTS .*errsole_logs_v3.*errsole_id/,
/CREATE TABLE IF NOT EXISTS errsole_users/,
/CREATE TABLE IF NOT EXISTS errsole_config/
];
// Ensure all expected queries were executed
expectedQueries.forEach(expectedQuery => {
expect(executedQueries.some(query => expectedQuery.test(query))).toBe(true);
});
});
it('should throw an error if table creation fails', async () => {
const error = new Error('Query error');
poolMock.query.mockRejectedValueOnce(error);
await expect(errsolePostgres.createTables()).rejects.toThrow('Query error');
expect(poolMock.query).toHaveBeenCalled();
expect(errsolePostgres.isConnectionInProgress).toBe(false);
});
});
describe('#getConfig', () => {
it('should retrieve a configuration based on the provided key', async () => {
const config = { key: 'testKey', value: 'testValue' };
poolMock.query.mockResolvedValueOnce({ rows: [config] });
const result = await errsolePostgres.getConfig('testKey');
expect(poolMock.query).toHaveBeenCalledWith('SELECT * FROM errsole_config WHERE key = $1', ['testKey']);
expect(result).toEqual({ item: config });
});
it('should return null if configuration key is not found', async () => {
poolMock.query.mockResolvedValueOnce({ rows: [] });
const result = await errsolePostgres.getConfig('nonexistentKey');
expect(poolMock.query).toHaveBeenCalledWith('SELECT * FROM errsole_config WHERE key = $1', ['nonexistentKey']);
expect(result).toEqual({ item: null });
});
it('should handle errors during the query execution', async () => {
poolMock.query.mockRejectedValueOnce(new Error('Query error'));
await expect(errsolePostgres.getConfig('testKey')).rejects.toThrow('Query error');
expect(poolMock.query).toHaveBeenCalledWith('SELECT * FROM errsole_config WHERE key = $1', ['testKey']);
});
});
describe('#deleteConfig', () => {
beforeEach(() => {
poolMock.query.mockClear(); // Reset the mock for each test
});
it('should delete config by key', async () => {
poolMock.query.mockResolvedValueOnce({ rowCount: 1 });
const result = await errsolePostgres.deleteConfig('logsTTL');
expect(poolMock.query).toHaveBeenCalledWith('DELETE FROM errsole_config WHERE key = $1', ['logsTTL']);
expect(result).toEqual({});
});
it('should handle errors during the deleteConfig operation', async () => {
poolMock.query.mockRejectedValueOnce(new Error('Query error'));
await expect(errsolePostgres.deleteConfig('logsTTL')).rejects.toThrow('Query error');
expect(poolMock.query).toHaveBeenCalledWith('DELETE FROM errsole_config WHERE key = $1', ['logsTTL']);
});
});
describe('#postLogs', () => {
it('should add log entries to pending logs', () => {
const logEntries = [
{ timestamp: new Date(), hostname: 'localhost', pid: 1234, source: 'test', level: 'info', message: 'test message', meta: 'meta' }
];
errsolePostgres.postLogs(logEntries);
expect(errsolePostgres.pendingLogs).toHaveLength(1);
expect(errsolePostgres.pendingLogs[0]).toEqual(logEntries[0]);
});
it('should call flushLogs if pending logs exceed batch size', async () => {
const logEntries = Array.from({ length: errsolePostgres.batchSize + 1 }, (_, i) => ({
timestamp: new Date(),
hostname: 'localhost',
pid: 1234,
source: 'test',
level: 'info',
message: `test message ${i}`,
meta: 'meta'
}));
const flushLogsSpy = jest.spyOn(errsolePostgres, 'flushLogs').mockImplementation(() => Promise.resolve({}));
errsolePostgres.postLogs(logEntries);
expect(flushLogsSpy).toHaveBeenCalled();
});
});
describe('#verifyUser', () => {
it('should throw an error if email is missing', async () => {
await expect(errsolePostgres.verifyUser(null, 'password'))
.rejects.toThrow('Both email and password are required for verification.');
});
it('should throw an error if password is missing', async () => {
await expect(errsolePostgres.verifyUser('email@example.com', null))
.rejects.toThrow('Both email and password are required for verification.');
});
it('should throw an error if user is not found', async () => {
poolMock.query.mockResolvedValueOnce({ rows: [] });
await expect(errsolePostgres.verifyUser('email@example.com', 'password'))
.rejects.toThrow('User not found.');
});
it('should throw an error if the password is incorrect', async () => {
const user = { email: 'email@example.com', hashed_password: 'hashed_password' };
poolMock.query.mockResolvedValueOnce({ rows: [user] });
bcrypt.compare.mockResolvedValueOnce(false);
await expect(errsolePostgres.verifyUser('email@example.com', 'wrongpassword'))
.rejects.toThrow('Incorrect password.');
});
it('should return the user object if email and password are correct', async () => {
const user = { id: 1, email: 'email@example.com', name: 'John Doe', hashed_password: 'hashed_password' };
poolMock.query.mockResolvedValueOnce({ rows: [user] });
bcrypt.compare.mockResolvedValueOnce(true);
const result = await errsolePostgres.verifyUser('email@example.com', 'password');
expect(result).toEqual({ item: { id: 1, email: 'email@example.com', name: 'John Doe' } });
});
});
describe('#getAllUsers', () => {
it('should successfully retrieve all users', async () => {
const users = [
{ id: 1, name: 'John Doe', email: 'john@example.com', role: 'admin' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com', role: 'user' }
];
poolMock.query.mockResolvedValueOnce({ rows: users });
const result = await errsolePostgres.getAllUsers();
expect(poolMock.query).toHaveBeenCalledWith('SELECT id, name, email, role FROM errsole_users');
expect(result).toEqual({ items: users });
});
it('should return an empty array if no users are found', async () => {
poolMock.query.mockResolvedValueOnce({ rows: [] });
const result = await errsolePostgres.getAllUsers();
expect(poolMock.query).toHaveBeenCalledWith('SELECT id, name, email, role FROM errsole_users');
expect(result).toEqual({ items: [] });
});
it('should handle errors during query execution', async () => {
const error = new Error('Query error');
poolMock.query.mockRejectedValueOnce(error);
await expect(errsolePostgres.getAllUsers()).rejects.toThrow('Query error');
expect(poolMock.query).toHaveBeenCalledWith('SELECT id, name, email, role FROM errsole_users');
});
});
describe('#updateUserByEmail', () => {
let poolQuerySpy;
let getUserByEmailSpy;
beforeEach(() => {
poolQuerySpy = jest.spyOn(poolMock, 'query');
getUserByEmailSpy = jest.spyOn(errsolePostgres, 'getUserByEmail').mockResolvedValue({ item: { id: 1, name: 'updated', email: 'test@example.com', role: 'admin' } });
});
afterEach(() => {
jest.clearAllMocks();
});
it('should update user by email', async () => {
poolQuerySpy.mockResolvedValue({ rowCount: 1 });
const user = await errsolePostgres.updateUserByEmail('test@example.com', { name: 'updated' });
expect(poolQuerySpy).toHaveBeenCalledWith(
'UPDATE errsole_users SET name = $1 WHERE email = $2',
['updated', 'test@example.com']
);
expect(getUserByEmailSpy).toHaveBeenCalledWith('test@example.com');
expect(user).toEqual({ item: { id: 1, name: 'updated', email: 'test@example.com', role: 'admin' } });
});
it('should throw an error if no email is provided', async () => {
await expect(errsolePostgres.updateUserByEmail('', { name: 'updated' })).rejects.toThrow('Email is required.');
});
it('should throw an error if no updates are provided', async () => {
await expect(errsolePostgres.updateUserByEmail('test@example.com', {})).rejects.toThrow('No updates provided.');
});
it('should throw an error if no updates are applied', async () => {
poolQuerySpy.mockResolvedValue({ rowCount: 0 });
await expect(errsolePostgres.updateUserByEmail('test@example.com', { name: 'updated' })).rejects.toThrow('No updates applied.');
});
it('should handle restricted fields', async () => {
poolQuerySpy.mockResolvedValue({ rowCount: 1 });
await errsolePostgres.updateUserByEmail('test@example.com', { name: 'updated', id: 2, hashed_password: 'secret' });
expect(poolQuerySpy).toHaveBeenCalledWith(
'UPDATE errsole_users SET name = $1 WHERE email = $2',
['updated', 'test@example.com']
);
});
it('should handle query errors during user update', async () => {
poolQuerySpy.mockRejectedValue(new Error('Query error'));
await expect(errsolePostgres.updateUserByEmail('test@example.com', { name: 'updated' })).rejects.toThrow('Query error');
});
});
describe('#updatePassword', () => {
it('should update user password', async () => {
const user = { id: 1, name: 'test', email: 'test@example.com', hashed_password: 'hashedPassword', role: 'admin' };
poolMock.query
.mockResolvedValueOnce({ rows: [user] }) // First query response
.mockResolvedValueOnce({ rowCount: 1 }); // Second query response
bcrypt.compare.mockResolvedValue(true);
bcrypt.hash.mockResolvedValue('newHashedPassword');
const result = await errsolePostgres.updatePassword('test@example.com', 'password', 'newPassword');
expect(poolMock.query).toHaveBeenCalledWith('SELECT * FROM errsole_users WHERE email = $1', ['test@example.com']);
expect(bcrypt.compare).toHaveBeenCalledWith('password', 'hashedPassword');
expect(bcrypt.hash).toHaveBeenCalledWith('newPassword', 10);
expect(poolMock.query).toHaveBeenCalledWith('UPDATE errsole_users SET hashed_password = $1 WHERE email = $2', ['newHashedPassword', 'test@example.com']);
expect(result).toEqual({ item: { id: 1, name: 'test', email: 'test@example.com', role: 'admin' } });
});
it('should throw an error if email, current password, or new password is missing', async () => {
await expect(errsolePostgres.updatePassword('', 'password', 'newPassword')).rejects.toThrow('Email, current password, and new password are required.');
await expect(errsolePostgres.updatePassword('test@example.com', '', 'newPassword')).rejects.toThrow('Email, current password, and new password are required.');
await expect(errsolePostgres.updatePassword('test@example.com', 'password', '')).rejects.toThrow('Email, current password, and new password are required.');
});
it('should throw an error if user is not found', async () => {
poolMock.query.mockResolvedValue({ rows: [] });
await expect(errsolePostgres.updatePassword('test@example.com', 'password', 'newPassword')).rejects.toThrow('User not found.');
});
it('should throw an error if current password is incorrect', async () => {
const user = { id: 1, name: 'test', email: 'test@example.com', hashed_password: 'hashedPassword', role: 'admin' };
poolMock.query.mockResolvedValue({ rows: [user] });
bcrypt.compare.mockResolvedValue(false);
await expect(errsolePostgres.updatePassword('test@example.com', 'wrongPassword', 'newPassword')).rejects.toThrow('Current password is incorrect.');
});
});
describe('#getUserByEmail', () => {
let poolQuerySpy;
beforeEach(() => {
poolQuerySpy = jest.spyOn(poolMock, 'query');
});
afterEach(() => {
jest.clearAllMocks();
});
it('should throw an error if no email is provided', async () => {
poolQuerySpy.mockClear();
await expect(errsolePostgres.getUserByEmail()).rejects.toThrow('Email is required.');
expect(poolQuerySpy).not.toHaveBeenCalled(); // Ensures no query is made for this case
});
it('should throw an error if the user is not found', async () => {
poolQuerySpy.mockResolvedValueOnce({ rows: [] });
await expect(errsolePostgres.getUserByEmail('nonexistent@example.com')).rejects.toThrow('User not found.');
expect(poolQuerySpy).toHaveBeenCalledWith(
expect.stringContaining('SELECT id, name, email, role FROM'),
['nonexistent@example.com']
);
});
it('should return the user object if the user is found', async () => {
const user = { id: 1, name: 'John Doe', email: 'john@example.com', role: 'admin' };
poolQuerySpy.mockResolvedValueOnce({ rows: [user] });
const result = await errsolePostgres.getUserByEmail('john@example.com');
expect(poolQuerySpy).toHaveBeenCalledWith(
expect.stringContaining('SELECT id, name, email, role FROM'),
['john@example.com']
);
expect(result).toEqual({ item: user });
});
it('should handle database errors gracefully', async () => {
const error = new Error('Database query failed');
poolQuerySpy.mockRejectedValueOnce(error);
await expect(errsolePostgres.getUserByEmail('john@example.com')).rejects.toThrow('Database query failed');
expect(poolQuerySpy).toHaveBeenCalledWith(
expect.stringContaining('SELECT id, name, email, role FROM'),
['john@example.com']
);
});
});
describe('#getLogs', () => {
let poolQuerySpy;
beforeEach(() => {
poolQuerySpy = jest.spyOn(poolMock, 'query');
});
afterEach(() => {
jest.clearAllMocks();
});
it('should retrieve logs with no filters', async () => {
const logs = [
{ id: 1, hostname: 'localhost', pid: 1234, source: 'test', timestamp: new Date(), level: 'info', message: 'test message' }
];
poolMock.query.mockResolvedValueOnce({ rows: logs });
const result = await errsolePostgres.getLogs();
expect(poolMock.query).toHaveBeenCalledWith(
expect.stringContaining('SELECT id, hostname, pid, source, timestamp, level, message, errsole_id FROM errsole_logs_v3'),
[100]
);
expect(result).toEqual({ items: logs });
});
it('should apply lt_id filter', async () => {
const logs = [
{ id: 1, hostname: 'localhost', pid: 1234, source: 'test', timestamp: new Date(), level: 'info', message: 'test message' }
];
const filters = {
lt_id: 10,
limit: 50
};
poolMock.query.mockResolvedValueOnce({ rows: logs });
const result = await errsolePostgres.getLogs(filters);
expect(poolMock.query).toHaveBeenCalledWith(
expect.stringContaining('SELECT id, hostname, pid, source, timestamp, level, message, errsole_id FROM errsole_logs_v3 WHERE id < $1 ORDER BY id DESC LIMIT $2'),
[10, 50]
);
expect(result).toEqual({ items: logs });
});
it('should apply gt_id filter', async () => {
const logs = [
{ id: 1, hostname: 'localhost', pid: 1234, source: 'test', timestamp: new Date(), level: 'info', message: 'test message' }
];
const filters = {
gt_id: 5,
limit: 50
};
poolMock.query.mockResolvedValueOnce({ rows: logs });
const result = await errsolePostgres.getLogs(filters);
expect(poolMock.query).toHaveBeenCalledWith(
expect.stringContaining('SELECT id, hostname, pid, source, timestamp, level, message, errsole_id FROM errsole_logs_v3 WHERE id > $1 ORDER BY id ASC LIMIT $2'),
[5, 50]
);
expect(result).toEqual({ items: logs });
});
it('should apply lte_timestamp filter', async () => {
const logs = [
{ id: 1, hostname: 'localhost', pid: 1234, source: 'test', timestamp: new Date('2023-01-01T00:00:00Z'), level: 'info', message: 'test message' }
];
const filters = {
lte_timestamp: new Date('2023-01-02T00:00:00Z'),
limit: 50
};
poolMock.query.mockResolvedValueOnce({ rows: logs });
const result = await errsolePostgres.getLogs(filters);
expect(poolMock.query).toHaveBeenCalledWith(
expect.stringContaining('SELECT id, hostname, pid, source, timestamp, level, message, errsole_id FROM errsole_logs_v3 WHERE timestamp <= $1 ORDER BY timestamp DESC, id DESC LIMIT $2'),
[new Date('2023-01-02T00:00:00Z'), 50]
);
expect(result).toEqual({ items: logs });
});
it('should apply gte_timestamp filter', async () => {
const logs = [
{ id: 1, hostname: 'localhost', pid: 1234, source: 'test', timestamp: new Date('2023-01-01T00:00:00Z'), level: 'info', message: 'test message' }
];
const filters = {
gte_timestamp: new Date('2023-01-01T00:00:00Z'),
limit: 50
};
poolMock.query.mockResolvedValueOnce({ rows: logs });
const result = await errsolePostgres.getLogs(filters);
expect(poolMock.query).toHaveBeenCalledWith(
expect.stringContaining('SELECT id, hostname, pid, source, timestamp, level, message, errsole_id FROM errsole_logs_v3 WHERE timestamp >= $1 ORDER BY timestamp ASC, id ASC LIMIT $2'),
[new Date('2023-01-01T00:00:00Z'), 50]
);
expect(result).toEqual({ items: logs });
});
it('should apply level_json filter', async () => {
const logs = [
{ id: 1, hostname: 'localhost', pid: 1234, source: 'test', timestamp: new Date(), level: 'info', message: 'test message' }
];
const filters = {
level_json: [
{ source: 'test', level: 'info' },
{ source: 'another_test', level: 'warn' }
],
limit: 50
};
poolMock.query.mockResolvedValueOnce({ rows: logs });
const result = await errsolePostgres.getLogs(filters);
expect(poolMock.query).toHaveBeenCalledWith(
expect.stringContaining('SELECT id, hostname, pid, source, timestamp, level, message, errsole_id FROM errsole_logs_v3'),
expect.arrayContaining(['test', 'info', 'another_test', 'warn', 50])
);
expect(result).toEqual({ items: logs });
});
it('should reverse the result if shouldReverse is true', async () => {
const logs = [
{ id: 1, hostname: 'localhost', pid: 1234, source: 'test', timestamp: new Date(), level: 'info', message: 'test message' },
{ id: 2, hostname: 'localhost', pid: 1234, source: 'test', timestamp: new Date(), level: 'info', message: 'another message' }
];
const filters = {
lt_id: 10,
limit: 50
};
poolMock.query.mockResolvedValueOnce({ rows: logs });
const result = await errsolePostgres.getLogs(filters);
expect(poolMock.query).toHaveBeenCalledWith(
expect.stringContaining('SELECT id, hostname, pid, source, timestamp, level, message, errsole_id FROM errsole_logs_v3 WHERE id < $1 ORDER BY id DESC LIMIT $2'),
[10, 50]
);
expect(result.items).toEqual(logs.reverse());
});
it('should retrieve logs filtered by a single hostname', async () => {
const mockLogs = [
{
id: 1,
hostname: 'localhost',
pid: 1234,
source: 'test',
timestamp: new Date(),
level: 'info',
message: 'Test message 1',
errsole_id: 'err1'
}
];
const filters = {
hostnames: ['localhost'],
limit: 50
};
poolMock.query.mockResolvedValueOnce({ rows: mockLogs });
const result = await errsolePostgres.getLogs(filters);
expect(poolMock.query).toHaveBeenCalledWith(
expect.stringContaining('WHERE hostname = ANY($1)'),
[['localhost'], 50]
);
expect(result).toEqual({ items: mockLogs });
});
it('should retrieve logs filtered by multiple hostnames', async () => {
const mockLogs = [
{
id: 2,
hostname: 'server1',
pid: 5678,
source: 'test',
timestamp: new Date(),
level: 'error',
message: 'Test message 2',
errsole_id: 'err2'
},
{
id: 3,
hostname: 'server2',
pid: 9101,
source: 'test',
timestamp: new Date(),
level: 'warn',
message: 'Test message 3',
errsole_id: 'err3'
}
];
const filters = {
hostnames: ['server1', 'server2'],
limit: 50
};
poolMock.query.mockResolvedValueOnce({ rows: mockLogs });
const result = await errsolePostgres.getLogs(filters);
expect(poolMock.query).toHaveBeenCalledWith(
expect.stringContaining('WHERE hostname = ANY($1)'),
[['server1', 'server2'], 50]
);
expect(result).toEqual({ items: mockLogs });
});
it('should ignore the hostnames filter if the array is empty', async () => {
const mockLogs = [
{
id: 4,
hostname: 'server3',
pid: 1121,
source: 'test',
timestamp: new Date(),
level: 'info',
message: 'Test message 4',
errsole_id: 'err4'
}
];
const filters = {
hostnames: [],
limit: 50
};
poolMock.query.mockResolvedValueOnce({ rows: mockLogs });
const result = await errsolePostgres.getLogs(filters);
expect(poolMock.query).toHaveBeenCalledWith(
expect.not.stringContaining('WHERE hostname = ANY'),
[50]
);
expect(result).toEqual({ items: mockLogs });
});
it('should retrieve all logs if hostnames filter is not provided', async () => {
const mockLogs = [
{
id: 5,
hostname: 'server4',
pid: 3141,
source: 'test',
timestamp: new Date(),
level: 'debug',
message: 'Test message 5',
errsole_id: 'err5'
}
];
const filters = {
limit: 50
};
poolMock.query.mockResolvedValueOnce({ rows: mockLogs });
const result = await errsolePostgres.getLogs(filters);
expect(poolMock.query).toHaveBeenCalledWith(
expect.not.stringContaining('WHERE hostname = ANY'),
[50]
);
expect(result).toEqual({ items: mockLogs });
});
it('should handle errors during log retrieval', async () => {
poolMock.query.mockRejectedValueOnce(new Error('Query error'));
await expect(errsolePostgres.getLogs()).rejects.toThrow('Query error');
expect(poolMock.query).toHaveBeenCalledWith(
expect.stringContaining('SELECT id, hostname, pid, source, timestamp, level, message, errsole_id FROM errsole_logs_v3'),
[100]
);
});
it('should retrieve logs using level_json filter', async () => {
const filters = {
level_json: [
{ source: 'source1', level: 'info' },
{ source: 'source2', level: 'error' }
],
limit: 50
};
const logs = [
{ id: 1, hostname: 'localhost', pid: 1234, source: 'source1', level: 'info', message: 'Log 1' },
{ id: 2, hostname: 'localhost', pid: 5678, source: 'source2', level: 'error', message: 'Log 2' }
];
poolMock.query.mockResolvedValueOnce({ rows: logs });
const result = await errsolePostgres.getLogs(filters);
expect(poolQuerySpy).toHaveBeenCalledWith(
expect.stringContaining(
'SELECT id, hostname, pid, source, timestamp, level, message, errsole_id FROM errsole_logs_v3 WHERE ('
),
expect.arrayContaining(['source1', 'info', 'source2', 'error', 50])
);
expect(result.items).toEqual(logs);
});
it('should retrieve logs using errsole_id filter', async () => {
const filters = {
errsole_id: 123,
limit: 50
};
const logs = [
{ id: 1, hostname: 'localhost', pid: 1234, source: 'source1', level: 'info', message: 'Log 1', errsole_id: 123 }
];
poolMock.query.mockResolvedValueOnce({ rows: logs });
const result = await errsolePostgres.getLogs(filters);
expect(poolQuerySpy).toHaveBeenCalledWith(
expect.stringContaining('SELECT id, hostname, pid, source, timestamp, level, message, errsole_id FROM errsole_logs_v3 WHERE ('),
expect.arrayContaining([123, 50])
);
expect(result.items).toEqual(logs);
});
it('should retrieve logs using both level_json and errsole_id filters', async () => {
const filters = {
level_json: [
{ source: 'source1', level: 'info' }
],
errsole_id: 123,
limit: 50
};
const logs = [
{ id: 1, hostname: 'localhost', pid: 1234, source: 'source1', level: 'info', message: 'Log 1', errsole_id: 123 }
];
poolMock.query.mockResolvedValueOnce({ rows: logs });
const result = await errsolePostgres.getLogs(filters);
expect(poolQuerySpy).toHaveBeenCalledWith(
expect.stringContaining('SELECT id, hostname, pid, source, timestamp, level, message, errsole_id FROM errsole_logs_v3 WHERE ('),
expect.arrayContaining(['source1', 'info', 123, 50])
);
expect(result.items).toEqual(logs);
});
it('should return empty array if no logs are found with level_json and errsole_id filters', async () => {
const filters = {
level_json: [
{ source: 'source1', level: 'info' }
],
errsole_id: 123,
limit: 50
};
poolMock.query.mockResolvedValueOnce({ rows: [] });
const result = await errsolePostgres.getLogs(filters);
expect(poolQuerySpy).toHaveBeenCalledWith(
expect.stringContaining('SELECT id, hostname, pid, source, timestamp, level, message, errsole_id FROM errsole_logs_v3 WHERE ('),
expect.arrayContaining(['source1', 'info', 123, 50])
);
expect(result.items).toEqual([]);
});
});
describe('#getUserCount', () => {
it('should successfully retrieve the user count', async () => {
poolMock.query.mockResolvedValueOnce({ rows: [{ count: '5' }] });
const result = await errsolePostgres.getUserCount();
expect(poolMock.query).toHaveBeenCalledWith('SELECT COUNT(*) as count FROM errsole_users');
expect(result).toEqual({ count: 5 });
});
it('should handle errors during query execution', async () => {
const error = new Error('Query error');
poolMock.query.mockRejectedValueOnce(error);
await expect(errsolePostgres.getUserCount()).rejects.toThrow('Query error');
expect(poolMock.query).toHaveBeenCalledWith('SELECT COUNT(*) as count FROM errsole_users');
});
});
describe('#getMeta', () => {
it('should successfully retrieve metadata for a given log ID', async () => {
const logMeta = { id: 1, meta: 'test meta data' };
poolMock.query.mockResolvedValueOnce({ rows: [logMeta] });
const result = await errsolePostgres.getMeta(1);
expect(poolMock.query).toHaveBeenCalledWith('SELECT id, meta FROM errsole_logs_v3 WHERE id = $1', [1]);
expect(result).toEqual({ item: logMeta });
});
it('should throw an error if the log entry is not found', async () => {
poolMock.query.mockResolvedValueOnce({ rows: [] });
await expect(errsolePostgres.getMeta(999)).rejects.toThrow('Log entry not found.');
expect(poolMock.query).toHaveBeenCalledWith('SELECT id, meta FROM errsole_logs_v3 WHERE id = $1', [999]);
});
it('should handle errors during query execution', async () => {
const error = new Error('Query error');
poolMock.query.mockRejectedValueOnce(error);
await expect(errsolePostgres.getMeta(1)).rejects.toThrow('Query error');
expect(poolMock.query).toHaveBeenCalledWith('SELECT id, meta FROM errsole_logs_v3 WHERE id = $1', [1]);
});
});
describe('#deleteUser', () => {
it('should delete user by id', async () => {
poolMock.query.mockResolvedValue({ rowCount: 1 });
await errsolePostgres.deleteUser(1);
expect(poolMock.query).toHaveBeenCalledWith('DELETE FROM errsole_users WHERE id = $1', [1]);
});
it('should throw error if user not found', async () => {
poolMock.query.mockResolvedValue({ rowCount: 0 });
await expect(errsolePostgres.deleteUser(1)).rejects.toThrow(new Error('User not found.'));
});
it('should throw error if no id is provided', async () => {
await expect(errsolePostgres.deleteUser()).rejects.toThrow('User ID is required.');
});
});
describe('#deleteExpiredLogs', () => {
let getConfigSpy;
let poolQuerySpy;
let setTimeoutSpy;
beforeEach(() => {
getConfigSpy = jest.spyOn(errsolePostgres, 'getConfig').mockResolvedValue({ item: { key: 'logsTTL', value: '2592000000' } });
poolQuerySpy = jest.spyOn(poolMock, 'query');
setTimeoutSpy = jest.spyOn(global, 'setTimeout').mockImplementation((callback) => callback());
errsolePostgres.deleteExpiredLogsRunning = false; // Reset the flag before each test
});
afterEach(() => {
jest.clearAllMocks();
});
it('should delete expired logs based on TTL', async () => {
poolQuerySpy
.mockResolvedValueOnce({ rowCount: 1000 }) // First query response
.mockResolvedValueOnce({ rowCount: 0 }); // Second query response
await errsolePostgres.deleteExpiredLogs();
expect(getConfigSpy).toHaveBeenCalledWith('logsTTL');
expect(poolQuerySpy).toHaveBeenCalledWith(expect.any(String), [expect.any(String)]);
expect(setTimeoutSpy).toHaveBeenCalled();