@@ -3,11 +3,20 @@ package telemetry
33import (
44 "bytes"
55 "context"
6+ "encoding/json"
7+ "io"
8+ "net/http"
9+ "net/http/httptest"
10+ "net/url"
11+ "os"
12+ "strings"
13+ "sync/atomic"
614 "testing"
715 "time"
816
917 "github.com/sourcegraph/src-cli/internal/api"
1018 apimock "github.com/sourcegraph/src-cli/internal/api/mock"
19+ "github.com/sourcegraph/src-cli/internal/oauth"
1120
1221 "github.com/sourcegraph/sourcegraph/lib/errors"
1322 "github.com/stretchr/testify/assert"
@@ -18,19 +27,50 @@ func testSource() Source {
1827 return Source {Client : ClientName , ClientVersion : "6.1.0" }
1928}
2029
30+ func response (statusCode int , body string ) * http.Response {
31+ return & http.Response {
32+ StatusCode : statusCode ,
33+ Status : http .StatusText (statusCode ),
34+ Body : io .NopCloser (strings .NewReader (body )),
35+ }
36+ }
37+
38+ type cancellationClient struct {
39+ api.Client
40+ canceled chan struct {}
41+ release chan struct {}
42+ }
43+
44+ func (c * cancellationClient ) NewHTTPRequest (ctx context.Context , method , _ string , body io.Reader ) (* http.Request , error ) {
45+ return http .NewRequestWithContext (ctx , method , "http://example.com/.api/graphql" , body )
46+ }
47+
48+ func (c * cancellationClient ) Do (req * http.Request ) (* http.Response , error ) {
49+ select {
50+ case <- req .Context ().Done ():
51+ close (c .canceled )
52+ return nil , req .Context ().Err ()
53+ case <- c .release :
54+ return nil , errors .New ("test client released" )
55+ }
56+ }
57+
2158func TestRecord_SendsWellFormedMutation (t * testing.T ) {
2259 client := & apimock.Client {}
23- req := & apimock. Request {}
60+ req := httptest . NewRequest ( http . MethodPost , "/.api/graphql" , nil )
2461
25- var gotQuery string
26- var gotVars map [string ]any
27- client .On ("NewRequest" , mock .Anything , mock .Anything ).
62+ var gotPayload struct {
63+ Query string `json:"query"`
64+ Variables map [string ]any `json:"variables"`
65+ }
66+ client .On ("NewHTTPRequest" , mock .Anything , http .MethodPost , ".api/graphql" , mock .Anything ).
2867 Run (func (args mock.Arguments ) {
29- gotQuery = args .Get (0 ).(string )
30- gotVars = args .Get (1 ).(map [string ]any )
68+ if err := json .NewDecoder (args .Get (3 ).(io.Reader )).Decode (& gotPayload ); err != nil {
69+ t .Fatal (err )
70+ }
3171 }).
32- Return (req )
33- req .On ("Do" , mock . Anything , mock . Anything ).Return (true , nil )
72+ Return (req , nil )
73+ client .On ("Do" , req ).Return (response ( http . StatusOK , "{}" ) , nil )
3474
3575 rec := NewRecorder (client , testSource ())
3676 rec .Record (context .Background (), Event {
@@ -39,11 +79,11 @@ func TestRecord_SendsWellFormedMutation(t *testing.T) {
3979 Metadata : map [string ]float64 {"durationMs" : 12 , "exitCode" : 0 },
4080 })
4181
42- assert .Equal (t , recordEventsMutation , gotQuery )
82+ assert .Equal (t , recordEventsMutation , gotPayload . Query )
4383
44- events , ok := gotVars ["events" ].([]any )
84+ events , ok := gotPayload . Variables ["events" ].([]any )
4585 if ! ok || len (events ) != 1 {
46- t .Fatalf ("expected 1 event, got %#v" , gotVars ["events" ])
86+ t .Fatalf ("expected 1 event, got %#v" , gotPayload . Variables ["events" ])
4787 }
4888 event := events [0 ].(map [string ]any )
4989 assert .Equal (t , "srcCli.search" , event ["feature" ])
@@ -54,7 +94,7 @@ func TestRecord_SendsWellFormedMutation(t *testing.T) {
5494 assert .Equal (t , "6.1.0" , source ["clientVersion" ])
5595
5696 params := event ["parameters" ].(map [string ]any )
57- assert .Equal (t , eventParametersVersion , params ["version" ])
97+ assert .Equal (t , float64 ( eventParametersVersion ) , params ["version" ])
5898
5999 metadata := params ["metadata" ].([]any )
60100 // sorted by key: durationMs, exitCode
@@ -64,43 +104,48 @@ func TestRecord_SendsWellFormedMutation(t *testing.T) {
64104 }, metadata )
65105
66106 client .AssertExpectations (t )
67- req .AssertExpectations (t )
68107}
69108
70109func TestRecord_EmptyMetadataSendsEmptyList (t * testing.T ) {
71110 client := & apimock.Client {}
72- req := & apimock. Request {}
111+ req := httptest . NewRequest ( http . MethodPost , "/.api/graphql" , nil )
73112
74- var gotVars map [string ]any
75- client .On ("NewRequest" , mock .Anything , mock .Anything ).
76- Run (func (args mock.Arguments ) { gotVars = args .Get (1 ).(map [string ]any ) }).
77- Return (req )
78- req .On ("Do" , mock .Anything , mock .Anything ).Return (true , nil )
113+ var gotPayload struct {
114+ Variables map [string ]any `json:"variables"`
115+ }
116+ client .On ("NewHTTPRequest" , mock .Anything , http .MethodPost , ".api/graphql" , mock .Anything ).
117+ Run (func (args mock.Arguments ) {
118+ if err := json .NewDecoder (args .Get (3 ).(io.Reader )).Decode (& gotPayload ); err != nil {
119+ t .Fatal (err )
120+ }
121+ }).
122+ Return (req , nil )
123+ client .On ("Do" , req ).Return (response (http .StatusOK , "{}" ), nil )
79124
80125 rec := NewRecorder (client , testSource ())
81126 rec .Record (context .Background (), Event {Feature : "srcCli.version" , Action : "succeeded" })
82127
83- event := gotVars ["events" ].([]any )[0 ].(map [string ]any )
128+ event := gotPayload . Variables ["events" ].([]any )[0 ].(map [string ]any )
84129 params := event ["parameters" ].(map [string ]any )
85130 assert .Equal (t , []any {}, params ["metadata" ])
86131}
87132
88133func TestRecord_ValidationFailsBeforeSending (t * testing.T ) {
89134 client := & apimock.Client {}
90- // No expectations set: NewRequest must never be called.
135+ // No expectations set: NewHTTPRequest must never be called.
91136
92137 rec := NewRecorder (client , testSource ())
93138 err := rec .record (context .Background (), Event {Feature : "Bad_Feature" , Action : "succeeded" })
94139
95140 assert .Error (t , err )
96- client .AssertNotCalled (t , "NewRequest" , mock .Anything , mock .Anything )
141+ client .AssertNotCalled (t , "NewHTTPRequest" , mock . Anything , mock . Anything , mock .Anything , mock .Anything )
97142}
98143
99144func TestRecord_NetworkErrorSwallowed (t * testing.T ) {
100145 client := & apimock.Client {}
101- req := & apimock. Request {}
102- client .On ("NewRequest " , mock .Anything , mock .Anything ).Return (req )
103- req .On ("Do" , mock . Anything , mock . Anything ).Return (false , errors .New ("connection refused" ))
146+ req := httptest . NewRequest ( http . MethodPost , "/.api/graphql" , nil )
147+ client .On ("NewHTTPRequest " , mock .Anything , http . MethodPost , ".api/graphql" , mock .Anything ).Return (req , nil )
148+ client .On ("Do" , req ).Return (nil , errors .New ("connection refused" ))
104149
105150 var debug bytes.Buffer
106151 rec := NewRecorder (client , testSource (), WithDebug (& debug ))
@@ -120,10 +165,9 @@ func TestRecord_GraphQLErrorSwallowed(t *testing.T) {
120165 // Simulates an instance too old to have the telemetry mutation: the server
121166 // returns GraphQL errors, which must be dropped silently.
122167 client := & apimock.Client {}
123- req := & apimock.Request {}
124- client .On ("NewRequest" , mock .Anything , mock .Anything ).Return (req )
125- req .On ("Do" , mock .Anything , mock .Anything ).
126- Return (false , api.GraphQlErrors {})
168+ req := httptest .NewRequest (http .MethodPost , "/.api/graphql" , nil )
169+ client .On ("NewHTTPRequest" , mock .Anything , http .MethodPost , ".api/graphql" , mock .Anything ).Return (req , nil )
170+ client .On ("Do" , req ).Return (response (http .StatusOK , "{\" errors\" :[{\" message\" :\" unknown field telemetry\" }]}" ), nil )
127171
128172 rec := NewRecorder (client , testSource ())
129173 assert .NotPanics (t , func () {
@@ -138,21 +182,101 @@ func TestRecord_NilClientDoesNotPanic(t *testing.T) {
138182 })
139183}
140184
185+ func TestRecord_OAuthUnauthorizedDoesNotWriteToStdout (t * testing.T ) {
186+ var requests atomic.Int32
187+ server := httptest .NewServer (http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
188+ requests .Add (1 )
189+ assert .Equal (t , "Bearer oauth-token" , r .Header .Get ("Authorization" ))
190+ w .WriteHeader (http .StatusUnauthorized )
191+ }))
192+ defer server .Close ()
193+
194+ endpointURL , err := url .Parse (server .URL )
195+ if err != nil {
196+ t .Fatal (err )
197+ }
198+ var clientOutput bytes.Buffer
199+ client := api .NewClient (api.ClientOpts {
200+ EndpointURL : endpointURL ,
201+ Out : & clientOutput ,
202+ OAuthToken : & oauth.Token {
203+ Endpoint : server .URL ,
204+ AccessToken : "oauth-token" ,
205+ ExpiresAt : time .Now ().Add (time .Hour ),
206+ },
207+ })
208+
209+ oldStdout := os .Stdout
210+ stdoutReader , stdoutWriter , err := os .Pipe ()
211+ if err != nil {
212+ t .Fatal (err )
213+ }
214+ os .Stdout = stdoutWriter
215+ t .Cleanup (func () { os .Stdout = oldStdout })
216+
217+ rec := NewRecorder (client , testSource ())
218+ rec .Record (context .Background (), Event {Feature : "srcCli.search" , Action : "succeeded" })
219+
220+ if err := stdoutWriter .Close (); err != nil {
221+ t .Fatal (err )
222+ }
223+ os .Stdout = oldStdout
224+ stdout , err := io .ReadAll (stdoutReader )
225+ if err != nil {
226+ t .Fatal (err )
227+ }
228+ if err := stdoutReader .Close (); err != nil {
229+ t .Fatal (err )
230+ }
231+ assert .Empty (t , stdout )
232+ assert .Empty (t , clientOutput .String ())
233+ assert .Equal (t , int32 (1 ), requests .Load ())
234+ }
235+
141236func TestRecord_AppliesTimeout (t * testing.T ) {
142237 client := & apimock.Client {}
143- req := & apimock. Request {}
238+ req := httptest . NewRequest ( http . MethodPost , "/.api/graphql" , nil )
144239
145240 var hadDeadline bool
146- client .On ("NewRequest" , mock .Anything , mock .Anything ).Return (req )
147- req .On ("Do" , mock .Anything , mock .Anything ).
241+ client .On ("NewHTTPRequest" , mock .Anything , http .MethodPost , ".api/graphql" , mock .Anything ).
148242 Run (func (args mock.Arguments ) {
149243 ctx := args .Get (0 ).(context.Context )
150244 _ , hadDeadline = ctx .Deadline ()
151245 }).
152- Return (true , nil )
246+ Return (req , nil )
247+ client .On ("Do" , req ).Return (response (http .StatusOK , "{}" ), nil )
153248
154249 rec := NewRecorder (client , testSource (), WithTimeout (50 * time .Millisecond ))
155250 rec .Record (context .Background (), Event {Feature : "srcCli.search" , Action : "succeeded" })
156251
157252 assert .True (t , hadDeadline , "expected Record to apply a context deadline" )
158253}
254+
255+ func TestRecord_TimeoutCancelsHTTPRequest (t * testing.T ) {
256+ requestCanceled := make (chan struct {})
257+ client := & cancellationClient {canceled : requestCanceled , release : make (chan struct {})}
258+ rec := NewRecorder (client , testSource (), WithTimeout (20 * time .Millisecond ))
259+
260+ ctx , cancel := context .WithCancel (context .Background ())
261+ defer cancel ()
262+ done := make (chan struct {})
263+ go func () {
264+ rec .Record (ctx , Event {Feature : "srcCli.search" , Action : "succeeded" })
265+ close (done )
266+ }()
267+
268+ select {
269+ case <- done :
270+ case <- time .After (time .Second ):
271+ cancel ()
272+ close (client .release )
273+ <- done
274+ t .Fatal ("Record did not return after telemetry timeout" )
275+ }
276+
277+ select {
278+ case <- requestCanceled :
279+ default :
280+ t .Fatal ("HTTP request was not canceled after telemetry timeout" )
281+ }
282+ }
0 commit comments