-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
util.go
114 lines (89 loc) · 2.32 KB
/
util.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
package testutil
import (
"fmt"
"os"
"runtime"
"unsafe"
common "github.com/DataDog/datadog-agent/rtloader/test/common"
"github.com/DataDog/datadog-agent/rtloader/test/helpers"
yaml "gopkg.in/yaml.v2"
)
/*
#include "rtloader_mem.h"
#include "datadog_agent_rtloader.h"
extern void headers(char **);
static void initDatadogAgentTests(rtloader_t *rtloader) {
set_cgo_free_cb(rtloader, _free);
set_headers_cb(rtloader, headers);
}
*/
import "C"
var (
rtloader *C.rtloader_t
tmpfile *os.File
)
type message struct {
Name string `yaml:"name"`
Body string `yaml:"body"`
Time int64 `yaml:"time"`
}
func setUp() error {
// Initialize memory tracking
helpers.InitMemoryTracker()
rtloader = (*C.rtloader_t)(common.GetRtLoader())
if rtloader == nil {
return fmt.Errorf("make failed")
}
var err error
tmpfile, err = os.CreateTemp("", "testout")
if err != nil {
return err
}
// Updates sys.path so testing Check can be found
C.add_python_path(rtloader, C.CString("../python"))
if ok := C.init(rtloader); ok != 1 {
return fmt.Errorf("`init` failed: %s", C.GoString(C.get_error(rtloader)))
}
C.initDatadogAgentTests(rtloader)
return nil
}
func tearDown() {
os.Remove(tmpfile.Name())
}
func run(call string) (string, error) {
tmpfile.Truncate(0)
code := (*C.char)(helpers.TrackedCString(fmt.Sprintf(`
try:
import util
import sys
%s
except Exception as e:
with open(r'%s', 'w') as f:
f.write("{}\n".format(e))
`, call, tmpfile.Name())))
defer C._free(unsafe.Pointer(code))
runtime.LockOSThread()
state := C.ensure_gil(rtloader)
ret := C.run_simple_string(rtloader, code) == 1
C.release_gil(rtloader, state)
runtime.UnlockOSThread()
if !ret {
return "", fmt.Errorf("`run_simple_string` errored")
}
output, err := os.ReadFile(tmpfile.Name())
return string(output), err
}
//export headers
func headers(in **C.char) {
h := map[string]string{
"User-Agent": "Datadog Agent/0.99",
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "text/html, */*",
}
retval, _ := yaml.Marshal(h)
*in = (*C.char)(helpers.TrackedCString(string(retval)))
}