github.com/goshafaq/sonic@v0.0.0-20231026082336-871835fb94c6/issue_test/plugin_test.go (about) 1 //go:build (linux && !race) || (unix && !race) 2 // +build linux,!race unix,!race 3 4 /* 5 * Copyright 2021 ByteDance 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 20 package issue_test 21 22 import ( 23 "bytes" 24 "fmt" 25 "os/exec" 26 "plugin" 27 "reflect" 28 "runtime" 29 "testing" 30 31 _ "github.com/goshafaq/sonic" 32 ) 33 34 func buildPlugin() { 35 out := bytes.NewBuffer(nil) 36 bin0, err := exec.LookPath("rm") 37 if err != nil { 38 panic(err) 39 } 40 cmd0 := exec.Cmd{ 41 Path: bin0, 42 Args: []string{"rm", "-f", "plugin/plugin." + runtime.Version() + ".so"}, 43 Stdout: out, 44 Stderr: out, 45 } 46 if err := cmd0.Run(); err != nil { 47 panic(string(out.Bytes())) 48 } 49 out.Reset() 50 bin, err := exec.LookPath("go") 51 if err != nil { 52 panic(err) 53 } 54 cmd := exec.Cmd{ 55 Path: bin, 56 Args: []string{"go", "build", "-buildmode", "plugin", "-o", "plugin/plugin." + runtime.Version() + ".so", "plugin/main.go"}, 57 Stdout: out, 58 Stderr: out, 59 } 60 if err := cmd.Run(); err != nil { 61 panic(string(out.Bytes())) 62 } 63 } 64 65 func TestPlugin(t *testing.T) { 66 buildPlugin() 67 p, err := plugin.Open("plugin/plugin." + runtime.Version() + ".so") 68 if err != nil { 69 t.Fatal(err) 70 } 71 v, err := p.Lookup("V") 72 if err != nil { 73 t.Fatal(err) 74 } 75 f, err := p.Lookup("F") 76 if err != nil { 77 t.Fatal(err) 78 } 79 *v.(*int) = 7 80 f.(func())() // prints "Hello, number 7" 81 obj, err := p.Lookup("Obj") 82 m := *(obj.(*map[string]string)) 83 fmt.Printf("%#v\n", m) 84 d, err := p.Lookup("Unmarshal") 85 if err != nil { 86 t.Fatal(err) 87 } 88 dec := d.(func(json string, val interface{}) error) 89 var exp map[string]string 90 if err := dec(`{"a":"b"}`, &exp); err != nil { 91 t.Fatal(err) 92 } 93 if !reflect.DeepEqual(m, exp) { 94 t.Fatal(m, exp) 95 } 96 }