-
Notifications
You must be signed in to change notification settings - Fork 748
/
auction_test.go
1900 lines (1750 loc) · 56.4 KB
/
auction_test.go
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
package openrtb2
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
"github.com/prebid/prebid-server/adapters"
"github.com/prebid/prebid-server/stored_requests"
metrics "github.com/rcrowley/go-metrics"
"github.com/buger/jsonparser"
jsonpatch "github.com/evanphx/json-patch"
"github.com/mxmCherry/openrtb"
analyticsConf "github.com/prebid/prebid-server/analytics/config"
"github.com/prebid/prebid-server/config"
"github.com/prebid/prebid-server/errortypes"
"github.com/prebid/prebid-server/exchange"
"github.com/prebid/prebid-server/openrtb_ext"
"github.com/prebid/prebid-server/pbsmetrics"
"github.com/prebid/prebid-server/stored_requests/backends/empty_fetcher"
"github.com/prebid/prebid-server/util/iputil"
"github.com/stretchr/testify/assert"
)
const maxSize = 1024 * 256
// Struct of data for the general purpose auction tester
type getResponseFromDirectory struct {
dir string
file string
payloadGetter func(*testing.T, []byte) []byte
messageGetter func(*testing.T, []byte) []byte
expectedCode int
aliased bool
disabledBidders []string
adaptersConfig map[string]config.Adapter
accountReq bool
accountDefaultDisabled bool
description string
}
// TestExplicitUserId makes sure that the cookie's ID doesn't override an explicit value sent in the request.
func TestExplicitUserId(t *testing.T) {
cookieName := "userid"
mockId := "12345"
cfg := &config.Configuration{
MaxRequestSize: maxSize,
HostCookie: config.HostCookie{
CookieName: cookieName,
},
}
ex := &mockExchange{}
request := httptest.NewRequest("POST", "/openrtb2/auction", strings.NewReader(`{
"id": "some-request-id",
"site": {
"page": "test.somepage.com"
},
"user": {
"id": "explicit"
},
"imp": [
{
"id": "my-imp-id",
"banner": {
"format": [
{
"w": 300,
"h": 600
}
]
},
"pmp": {
"deals": [
{
"id": "some-deal-id"
}
]
},
"ext": {
"appnexus": {
"placementId": 12883451
}
}
}
]
}`))
request.AddCookie(&http.Cookie{
Name: cookieName,
Value: mockId,
})
// NewMetrics() will create a new go_metrics MetricsEngine, bypassing the need for a crafted configuration set to support it.
// As a side effect this gives us some coverage of the go_metrics piece of the metrics engine.
theMetrics := pbsmetrics.NewMetrics(metrics.NewRegistry(), openrtb_ext.BidderList(), config.DisabledMetrics{})
endpoint, _ := NewEndpoint(ex, newParamsValidator(t), empty_fetcher.EmptyFetcher{}, empty_fetcher.EmptyFetcher{}, empty_fetcher.EmptyFetcher{}, cfg, theMetrics, analyticsConf.NewPBSAnalytics(&config.Analytics{}), map[string]string{}, []byte{}, openrtb_ext.BidderMap)
endpoint(httptest.NewRecorder(), request, nil)
if ex.lastRequest == nil {
t.Fatalf("The request never made it into the Exchange.")
}
if ex.lastRequest.User == nil {
t.Fatalf("The exchange should have received a request with a non-nil user.")
}
if ex.lastRequest.User.ID != "explicit" {
t.Errorf("Bad User ID. Expected explicit, got %s", ex.lastRequest.User.ID)
}
}
// TestGoodRequests makes sure we return 200s on good requests.
func TestGoodRequests(t *testing.T) {
exemplary := &getResponseFromDirectory{
dir: "sample-requests/valid-whole/exemplary",
payloadGetter: getRequestPayload,
messageGetter: nilReturner,
expectedCode: http.StatusOK,
aliased: true,
}
supplementary := &getResponseFromDirectory{
dir: "sample-requests/valid-whole/supplementary",
payloadGetter: noop,
messageGetter: nilReturner,
expectedCode: http.StatusOK,
aliased: true,
}
exemplary.assert(t)
supplementary.assert(t)
}
// TestGoodNativeRequests makes sure we return 200s on well-formed Native requests.
func TestGoodNativeRequests(t *testing.T) {
tests := &getResponseFromDirectory{
dir: "sample-requests/valid-native",
payloadGetter: buildNativeRequest,
messageGetter: nilReturner,
expectedCode: http.StatusOK,
aliased: true,
}
tests.assert(t)
}
// TestBadRequests makes sure we return 400s on bad requests.
func TestBadRequests(t *testing.T) {
// Need to turn off aliases for bad requests as applying the alias can fail on a bad request before the expected error is reached.
tests := &getResponseFromDirectory{
dir: "sample-requests/invalid-whole",
payloadGetter: getRequestPayload,
messageGetter: getMessage,
expectedCode: http.StatusBadRequest,
aliased: false,
}
tests.assert(t)
}
// TestBadRequests makes sure we return 400s on requests with bad Native requests.
func TestBadNativeRequests(t *testing.T) {
tests := &getResponseFromDirectory{
dir: "sample-requests/invalid-native",
payloadGetter: buildNativeRequest,
messageGetter: nilReturner,
expectedCode: http.StatusBadRequest,
aliased: false,
}
tests.assert(t)
}
// TestAliasedRequests makes sure we handle (default) aliased bidders properly
func TestAliasedRequests(t *testing.T) {
tests := &getResponseFromDirectory{
dir: "sample-requests/aliased",
payloadGetter: noop,
messageGetter: nilReturner,
expectedCode: http.StatusOK,
aliased: true,
}
tests.assert(t)
}
// TestDisabledBidders makes sure we don't break when encountering a disabled bidder
func TestDisabledBidders(t *testing.T) {
badTests := &getResponseFromDirectory{
dir: "sample-requests/disabled/bad",
payloadGetter: getRequestPayload,
messageGetter: getMessage,
expectedCode: http.StatusBadRequest,
aliased: false,
disabledBidders: []string{"appnexus", "rubicon"},
adaptersConfig: map[string]config.Adapter{
"appnexus": {Disabled: true},
"rubicon": {Disabled: true},
},
}
goodTests := &getResponseFromDirectory{
dir: "sample-requests/disabled/good",
payloadGetter: noop,
messageGetter: nilReturner,
expectedCode: http.StatusOK,
aliased: false,
disabledBidders: []string{"appnexus", "rubicon"},
adaptersConfig: map[string]config.Adapter{
"appnexus": {Disabled: true},
"rubicon": {Disabled: true},
},
}
badTests.assert(t)
goodTests.assert(t)
}
// TestBlacklistRequests makes sure we return 400s on blacklisted requests.
func TestBlacklistRequests(t *testing.T) {
// Need to turn off aliases for bad requests as applying the alias can fail on a bad request before the expected error is reached.
tests := &getResponseFromDirectory{
dir: "sample-requests/blacklisted",
payloadGetter: getRequestPayload,
messageGetter: getMessage,
expectedCode: http.StatusServiceUnavailable,
aliased: false,
}
tests.assert(t)
}
// TestRejectAccountRequired asserts we return a 400 code on a request that comes with no user id nor app id
// if the `AccountRequired` field in the `config.Configuration` structure is set to true
func TestRejectAccountRequired(t *testing.T) {
tests := []*getResponseFromDirectory{
{
// Account not required and not provided in prebid request
dir: "sample-requests/account-required",
file: "no-acct.json",
payloadGetter: getRequestPayload,
messageGetter: nilReturner,
expectedCode: http.StatusOK,
accountReq: false,
},
{
// Account was required but not provided in prebid request
dir: "sample-requests/account-required",
file: "no-acct.json",
payloadGetter: getRequestPayload,
messageGetter: getMessage,
expectedCode: http.StatusBadRequest,
accountReq: true,
},
{
// Account is required, was provided, not blacklisted, is not defined by host
dir: "sample-requests/account-required",
file: "with-acct.json",
payloadGetter: getRequestPayload,
messageGetter: nilReturner,
expectedCode: http.StatusOK,
aliased: true,
accountReq: true,
},
{
// Account is required, was provided, not blacklisted, is not defined by host
// but strict validation is in force because default account settings are disabled.
dir: "sample-requests/account-required",
file: "with-acct.json",
payloadGetter: getRequestPayload,
messageGetter: nilReturner,
expectedCode: http.StatusBadRequest,
aliased: true,
accountReq: true,
accountDefaultDisabled: true,
},
{
// Account is required, was provided, not blacklisted and is a valid account
dir: "sample-requests/account-required",
file: "valid-acct.json",
payloadGetter: getRequestPayload,
messageGetter: nilReturner,
expectedCode: http.StatusOK,
aliased: true,
accountReq: true,
},
{
// Account is required, was provided in request and is found in the blacklisted accounts map
dir: "sample-requests/blacklisted",
file: "blacklisted-acct.json",
payloadGetter: getRequestPayload,
messageGetter: getMessage,
expectedCode: http.StatusServiceUnavailable,
accountReq: true,
},
}
for _, test := range tests {
test.assert(t)
}
}
// assertResponseFromDirectory makes sure that the payload from each file in dir gets the expected response status code
// from the /openrtb2/auction endpoint.
func (gr *getResponseFromDirectory) assert(t *testing.T) {
//t *testing.T, dir string, payloadGetter func(*testing.T, []byte) []byte, messageGetter func(*testing.T, []byte) []byte, expectedCode int, aliased bool) {
t.Helper()
var filesToAssert []string
if gr.file == "" {
// Append every file found in `gr.dir` to the `filesToAssert` array and test them all
for _, fileInfo := range fetchFiles(t, gr.dir) {
filesToAssert = append(filesToAssert, gr.dir+"/"+fileInfo.Name())
}
} else {
// Just test the single `gr.file`, and not the entirety of files that may be found in `gr.dir`
filesToAssert = append(filesToAssert, gr.dir+"/"+gr.file)
}
var fileData []byte
// Test the one or more test files appended to `filesToAssert`
for _, testFile := range filesToAssert {
fileData = readFile(t, testFile)
code, msg := gr.doRequest(t, gr.payloadGetter(t, fileData))
fmt.Printf("Processing %s\n", testFile)
assertResponseCode(t, testFile, code, gr.expectedCode, msg)
expectMsg := gr.messageGetter(t, fileData)
if gr.description != "" {
if len(expectMsg) > 0 {
assert.Equal(t, string(expectMsg), msg, "Test failed. %s. Filename: \n", gr.description, testFile)
} else {
assert.Equal(t, string(expectMsg), msg, "file %s had bad response body", testFile)
}
}
}
}
// fetchFiles returns a list of the files from dir, or fails the test if an error occurs.
func fetchFiles(t *testing.T, dir string) []os.FileInfo {
t.Helper()
requestFiles, err := ioutil.ReadDir(dir)
if err != nil {
t.Fatalf("Failed to read folder: %s", dir)
}
return requestFiles
}
func readFile(t *testing.T, filename string) []byte {
data, err := ioutil.ReadFile(filename)
if err != nil {
t.Fatalf("Failed to read file %s: %v", filename, err)
}
return data
}
// doRequest populates the app with mock dependencies and sends requestData to the /openrtb2/auction endpoint.
func (gr *getResponseFromDirectory) doRequest(t *testing.T, requestData []byte) (int, string) {
aliasJSON := []byte{}
if gr.aliased {
aliasJSON = []byte(`{"ext":{"prebid":{"aliases": {"test1": "appnexus", "test2": "rubicon", "test3": "openx"}}}}`)
}
disabledBidders := map[string]string{
"indexExchange": "Bidder \"indexExchange\" has been deprecated and is no longer available. Please use bidder \"ix\" and note that the bidder params have changed.",
}
bidderMap := exchange.DisableBidders(getBidderInfos(gr.adaptersConfig, openrtb_ext.BidderList()), disabledBidders)
// NewMetrics() will create a new go_metrics MetricsEngine, bypassing the need for a crafted configuration set to support it.
// As a side effect this gives us some coverage of the go_metrics piece of the metrics engine.
theMetrics := pbsmetrics.NewMetrics(metrics.NewRegistry(), openrtb_ext.BidderList(), config.DisabledMetrics{})
cfg := config.Configuration{
MaxRequestSize: maxSize,
BlacklistedApps: []string{"spam_app"},
BlacklistedAppMap: map[string]bool{"spam_app": true},
BlacklistedAccts: []string{"bad_acct"},
BlacklistedAcctMap: map[string]bool{"bad_acct": true},
AccountRequired: gr.accountReq,
AccountDefaults: config.Account{Disabled: gr.accountDefaultDisabled},
}
assert.NoError(t, cfg.MarshalAccountDefaults())
endpoint, _ := NewEndpoint(
&nobidExchange{},
newParamsValidator(t),
&mockStoredReqFetcher{},
&mockAccountFetcher{},
empty_fetcher.EmptyFetcher{},
&cfg,
theMetrics,
analyticsConf.NewPBSAnalytics(&config.Analytics{}),
disabledBidders,
aliasJSON,
bidderMap,
)
request := httptest.NewRequest("POST", "/openrtb2/auction", bytes.NewReader(requestData))
recorder := httptest.NewRecorder()
endpoint(recorder, request, nil)
return recorder.Code, recorder.Body.String()
}
// TestBadAliasRequests() reuses two requests that would fail anyway. Here, we
// take advantage of our knowledge that processStoredRequests() in auction.go
// processes aliases before it processes stored imps. Changing that order
// would probably cause this test to fail.
func TestBadAliasRequests(t *testing.T) {
doBadAliasRequest(t, "sample-requests/invalid-stored/bad_stored_imp.json", "Invalid request: Invalid JSON in Default Request Settings: invalid character '\"' after object key:value pair at offset 51\n")
doBadAliasRequest(t, "sample-requests/invalid-stored/bad_incoming_imp.json", "Invalid request: Invalid JSON in Incoming Request: invalid character '\"' after object key:value pair at offset 230\n")
}
// doBadAliasRequest() is a customized variation of doRequest(), above
func doBadAliasRequest(t *testing.T, filename string, expectMsg string) {
t.Helper()
fileData := readFile(t, filename)
requestData := getRequestPayload(t, fileData)
// aliasJSON lacks a comma after the "appnexus" entry so is bad JSON
aliasJSON := []byte(`{"ext":{"prebid":{"aliases": {"test1": "appnexus" "test2": "rubicon", "test3": "openx"}}}}`)
disabledBidders := map[string]string{
"indexExchange": "Bidder \"indexExchange\" has been deprecated and is no longer available. Please use bidder \"ix\" and note that the bidder params have changed.",
}
adaptersConfigs := make(map[string]config.Adapter)
bidderMap := exchange.DisableBidders(getBidderInfos(adaptersConfigs, openrtb_ext.BidderList()), disabledBidders)
// NewMetrics() will create a new go_metrics MetricsEngine, bypassing the need for a crafted configuration set to support it.
// As a side effect this gives us some coverage of the go_metrics piece of the metrics engine.
theMetrics := pbsmetrics.NewMetrics(metrics.NewRegistry(), openrtb_ext.BidderList(), config.DisabledMetrics{})
endpoint, _ := NewEndpoint(&nobidExchange{}, newParamsValidator(t), &mockStoredReqFetcher{}, empty_fetcher.EmptyFetcher{}, empty_fetcher.EmptyFetcher{}, &config.Configuration{MaxRequestSize: maxSize}, theMetrics, analyticsConf.NewPBSAnalytics(&config.Analytics{}), disabledBidders, aliasJSON, bidderMap)
request := httptest.NewRequest("POST", "/openrtb2/auction", bytes.NewReader(requestData))
recorder := httptest.NewRecorder()
endpoint(recorder, request, nil)
assertResponseCode(t, filename, recorder.Code, http.StatusBadRequest, recorder.Body.String())
assert.Equal(t, string(expectMsg), recorder.Body.String(), "file %s had bad response body", filename)
}
func newParamsValidator(t *testing.T) openrtb_ext.BidderParamValidator {
paramValidator, err := openrtb_ext.NewBidderParamsValidator("../../static/bidder-params")
if err != nil {
t.Fatalf("Error creating the param validator: %v", err)
}
return paramValidator
}
func assertResponseCode(t *testing.T, filename string, actual int, expected int, msg string) {
t.Helper()
if actual != expected {
t.Errorf("Expected a %d response from %v. Got %d: %s", expected, filename, actual, msg)
}
}
// buildNativeRequest JSON-encodes the nativeData as a string, and puts it into request.imp[0].native.request
// of a request which is valid otherwise.
func buildNativeRequest(t *testing.T, nativeData []byte) []byte {
serialized, err := json.Marshal(string(nativeData))
if err != nil {
t.Fatalf("Failed to string-escape JSON data: %v", err)
}
buf := bytes.NewBuffer(nil)
buf.WriteString(`{"id":"req-id","site":{"page":"some.page.com"},"tmax":500,"imp":[{"id":"some-imp","native":{"request":`)
buf.Write(serialized)
buf.WriteString(`},"ext":{"appnexus":{"placementId":12883451}}}]}`)
return buf.Bytes()
}
func noop(t *testing.T, data []byte) []byte {
return data
}
func nilReturner(t *testing.T, data []byte) []byte {
return nil
}
func getRequestPayload(t *testing.T, example []byte) []byte {
t.Helper()
if value, _, _, err := jsonparser.Get(example, "requestPayload"); err != nil {
t.Fatalf("Error parsing root.requestPayload from request: %v.", err)
} else {
return value
}
return nil
}
// TestNilExchange makes sure we fail when given nil for the Exchange.
func TestNilExchange(t *testing.T) {
// NewMetrics() will create a new go_metrics MetricsEngine, bypassing the need for a crafted configuration set to support it.
// As a side effect this gives us some coverage of the go_metrics piece of the metrics engine.
theMetrics := pbsmetrics.NewMetrics(metrics.NewRegistry(), openrtb_ext.BidderList(), config.DisabledMetrics{})
_, err := NewEndpoint(nil, newParamsValidator(t), empty_fetcher.EmptyFetcher{}, empty_fetcher.EmptyFetcher{}, empty_fetcher.EmptyFetcher{}, &config.Configuration{MaxRequestSize: maxSize}, theMetrics, analyticsConf.NewPBSAnalytics(&config.Analytics{}), map[string]string{}, []byte{}, openrtb_ext.BidderMap)
if err == nil {
t.Errorf("NewEndpoint should return an error when given a nil Exchange.")
}
}
// TestNilValidator makes sure we fail when given nil for the BidderParamValidator.
func TestNilValidator(t *testing.T) {
// NewMetrics() will create a new go_metrics MetricsEngine, bypassing the need for a crafted configuration set to support it.
// As a side effect this gives us some coverage of the go_metrics piece of the metrics engine.
theMetrics := pbsmetrics.NewMetrics(metrics.NewRegistry(), openrtb_ext.BidderList(), config.DisabledMetrics{})
_, err := NewEndpoint(&nobidExchange{}, nil, empty_fetcher.EmptyFetcher{}, empty_fetcher.EmptyFetcher{}, empty_fetcher.EmptyFetcher{}, &config.Configuration{MaxRequestSize: maxSize}, theMetrics, analyticsConf.NewPBSAnalytics(&config.Analytics{}), map[string]string{}, []byte{}, openrtb_ext.BidderMap)
if err == nil {
t.Errorf("NewEndpoint should return an error when given a nil BidderParamValidator.")
}
}
// TestExchangeError makes sure we return a 500 if the exchange auction fails.
func TestExchangeError(t *testing.T) {
// NewMetrics() will create a new go_metrics MetricsEngine, bypassing the need for a crafted configuration set to support it.
// As a side effect this gives us some coverage of the go_metrics piece of the metrics engine.
theMetrics := pbsmetrics.NewMetrics(metrics.NewRegistry(), openrtb_ext.BidderList(), config.DisabledMetrics{})
endpoint, _ := NewEndpoint(&brokenExchange{}, newParamsValidator(t), empty_fetcher.EmptyFetcher{}, empty_fetcher.EmptyFetcher{}, empty_fetcher.EmptyFetcher{}, &config.Configuration{MaxRequestSize: maxSize}, theMetrics, analyticsConf.NewPBSAnalytics(&config.Analytics{}), map[string]string{}, []byte{}, openrtb_ext.BidderMap)
request := httptest.NewRequest("POST", "/openrtb2/auction", strings.NewReader(validRequest(t, "site.json")))
recorder := httptest.NewRecorder()
endpoint(recorder, request, nil)
if recorder.Code != http.StatusInternalServerError {
t.Errorf("Expected status %d. Got %d. Input was: %s", http.StatusInternalServerError, recorder.Code, validRequest(t, "site.json"))
}
}
// TestUserAgentSetting makes sure we read the User-Agent header if it wasn't defined on the request.
func TestUserAgentSetting(t *testing.T) {
httpReq := httptest.NewRequest("POST", "/openrtb2/auction", strings.NewReader(validRequest(t, "site.json")))
httpReq.Header.Set("User-Agent", "foo")
bidReq := &openrtb.BidRequest{}
setUAImplicitly(httpReq, bidReq)
if bidReq.Device == nil {
t.Fatal("bidrequest.device should have been set implicitly.")
}
if bidReq.Device.UA != "foo" {
t.Errorf("bidrequest.device.ua should have been \"foo\". Got %s", bidReq.Device.UA)
}
}
// TestUserAgentOverride makes sure that the explicit UA from the request takes precedence.
func TestUserAgentOverride(t *testing.T) {
httpReq := httptest.NewRequest("POST", "/openrtb2/auction", strings.NewReader(validRequest(t, "site.json")))
httpReq.Header.Set("User-Agent", "foo")
bidReq := &openrtb.BidRequest{
Device: &openrtb.Device{
UA: "bar",
},
}
setUAImplicitly(httpReq, bidReq)
if bidReq.Device.UA != "bar" {
t.Errorf("bidrequest.device.ua should have been \"bar\". Got %s", bidReq.Device.UA)
}
}
func TestAuctionTypeDefault(t *testing.T) {
bidReq := &openrtb.BidRequest{}
setAuctionTypeImplicitly(bidReq)
if bidReq.AT != 1 {
t.Errorf("Expected request.at to be 1. Got %d", bidReq.AT)
}
}
func TestImplicitIPsEndToEnd(t *testing.T) {
testCases := []struct {
description string
reqJSONFile string
xForwardedForHeader string
privateNetworksIPv4 []net.IPNet
privateNetworksIPv6 []net.IPNet
expectedDeviceIPv4 string
expectedDeviceIPv6 string
}{
{
description: "IPv4",
reqJSONFile: "site.json",
xForwardedForHeader: "1.1.1.1",
expectedDeviceIPv4: "1.1.1.1",
},
{
description: "IPv6",
reqJSONFile: "site.json",
xForwardedForHeader: "1111::",
expectedDeviceIPv6: "1111::",
},
{
description: "IPv4 - Defined In Request",
reqJSONFile: "site-has-ipv4.json",
xForwardedForHeader: "1.1.1.1",
expectedDeviceIPv4: "8.8.8.8", // Hardcoded value in test file.
},
{
description: "IPv6 - Defined In Request",
reqJSONFile: "site-has-ipv6.json",
xForwardedForHeader: "1111::",
expectedDeviceIPv6: "8888::", // Hardcoded value in test file.
},
{
description: "IPv4 - Defined In Request - Private Network",
reqJSONFile: "site-has-ipv4.json",
xForwardedForHeader: "1.1.1.1",
privateNetworksIPv4: []net.IPNet{{IP: net.IP{8, 8, 8, 0}, Mask: net.CIDRMask(24, 32)}}, // Hardcoded value in test file.
expectedDeviceIPv4: "1.1.1.1",
},
{
description: "IPv6 - Defined In Request - Private Network",
reqJSONFile: "site-has-ipv6.json",
xForwardedForHeader: "1111::",
privateNetworksIPv6: []net.IPNet{{IP: net.ParseIP("8800::"), Mask: net.CIDRMask(8, 128)}}, // Hardcoded value in test file.
expectedDeviceIPv6: "1111::",
},
}
metrics := pbsmetrics.NewMetrics(metrics.NewRegistry(), openrtb_ext.BidderList(), config.DisabledMetrics{})
for _, test := range testCases {
exchange := &nobidExchange{}
cfg := &config.Configuration{
MaxRequestSize: maxSize,
RequestValidation: config.RequestValidation{
IPv4PrivateNetworksParsed: test.privateNetworksIPv4,
IPv6PrivateNetworksParsed: test.privateNetworksIPv6,
},
}
endpoint, _ := NewEndpoint(exchange, newParamsValidator(t), &mockStoredReqFetcher{}, empty_fetcher.EmptyFetcher{}, empty_fetcher.EmptyFetcher{}, cfg, metrics, analyticsConf.NewPBSAnalytics(&config.Analytics{}), map[string]string{}, []byte{}, openrtb_ext.BidderMap)
httpReq := httptest.NewRequest("POST", "/openrtb2/auction", strings.NewReader(validRequest(t, test.reqJSONFile)))
httpReq.Header.Set("X-Forwarded-For", test.xForwardedForHeader)
endpoint(httptest.NewRecorder(), httpReq, nil)
result := exchange.gotRequest
if !assert.NotEmpty(t, result, test.description+"Request received by the exchange.") {
t.FailNow()
}
assert.Equal(t, test.expectedDeviceIPv4, result.Device.IP, test.description+":ipv4")
assert.Equal(t, test.expectedDeviceIPv6, result.Device.IPv6, test.description+":ipv6")
}
}
func TestImplicitDNT(t *testing.T) {
var (
disabled int8 = 0
enabled int8 = 1
)
testCases := []struct {
description string
dntHeader string
request openrtb.BidRequest
expectedRequest openrtb.BidRequest
}{
{
description: "Device Missing - Not Set In Header",
dntHeader: "",
request: openrtb.BidRequest{},
expectedRequest: openrtb.BidRequest{},
},
{
description: "Device Missing - Set To 0 In Header",
dntHeader: "0",
request: openrtb.BidRequest{},
expectedRequest: openrtb.BidRequest{
Device: &openrtb.Device{
DNT: &disabled,
},
},
},
{
description: "Device Missing - Set To 1 In Header",
dntHeader: "1",
request: openrtb.BidRequest{},
expectedRequest: openrtb.BidRequest{
Device: &openrtb.Device{
DNT: &enabled,
},
},
},
{
description: "Not Set In Request - Not Set In Header",
dntHeader: "",
request: openrtb.BidRequest{
Device: &openrtb.Device{},
},
expectedRequest: openrtb.BidRequest{
Device: &openrtb.Device{},
},
},
{
description: "Not Set In Request - Set To 0 In Header",
dntHeader: "0",
request: openrtb.BidRequest{
Device: &openrtb.Device{},
},
expectedRequest: openrtb.BidRequest{
Device: &openrtb.Device{
DNT: &disabled,
},
},
},
{
description: "Not Set In Request - Set To 1 In Header",
dntHeader: "1",
request: openrtb.BidRequest{
Device: &openrtb.Device{},
},
expectedRequest: openrtb.BidRequest{
Device: &openrtb.Device{
DNT: &enabled,
},
},
},
{
description: "Set In Request - Not Set In Header",
dntHeader: "",
request: openrtb.BidRequest{
Device: &openrtb.Device{
DNT: &enabled,
},
},
expectedRequest: openrtb.BidRequest{
Device: &openrtb.Device{
DNT: &enabled,
},
},
},
{
description: "Set In Request - Set To 0 In Header",
dntHeader: "0",
request: openrtb.BidRequest{
Device: &openrtb.Device{
DNT: &enabled,
},
},
expectedRequest: openrtb.BidRequest{
Device: &openrtb.Device{
DNT: &enabled,
},
},
},
{
description: "Set In Request - Set To 1 In Header",
dntHeader: "1",
request: openrtb.BidRequest{
Device: &openrtb.Device{
DNT: &enabled,
},
},
expectedRequest: openrtb.BidRequest{
Device: &openrtb.Device{
DNT: &enabled,
},
},
},
}
for _, test := range testCases {
httpReq := httptest.NewRequest("POST", "/openrtb2/auction", nil)
httpReq.Header.Set("DNT", test.dntHeader)
setDoNotTrackImplicitly(httpReq, &test.request)
assert.Equal(t, test.expectedRequest, test.request)
}
}
func TestImplicitDNTEndToEnd(t *testing.T) {
var (
disabled int8 = 0
enabled int8 = 1
)
testCases := []struct {
description string
reqJSONFile string
dntHeader string
expectedDNT *int8
}{
{
description: "Not Set In Request - Not Set In Header",
reqJSONFile: "site.json",
dntHeader: "",
expectedDNT: nil,
},
{
description: "Not Set In Request - Set To 0 In Header",
reqJSONFile: "site.json",
dntHeader: "0",
expectedDNT: &disabled,
},
{
description: "Not Set In Request - Set To 1 In Header",
reqJSONFile: "site.json",
dntHeader: "1",
expectedDNT: &enabled,
},
{
description: "Set In Request - Not Set In Header",
reqJSONFile: "site-has-dnt.json",
dntHeader: "",
expectedDNT: &enabled, // Hardcoded value in test file.
},
{
description: "Set In Request - Not Overwritten By Header",
reqJSONFile: "site-has-dnt.json",
dntHeader: "0",
expectedDNT: &enabled, // Hardcoded value in test file.
},
}
metrics := pbsmetrics.NewMetrics(metrics.NewRegistry(), openrtb_ext.BidderList(), config.DisabledMetrics{})
for _, test := range testCases {
exchange := &nobidExchange{}
endpoint, _ := NewEndpoint(exchange, newParamsValidator(t), &mockStoredReqFetcher{}, empty_fetcher.EmptyFetcher{}, empty_fetcher.EmptyFetcher{}, &config.Configuration{MaxRequestSize: maxSize}, metrics, analyticsConf.NewPBSAnalytics(&config.Analytics{}), map[string]string{}, []byte{}, openrtb_ext.BidderMap)
httpReq := httptest.NewRequest("POST", "/openrtb2/auction", strings.NewReader(validRequest(t, test.reqJSONFile)))
httpReq.Header.Set("DNT", test.dntHeader)
endpoint(httptest.NewRecorder(), httpReq, nil)
result := exchange.gotRequest
if !assert.NotEmpty(t, result, test.description+"Request received by the exchange.") {
t.FailNow()
}
assert.Equal(t, test.expectedDNT, result.Device.DNT, test.description+":dnt")
}
}
func TestImplicitSecure(t *testing.T) {
httpReq := httptest.NewRequest("POST", "/openrtb2/auction", strings.NewReader(validRequest(t, "site.json")))
httpReq.Header.Set(http.CanonicalHeaderKey("X-Forwarded-Proto"), "https")
imps := []openrtb.Imp{
{},
{},
}
setImpsImplicitly(httpReq, imps)
for _, imp := range imps {
if imp.Secure == nil || *imp.Secure != 1 {
t.Errorf("imp.Secure should be set to 1 if the request is https. Got %#v", imp.Secure)
}
}
}
func TestRefererParsing(t *testing.T) {
httpReq := httptest.NewRequest("POST", "/openrtb2/auction", strings.NewReader(validRequest(t, "site.json")))
httpReq.Header.Set("Referer", "http://test.mysite.com")
bidReq := &openrtb.BidRequest{}
setSiteImplicitly(httpReq, bidReq)
if bidReq.Site == nil {
t.Fatalf("bidrequest.site should not be nil.")
}
if bidReq.Site.Domain != "mysite.com" {
t.Errorf("Bad bidrequest.site.domain. Expected mysite.com, got %s", bidReq.Site.Domain)
}
if bidReq.Site.Page != "http://test.mysite.com" {
t.Errorf("Bad bidrequest.site.page. Expected mysite.com, got %s", bidReq.Site.Page)
}
}
// TestBadStoredRequests tests diagnostic messages for invalid stored requests
func TestBadStoredRequests(t *testing.T) {
// Need to turn off aliases for bad requests as applying the alias can fail on a bad request before the expected error is reached.
tests := &getResponseFromDirectory{
dir: "sample-requests/invalid-stored",
payloadGetter: getRequestPayload,
messageGetter: getMessage,
expectedCode: http.StatusBadRequest,
aliased: false,
}
tests.assert(t)
}
// Test the stored request functionality
func TestStoredRequests(t *testing.T) {
// NewMetrics() will create a new go_metrics MetricsEngine, bypassing the need for a crafted configuration set to support it.
// As a side effect this gives us some coverage of the go_metrics piece of the metrics engine.
theMetrics := pbsmetrics.NewMetrics(metrics.NewRegistry(), openrtb_ext.BidderList(), config.DisabledMetrics{})
deps := &endpointDeps{
&nobidExchange{},
newParamsValidator(t),
&mockStoredReqFetcher{},
empty_fetcher.EmptyFetcher{},
empty_fetcher.EmptyFetcher{},
empty_fetcher.EmptyFetcher{},
&config.Configuration{MaxRequestSize: maxSize},
theMetrics,
analyticsConf.NewPBSAnalytics(&config.Analytics{}),
map[string]string{},
false,
[]byte{},
openrtb_ext.BidderMap,
nil,
nil,
hardcodedResponseIPValidator{response: true},
}
for i, requestData := range testStoredRequests {
newRequest, errList := deps.processStoredRequests(context.Background(), json.RawMessage(requestData))
if len(errList) != 0 {
for _, err := range errList {
if err != nil {
t.Errorf("processStoredRequests Error: %s", err.Error())
} else {
t.Error("processStoredRequests Error: received nil error")
}
}
}
expectJson := json.RawMessage(testFinalRequests[i])
if !jsonpatch.Equal(newRequest, expectJson) {
t.Errorf("Error in processStoredRequests, test %d failed on compare\nFound:\n%s\nExpected:\n%s", i, string(newRequest), string(expectJson))
}
}
}
// TestOversizedRequest makes sure we behave properly when the request size exceeds the configured max.
func TestOversizedRequest(t *testing.T) {
reqBody := validRequest(t, "site.json")
deps := &endpointDeps{
&nobidExchange{},
newParamsValidator(t),
&mockStoredReqFetcher{},
empty_fetcher.EmptyFetcher{},
empty_fetcher.EmptyFetcher{},
empty_fetcher.EmptyFetcher{},
&config.Configuration{MaxRequestSize: int64(len(reqBody) - 1)},
pbsmetrics.NewMetrics(metrics.NewRegistry(), openrtb_ext.BidderList(), config.DisabledMetrics{}),
analyticsConf.NewPBSAnalytics(&config.Analytics{}),
map[string]string{},
false,
[]byte{},
openrtb_ext.BidderMap,
nil,
nil,
hardcodedResponseIPValidator{response: true},
}
req := httptest.NewRequest("POST", "/openrtb2/auction", strings.NewReader(reqBody))
recorder := httptest.NewRecorder()
deps.Auction(recorder, req, nil)
if recorder.Code != http.StatusBadRequest {
t.Errorf("Endpoint should return a 400 if the request exceeds the size max.")
}
if bytesRead, err := req.Body.Read(make([]byte, 1)); bytesRead != 0 || err != io.EOF {
t.Errorf("The request body should still be fully read.")
}
}
// TestRequestSizeEdgeCase makes sure we behave properly when the request size *equals* the configured max.
func TestRequestSizeEdgeCase(t *testing.T) {
reqBody := validRequest(t, "site.json")
deps := &endpointDeps{
&nobidExchange{},
newParamsValidator(t),
&mockStoredReqFetcher{},
empty_fetcher.EmptyFetcher{},
empty_fetcher.EmptyFetcher{},
empty_fetcher.EmptyFetcher{},
&config.Configuration{MaxRequestSize: int64(len(reqBody))},
pbsmetrics.NewMetrics(metrics.NewRegistry(), openrtb_ext.BidderList(), config.DisabledMetrics{}),
analyticsConf.NewPBSAnalytics(&config.Analytics{}),
map[string]string{},
false,
[]byte{},
openrtb_ext.BidderMap,
nil,
nil,
hardcodedResponseIPValidator{response: true},
}
req := httptest.NewRequest("POST", "/openrtb2/auction", strings.NewReader(reqBody))
recorder := httptest.NewRecorder()
deps.Auction(recorder, req, nil)
if recorder.Code != http.StatusOK {
t.Errorf("Endpoint should return a 200 if the request equals the size max.")
}
if bytesRead, err := req.Body.Read(make([]byte, 1)); bytesRead != 0 || err != io.EOF {
t.Errorf("The request body should have been read to completion.")
}
}
// TestNoEncoding prevents #231.
func TestNoEncoding(t *testing.T) {
endpoint, _ := NewEndpoint(
&mockExchange{},
newParamsValidator(t),
&mockStoredReqFetcher{},
empty_fetcher.EmptyFetcher{},
empty_fetcher.EmptyFetcher{},
&config.Configuration{MaxRequestSize: maxSize},
pbsmetrics.NewMetrics(metrics.NewRegistry(), openrtb_ext.BidderList(), config.DisabledMetrics{}),
analyticsConf.NewPBSAnalytics(&config.Analytics{}),
map[string]string{},
[]byte{},
openrtb_ext.BidderMap,
)