-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patherrors_test.go
More file actions
61 lines (49 loc) · 1.86 KB
/
errors_test.go
File metadata and controls
61 lines (49 loc) · 1.86 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
// Copyright (c) Codesphere Inc.
// SPDX-License-Identifier: Apache-2.0
package errors_test
import (
"fmt"
"net/http"
"net/url"
"reflect"
"unsafe"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/codesphere-cloud/cs-go/api/errors"
"github.com/codesphere-cloud/cs-go/api/openapi_client"
)
func makeGenericOpenAPIError(body []byte, errStr string) error {
typ := reflect.TypeOf(openapi_client.GenericOpenAPIError{})
val := reflect.New(typ).Elem()
bodyField := val.FieldByName("body")
errField := val.FieldByName("error")
reflect.NewAt(bodyField.Type(), unsafe.Pointer(bodyField.UnsafeAddr())).Elem().Set(reflect.ValueOf(body))
reflect.NewAt(errField.Type(), unsafe.Pointer(errField.UnsafeAddr())).Elem().Set(reflect.ValueOf(errStr))
return val.Addr().Interface().(error)
}
var _ = Describe("FormatAPIError", func() {
var (
r *http.Response
)
BeforeEach(func() {
r = &http.Response{
StatusCode: 123,
Request: &http.Request{URL: &url.URL{Scheme: "http", Host: "codesphere.com", Path: "/api/fake"}},
}
})
It("returns nil for nil error", func() {
Expect(errors.FormatAPIError(nil, nil)).To(BeNil())
})
It("returns regular error unchanged", func() {
err := fmt.Errorf("regular error")
res := errors.FormatAPIError(r, err)
Expect(res).ToNot(BeNil())
Expect(res.Error()).To(Equal(fmt.Sprintf("unexpected error %d at URL %s: %s", r.StatusCode, r.Request.URL.String(), err.Error())))
})
It("parses API JSON error and formats it", func() {
apiErr := makeGenericOpenAPIError([]byte(`{"status":400,"title":"Workspace is not running","detail":"Workspace '796636' is not in a running state.","traceId":"svJDMa5"}`), "400 Bad Request")
res := errors.FormatAPIError(r, apiErr)
Expect(res).ToNot(BeNil())
Expect(res.Error()).To(Equal("API error 400 Workspace is not running: Workspace '796636' is not in a running state."))
})
})