forked from extism/python-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_extism.py
More file actions
239 lines (192 loc) · 8.05 KB
/
test_extism.py
File metadata and controls
239 lines (192 loc) · 8.05 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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
from collections import namedtuple
import unittest
import extism
import hashlib
import json
import time
from threading import Thread
from datetime import datetime, timedelta
from os.path import join, dirname
import typing
import pickle
# A pickle-able object.
class Gribble:
def __init__(self, v):
self.v = v
def frobbitz(self):
return "gromble %s" % self.v
class TestExtism(unittest.TestCase):
def test_call_plugin(self):
plugin = extism.Plugin(self._manifest(), functions=[])
j = json.loads(plugin.call("count_vowels", "this is a test"))
self.assertEqual(j["count"], 4)
j = json.loads(plugin.call("count_vowels", "this is a test again"))
self.assertEqual(j["count"], 7)
j = json.loads(plugin.call("count_vowels", "this is a test thrice"))
self.assertEqual(j["count"], 6)
j = json.loads(plugin.call("count_vowels", "🌎hello🌎world🌎"))
self.assertEqual(j["count"], 3)
def test_function_exists(self):
plugin = extism.Plugin(self._manifest(), functions=[])
self.assertTrue(plugin.function_exists("count_vowels"))
self.assertFalse(plugin.function_exists("i_dont_exist"))
def test_errors_on_unknown_function(self):
plugin = extism.Plugin(self._manifest())
self.assertRaises(
extism.Error, lambda: plugin.call("i_dont_exist", "someinput")
)
def test_can_free_plugin(self):
plugin = extism.Plugin(self._manifest())
del plugin
def test_errors_on_bad_manifest(self):
self.assertRaises(
extism.Error, lambda: extism.Plugin({"invalid_manifest": True})
)
def test_extism_version(self):
self.assertIsNotNone(extism.extism_version())
def test_extism_plugin_timeout(self):
plugin = extism.Plugin(self._loop_manifest())
start = datetime.now()
self.assertRaises(extism.Error, lambda: plugin.call("infinite_loop", b""))
end = datetime.now()
self.assertLess(
end,
start + timedelta(seconds=1.1),
"plugin timeout exceeded 1000ms expectation",
)
def test_extism_host_function(self):
@extism.host_fn(
signature=([extism.ValType.I64], [extism.ValType.I64]), user_data=b"test"
)
def hello_world(plugin, params, results, user_data):
offs = plugin.alloc(len(user_data))
mem = plugin.memory(offs)
mem[:] = user_data
results[0].value = offs.offset
plugin = extism.Plugin(
self._manifest(functions=True), functions=[hello_world], wasi=True
)
res = plugin.call("count_vowels", "aaa")
self.assertEqual(res, b"test")
def test_inferred_extism_host_function(self):
@extism.host_fn(user_data=b"test")
def hello_world(inp: str, *user_data) -> str:
return "hello world: %s %s" % (inp, user_data[0].decode("utf-8"))
plugin = extism.Plugin(
self._manifest(functions=True), functions=[hello_world], wasi=True
)
res = plugin.call("count_vowels", "aaa")
self.assertEqual(res, b'hello world: {"count": 3} test')
def test_inferred_json_param_extism_host_function(self):
if not hasattr(typing, "Annotated"):
return
@extism.host_fn(user_data=b"test")
def hello_world(inp: typing.Annotated[dict, extism.Json], *user_data) -> str:
return "hello world: %s %s" % (inp["count"], user_data[0].decode("utf-8"))
plugin = extism.Plugin(
self._manifest(functions=True), functions=[hello_world], wasi=True
)
res = plugin.call("count_vowels", "aaa")
self.assertEqual(res, b"hello world: 3 test")
def test_codecs(self):
if not hasattr(typing, "Annotated"):
return
@extism.host_fn(user_data=b"test")
def hello_world(
inp: typing.Annotated[
str, extism.Codec(lambda xs: xs.decode().replace("o", "u"))
],
*user_data,
) -> typing.Annotated[
str, extism.Codec(lambda xs: xs.replace("u", "a").encode())
]:
return inp
foo = b"bar"
plugin = extism.Plugin(
self._manifest(functions=True), functions=[hello_world], wasi=True
)
res = plugin.call("count_vowels", "aaa")
# Iiiiiii
self.assertEqual(res, b'{"caant": 3}') # stand it, I know you planned it
def test_inferred_pickle_return_param_extism_host_function(self):
if not hasattr(typing, "Annotated"):
return
@extism.host_fn(user_data=b"test")
def hello_world(
inp: typing.Annotated[dict, extism.Json], *user_data
) -> typing.Annotated[Gribble, extism.Pickle]:
return Gribble("robble")
plugin = extism.Plugin(
self._manifest(functions=True), functions=[hello_world], wasi=True
)
res = plugin.call("count_vowels", "aaa")
result = pickle.loads(res)
self.assertIsInstance(result, Gribble)
self.assertEqual(result.frobbitz(), "gromble robble")
def test_host_context(self):
if not hasattr(typing, "Annotated"):
return
# Testing two things here: one, if we see CurrentPlugin as the first arg, we pass it through.
# Two, it's possible to refer to fetch the host context from the current plugin.
@extism.host_fn(user_data=b"test")
def hello_world(
current_plugin: extism.CurrentPlugin,
inp: typing.Annotated[dict, extism.Json],
*user_data,
) -> typing.Annotated[Gribble, extism.Pickle]:
ctx = current_plugin.host_context()
ctx.x = 1000
return Gribble("robble")
plugin = extism.Plugin(
self._manifest(functions=True), functions=[hello_world], wasi=True
)
class Foo:
x = 100
y = 200
foo = Foo()
res = plugin.call("count_vowels", "aaa", host_context=foo)
self.assertEqual(foo.x, 1000)
self.assertEqual(foo.y, 200)
result = pickle.loads(res)
self.assertIsInstance(result, Gribble)
self.assertEqual(result.frobbitz(), "gromble robble")
def test_extism_plugin_cancel(self):
plugin = extism.Plugin(self._loop_manifest())
cancel_handle = plugin.cancel_handle()
def cancel(handle):
time.sleep(0.5)
handle.cancel()
Thread(target=cancel, args=[cancel_handle]).run()
self.assertRaises(extism.Error, lambda: plugin.call("infinite_loop", b""))
def _manifest(self, functions=False):
wasm = self._count_vowels_wasm(functions)
hash = hashlib.sha256(wasm).hexdigest()
return {"wasm": [{"data": wasm, "hash": hash}]}
def _loop_manifest(self):
wasm = self._infinite_loop_wasm()
hash = hashlib.sha256(wasm).hexdigest()
return {
"wasm": [{"data": wasm, "hash": hash}],
"timeout_ms": 1000,
}
def _count_vowels_wasm(self, functions=False):
return read_test_wasm("code.wasm" if not functions else "code-functions.wasm")
def _infinite_loop_wasm(self):
return read_test_wasm("loop.wasm")
ExtismVal = namedtuple("ExtismVal", ["t", "v"])
class TestConvertValue(unittest.TestCase):
"""Tests for the _convert_value helper that converts CFFI ExtismVal structs."""
def _make_extism_val(self, t, **kwargs):
"""Create a mock ExtismVal with type tag `t` and value fields."""
val_union = namedtuple("ValUnion", kwargs.keys())(**kwargs)
return ExtismVal(t=t, v=val_union)
def test_convert_f64_value(self):
x = self._make_extism_val(3, f64=3.14)
result = extism.extism._convert_value(x)
self.assertIsNotNone(result, "_convert_value returned None for F64 input")
self.assertEqual(result.t, extism.ValType.F64)
self.assertAlmostEqual(result.value, 3.14)
def read_test_wasm(p):
path = join(dirname(__file__), "..", "wasm", p)
with open(path, "rb") as wasm_file:
return wasm_file.read()