Debian Codegraph @

samplers/jaegerremote/internal/testutils/http_json_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Copyright (c) 2021 The Jaeger Authors.
5 // Copyright (c) 2017 Uber Technologies, Inc.
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 // http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18
19 package testutils
20
21 import (
22 "net/http"
23 "net/http/httptest"
24 "testing"
25
26 "github.com/stretchr/testify/assert"
27 "github.com/stretchr/testify/require"
28 )
29
30 type testJSONStruct struct {
31 Name string
32 Age int
33 }
34
35 func TestGetJSON(t *testing.T) {
36 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
37 w.Header().Add("Content-Type", "application/json")
38 _, err := w.Write([]byte("{\"name\": \"Bender\", \"age\": 3}"))
39 assert.NoError(t, err)
40 }))
41 defer server.Close()
42
43 var s testJSONStruct
44 err := getJSON(t.Context(), server.URL, &s)
45 require.NoError(t, err)
46
47 assert.Equal(t, "Bender", s.Name)
48 assert.Equal(t, 3, s.Age)
49 }
50
51 func TestGetJSONErrors(t *testing.T) {
52 var s testJSONStruct
53 err := getJSON(t.Context(), "localhost:0", &s)
54 assert.Error(t, err)
55
56 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
57 http.Error(w, "some error", http.StatusInternalServerError)
58 }))
59 defer server.Close()
60
61 err = getJSON(t.Context(), server.URL, &s)
62 assert.Error(t, err)
63 }