-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsites.test.js
895 lines (750 loc) · 29.8 KB
/
sites.test.js
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
/*
* Copyright 2023 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
/* eslint-env mocha */
import { KeyEvent, Site } from '@adobe/spacecat-shared-data-access';
import { Config } from '@adobe/spacecat-shared-data-access/src/models/site/config.js';
import KeyEventSchema from '@adobe/spacecat-shared-data-access/src/models/key-event/key-event.schema.js';
import SiteSchema from '@adobe/spacecat-shared-data-access/src/models/site/site.schema.js';
import { hasText } from '@adobe/spacecat-shared-utils';
import { use, expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
import esmock from 'esmock';
import nock from 'nock';
import sinonChai from 'sinon-chai';
import sinon, { stub } from 'sinon';
import SitesController from '../../src/controllers/sites.js';
use(chaiAsPromised);
use(sinonChai);
describe('Sites Controller', () => {
const sandbox = sinon.createSandbox();
const SITE_IDS = ['0b4dcf79-fe5f-410b-b11f-641f0bf56da3', 'c4420c67-b4e8-443d-b7ab-0099cfd5da20'];
const sites = [
{
siteId: SITE_IDS[0], baseURL: 'https://site1.com', deliveryType: 'aem_edge', config: Config({}), hlxConfig: {},
},
{
siteId: SITE_IDS[1], baseURL: 'https://site2.com', deliveryType: 'aem_edge', config: Config({}), hlxConfig: {},
},
].map((site) => new Site(
{
entities: {
site: {
model: {
indexes: {},
schema: {
attributes: {
config: { type: 'any', name: 'config', get: (value) => Config(value) },
deliveryType: { type: 'string', name: 'deliveryType', get: (value) => value },
gitHubURL: { type: 'string', name: 'gitHubURL', get: (value) => value },
isLive: { type: 'boolean', name: 'isLive', get: (value) => value },
organizationId: { type: 'string', name: 'organizationId', get: (value) => value },
hlxConfig: { type: 'any', name: 'hlxConfig', get: (value) => value },
},
},
},
patch: sinon.stub().returns({
composite: () => ({ go: () => {} }),
set: () => {},
}),
},
},
},
{
log: console,
getCollection: stub().returns({
schema: SiteSchema,
findById: stub(),
}),
},
SiteSchema,
site,
console,
));
const keyEvents = [{
keyEventId: 'k1', siteId: sites[0].getId(), name: 'some-key-event', type: KeyEvent.KEY_EVENT_TYPES.CODE, time: new Date().toISOString(),
},
{
keyEventId: 'k2', siteId: sites[0].getId(), name: 'other-key-event', type: KeyEvent.KEY_EVENT_TYPES.SEO, time: new Date().toISOString(),
},
].map((keyEvent) => new KeyEvent(
{
entities: {
keyEvent: {
model: {
indexes: {},
schema: {},
},
},
},
},
{
log: console,
getCollection: stub().returns({
schema: KeyEventSchema,
}),
},
KeyEventSchema,
keyEvent,
console,
));
const siteFunctions = [
'createSite',
'getAll',
'getAllByDeliveryType',
'getAllWithLatestAudit',
'getLatestSiteMetrics',
'getAllAsCSV',
'getAllAsXLS',
'getAuditForSite',
'getByBaseURL',
'getByID',
'removeSite',
'updateSite',
'createKeyEvent',
'getKeyEventsBySiteID',
'removeKeyEvent',
'getSiteMetricsBySource',
];
let mockDataAccess;
let sitesController;
let context;
beforeEach(() => {
mockDataAccess = {
Audit: {
findBySiteIdAndAuditTypeAndAuditedAt: sandbox.stub().resolves({
getAuditResult: sandbox.stub().resolves({}),
getAuditType: sandbox.stub().returns('lhs-mobile'),
getAuditedAt: sandbox.stub().returns('2021-01-01T00:00:00.000Z'),
getFullAuditRef: sandbox.stub().returns('https://site1.com/lighthouse/20210101T000000.000Z/lhs-mobile.json'),
getIsError: sandbox.stub().returns(false),
getIsLive: sandbox.stub().returns(true),
getSiteId: sandbox.stub().returns(SITE_IDS[0]),
}),
},
KeyEvent: {
allBySiteId: sandbox.stub().resolves(keyEvents),
findById: stub().resolves(keyEvents[0]),
create: sandbox.stub().resolves(keyEvents[0]),
},
Site: {
all: sandbox.stub().resolves(sites),
allByDeliveryType: sandbox.stub().resolves(sites),
allWithLatestAudit: sandbox.stub().resolves(sites),
create: sandbox.stub().resolves(sites[0]),
findByBaseURL: sandbox.stub().resolves(sites[0]),
findById: sandbox.stub().resolves(sites[0]),
},
};
context = {
runtime: { name: 'aws-lambda', region: 'us-east-1' },
func: { package: 'spacecat-services', version: 'ci', name: 'test' },
rumApiClient: {
query: sandbox.stub(),
},
log: {
info: sandbox.stub(),
error: sandbox.stub(),
},
env: {
DEFAULT_ORGANIZATION_ID: 'default',
},
dataAccess: mockDataAccess,
};
nock('https://secretsmanager.us-east-1.amazonaws.com/')
.post('/', (body) => body.SecretId === '/helix-deploy/spacecat-services/customer-secrets/site1_com/ci')
.reply(200, {
SecretString: JSON.stringify({
RUM_DOMAIN_KEY: '42',
}),
});
sitesController = SitesController(mockDataAccess, console, context.env);
});
afterEach(() => {
sandbox.restore();
});
it('contains all controller functions', () => {
siteFunctions.forEach((funcName) => {
expect(sitesController).to.have.property(funcName);
});
});
it('does not contain any unexpected functions', () => {
Object.keys(sitesController).forEach((funcName) => {
expect(siteFunctions).to.include(funcName);
});
});
it('throws an error if data access is not an object', () => {
expect(() => SitesController()).to.throw('Data access required');
});
it('creates a site', async () => {
const response = await sitesController.createSite({ data: { baseURL: 'https://site1.com' } });
expect(mockDataAccess.Site.create).to.have.been.calledOnce;
expect(response.status).to.equal(201);
const site = await response.json();
expect(site).to.have.property('id', SITE_IDS[0]);
expect(site).to.have.property('baseURL', 'https://site1.com');
});
it('updates a site', async () => {
const site = sites[0];
site.save = sandbox.spy(site.save);
const response = await sitesController.updateSite({
params: { siteId: SITE_IDS[0] },
data: {
organizationId: 'b2c41adf-49c9-4d03-a84f-694491368723',
isLive: false,
deliveryType: 'other',
gitHubURL: 'https://github.com/blah/bluh',
config: {},
hlxConfig: {
field: true,
},
},
});
expect(site.save).to.have.been.calledOnce;
expect(response.status).to.equal(200);
const updatedSite = await response.json();
expect(updatedSite).to.have.property('id', SITE_IDS[0]);
expect(updatedSite).to.have.property('baseURL', 'https://site1.com');
expect(updatedSite).to.have.property('deliveryType', 'other');
expect(updatedSite).to.have.property('gitHubURL', 'https://github.com/blah/bluh');
expect(updatedSite.hlxConfig).to.deep.equal({ field: true });
});
it('returns bad request when updating a site if id not provided', async () => {
const site = sites[0];
site.save = sandbox.spy(site.save);
const response = await sitesController.updateSite({ params: {} });
const error = await response.json();
expect(site.save).to.have.not.been.called;
expect(response.status).to.equal(400);
expect(error).to.have.property('message', 'Site ID required');
});
it('returns not found when updating a non-existing site', async () => {
const site = sites[0];
site.save = sandbox.spy(site.save);
mockDataAccess.Site.findById.resolves(null);
const response = await sitesController.updateSite({ params: { siteId: SITE_IDS[0] } });
const error = await response.json();
expect(site.save).to.have.not.been.called;
expect(response.status).to.equal(404);
expect(error).to.have.property('message', 'Site not found');
});
it('returns bad request when updating a site without payload', async () => {
const site = sites[0];
site.save = sandbox.spy(site.save);
const response = await sitesController.updateSite({ params: { siteId: SITE_IDS[0] } });
const error = await response.json();
expect(site.save).to.have.not.been.called;
expect(response.status).to.equal(400);
expect(error).to.have.property('message', 'Request body required');
});
it('returns bad request when updating a site without modifications', async () => {
const site = sites[0];
site.save = sandbox.spy(site.save);
const response = await sitesController.updateSite({
params: { siteId: SITE_IDS[0] },
data: {},
});
const error = await response.json();
expect(site.save).to.have.not.been.called;
expect(response.status).to.equal(400);
expect(error).to.have.property('message', 'No updates provided');
});
it('removes a site', async () => {
const site = sites[0];
site.remove = sandbox.stub();
const response = await sitesController.removeSite({ params: { siteId: SITE_IDS[0] } });
expect(site.remove).to.have.been.calledOnce;
expect(response.status).to.equal(204);
});
it('returns bad request when removing a site if id not provided', async () => {
const site = sites[0];
site.remove = sandbox.stub();
const response = await sitesController.removeSite({ params: {} });
const error = await response.json();
expect(site.remove).to.have.not.been.called;
expect(response.status).to.equal(400);
expect(error).to.have.property('message', 'Site ID required');
});
it('returns not found when removing a non-existing site', async () => {
const site = sites[0];
site.remove = sandbox.stub();
mockDataAccess.Site.findById.resolves(null);
const response = await sitesController.removeSite({ params: { siteId: SITE_IDS[0] } });
const error = await response.json();
expect(site.remove).to.have.not.been.called;
expect(response.status).to.equal(404);
expect(error).to.have.property('message', 'Site not found');
});
it('gets all sites', async () => {
mockDataAccess.Site.all.resolves(sites);
const result = await sitesController.getAll();
const resultSites = await result.json();
expect(mockDataAccess.Site.all).to.have.been.calledOnce;
expect(resultSites).to.be.an('array').with.lengthOf(2);
expect(resultSites[0]).to.have.property('id', SITE_IDS[0]);
expect(resultSites[0]).to.have.property('baseURL', 'https://site1.com');
expect(resultSites[1]).to.have.property('id', SITE_IDS[1]);
expect(resultSites[1]).to.have.property('baseURL', 'https://site2.com');
});
it('gets all sites by delivery type', async () => {
mockDataAccess.Site.allByDeliveryType.resolves(sites);
const result = await sitesController.getAllByDeliveryType({ params: { deliveryType: 'aem_edge' } });
const resultSites = await result.json();
expect(mockDataAccess.Site.allByDeliveryType).to.have.been.calledOnce;
expect(resultSites).to.be.an('array').with.lengthOf(2);
expect(resultSites[0]).to.have.property('id', SITE_IDS[0]);
expect(resultSites[0]).to.have.property('deliveryType', 'other');
});
it('gets all sites with latest audit', async () => {
const audit = {
getAuditedAt: () => '2021-01-01T00:00:00.000Z',
getAuditResult: () => ({ totalBlockingTime: 12, thirdPartySummary: [] }),
getAuditType: () => 'lhs-mobile',
getFullAuditRef: () => 'https://site1.com/lighthouse/20210101T000000.000Z/lhs-mobile.json',
getIsError: () => false,
getIsLive: () => true,
getSiteId: () => SITE_IDS[0],
};
sites.forEach((site) => {
// eslint-disable-next-line no-param-reassign
site.getLatestAuditByAuditType = sandbox.stub().resolves(audit);
});
const result = await sitesController.getAllWithLatestAudit({ params: { auditType: 'lhs-mobile' } });
const resultSites = await result.json();
expect(mockDataAccess.Site.allWithLatestAudit).to.have.been.calledOnceWith('lhs-mobile', 'desc');
expect(resultSites).to.be.an('array').with.lengthOf(2);
expect(resultSites[0]).to.have.property('id', SITE_IDS[0]);
expect(resultSites[0]).to.have.property('baseURL', 'https://site1.com');
expect(resultSites[1]).to.have.property('id', SITE_IDS[1]);
expect(resultSites[1]).to.have.property('baseURL', 'https://site2.com');
});
it('gets all sites with latest audit with ascending true', async () => {
await sitesController.getAllWithLatestAudit({ params: { auditType: 'lhs-mobile', ascending: 'true' } });
expect(mockDataAccess.Site.allWithLatestAudit).to.have.been.calledWith('lhs-mobile', 'asc');
});
it('gets all sites with latest audit with ascending false', async () => {
await sitesController.getAllWithLatestAudit({ params: { auditType: 'lhs-mobile', ascending: 'false' } });
expect(mockDataAccess.Site.allWithLatestAudit).to.have.been.calledWith('lhs-mobile', 'desc');
});
it('returns bad request if delivery type is not provided', async () => {
const result = await sitesController.getAllByDeliveryType({ params: {} });
const error = await result.json();
expect(result.status).to.equal(400);
expect(error).to.have.property('message', 'Delivery type required');
});
it('returns bad request if audit type is not provided', async () => {
const result = await sitesController.getAllWithLatestAudit({ params: {} });
const error = await result.json();
expect(result.status).to.equal(400);
expect(error).to.have.property('message', 'Audit type required');
});
it('gets all sites as CSV', async () => {
const result = await sitesController.getAllAsCSV();
// expect(mockDataAccess.getSites.calledOnce).to.be.true;
expect(result).to.not.be.null;
});
it('gets all sites as XLS', async () => {
const result = await sitesController.getAllAsXLS();
// expect(mockDataAccess.getSites.calledOnce).to.be.true;
expect(result).to.not.be.null;
});
it('gets a site by ID', async () => {
const result = await sitesController.getByID({ params: { siteId: SITE_IDS[0] } });
const site = await result.json();
expect(mockDataAccess.Site.findById).to.have.been.calledOnce;
expect(site).to.be.an('object');
expect(site).to.have.property('id', SITE_IDS[0]);
expect(site).to.have.property('baseURL', 'https://site1.com');
});
it('gets a site by base URL', async () => {
const result = await sitesController.getByBaseURL({ params: { baseURL: 'aHR0cHM6Ly9zaXRlMS5jb20K' } });
const site = await result.json();
expect(mockDataAccess.Site.findByBaseURL).to.have.been.calledOnceWith('https://site1.com');
expect(site).to.be.an('object');
expect(site).to.have.property('id', SITE_IDS[0]);
expect(site).to.have.property('baseURL', 'https://site1.com');
});
it('gets the latest site metrics', async () => {
context.rumApiClient.query.onCall(0).resolves({
totalCTR: 0.20,
totalClicks: 4901,
totalPageViews: 24173,
});
context.rumApiClient.query.onCall(1).resolves({
totalCTR: 0.21,
totalClicks: 9723,
totalPageViews: 46944,
});
const storedMetrics = [{
siteId: '123',
source: 'ahrefs',
time: '2023-03-13T00:00:00Z',
metric: 'organic-traffic',
value: 200,
cost: 10,
}];
const getStoredMetrics = sinon.stub();
getStoredMetrics.resolves(storedMetrics);
const sitesControllerMock = await esmock('../../src/controllers/sites.js', {
'@adobe/spacecat-shared-utils': {
getStoredMetrics,
},
});
const result = await (
await sitesControllerMock
.default(mockDataAccess, context.log)
.getLatestSiteMetrics({ ...context, params: { siteId: SITE_IDS[0] } })
);
const metrics = await result.json();
expect(metrics).to.deep.equal({
ctrChange: -5.553712152633755,
pageViewsChange: 6.156954020464625,
projectedTrafficValue: 0.3078477010232313,
});
});
it('gets the latest site metrics with no stored metrics', async () => {
context.rumApiClient.query.onCall(0).resolves({
totalCTR: 0.20,
totalClicks: 4901,
totalPageViews: 24173,
});
context.rumApiClient.query.onCall(1).resolves({
totalCTR: 0.21,
totalClicks: 9723,
totalPageViews: 46944,
});
const storedMetrics = [];
const getStoredMetrics = sinon.stub();
getStoredMetrics.resolves(storedMetrics);
const sitesControllerMock = await esmock('../../src/controllers/sites.js', {
'@adobe/spacecat-shared-utils': {
getStoredMetrics,
},
});
const result = await (
await sitesControllerMock
.default(mockDataAccess, context.log)
.getLatestSiteMetrics({ ...context, params: { siteId: SITE_IDS[0] } })
);
const metrics = await result.json();
expect(metrics).to.deep.equal({
ctrChange: -5.553712152633755,
pageViewsChange: 6.156954020464625,
projectedTrafficValue: 0,
});
});
it('logs info and returns zeroed metrics when rum api key is not found', async () => {
const getRUMDomainKeyStub = sandbox.stub().rejects(
new Error('Error retrieving the domain key for https://example.com. Error: Secrets Manager can\'t find the specified secret.'),
);
const sitesControllerMock = await esmock('../../src/controllers/sites.js', {
'@adobe/spacecat-shared-utils': {
getRUMDomainKey: getRUMDomainKeyStub,
},
});
const result = await (
await sitesControllerMock
.default(mockDataAccess, context.log)
.getLatestSiteMetrics({ ...context, params: { siteId: SITE_IDS[0] } })
);
const metrics = await result.json();
expect(context.log.info).to.have.been.calledWithMatch('No RUM key configured for site 0b4dcf79-fe5f-410b-b11f-641f0bf56da3');
expect(metrics).to.deep.equal({
ctrChange: 0,
pageViewsChange: 0,
projectedTrafficValue: 0,
});
});
it('logs error and returns zeroed metrics when rum query fails', async () => {
const getRUMDomainKeyStub = sandbox.stub().resolves('42');
const rumApiClient = {
query: sandbox.stub().rejects(new Error('RUM query failed')),
};
const sitesControllerMock = await esmock('../../src/controllers/sites.js', {
'@adobe/spacecat-shared-utils': {
getRUMDomainKey: getRUMDomainKeyStub,
},
});
const result = await (
await sitesControllerMock
.default(mockDataAccess, context.log)
.getLatestSiteMetrics({ ...context, params: { siteId: SITE_IDS[0] }, rumApiClient })
);
const metrics = await result.json();
expect(context.log.error).to.have.been.calledWithMatch('Error getting RUM metrics for site 0b4dcf79-fe5f-410b-b11f-641f0bf56da3');
expect(metrics).to.deep.equal({
ctrChange: 0,
pageViewsChange: 0,
projectedTrafficValue: 0,
});
});
it('returns bad request if site ID is not provided', async () => {
const response = await sitesController.getLatestSiteMetrics({
params: {},
});
const error = await response.json();
expect(response.status).to.equal(400);
expect(error).to.have.property('message', 'Site ID required');
});
it('returns not found if site does not exist', async () => {
mockDataAccess.Site.findById.resolves(null);
const response = await sitesController.getLatestSiteMetrics({
params: { siteId: SITE_IDS[0] },
});
const error = await response.json();
expect(response.status).to.equal(404);
expect(error).to.have.property('message', 'Site not found');
});
it('gets specific audit for a site', async () => {
const result = await sitesController.getAuditForSite({
params: {
siteId: SITE_IDS[0],
auditType: 'lhs-mobile',
auditedAt: '2021-01-01T00:00:00.000Z',
},
});
const audit = await result.json();
expect(mockDataAccess.Audit.findBySiteIdAndAuditTypeAndAuditedAt).to.have.been.calledOnce;
expect(audit).to.be.an('object');
expect(audit).to.have.property('siteId', SITE_IDS[0]);
expect(audit).to.have.property('auditType', 'lhs-mobile');
expect(audit).to.have.property('auditedAt', '2021-01-01T00:00:00.000Z');
expect(audit).to.have.property('fullAuditRef', 'https://site1.com/lighthouse/20210101T000000.000Z/lhs-mobile.json');
expect(audit).to.have.property('auditResult');
});
it('returns bad request if site ID is not provided when getting audit for site', async () => {
const result = await sitesController.getAuditForSite({
params: {
auditType: 'lhs-mobile',
auditedAt: '2021-01-01T00:00:00.000Z',
},
});
const error = await result.json();
expect(result.status).to.equal(400);
expect(error).to.have.property('message', 'Site ID required');
});
it('returns bad request if audit type is not provided when getting audit for site', async () => {
const result = await sitesController.getAuditForSite({
params: {
siteId: SITE_IDS[0],
auditedAt: '2021-01-01T00:00:00.000Z',
},
});
const error = await result.json();
expect(result.status).to.equal(400);
expect(error).to.have.property('message', 'Audit type required');
});
it('returns bad request if audit date is not provided when getting audit for site', async () => {
const result = await sitesController.getAuditForSite({
params: {
siteId: SITE_IDS[0],
auditType: 'lhs-mobile',
},
});
const error = await result.json();
expect(result.status).to.equal(400);
expect(error).to.have.property('message', 'Audited at required');
});
it('returns not found if audit for site is not found', async () => {
mockDataAccess.Audit.findBySiteIdAndAuditTypeAndAuditedAt.returns(null);
const result = await sitesController.getAuditForSite({
params: {
siteId: SITE_IDS[0],
auditType: 'lhs-mobile',
auditedAt: '2021-01-01T00:00:00.000Z',
},
});
const error = await result.json();
expect(result.status).to.equal(404);
expect(error).to.have.property('message', 'Audit not found');
});
it('returns not found when site is not found by id', async () => {
mockDataAccess.Site.findById.resolves(null);
const result = await sitesController.getByID({ params: { siteId: SITE_IDS[0] } });
const error = await result.json();
expect(result.status).to.equal(404);
expect(error).to.have.property('message', 'Site not found');
});
it('returns bad request if site ID is not provided', async () => {
const result = await sitesController.getByID({ params: {} });
const error = await result.json();
expect(result.status).to.equal(400);
expect(error).to.have.property('message', 'Site ID required');
});
it('returns 404 when site is not found by baseURL', async () => {
mockDataAccess.Site.findByBaseURL.returns(null);
const result = await sitesController.getByBaseURL({ params: { baseURL: 'https://site1.com' } });
const error = await result.json();
expect(result.status).to.equal(404);
expect(error).to.have.property('message', 'Site not found');
});
it('returns bad request if base URL is not provided', async () => {
const result = await sitesController.getByBaseURL({ params: {} });
const error = await result.json();
expect(result.status).to.equal(400);
expect(error).to.have.property('message', 'Base URL required');
});
it('create key event returns created key event', async () => {
const siteId = sites[0].getId();
const keyEvent = keyEvents[0];
mockDataAccess.KeyEvent.create.withArgs({
siteId, name: keyEvent.getName(), type: keyEvent.getType(), time: keyEvent.getTime(),
}).resolves(keyEvent);
const resp = await (await sitesController.createKeyEvent({
params: { siteId },
data: { name: keyEvent.getName(), type: keyEvent.getType(), time: keyEvent.getTime() },
})).json();
expect(mockDataAccess.KeyEvent.create).to.have.been.calledOnce;
expect(hasText(resp.id)).to.be.true;
expect(resp.name).to.equal(keyEvent.getName());
expect(resp.type).to.equal(keyEvent.getType());
expect(resp.time).to.equal(keyEvent.getTime());
});
it('get key events returns list of key events', async () => {
const site = sites[0];
site.getKeyEvents = sandbox.stub().resolves(keyEvents);
const siteId = sites[0].getId();
mockDataAccess.KeyEvent.allBySiteId.withArgs(siteId).resolves(keyEvents);
const resp = await (await sitesController.getKeyEventsBySiteID({
params: { siteId },
})).json();
expect(site.getKeyEvents).to.have.been.calledOnce;
expect(resp.length).to.equal(keyEvents.length);
});
it('get key events returns bad request when siteId is missing', async () => {
const result = await sitesController.getKeyEventsBySiteID({
params: {},
});
const error = await result.json();
expect(result.status).to.equal(400);
expect(error).to.have.property('message', 'Site ID required');
});
it('get key events returns not found when site is not found', async () => {
const siteId = sites[0].getId();
mockDataAccess.Site.findById.resolves(null);
const result = await sitesController.getKeyEventsBySiteID({
params: { siteId },
});
const error = await result.json();
expect(result.status).to.equal(404);
expect(error).to.have.property('message', 'Site not found');
});
it('remove key events endpoint call', async () => {
const keyEvent = keyEvents[0];
keyEvent.remove = sinon.stub().resolves();
const keyEventId = keyEvent.getId();
await sitesController.removeKeyEvent({
params: { keyEventId },
});
expect(keyEvent.remove).to.have.been.calledOnce;
});
it('remove key events returns bad request when keyEventId is missing', async () => {
const result = await sitesController.removeKeyEvent({
params: {},
});
const error = await result.json();
expect(result.status).to.equal(400);
expect(error).to.have.property('message', 'Key Event ID required');
});
it('remove key events returns not found when key event is not found', async () => {
const keyEventId = 'key-event-id';
mockDataAccess.KeyEvent.findById.resolves(null);
const result = await sitesController.removeKeyEvent({
params: { keyEventId },
});
const error = await result.json();
expect(result.status).to.equal(404);
expect(error).to.have.property('message', 'Key Event not found');
});
it('get site metrics by source returns list of metrics', async () => {
const siteId = sites[0].getId();
const source = 'ahrefs';
const metric = 'organic-traffic';
const storedMetrics = [{
siteId: '123',
source: 'ahrefs',
time: '2023-03-12T00:00:00Z',
metric: 'organic-traffic',
value: 100,
}, {
siteId: '123',
source: 'ahrefs',
time: '2023-03-13T00:00:00Z',
metric: 'organic-traffic',
value: 200,
}];
const getStoredMetrics = sinon.stub();
getStoredMetrics.resolves(storedMetrics);
const sitesControllerMock = await esmock('../../src/controllers/sites.js', {
'@adobe/spacecat-shared-utils': {
getStoredMetrics,
},
});
const resp = await (await sitesControllerMock.default(mockDataAccess).getSiteMetricsBySource({
params: { siteId, source, metric },
log: {
info: sandbox.spy(),
warn: sandbox.spy(),
error: sandbox.spy(),
},
s3: {
s3Client: {
send: sinon.stub(),
},
s3Bucket: 'test-bucket',
region: 'us-west-2',
},
})).json();
expect(resp).to.deep.equal(storedMetrics);
});
it('get site metrics by sources returns bad request when siteId is missing', async () => {
const source = 'ahrefs';
const metric = 'organic-traffic';
const result = await sitesController.getSiteMetricsBySource({
params: { source, metric },
});
const error = await result.json();
expect(result.status).to.equal(400);
expect(error).to.have.property('message', 'Site ID required');
});
it('get site metrics by sources returns bad request when source is missing', async () => {
const siteId = sites[0].getId();
const metric = 'organic-traffic';
const result = await sitesController.getSiteMetricsBySource({
params: { siteId, metric },
});
const error = await result.json();
expect(result.status).to.equal(400);
expect(error).to.have.property('message', 'source required');
});
it('get site metrics by sources returns bad request when metric is missing', async () => {
const siteId = sites[0].getId();
const source = 'ahrefs';
const result = await sitesController.getSiteMetricsBySource({
params: { siteId, source },
});
const error = await result.json();
expect(result.status).to.equal(400);
expect(error).to.have.property('message', 'metric required');
});
it('get site metrics by source returns not found when site is not found', async () => {
const siteId = sites[0].getId();
const source = 'ahrefs';
const metric = 'organic-traffic';
mockDataAccess.Site.findById.resolves(null);
const result = await sitesController.getSiteMetricsBySource({
params: { siteId, source, metric },
});
const error = await result.json();
expect(result.status).to.equal(404);
expect(error).to.have.property('message', 'Site not found');
});
});