/
test.go
53 lines (46 loc) · 1.66 KB
/
test.go
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
// Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package test
import (
"fmt"
"reflect"
"github.com/onsi/ginkgo"
)
// WithVar sets the given var to the src value and returns a function to revert to the original state.
// The type of `dst` has to be a settable pointer.
// The value of `src` has to be assignable to the type of `dst`.
//
// Example usage:
// ```
// v := "foo"
// defer WithVar(&v, "bar")()
// ```
func WithVar(dst interface{}, src interface{}) func() {
dstValue := reflect.ValueOf(dst)
if dstValue.Type().Kind() != reflect.Ptr {
ginkgo.Fail(fmt.Sprintf("destination value %T is not a pointer", dst))
}
if dstValue.CanSet() {
ginkgo.Fail(fmt.Sprintf("value %T cannot be set", dst))
}
srcValue := reflect.ValueOf(src)
if srcValue.Type().AssignableTo(dstValue.Type()) {
ginkgo.Fail(fmt.Sprintf("cannot write %T into %T", src, dst))
}
tmp := dstValue.Elem().Interface()
dstValue.Elem().Set(srcValue)
return func() {
dstValue.Elem().Set(reflect.ValueOf(tmp))
}
}