Quotes: TestAlpacaStream on a clock of its own

The test's stream trades are Monday 2026-11-09's, and it took the session
from the real clock: since that Monday's close the session reads closed,
the last trade stands for the close, and the test failed (on main too).
Alpaca takes a Now for its clock, and the test sets Monday before the
open, so it passes whatever day it is run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B82eRTXE7MNm3r3hHAmTG2
This commit is contained in:
Claude committed 2026-11-10 16:28:10 +00:00
1 parent 217e672522
commit ef1b9ef035
2 files changed
+17 -3

No files matched your search

+13 -2
View File
@@ -40,6 +40,9 @@ type Alpaca struct {
StreamURL string // AlpacaStream if "" (the feed is added)
DataURL string // AlpacaData if ""
Log func(format string, args ...any)
// Now is the time, by which the session is open or over (nil:
// time.Now; a test's clock)
Now func() time.Time
mu sync.Mutex
wanted map[string]time.Time // when each symbol was last wanted
@@ -49,6 +52,14 @@ type Alpaca struct {
err error // the stream's last failure (nil: connected)
}
// now is the time by a's clock.
func (a *Alpaca) now() time.Time {
if a.Now != nil {
return a.Now()
}
return time.Now()
}
func (a *Alpaca) init() {
if a.wanted == nil {
a.wanted, a.fetched, a.subbed = map[string]time.Time{}, map[string]time.Time{}, map[string]bool{}
@@ -255,7 +266,7 @@ func (a *Alpaca) fetch(ctx context.Context, syms []string) error {
if err := json.Unmarshal(body, &snaps); err != nil {
return fmt.Errorf("Alpaca: %w", err)
}
now := time.Now()
now := a.now()
a.mu.Lock()
for _, s := range syms {
a.fetched[s] = now
@@ -358,7 +369,7 @@ func (a *Alpaca) clock(ctx context.Context) {
defer t.Stop()
n := 0
for {
a.Book.Clock(time.Now())
a.Book.Clock(a.now())
if n++; n%5 == 0 {
var syms []string
for s := range a.following() {
+4 -1
View File
@@ -121,8 +121,11 @@ func TestAlpacaSnapshots(t *testing.T) {
func TestAlpacaStream(t *testing.T) {
srv, subs := fakeAlpaca(t)
ws := "ws" + strings.TrimPrefix(srv.URL, "http") + "/v2/"
// Monday before the open, whenever the test is run: the session not
// over, so no close yet
monday := time.Date(2026, 11, 9, 9, 0, 0, 0, eastern)
a := &Alpaca{Key: "KEY", Secret: "SECRET", Book: NewBook(nil), Pinned: []string{"AAPL"},
DataURL: srv.URL + "/v2/", StreamURL: ws}
DataURL: srv.URL + "/v2/", StreamURL: ws, Now: func() time.Time { return monday }}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go a.Run(ctx)