-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_test.go
More file actions
861 lines (798 loc) · 26.1 KB
/
Copy pathserver_test.go
File metadata and controls
861 lines (798 loc) · 26.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
// Copyright 2026ff novatechflow (Alexander Alten)
// SPDX-License-Identifier: PolyForm-Shield-1.0.0
package main
import (
"net/http"
"net/http/httptest"
"os"
"os/exec"
"strings"
"sync/atomic"
"testing"
"time"
)
func TestParseRetryAfter(t *testing.T) {
cases := []struct {
in string
want time.Duration
}{
{"", 0},
{"30", 30 * time.Second},
{" 5 ", 5 * time.Second},
{"0", 0},
{"-1", 0},
{"garbage", 0},
{http.TimeFormat, 0}, // unparseable as a date -> 0
}
for _, c := range cases {
if got := parseRetryAfter(c.in); got != c.want {
t.Errorf("parseRetryAfter(%q) = %v, want %v", c.in, got, c.want)
}
}
// HTTP-date form: a minute out should land near a minute.
got := parseRetryAfter(time.Now().Add(time.Minute).UTC().Format(http.TimeFormat))
if got < 50*time.Second || got > time.Minute {
t.Errorf("parseRetryAfter(date +1m) = %v, want ~1m", got)
}
// A date in the past must not produce a negative wait.
if got := parseRetryAfter(time.Now().Add(-time.Hour).UTC().Format(http.TimeFormat)); got != 0 {
t.Errorf("parseRetryAfter(past date) = %v, want 0", got)
}
}
func TestPolyRateLimitedBackoff(t *testing.T) {
polyNextAt, polyBackoff = time.Time{}, 0
t.Cleanup(func() { polyNextAt, polyBackoff = time.Time{}, 0 })
// doubles from the floor, then clamps at the ceiling
want := []time.Duration{
polyBackoffMin,
2 * polyBackoffMin,
4 * polyBackoffMin,
8 * polyBackoffMin,
polyBackoffMax,
polyBackoffMax,
}
for i, w := range want {
polyRateLimited(0)
if polyBackoff != w {
t.Fatalf("after %d rate limits: backoff = %v, want %v", i+1, polyBackoff, w)
}
if d := time.Until(polyNextAt); d > w || d < w-time.Second {
t.Fatalf("after %d rate limits: next call in %v, want ~%v", i+1, d, w)
}
}
}
func TestPolyRateLimitedHonoursRetryAfter(t *testing.T) {
polyNextAt, polyBackoff = time.Time{}, 0
t.Cleanup(func() { polyNextAt, polyBackoff = time.Time{}, 0 })
// Retry-After longer than our own backoff wins...
polyRateLimited(polyBackoffMin + time.Minute)
if d := time.Until(polyNextAt); d < polyBackoffMin+50*time.Second {
t.Errorf("next call in %v, want the longer Retry-After", d)
}
// ...and a shorter one does not shorten the backoff.
polyNextAt, polyBackoff = time.Time{}, 0
polyRateLimited(time.Second)
if d := time.Until(polyNextAt); d < polyBackoffMin-time.Second {
t.Errorf("next call in %v, want at least the %v floor", d, polyBackoffMin)
}
}
// End-to-end: a rate-limited data-api must not blank the dashboard, must stop
// calling until the backoff expires, and must say why in the banner.
func TestRefreshFastBacksOffAndKeepsLastPositions(t *testing.T) {
var hits int32
rateLimited := int32(1)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt32(&hits, 1)
if atomic.LoadInt32(&rateLimited) == 1 {
w.Header().Set("Retry-After", "1")
w.WriteHeader(http.StatusTooManyRequests)
return
}
if strings.HasPrefix(r.URL.Path, "/positions") {
w.Write([]byte(`[{"title":"Will Bitcoin win","outcome":"Yes","size":1,"currentValue":2}]`))
return
}
w.Write([]byte(`[]`))
}))
defer srv.Close()
origBase := polyBase
polyBase = srv.URL
cfg = Config{Wallet: "0xtest", CandleDays: 1, Sort: "az"} // no coins -> no market-data calls
polyNextAt, polyBackoff, polyWallet = time.Time{}, 0, ""
lastPositions, lastActivity = nil, nil
t.Cleanup(func() {
polyBase = origBase
cfg, state = Config{}, State{}
polyNextAt, polyBackoff, polyWallet = time.Time{}, 0, ""
lastPositions, lastActivity = nil, nil
})
// First cycle succeeds: we have real positions to protect.
atomic.StoreInt32(&rateLimited, 0)
refreshFast()
if len(state.Positions) != 1 || state.Note != "" {
t.Fatalf("healthy cycle: positions=%d note=%q, want 1 and no note", len(state.Positions), state.Note)
}
// Now the API starts rate limiting. Force the next call to be due.
atomic.StoreInt32(&rateLimited, 1)
polyNextAt = time.Time{}
refreshFast()
if len(state.Positions) != 1 {
t.Errorf("after 429: positions=%d, want the last good ones kept", len(state.Positions))
}
if !strings.Contains(state.Note, "rate limited") {
t.Errorf("after 429: note=%q, want a rate-limit explanation", state.Note)
}
if polyBackoff != polyBackoffMin {
t.Errorf("after 429: backoff=%v, want %v", polyBackoff, polyBackoffMin)
}
// Subsequent cycles inside the backoff window must not touch the API.
before := atomic.LoadInt32(&hits)
refreshFast()
refreshFast()
if got := atomic.LoadInt32(&hits); got != before {
t.Errorf("made %d calls during backoff, want 0", got-before)
}
if len(state.Positions) != 1 || !strings.Contains(state.Note, "rate limited") {
t.Errorf("during backoff: positions=%d note=%q", len(state.Positions), state.Note)
}
// Once the window passes and the API recovers, we resume and clear the note.
atomic.StoreInt32(&rateLimited, 0)
polyNextAt = time.Now().Add(-time.Second)
refreshFast()
if state.Note != "" || polyBackoff != 0 {
t.Errorf("after recovery: note=%q backoff=%v, want cleared", state.Note, polyBackoff)
}
}
func TestFetchPositionsFiltersResolvedLosses(t *testing.T) {
cases := []struct {
name string
body string
want int
}{
{"resolved loss", `[{"size":15,"curPrice":0,"currentValue":0,"percentPnl":-99.9991,"redeemable":true}]`, 0},
{"unresolved zero price", `[{"curPrice":0,"redeemable":false}]`, 1},
{"winner awaiting redemption", `[{"curPrice":1,"redeemable":true}]`, 1},
{"missing resolution flag", `[{"curPrice":0}]`, 1},
{"mixed positions", `[{"curPrice":0,"redeemable":true},{"curPrice":0.68,"redeemable":false},{"curPrice":1,"redeemable":true}]`, 2},
{"empty portfolio", `[]`, 0},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(tc.body))
}))
defer srv.Close()
origBase := polyBase
polyBase = srv.URL
t.Cleanup(func() { polyBase = origBase })
positions, err := fetchPositions("0xtest")
if err != nil {
t.Fatal(err)
}
if len(positions) != tc.want {
t.Fatalf("got %d positions, want %d", len(positions), tc.want)
}
for _, p := range positions {
if p.Redeemable && p.CurPrice == 0 {
t.Error("resolved loss remains visible")
}
}
})
}
}
func TestFetchPositionsSortsByEndTime(t *testing.T) {
// Same calendar day for noon/evening: only gamma's timestamp separates them.
poly := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`[
{"title":"later","conditionId":"0xlater","endDate":"2026-09-01","currentValue":90},
{"title":"undated","conditionId":"0xnone","currentValue":80},
{"title":"evening-big","conditionId":"0xeve","endDate":"2026-08-12","currentValue":70},
{"title":"noon-small","conditionId":"0xnoon","endDate":"2026-08-12","currentValue":5}
]`))
}))
defer poly.Close()
var gammaCalls int
gamma := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gammaCalls++
w.Write([]byte(`[
{"conditionId":"0xlater","endDate":"2026-09-01T16:00:00Z"},
{"conditionId":"0xeve","endDate":"2026-08-12T18:00:00Z"},
{"conditionId":"0xnoon","endDate":"2026-08-12T12:00:00Z"}
]`))
}))
defer gamma.Close()
origPoly, origGamma := polyBase, gammaBase
polyBase, gammaBase = poly.URL, gamma.URL
marketMetadata = map[string]marketMeta{}
t.Cleanup(func() {
polyBase, gammaBase = origPoly, origGamma
marketMetadata = map[string]marketMeta{}
})
got, err := fetchPositions("0xtest")
if err != nil {
t.Fatalf("fetchPositions: %v", err)
}
want := []string{"noon-small", "evening-big", "later", "undated"}
for i, w := range want {
if got[i].Title != w {
t.Errorf("position %d = %q, want %q", i, got[i].Title, w)
}
}
// Second cycle must be served from cache, including the market gamma
// didn't know about.
if _, err := fetchPositions("0xtest"); err != nil {
t.Fatalf("second fetchPositions: %v", err)
}
if gammaCalls != 1 {
t.Errorf("gamma calls = %d, want 1", gammaCalls)
}
}
func TestFetchPositionsAddsBTCPriceToBeat(t *testing.T) {
poly := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`[{"title":"Bitcoin Up or Down - September 12, 8:00AM-12:00PM ET","eventSlug":"btc-updown-4h-1789214400","conditionId":"0xbtc"}]`))
}))
defer poly.Close()
var gammaCalls int
gamma := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gammaCalls++
if gammaCalls == 1 {
w.Write([]byte(`[{"conditionId":"0xbtc","endDate":"2026-09-12T16:00:00Z","events":[{"eventMetadata":{}}]}]`))
return
}
w.Write([]byte(`[{"conditionId":"0xbtc","endDate":"2026-09-12T16:00:00Z","events":[{"eventMetadata":{"priceToBeat":77338.86223947103}}]}]`))
}))
defer gamma.Close()
origPoly, origGamma := polyBase, gammaBase
polyBase, gammaBase = poly.URL, gamma.URL
marketMetadata = map[string]marketMeta{}
t.Cleanup(func() {
polyBase, gammaBase = origPoly, origGamma
marketMetadata = map[string]marketMeta{}
})
first, err := fetchPositions("0xtest")
if err != nil {
t.Fatalf("fetchPositions: %v", err)
}
if first[0].PriceToBeat != nil {
t.Fatalf("price to beat unexpectedly set before Gamma publishes it: %v", *first[0].PriceToBeat)
}
got, err := fetchPositions("0xtest")
if err != nil {
t.Fatalf("second fetchPositions: %v", err)
}
if len(got) != 1 || got[0].PriceToBeat == nil {
t.Fatalf("price to beat missing from position: %+v", got)
}
if want := 77338.86223947103; *got[0].PriceToBeat != want {
t.Errorf("price to beat = %v, want %v", *got[0].PriceToBeat, want)
}
if got[0].EndDate != "2026-09-12T16:00:00Z" {
t.Errorf("end date = %q", got[0].EndDate)
}
if gammaCalls != 2 {
t.Errorf("gamma calls = %d, want retry after missing price", gammaCalls)
}
}
func TestMarketPairsPreserveLegacyOverride(t *testing.T) {
if got := krakenPair(Coin{Sym: "BTC"}); got != "XBTUSD" {
t.Errorf("kraken BTC pair = %q, want XBTUSD", got)
}
c := Coin{Sym: "OLD", Bn: "WIFUSDT"}
if got := krakenPair(c); got != "WIFUSD" {
t.Errorf("legacy Kraken pair = %q, want WIFUSD", got)
}
if got := coinbaseProduct(c); got != "WIF-USD" {
t.Errorf("legacy Coinbase product = %q, want WIF-USD", got)
}
}
func TestFetchMarketCandlesFallsBackToCoinbase(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/0/public/OHLC":
w.WriteHeader(http.StatusUnavailableForLegalReasons)
case r.URL.Path == "/products/BTC-USD/candles":
// Coinbase is newest-first: [time, low, high, open, close, volume].
w.Write([]byte(`[[200,2,4,3,3.5,10],[100,1,3,2,2.5,8]]`))
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
origKraken, origCoinbase := krakenBase, coinbaseBase
krakenBase, coinbaseBase = srv.URL, srv.URL
t.Cleanup(func() { krakenBase, coinbaseBase = origKraken, origCoinbase })
got, source, err := fetchMarketCandles(Coin{Sym: "BTC", ID: "bitcoin"}, 1)
if err != nil {
t.Fatal(err)
}
if source != "coinbase" {
t.Errorf("source = %q, want coinbase", source)
}
if len(got) != 2 || got[0] != (Candle{100000, 2, 3, 1, 2.5}) || got[1][0] != 200000 {
t.Errorf("normalized Coinbase candles = %#v", got)
}
}
func TestFetchKrakenCandlesNormalizesAndSorts(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"error":[],"result":{"BTC/USD":[[200,"3","4","2","3.5","0",1,1],[100,"2","3","1","2.5","0",1,1]],"last":200}}`))
}))
defer srv.Close()
orig := krakenBase
krakenBase = srv.URL
t.Cleanup(func() { krakenBase = orig })
got, err := fetchKrakenCandles(Coin{Sym: "BTC"}, 1)
if err != nil {
t.Fatal(err)
}
if len(got) != 2 || got[0] != (Candle{100000, 2, 3, 1, 2.5}) || got[1][0] != 200000 {
t.Errorf("normalized Kraken candles = %#v", got)
}
}
func TestFetchKrakenPricesBatchesPairs(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
pairs := r.URL.Query().Get("pair")
if !strings.Contains(pairs, "XBTUSD") || !strings.Contains(pairs, "ETHUSD") {
t.Errorf("pair query = %q", pairs)
}
w.Write([]byte(`{"error":[],"result":{"BTC/USD":{"c":["100.5","1"]},"ETH/USD":{"c":["20.25","1"]}}}`))
}))
defer srv.Close()
orig := krakenBase
krakenBase = srv.URL
t.Cleanup(func() { krakenBase = orig })
got, err := fetchKrakenPrices([]Coin{{Sym: "BTC", ID: "bitcoin"}, {Sym: "ETH", ID: "ethereum"}})
if err != nil {
t.Fatal(err)
}
if got["bitcoin"] != 100.5 || got["ethereum"] != 20.25 {
t.Errorf("prices = %#v", got)
}
}
func TestRefreshFastUsesCoinbaseAndKeepsLastPrice(t *testing.T) {
var krakenOK, coinbaseOK atomic.Bool
krakenOK.Store(true)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/0/public/Ticker":
if !krakenOK.Load() {
w.WriteHeader(http.StatusUnavailableForLegalReasons)
return
}
w.Write([]byte(`{"error":[],"result":{"BTC/USD":{"c":["100","1"]}}}`))
case "/products/BTC-USD/ticker":
if !coinbaseOK.Load() {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.Write([]byte(`{"price":"101"}`))
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
origKraken, origCoinbase := krakenBase, coinbaseBase
krakenBase, coinbaseBase = srv.URL, srv.URL
cfg = Config{CandleDays: 1, Sort: "az", Coins: []Coin{{Sym: "BTC", ID: "bitcoin"}}}
marketPrice = map[string]float64{}
t.Cleanup(func() {
krakenBase, coinbaseBase = origKraken, origCoinbase
cfg, state = Config{}, State{}
marketPrice = map[string]float64{}
})
refreshFast()
if got := state.Coins[0].Price; got != 100 {
t.Fatalf("Kraken price = %v, want 100", got)
}
krakenOK.Store(false)
coinbaseOK.Store(true)
refreshFast()
if got := state.Coins[0].Price; got != 101 {
t.Fatalf("Coinbase fallback price = %v, want 101", got)
}
coinbaseOK.Store(false)
refreshFast()
if got := state.Coins[0].Price; got != 101 {
t.Fatalf("price after both providers fail = %v, want last good 101", got)
}
}
func TestCandleChange24(t *testing.T) {
got := candleChange24(110, []Candle{{0, 100, 0, 0, 0}})
if got < 9.999 || got > 10.001 {
t.Errorf("change = %v, want 10%%", got)
}
}
func TestShortURLDropsWallet(t *testing.T) {
in := "https://data-api.polymarket.com/positions?user=0xdeadbeef&limit=100"
if got := shortURL(in); got != "data-api.polymarket.com/positions" {
t.Errorf("shortURL = %q, want the host+path with no query", got)
}
}
func TestDefaultConfigHasNoWallet(t *testing.T) {
if got := defaultConfig().Wallet; got != "" {
t.Errorf("default wallet = %q, want empty", got)
}
}
func TestEnvExampleIsPolymarketCore(t *testing.T) {
b, err := os.ReadFile(".env.example")
if err != nil {
t.Fatal(err)
}
var raw string
for _, line := range strings.Split(string(b), "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "POLYDISPLAY_ASSETS=") {
raw = strings.Trim(strings.TrimPrefix(line, "POLYDISPLAY_ASSETS="), `"'`)
break
}
}
if raw == "" {
t.Fatal(".env.example missing POLYDISPLAY_ASSETS")
}
got := parseAssets(raw)
want := []string{"BTC", "ETH", "SOL", "XRP"}
if len(got) != len(want) {
t.Fatalf("example assets=%d (%v), want the 4 Polymarket names %v", len(got), got, want)
}
for i, sym := range want {
if got[i].Sym != sym {
t.Errorf("example[%d]=%q, want %q", i, got[i].Sym, sym)
}
if got[i].ID == "" {
t.Errorf("example[%d] %s missing coingecko id", i, sym)
}
}
}
func TestDefaultConfigHasNoCoins(t *testing.T) {
if n := len(defaultConfig().Coins); n != 0 {
t.Errorf("default coins=%d, want none (list comes from POLYDISPLAY_ASSETS)", n)
}
}
func TestParseAssets(t *testing.T) {
got := parseAssets("BTC:Bitcoin:bitcoin, ETH:ethereum, TRUMP:Official Trump:official-trump, WIF:dogwifhat:dogwifcoin:WIFUSDT, skipme, :noid")
want := []Coin{
{Sym: "BTC", Name: "Bitcoin", ID: "bitcoin"},
{Sym: "ETH", Name: "ETH", ID: "ethereum"},
{Sym: "TRUMP", Name: "Official Trump", ID: "official-trump"},
{Sym: "WIF", Name: "dogwifhat", ID: "dogwifcoin", Bn: "WIFUSDT"},
}
if len(got) != len(want) {
t.Fatalf("len=%d, want %d: %+v", len(got), len(want), got)
}
for i := range want {
if got[i] != want[i] {
t.Errorf("[%d]=%+v, want %+v", i, got[i], want[i])
}
}
}
func TestListenPort(t *testing.T) {
t.Setenv("POLYDISPLAY_PORT", "")
if p := listenPort(0); p != 8080 {
t.Errorf("empty env, no file: %d, want 8080", p)
}
if p := listenPort(9090); p != 9090 {
t.Errorf("empty env, file 9090: %d", p)
}
t.Setenv("POLYDISPLAY_PORT", "3000")
if p := listenPort(9090); p != 3000 {
t.Errorf("env 3000 should win over file, got %d", p)
}
t.Setenv("POLYDISPLAY_PORT", "nope")
if p := listenPort(0); p != 8080 {
t.Errorf("bad env: %d, want 8080", p)
}
}
func TestCoinsFromEnv(t *testing.T) {
t.Setenv("POLYDISPLAY_ASSETS", "SOL:Solana:solana,XRP:XRP:ripple")
got := coinsFromEnv()
if len(got) != 2 || got[0].Sym != "SOL" || got[1].ID != "ripple" {
t.Fatalf("coinsFromEnv=%+v", got)
}
}
func TestLoadEnvFileDoesNotOverride(t *testing.T) {
dir := t.TempDir()
path := dir + "/.env"
if err := os.WriteFile(path, []byte("POLYDISPLAY_ASSETS=BTC:bitcoin\nCG_DEMO_KEY=fromfile\n"), 0644); err != nil {
t.Fatal(err)
}
t.Setenv("CG_DEMO_KEY", "fromproc")
t.Setenv("POLYDISPLAY_ASSETS", "")
loadEnvFile(path)
if os.Getenv("CG_DEMO_KEY") != "fromproc" {
t.Errorf("CG_DEMO_KEY=%q, want process env to win", os.Getenv("CG_DEMO_KEY"))
}
if os.Getenv("POLYDISPLAY_ASSETS") != "BTC:bitcoin" {
t.Errorf("POLYDISPLAY_ASSETS=%q, want value from file", os.Getenv("POLYDISPLAY_ASSETS"))
}
}
func TestRefreshFastSkipsPolymarketWithoutWallet(t *testing.T) {
var hits int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt32(&hits, 1)
t.Errorf("unexpected call %s", r.URL.Path)
}))
defer srv.Close()
origBase := polyBase
polyBase = srv.URL
cfg = Config{Wallet: " ", CandleDays: 1, Sort: "az"}
polyNextAt, polyBackoff, polyWallet = time.Time{}, 0, "stale"
lastPositions = []Position{{Title: "leftover"}}
lastActivity = []Act{{Title: "leftover"}}
t.Cleanup(func() {
polyBase = origBase
cfg, state = Config{}, State{}
polyNextAt, polyBackoff, polyWallet = time.Time{}, 0, ""
lastPositions, lastActivity = nil, nil
})
refreshFast()
if atomic.LoadInt32(&hits) != 0 {
t.Errorf("called Polymarket %d times with no wallet, want 0", hits)
}
if len(state.Positions) != 0 || len(state.Activity) != 0 {
t.Errorf("positions=%d activity=%d, want both empty", len(state.Positions), len(state.Activity))
}
if state.Wallet != "" || state.Note != "" {
t.Errorf("wallet=%q note=%q, want both empty", state.Wallet, state.Note)
}
}
func binaryLicenseSkip(path string) bool {
i := strings.LastIndex(path, ".")
if i < 0 {
return false
}
switch strings.ToLower(path[i+1:]) {
case "png", "jpg", "jpeg", "gif", "webp", "ico":
return true
default:
return false
}
}
func TestLicenseHeaders(t *testing.T) {
out, err := exec.Command("git", "ls-files").Output()
if err != nil {
t.Fatal(err)
}
plain := "Copyright 2026ff novatechflow (Alexander Alten)"
linked := "Copyright 2026ff [novatechflow](https://www.novatechflow.com) (Alexander Alten)"
for _, path := range strings.Split(strings.TrimSpace(string(out)), "\n") {
if path == "" {
continue
}
b, err := os.ReadFile(path)
if err != nil {
t.Errorf("%s: %v", path, err)
continue
}
if binaryLicenseSkip(path) {
continue
}
s := string(b)
if !strings.Contains(s, plain) && !strings.Contains(s, linked) {
t.Errorf("%s: missing copyright notice", path)
}
}
}
func TestInstallScriptSyntax(t *testing.T) {
for _, sh := range []string{"install.sh"} {
out, err := exec.Command("bash", "-n", sh).CombinedOutput()
if err != nil {
t.Errorf("%s: bash -n: %v\n%s", sh, err, out)
}
}
b, err := os.ReadFile("install.sh")
if err != nil {
t.Fatal(err)
}
s := string(b)
for _, want := range []string{
"POLYMARKET_WALLET",
"darwin) install_macos",
"linux) install_linux",
"https://go.dev/dl/",
".env.example",
"POLYDISPLAY_ASSETS",
"POLYDISPLAY_PIN",
"POLYDISPLAY_TOKEN_SECRET",
"POLYDISPLAY_EXTRA_ASSETS",
"api.coingecko.com/api/v3/search",
"Kraken",
"Coinbase",
} {
if !strings.Contains(s, want) {
t.Errorf("install.sh missing %q", want)
}
}
if strings.Contains(s, "install_windows") {
t.Error("install.sh should not install a Windows service")
}
if strings.Contains(s, "api.binance.com") {
t.Error("install.sh must not probe the geo-blocked Binance API")
}
}
func TestLiveConfigIsGitignored(t *testing.T) {
out, err := exec.Command("git", "check-ignore", "-v", "config.json").Output()
if err != nil {
t.Fatalf("config.json must be gitignored: %v", err)
}
if !strings.Contains(string(out), "config.json") {
t.Errorf("check-ignore: %s", out)
}
if _, err := exec.Command("git", "ls-files", "--error-unmatch", "config.json").Output(); err == nil {
t.Error("config.json is tracked; it must not be")
}
}
func TestAutoThemeFollowsColorScheme(t *testing.T) {
b, err := os.ReadFile("index.html")
if err != nil {
t.Fatal(err)
}
s := string(b)
if !strings.Contains(s, "prefers-color-scheme:light") && !strings.Contains(s, "prefers-color-scheme: light") {
t.Error("index.html missing prefers-color-scheme light palette")
}
if !strings.Contains(s, "--bg:#0b0e13") {
t.Error("dark default palette missing")
}
if !strings.Contains(s, `col=up?"var(--green)":"var(--red)"`) {
t.Error("candles must use theme variables, not hardcoded colors")
}
}
func TestWebManifestContentType(t *testing.T) {
srv := httptest.NewServer(staticHandler())
defer srv.Close()
resp, err := http.Get(srv.URL + "/manifest.webmanifest")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatalf("status %d", resp.StatusCode)
}
ct := resp.Header.Get("Content-Type")
if !strings.HasPrefix(ct, "application/manifest+json") {
t.Errorf("Content-Type=%q, want application/manifest+json", ct)
}
}
func TestPadWebAppIcons(t *testing.T) {
b, err := os.ReadFile("manifest.webmanifest")
if err != nil {
t.Fatal(err)
}
s := string(b)
for _, want := range []string{"/media/icon-192.png", "/media/icon-512.png", `"purpose": "any"`} {
if !strings.Contains(s, want) {
t.Errorf("manifest.webmanifest missing %q", want)
}
}
if strings.Contains(s, "maskable") {
t.Error("do not pre-mask icons; the pad rounds a full-bleed square")
}
html, err := os.ReadFile("index.html")
if err != nil {
t.Fatal(err)
}
h := string(html)
if !strings.Contains(h, `rel="apple-touch-icon"`) || !strings.Contains(h, "/media/icon-180.png") {
t.Error("index.html missing apple-touch-icon 180")
}
if !strings.Contains(h, `rel="manifest"`) || !strings.Contains(h, "/manifest.webmanifest") {
t.Error("index.html missing web app manifest link")
}
for _, p := range []string{"media/icon-180.png", "media/icon-192.png", "media/icon-512.png"} {
if _, err := os.Stat(p); err != nil {
t.Errorf("%s: %v", p, err)
}
}
}
func TestNoAppCacheManifest(t *testing.T) {
b, err := os.ReadFile("index.html")
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(b), `manifest=`) {
t.Error("index.html must not set an AppCache manifest")
}
if _, err := os.Stat("polydisplay.appcache"); err == nil {
t.Error("must not ship an .appcache file")
}
}
func TestIndexExplainsMissingWallet(t *testing.T) {
b, err := os.ReadFile("index.html")
if err != nil {
t.Fatal(err)
}
s := string(b)
if !strings.Contains(s, "No Polymarket wallet") {
t.Error("index.html missing the no-wallet empty state")
}
if !strings.Contains(s, "paste an address") {
t.Error("index.html missing how to add a wallet")
}
}
func TestPnlTodayUsesTwoDecimals(t *testing.T) {
b, err := os.ReadFile("index.html")
if err != nil {
t.Fatal(err)
}
s := string(b)
if !strings.Contains(s, `minimumFractionDigits:2,maximumFractionDigits:2`) {
t.Error("index.html missing fixed two-decimal currency formatter")
}
if !strings.Contains(s, `var day=(p.d1==null)?"—":fmtSignedUsd2(p.d1)`) {
t.Error("P/L today must use the fixed two-decimal formatter")
}
}
func TestIndexShowsPriceToBeatWhenAvailable(t *testing.T) {
b, err := os.ReadFile("index.html")
if err != nil {
t.Fatal(err)
}
s := string(b)
if !strings.Contains(s, `p.priceToBeat!=null&&+p.priceToBeat>0`) {
t.Error("price to beat must only render for a positive API value")
}
if !strings.Contains(s, `price to beat</span><span>'+fmtUsd2(+p.priceToBeat)`) {
t.Error("position card missing formatted price to beat")
}
}
func hourly(vals ...float64) [][2]float64 {
now := float64(time.Now().Unix())
out := make([][2]float64, len(vals))
for i, v := range vals {
out[i] = [2]float64{now - float64(len(vals)-1-i)*3600, v}
}
return out
}
func TestPnlDeltaMatchesPolymarketAnchor(t *testing.T) {
// polymarket.com's 1D series is 24 hourly points spanning 23h, so the day's
// P/L is measured against the point 24 samples back.
series := hourly(10, 12, 20, 25)
d := pnlDelta(series, 3)
if d == nil {
t.Fatal("3-sample delta over a 4-point series must resolve")
}
if *d != 13 { // 25 - 12
t.Errorf("3-sample delta = %v, want 13", *d)
}
if pnlDelta(series, 24) != nil {
t.Error("day delta over a 4-point series must be nil, not the all-time change")
}
}
func TestPnlDeltaSpansExactSeries(t *testing.T) {
// what the feed returns for 30d: exactly 720 hourly points
vals := make([]float64, 720)
for i := range vals {
vals[i] = float64(i)
}
d := pnlDelta(hourly(vals...), 720)
if d == nil || *d != 719 {
t.Errorf("30d delta = %v, want the whole series span (719)", d)
}
}
func TestThinKeepsEnds(t *testing.T) {
in := hourly(make([]float64, 500)...)
for i := range in {
in[i][1] = float64(i)
}
out := thin(in, 120)
if len(out) != 120 {
t.Fatalf("thin returned %d points, want 120", len(out))
}
if out[0] != in[0] || out[len(out)-1] != in[len(in)-1] {
t.Error("thin must keep the first and last point")
}
if got := thin(in[:50], 120); len(got) != 50 {
t.Errorf("thin shortened a series below the cap: %d", len(got))
}
}
func TestBuildPnlUsesSeriesEnd(t *testing.T) {
p := buildPnl(hourly(1, 2, 3))
if p == nil {
t.Fatal("buildPnl returned nil for a non-empty series")
}
if p.Total != 3 {
t.Errorf("Total = %v, want the last series point (3)", p.Total)
}
if buildPnl(nil) != nil {
t.Error("buildPnl must return nil without a series")
}
}