-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
test-amp-a4a.js
2190 lines (2095 loc) · 86.3 KB
/
test-amp-a4a.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
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
/**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed 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 CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
MockA4AImpl,
TEST_URL,
SIGNATURE_HEADER,
} from './utils';
import {createIframePromise} from '../../../../testing/iframe';
import {
AmpA4A,
RENDERING_TYPE_HEADER,
DEFAULT_SAFEFRAME_VERSION,
SAFEFRAME_VERSION_HEADER,
protectFunctionWrapper,
assignAdUrlToError,
} from '../amp-a4a';
import {FriendlyIframeEmbed} from '../../../../src/friendly-iframe-embed';
import {Signals} from '../../../../src/utils/signals';
import {Xhr} from '../../../../src/service/xhr-impl';
import {Extensions} from '../../../../src/service/extensions-impl';
import {Viewer} from '../../../../src/service/viewer-impl';
import {ampdocServiceFor} from '../../../../src/ampdoc';
import {cancellation} from '../../../../src/error';
import {
data as validCSSAmp,
} from './testdata/valid_css_at_rules_amp.reserialized';
import {data as testFragments} from './testdata/test_fragments';
import {FetchResponseHeaders} from '../../../../src/service/xhr-impl';
import {base64UrlDecodeToBytes} from '../../../../src/utils/base64';
import {utf8Encode} from '../../../../src/utils/bytes';
import {resetScheduledElementForTesting} from '../../../../src/custom-element';
import {urlReplacementsForDoc} from '../../../../src/services';
import {incrementLoadingAds} from '../../../amp-ad/0.1/concurrent-load';
import {platformFor, timerFor} from '../../../../src/services';
import '../../../../extensions/amp-ad/0.1/amp-ad-xorigin-iframe-handler';
import {dev, user} from '../../../../src/log';
import {createElementWithAttributes} from '../../../../src/dom';
import {layoutRectLtwh} from '../../../../src/layout-rect';
import {installDocService} from '../../../../src/service/ampdoc-impl';
import * as sinon from 'sinon';
function setupForAdTesting(fixture) {
installDocService(fixture.win, /* isSingleDoc */ true);
const doc = fixture.doc;
// TODO(a4a-cam@): This is necessary in the short term, until A4A is
// smarter about host document styling. The issue is that it needs to
// inherit the AMP runtime style element in order for shadow DOM-enclosed
// elements to behave properly. So we have to set up a minimal one here.
const ampStyle = doc.createElement('style');
ampStyle.setAttribute('amp-runtime', 'scratch-fortesting');
doc.head.appendChild(ampStyle);
}
describe('amp-a4a', () => {
let sandbox;
let xhrMock;
let xhrMockJson;
let getSigningServiceNamesMock;
let viewerWhenVisibleMock;
let mockResponse;
let onCreativeRenderSpy;
let headers;
beforeEach(() => {
sandbox = sinon.sandbox.create();
xhrMock = sandbox.stub(Xhr.prototype, 'fetch');
xhrMockJson = sandbox.stub(Xhr.prototype, 'fetchJson');
getSigningServiceNamesMock = sandbox.stub(AmpA4A.prototype,
'getSigningServiceNames');
onCreativeRenderSpy =
sandbox.spy(AmpA4A.prototype, 'onCreativeRender');
getSigningServiceNamesMock.returns(['google']);
xhrMockJson.withArgs(
'https://cdn.ampproject.org/amp-ad-verifying-keyset.json',
{
mode: 'cors',
method: 'GET',
ampCors: false,
credentials: 'omit',
}).returns(Promise.resolve({
json() {
return Promise.resolve({keys: [JSON.parse(validCSSAmp.publicKey)]});
},
}));
viewerWhenVisibleMock = sandbox.stub(Viewer.prototype, 'whenFirstVisible');
viewerWhenVisibleMock.returns(Promise.resolve());
mockResponse = {
arrayBuffer() {
return utf8Encode(validCSSAmp.reserialized);
},
bodyUsed: false,
headers: new FetchResponseHeaders({
getResponseHeader(name) {
return headers[name];
},
}),
catch: callback => callback(),
};
headers = {};
headers[SIGNATURE_HEADER] = validCSSAmp.signature;
});
afterEach(() => {
sandbox.restore();
resetScheduledElementForTesting(window, 'amp-a4a');
});
function createA4aElement(doc, opt_rect) {
const element = createElementWithAttributes(doc, 'amp-a4a', {
'width': opt_rect ? String(opt_rect.width) : '200',
'height': opt_rect ? String(opt_rect.height) : '50',
'type': 'adsense',
});
element.getAmpDoc = () => {
const ampdocService = ampdocServiceFor(doc.defaultView);
return ampdocService.getAmpDoc(element);
};
element.isBuilt = () => {return true;};
element.getLayoutBox = () => {
return opt_rect || layoutRectLtwh(0, 0, 200, 50);
};
element.getPageLayoutBox = () => {
return element.getLayoutBox.apply(element, arguments);
};
element.getIntersectionChangeEntry = () => {return null;};
const signals = new Signals();
element.signals = () => signals;
element.renderStarted = () => {
signals.signal('render-start');
};
doc.body.appendChild(element);
return element;
}
function buildCreativeString(opt_additionalInfo) {
const baseTestDoc = testFragments.minimalDocOneStyle;
const offsets = opt_additionalInfo || {};
offsets.ampRuntimeUtf16CharOffsets = [
baseTestDoc.indexOf('<style amp4ads-boilerplate'),
baseTestDoc.lastIndexOf('</script>') + '</script>'.length,
];
const splicePoint = baseTestDoc.indexOf('</body>');
return baseTestDoc.slice(0, splicePoint) +
'<script type="application/json" amp-ad-metadata>' +
JSON.stringify(offsets) + '</script>' +
baseTestDoc.slice(splicePoint);
}
// Checks that element is an amp-ad that is rendered via A4A.
function verifyA4ARender(element) {
expect(element.tagName.toLowerCase()).to.equal('amp-a4a');
expect(element.querySelectorAll('iframe')).to.have.lengthOf(1);
expect(element.querySelector('iframe[name]')).to.not.be.ok;
expect(element.querySelector('iframe[src]')).to.not.be.ok;
const friendlyChild = element.querySelector('iframe[srcdoc]');
expect(friendlyChild).to.be.ok;
expect(friendlyChild.getAttribute('srcdoc')).to.have.string(
'<html ⚡4ads>');
expect(element).to.be.visible;
expect(friendlyChild).to.be.visible;
}
// Checks that element is an amp-ad that is rendered via SafeFrame.
function verifySafeFrameRender(element, sfVersion) {
expect(element.tagName.toLowerCase()).to.equal('amp-a4a');
expect(element).to.be.visible;
expect(element.querySelectorAll('iframe')).to.have.lengthOf(1);
const safeFrameUrl = 'https://tpc.googlesyndication.com/safeframe/' +
sfVersion + '/html/container.html';
const child = element.querySelector(`iframe[src^="${safeFrameUrl}"][name]`);
expect(child).to.be.ok;
const name = child.getAttribute('name');
expect(name).to.match(/[^;]+;\d+;[\s\S]+/);
const re = /^([^;]+);(\d+);([\s\S]*)$/;
const match = re.exec(name);
expect(match).to.be.ok;
const contentLength = Number(match[2]);
const rest = match[3];
expect(rest.length > contentLength).to.be.true;
const data = JSON.parse(rest.substr(contentLength));
expect(data).to.be.ok;
verifyContext(data._context);
}
function verifyContext(context) {
expect(context).to.be.ok;
expect(context.sentinel).to.be.ok;
expect(context.sentinel).to.match(/((\d+)-\d+)/);
}
// Checks that element is an amp-ad that is rendered via nameframe.
function verifyNameFrameRender(element) {
expect(element.tagName.toLowerCase()).to.equal('amp-a4a');
expect(element).to.be.visible;
expect(element.querySelectorAll('iframe')).to.have.lengthOf(1);
const child = element.querySelector('iframe[src][name]');
expect(child).to.be.ok;
expect(child.src).to.match(/^https?:[^?#]+nameframe(\.max)?\.html/);
const nameData = child.getAttribute('name');
expect(nameData).to.be.ok;
verifyNameData(nameData);
expect(child).to.be.visible;
}
function verifyCachedContentIframeRender(element, srcUrl) {
expect(element.tagName.toLowerCase()).to.equal('amp-a4a');
expect(element).to.be.visible;
expect(element.querySelectorAll('iframe')).to.have.lengthOf(1);
const child = element.querySelector('iframe[src]');
expect(child).to.be.ok;
expect(child.src).to.have.string(srcUrl);
const nameData = child.getAttribute('name');
expect(nameData).to.be.ok;
verifyNameData(nameData);
expect(child).to.be.visible;
}
function verifyNameData(nameData) {
let attributes;
expect(() => {attributes = JSON.parse(nameData);}).not.to.throw(Error);
expect(attributes).to.be.ok;
verifyContext(attributes._context);
}
describe('ads are visible', () => {
let a4aElement;
let a4a;
let fixture;
beforeEach(() => {
xhrMock.withArgs(TEST_URL, {
mode: 'cors',
method: 'GET',
credentials: 'include',
}).onFirstCall().returns(Promise.resolve(mockResponse));
return createIframePromise().then(f => {
fixture = f;
setupForAdTesting(fixture);
a4aElement = createA4aElement(fixture.doc);
a4a = new MockA4AImpl(a4aElement);
return fixture;
});
});
it('for SafeFrame rendering case', () => {
// Make sure there's no signature, so that we go down the 3p iframe path.
delete headers[SIGNATURE_HEADER];
// If rendering type is safeframe, we SHOULD attach a SafeFrame.
headers[RENDERING_TYPE_HEADER] = 'safeframe';
a4a.buildCallback();
a4a.onLayoutMeasure();
return a4a.layoutCallback().then(() => {
const child = a4aElement.querySelector('iframe[name]');
expect(child).to.be.ok;
expect(child).to.be.visible;
expect(onCreativeRenderSpy.withArgs(false)).to.be.called;
});
});
it('for ios defaults to SafeFrame rendering', () => {
const platform = platformFor(fixture.win);
sandbox.stub(platform, 'isIos').returns(true);
a4a = new MockA4AImpl(a4aElement);
// Make sure there's no signature, so that we go down the 3p iframe path.
delete headers[SIGNATURE_HEADER];
// Ensure no rendering type header (ios on safari will default to
// safeframe).
delete headers[RENDERING_TYPE_HEADER];
fixture.doc.body.appendChild(a4aElement);
a4a.buildCallback();
a4a.onLayoutMeasure();
return a4a.layoutCallback().then(() => {
// Force vsync system to run all queued tasks, so that DOM mutations
// are actually completed before testing.
a4a.vsync_.runScheduledTasks_();
const child = a4aElement.querySelector('iframe[name]');
expect(child).to.be.ok;
expect(child).to.be.visible;
expect(onCreativeRenderSpy.withArgs(false)).to.be.called;
});
});
it('for cached content iframe rendering case', () => {
// Make sure there's no signature, so that we go down the 3p iframe path.
delete headers[SIGNATURE_HEADER];
a4a.buildCallback();
a4a.onLayoutMeasure();
return a4a.layoutCallback().then(() => {
const child = a4aElement.querySelector('iframe[src]');
expect(child).to.be.ok;
expect(child).to.be.visible;
expect(onCreativeRenderSpy.withArgs(false)).to.be.called;
});
});
it('for A4A friendly iframe rendering case', () => {
expect(a4a.friendlyIframeEmbed_).to.not.exist;
a4a.buildCallback();
a4a.onLayoutMeasure();
return a4a.layoutCallback().then(() => {
const child = a4aElement.querySelector('iframe[srcdoc]');
expect(child).to.be.ok;
expect(child).to.be.visible;
const a4aBody = child.contentDocument.body;
expect(a4aBody).to.be.ok;
expect(a4aBody).to.be.visible;
expect(a4a.friendlyIframeEmbed_).to.exist;
});
});
it('for A4A FIE should wait for initial layout', () => {
let iniLoadResolver;
const iniLoadPromise = new Promise(resolve => {
iniLoadResolver = resolve;
});
const whenIniLoadedStub = sandbox.stub(
FriendlyIframeEmbed.prototype,
'whenIniLoaded',
() => iniLoadPromise);
const lifecycleEventStub = sandbox.stub(
a4a, 'protectedEmitLifecycleEvent_');
a4a.buildCallback();
a4a.onLayoutMeasure();
const layoutPromise = a4a.layoutCallback();
return Promise.resolve().then(() => {
expect(whenIniLoadedStub).to.not.be.called;
iniLoadResolver();
return layoutPromise;
}).then(() => {
expect(a4a.friendlyIframeEmbed_).to.exist;
expect(a4a.friendlyIframeEmbed_.host).to.equal(a4a.element);
expect(whenIniLoadedStub).to.be.calledOnce;
expect(lifecycleEventStub).to.be.calledWith('friendlyIframeIniLoad');
});
});
it('should reset state to null on non-FIE unlayoutCallback', () => {
// Make sure there's no signature, so that we go down the 3p iframe path.
delete headers[SIGNATURE_HEADER];
a4a.buildCallback();
a4a.onLayoutMeasure();
return a4a.layoutCallback().then(() => {
expect(a4aElement.querySelector('iframe[src]')).to.be.ok;
expect(a4a.unlayoutCallback()).to.be.true;
expect(a4aElement.querySelector('iframe[src]')).to.not.be.ok;
});
});
it('should not reset state to null on FIE unlayoutCallback', () => {
a4a.buildCallback();
a4a.onLayoutMeasure();
return a4a.layoutCallback().then(() => {
a4a.vsync_.runScheduledTasks_();
expect(a4a.friendlyIframeEmbed_).to.exist;
const destroySpy = sandbox.spy();
a4a.friendlyIframeEmbed_.destroy = destroySpy;
expect(a4a.unlayoutCallback()).to.be.false;
expect(a4a.friendlyIframeEmbed_).to.exist;
expect(destroySpy).to.not.be.called;
});
});
it('should update embed visibility', () => {
sandbox.stub(a4a, 'isInViewport', () => false);
a4a.buildCallback();
a4a.onLayoutMeasure();
return a4a.layoutCallback().then(() => {
a4a.vsync_.runScheduledTasks_();
expect(a4a.friendlyIframeEmbed_).to.exist;
expect(a4a.friendlyIframeEmbed_.isVisible()).to.be.false;
a4a.viewportCallback(true);
expect(a4a.friendlyIframeEmbed_.isVisible()).to.be.true;
a4a.viewportCallback(false);
expect(a4a.friendlyIframeEmbed_.isVisible()).to.be.false;
a4a.viewportCallback(true);
expect(a4a.friendlyIframeEmbed_.isVisible()).to.be.true;
});
});
});
describe('layoutCallback cancels properly', () => {
let a4aElement;
let a4a;
let fixture;
beforeEach(() => {
xhrMock.withArgs(TEST_URL, {
mode: 'cors',
method: 'GET',
credentials: 'include',
}).onFirstCall().returns(Promise.resolve(mockResponse));
return createIframePromise().then(f => {
fixture = f;
setupForAdTesting(fixture);
a4aElement = createA4aElement(fixture.doc);
a4a = new MockA4AImpl(a4aElement);
return fixture;
});
});
it('when unlayoutCallback called after adPromise', () => {
a4a.buildCallback();
a4a.onLayoutMeasure();
let promiseResolver;
a4a.adPromise_ = new Promise(resolver => {
promiseResolver = resolver;
});
const layoutCallbackPromise = a4a.layoutCallback();
a4a.unlayoutCallback();
const renderNonAmpCreativeSpy = sandbox.spy(
AmpA4A.prototype, 'renderNonAmpCreative_');
promiseResolver();
layoutCallbackPromise.then(() => {
// We should never get in here.
expect(false).to.be.true;
}).catch(err => {
expect(renderNonAmpCreativeSpy).to.not.be.called;
expect(err).to.be.ok;
expect(err.message).to.equal('CANCELLED');
});
});
it('when unlayoutCallback called before renderAmpCreative_', () => {
a4a.buildCallback();
a4a.onLayoutMeasure();
let promiseResolver;
a4a.renderAmpCreative_ = new Promise(resolver => {
promiseResolver = resolver;
});
const layoutCallbackPromise = a4a.layoutCallback();
a4a.unlayoutCallback();
promiseResolver();
layoutCallbackPromise.then(() => {
// We should never get in here.
expect(false).to.be.true;
}).catch(err => {
expect(err).to.be.ok;
expect(err.message).to.equal('CANCELLED');
});
});
});
describe('cross-domain rendering', () => {
let a4aElement;
let a4a;
beforeEach(() => {
// Make sure there's no signature, so that we go down the 3p iframe path.
delete headers[SIGNATURE_HEADER];
// If rendering type is safeframe, we SHOULD attach a SafeFrame.
headers[RENDERING_TYPE_HEADER] = 'safeframe';
xhrMock.withArgs(TEST_URL, {
mode: 'cors',
method: 'GET',
credentials: 'include',
}).onFirstCall().returns(Promise.resolve(mockResponse));
return createIframePromise().then(fixture => {
setupForAdTesting(fixture);
const doc = fixture.doc;
a4aElement = createA4aElement(doc);
a4a = new MockA4AImpl(a4aElement);
a4a.createdCallback();
a4a.firstAttachedCallback();
a4a.buildCallback();
expect(onCreativeRenderSpy).to.not.be.called;
});
});
describe('illegal render mode value', () => {
let devErrLogSpy;
beforeEach(() => {
devErrLogSpy = sandbox.spy(dev(), 'error');
// If rendering type is unknown, should fall back to cached content
// iframe and generate an error.
headers[RENDERING_TYPE_HEADER] = 'random illegal value';
a4a.onLayoutMeasure();
});
it('should render via cached iframe', () => {
return a4a.layoutCallback().then(() => {
verifyCachedContentIframeRender(a4aElement, TEST_URL);
// Should have reported an error.
expect(devErrLogSpy).to.be.calledOnce;
expect(devErrLogSpy.getCall(0).args[1]).to.have.string(
'random illegal value');
expect(xhrMock).to.be.calledOnce;
});
});
});
describe('#renderViaNameFrame', () => {
beforeEach(() => {
// If rendering type is nameframe, we SHOULD attach a NameFrame.
headers[RENDERING_TYPE_HEADER] = 'nameframe';
a4a.onLayoutMeasure();
});
it('should attach a NameFrame when header is set', () => {
return a4a.layoutCallback().then(() => {
// Force vsync system to run all queued tasks, so that DOM mutations
// are actually completed before testing.
a4a.vsync_.runScheduledTasks_();
verifyNameFrameRender(a4aElement);
expect(xhrMock).to.be.calledOnce;
});
});
it('should make only one NameFrame even if onLayoutMeasure called ' +
'multiple times', () => {
a4a.onLayoutMeasure();
a4a.onLayoutMeasure();
a4a.onLayoutMeasure();
a4a.onLayoutMeasure();
return a4a.layoutCallback().then(() => {
// Force vsync system to run all queued tasks, so that DOM mutations
// are actually completed before testing.
a4a.vsync_.runScheduledTasks_();
verifyNameFrameRender(a4aElement);
expect(xhrMock).to.be.calledOnce;
});
});
['', 'client_cache', 'safeframe', 'some_random_thing'].forEach(
headerVal => {
it(`should not attach a NameFrame when header is ${headerVal}`,
() => {
// Make sure there's no signature, so that we go down the 3p iframe path.
delete headers[SIGNATURE_HEADER];
// If rendering type is anything but nameframe, we SHOULD NOT
// attach a NameFrame.
headers[RENDERING_TYPE_HEADER] = headerVal;
a4a.onLayoutMeasure();
return a4a.layoutCallback().then(() => {
// Force vsync system to run all queued tasks, so that
// DOM mutations are actually completed before testing.
a4a.vsync_.runScheduledTasks_();
const nameChild = a4aElement.querySelector(
'iframe[src^="nameframe"]');
expect(nameChild).to.not.be.ok;
if (headerVal != 'safeframe') {
const unsafeChild = a4aElement.querySelector('iframe');
expect(unsafeChild).to.be.ok;
expect(unsafeChild.getAttribute('src')).to.have.string(
TEST_URL);
}
expect(xhrMock).to.be.calledOnce;
});
});
});
});
describe('#renderViaSafeFrame', () => {
beforeEach(() => {
// If rendering type is safeframe, we SHOULD attach a SafeFrame.
headers[RENDERING_TYPE_HEADER] = 'safeframe';
a4a.onLayoutMeasure();
});
it('should attach a SafeFrame when header is set', () => {
return a4a.layoutCallback().then(() => {
// Force vsync system to run all queued tasks, so that DOM mutations
// are actually completed before testing.
a4a.vsync_.runScheduledTasks_();
verifySafeFrameRender(a4aElement, DEFAULT_SAFEFRAME_VERSION);
expect(xhrMock).to.be.calledOnce;
});
});
it('should use safeframe version header value', () => {
a4a.safeframeVersion_ = '1-2-3';
return a4a.layoutCallback().then(() => {
// Force vsync system to run all queued tasks, so that DOM mutations
// are actually completed before testing.
a4a.vsync_.runScheduledTasks_();
verifySafeFrameRender(a4aElement, '1-2-3');
expect(xhrMock).to.be.calledOnce;
});
});
it('should make only one SafeFrame even if onLayoutMeasure called ' +
'multiple times', () => {
a4a.onLayoutMeasure();
a4a.onLayoutMeasure();
a4a.onLayoutMeasure();
a4a.onLayoutMeasure();
return a4a.layoutCallback().then(() => {
// Force vsync system to run all queued tasks, so that DOM mutations
// are actually completed before testing.
a4a.vsync_.runScheduledTasks_();
verifySafeFrameRender(a4aElement, DEFAULT_SAFEFRAME_VERSION);
expect(xhrMock).to.be.calledOnce;
});
});
['', 'client_cache', 'nameframe', 'some_random_thing'].forEach(
headerVal => {
it(`should not attach a SafeFrame when header is ${headerVal}`,
() => {
// If rendering type is anything but safeframe, we SHOULD NOT attach a
// SafeFrame.
headers[RENDERING_TYPE_HEADER] = headerVal;
a4a.onLayoutMeasure();
return a4a.layoutCallback().then(() => {
// Force vsync system to run all queued tasks, so that
// DOM mutations are actually completed before testing.
a4a.vsync_.runScheduledTasks_();
const safeframeUrl = 'https://tpc.googlesyndication.com/safeframe/' +
DEFAULT_SAFEFRAME_VERSION + '/html/container.html';
const safeChild = a4aElement.querySelector(
`iframe[src^="${safeframeUrl}"]`);
expect(safeChild).to.not.be.ok;
if (headerVal != 'nameframe') {
const unsafeChild = a4aElement.querySelector('iframe');
expect(unsafeChild).to.be.ok;
expect(unsafeChild.getAttribute('src')).to.have.string(
TEST_URL);
}
expect(xhrMock).to.be.calledOnce;
});
});
});
it('should reset state to null on unlayoutCallback', () => {
return a4a.layoutCallback().then(() => {
// Force vsync system to run all queued tasks, so that DOM mutations
// are actually completed before testing.
a4a.vsync_.runScheduledTasks_();
expect(a4a.experimentalNonAmpCreativeRenderMethod_)
.to.equal('safeframe');
a4a.unlayoutCallback();
// QUESTION TO REVIEWERS: Do we really need the vsync.mutate in
// AmpA4A.unlayoutCallback? We have an open question there about
// whether it's necessary or perhaps hazardous. Feedback welcome.
a4a.vsync_.runScheduledTasks_();
expect(a4a.experimentalNonAmpCreativeRenderMethod_).to.be.null;
expect(xhrMock).to.be.calledOnce;
});
});
});
});
describe('cross-domain vs A4A', () => {
let a4a;
let a4aElement;
beforeEach(() => {
xhrMock.withArgs(TEST_URL, {
mode: 'cors',
method: 'GET',
credentials: 'include',
}).onFirstCall().returns(Promise.resolve(mockResponse));
return createIframePromise().then(fixture => {
setupForAdTesting(fixture);
const doc = fixture.doc;
a4aElement = createA4aElement(doc);
a4a = new MockA4AImpl(a4aElement);
});
});
afterEach(() => {
expect(xhrMock).to.be.calledOnce;
});
['nameframe', 'safeframe'].forEach(renderType => {
it(`should not use ${renderType} if creative is A4A`, () => {
headers[RENDERING_TYPE_HEADER] = renderType;
a4a.buildCallback();
a4a.onLayoutMeasure();
return a4a.layoutCallback().then(() => {
// Force vsync system to run all queued tasks, so that DOM mutations
// are actually completed before testing.
a4a.vsync_.runScheduledTasks_();
verifyA4ARender(a4aElement);
});
});
it(`should not use ${renderType} even if onLayoutMeasure called ` +
'multiple times', () => {
headers[RENDERING_TYPE_HEADER] = renderType;
a4a.buildCallback();
a4a.onLayoutMeasure();
a4a.onLayoutMeasure();
a4a.onLayoutMeasure();
a4a.onLayoutMeasure();
return a4a.layoutCallback().then(() => {
const safeChild = a4aElement.querySelector('iframe[name]');
expect(safeChild).to.not.be.ok;
const crossDomainChild = a4aElement.querySelector('iframe[src]');
expect(crossDomainChild).to.not.be.okay;
const friendlyChild = a4aElement.querySelector('iframe[srcdoc]');
expect(friendlyChild).to.be.ok;
expect(friendlyChild.getAttribute('srcdoc')).to.have.string(
'<html ⚡4ads>');
});
});
});
it('should set height/width on iframe matching header value', () => {
// Make sure there's no signature, so that we go down the 3p iframe path.
delete headers[SIGNATURE_HEADER];
headers['X-CreativeSize'] = '320x50';
xhrMock.withArgs(TEST_URL, {
mode: 'cors',
method: 'GET',
credentials: 'include',
requireAmpResponseSourceOrigin: true,
}).onFirstCall().returns(Promise.resolve(mockResponse));
return createIframePromise().then(fixture => {
setupForAdTesting(fixture);
const doc = fixture.doc;
const a4aElement = createA4aElement(doc);
a4aElement.setAttribute('width', 480);
a4aElement.setAttribute('height', 75);
a4aElement.setAttribute('type', 'doubleclick');
const a4a = new MockA4AImpl(a4aElement);
doc.body.appendChild(a4aElement);
a4a.buildCallback();
a4a.onLayoutMeasure();
const renderPromise = a4a.layoutCallback();
return renderPromise.then(() => {
// Force vsync system to run all queued tasks, so that DOM mutations
// are actually completed before testing.
a4a.vsync_.runScheduledTasks_();
const child = a4aElement.querySelector('iframe[name]');
expect(child).to.be.ok;
expect(child.getAttribute('width')).to.equal('320');
expect(child.getAttribute('height')).to.equal('50');
});
});
});
});
describe('#onLayoutMeasure', () => {
it('resumeCallback calls onLayoutMeasure', () => {
// Force non-FIE
delete headers[SIGNATURE_HEADER];
xhrMock.onFirstCall().returns(Promise.resolve(mockResponse));
return createIframePromise().then(fixture => {
setupForAdTesting(fixture);
const doc = fixture.doc;
const a4aElement = createA4aElement(doc);
const s = doc.createElement('style');
s.textContent = '.fixed {position:fixed;}';
doc.head.appendChild(s);
const a4a = new MockA4AImpl(a4aElement);
const renderNonAmpCreativeSpy =
sandbox.spy(a4a, 'renderNonAmpCreative_');
a4a.buildCallback();
a4a.onLayoutMeasure();
expect(a4a.adPromise_).to.be.ok;
return a4a.layoutCallback().then(() => {
expect(renderNonAmpCreativeSpy.calledOnce,
'renderNonAmpCreative_ called exactly once').to.be.true;
a4a.unlayoutCallback();
sandbox.stub(AmpA4A.prototype, 'getResource').returns(
{'hasBeenMeasured': () => true, 'isMeasureRequested': () => false});
const onLayoutMeasureSpy = sandbox.spy(a4a, 'onLayoutMeasure');
a4a.resumeCallback();
expect(onLayoutMeasureSpy).to.be.calledOnce;
expect(a4a.fromResumeCallback).to.be.true;
});
});
});
it('resumeCallback does not call onLayoutMeasure for FIE', () => {
xhrMock.onFirstCall().returns(Promise.resolve(mockResponse));
return createIframePromise().then(fixture => {
setupForAdTesting(fixture);
const doc = fixture.doc;
const a4aElement = createA4aElement(doc);
const s = doc.createElement('style');
s.textContent = '.fixed {position:fixed;}';
doc.head.appendChild(s);
const a4a = new MockA4AImpl(a4aElement);
const renderAmpCreativeSpy = sandbox.spy(a4a, 'renderAmpCreative_');
a4a.buildCallback();
a4a.onLayoutMeasure();
expect(a4a.adPromise_).to.be.ok;
return a4a.layoutCallback().then(() => {
expect(renderAmpCreativeSpy.calledOnce,
'renderAmpCreative_ called exactly once').to.be.true;
a4a.unlayoutCallback();
const onLayoutMeasureSpy = sandbox.spy(a4a, 'onLayoutMeasure');
a4a.resumeCallback();
expect(onLayoutMeasureSpy).to.not.be.called;
expect(a4a.fromResumeCallback).to.be.false;
});
});
});
it('resumeCallback w/ measure required no onLayoutMeasure', () => {
// Force non-FIE
delete headers[SIGNATURE_HEADER];
xhrMock.onFirstCall().returns(Promise.resolve(mockResponse));
return createIframePromise().then(fixture => {
setupForAdTesting(fixture);
const doc = fixture.doc;
const a4aElement = createA4aElement(doc);
const s = doc.createElement('style');
s.textContent = '.fixed {position:fixed;}';
doc.head.appendChild(s);
const a4a = new MockA4AImpl(a4aElement);
const renderNonAmpCreativeSpy =
sandbox.spy(a4a, 'renderNonAmpCreative_');
a4a.buildCallback();
a4a.onLayoutMeasure();
expect(a4a.adPromise_).to.be.ok;
return a4a.layoutCallback().then(() => {
expect(renderNonAmpCreativeSpy.calledOnce,
'renderNonAmpCreative_ called exactly once').to.be.true;
a4a.unlayoutCallback();
const onLayoutMeasureSpy = sandbox.spy(a4a, 'onLayoutMeasure');
sandbox.stub(AmpA4A.prototype, 'getResource').returns(
{'hasBeenMeasured': () => false});
a4a.resumeCallback();
expect(onLayoutMeasureSpy).to.not.be.called;
expect(a4a.fromResumeCallback).to.be.true;
});
});
});
it('should run end-to-end and render in friendly iframe', () => {
xhrMock.withArgs(TEST_URL, {
mode: 'cors',
method: 'GET',
credentials: 'include',
}).onFirstCall().returns(Promise.resolve(mockResponse));
return createIframePromise().then(fixture => {
setupForAdTesting(fixture);
const doc = fixture.doc;
const a4aElement = createA4aElement(doc);
const a4a = new MockA4AImpl(a4aElement);
const getAdUrlSpy = sandbox.spy(a4a, 'getAdUrl');
const updatePriorityStub = sandbox.stub(a4a, 'updatePriority');
const extractCreativeAndSignatureSpy = sandbox.spy(
a4a, 'extractCreativeAndSignature');
const renderAmpCreativeSpy = sandbox.spy(a4a, 'renderAmpCreative_');
const loadExtensionSpy =
sandbox.spy(Extensions.prototype, 'loadExtension');
a4a.buildCallback();
a4a.onLayoutMeasure();
expect(a4a.adPromise_).to.be.instanceof(Promise);
return a4a.adPromise_.then(promiseResult => {
expect(promiseResult).to.be.ok;
expect(promiseResult.minifiedCreative).to.be.ok;
expect(a4a.isVerifiedAmpCreative_).to.be.true;
expect(getAdUrlSpy.calledOnce, 'getAdUrl called exactly once')
.to.be.true;
expect(xhrMock.calledOnce,
'xhr.fetchTextAndHeaders called exactly once').to.be.true;
expect(extractCreativeAndSignatureSpy.calledOnce,
'extractCreativeAndSignatureSpy called exactly once').to.be.true;
expect(loadExtensionSpy.withArgs('amp-font')).to.be.calledOnce;
return a4a.layoutCallback().then(() => {
expect(renderAmpCreativeSpy.calledOnce,
'renderAmpCreative_ called exactly once').to.be.true;
expect(a4aElement.getElementsByTagName('iframe').length)
.to.equal(1);
const friendlyIframe = a4aElement.querySelector('iframe[srcdoc]');
expect(friendlyIframe).to.not.be.null;
expect(friendlyIframe.getAttribute('src')).to.be.null;
const expectedAttributes = {
'frameborder': '0', 'allowfullscreen': '',
'allowtransparency': '', 'scrolling': 'no'};
Object.keys(expectedAttributes).forEach(key => {
expect(friendlyIframe.getAttribute(key)).to.equal(
expectedAttributes[key]);
});
// Should not contain v0.js, any extensions, or amp-boilerplate.
const iframeDoc = friendlyIframe.contentDocument;
expect(iframeDoc.querySelector('script[src]')).to.not.be.ok;
expect(iframeDoc.querySelector('script[custom-element]'))
.to.not.be.ok;
expect(iframeDoc.querySelector('style[amp-boilerplate]'))
.to.not.be.ok;
expect(iframeDoc.querySelector('noscript')).to.not.be.ok;
// Should contain font link and extension in main document.
expect(iframeDoc.querySelector(
'link[href="https://fonts.googleapis.com/css?family=Questrial"]'))
.to.be.ok;
expect(doc.querySelector('script[src*="amp-font-0.1"]')).to.be.ok;
expect(onCreativeRenderSpy).to.be.calledOnce;
expect(updatePriorityStub).to.be.calledOnce;
expect(updatePriorityStub.args[0][0]).to.equal(0);
});
});
});
});
it('must not be position:fixed', () => {
xhrMock.onFirstCall().returns(Promise.resolve(mockResponse));
return createIframePromise().then(fixture => {
setupForAdTesting(fixture);
const doc = fixture.doc;
const a4aElement = createA4aElement(doc);
const s = doc.createElement('style');
s.textContent = '.fixed {position:fixed;}';
doc.head.appendChild(s);
a4aElement.className = 'fixed';
const a4a = new MockA4AImpl(a4aElement);
a4a.onLayoutMeasure();
expect(a4a.adPromise_).to.not.be.ok;
});
});
it('does not initialize promise chain 0 height/width', () => {
xhrMock.onFirstCall().returns(Promise.resolve(mockResponse));
return createIframePromise().then(fixture => {
setupForAdTesting(fixture);
const doc = fixture.doc;
const rect = layoutRectLtwh(0, 0, 200, 0);
const a4aElement = createA4aElement(doc, rect);
const a4a = new MockA4AImpl(a4aElement);
// test 0 height
a4a.onLayoutMeasure();
expect(a4a.adPromise_).to.not.be.ok;
// test 0 width
rect.height = 50;
rect.width = 0;
a4a.onLayoutMeasure();
expect(a4a.adPromise_).to.not.be.ok;
// test with non-zero height/width
rect.width = 200;
a4a.onLayoutMeasure();
expect(a4a.adPromise_).to.be.ok;
});
});
function executeLayoutCallbackTest(isValidCreative, opt_failAmpRender) {
xhrMock.withArgs(TEST_URL, {
mode: 'cors',
method: 'GET',
credentials: 'include',
}).onFirstCall().returns(Promise.resolve(mockResponse));
return createIframePromise().then(fixture => {
setupForAdTesting(fixture);
const doc = fixture.doc;
const a4aElement = createA4aElement(doc);
const a4a = new MockA4AImpl(a4aElement);
const getAdUrlSpy = sandbox.spy(a4a, 'getAdUrl');
const updatePriorityStub = sandbox.stub(a4a, 'updatePriority');
if (!isValidCreative) {
sandbox.stub(a4a, 'extractCreativeAndSignature').returns(
Promise.resolve({creative: mockResponse.arrayBuffer()}));
}
if (opt_failAmpRender) {
sandbox.stub(a4a, 'renderAmpCreative_').returns(
Promise.reject('amp render failure'));
}
a4a.buildCallback();
a4a.onLayoutMeasure();
expect(a4a.adPromise_).to.be.instanceof(Promise);
return a4a.adPromise_.then(promiseResult => {
expect(getAdUrlSpy.calledOnce, 'getAdUrl called exactly once')
.to.be.true;
expect(xhrMock.calledOnce,
'xhr.fetchTextAndHeaders called exactly once').to.be.true;
expect(a4a.isVerifiedAmpCreative_).to.equal(isValidCreative);
if (isValidCreative) {
expect(promiseResult).to.be.ok;
expect(promiseResult.minifiedCreative).to.be.ok;
} else {
expect(promiseResult).to.not.be.ok;
}
return a4a.layoutCallback().then(() => {
expect(a4aElement.getElementsByTagName('iframe').length)
.to.not.equal(0);
const iframe = a4aElement.getElementsByTagName('iframe')[0];
if (isValidCreative && !opt_failAmpRender) {
expect(iframe.getAttribute('src')).to.be.null;
expect(onCreativeRenderSpy.withArgs(true)).to.be.calledOnce;
expect(updatePriorityStub).to.be.calledOnce;
expect(updatePriorityStub.args[0][0]).to.equal(0);
} else {
expect(iframe.getAttribute('srcdoc')).to.be.null;
expect(iframe.src, 'verify iframe src w/ origin').to
.equal(TEST_URL +
'&__amp_source_origin=about%3Asrcdoc');
expect(onCreativeRenderSpy.withArgs(false)).to.be.called;
if (!opt_failAmpRender) {
expect(updatePriorityStub).to.not.be.called;
}
}
});
});
});
}
it('#layoutCallback valid AMP', () => {
return executeLayoutCallbackTest(true);
});
it('#layoutCallback not valid AMP', () => {
return executeLayoutCallbackTest(false);
});
it('#layoutCallback AMP render fail, recover non-AMP', () => {