forked from denosaurs/deno_python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.ts
More file actions
390 lines (332 loc) Β· 9.26 KB
/
test.ts
File metadata and controls
390 lines (332 loc) Β· 9.26 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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
import { assert, assertEquals, assertThrows } from "./asserts.ts";
import {
kw,
NamedArgument,
ProxiedPyObject,
PyObject,
python,
type PythonProxy,
} from "../mod.ts";
const { version, executable } = python.import("sys");
console.log("Python version:", version);
console.log("Executable:", executable);
Deno.test("python version", () => {
assert(version.toString().match(/^\d+\.\d+\.\d+/));
});
Deno.test("types", async (t) => {
await t.step("bool", () => {
const value = python.bool(true);
assertEquals(value.valueOf(), true);
});
await t.step("int", () => {
const value = python.int(42);
assertEquals(value.valueOf(), 42);
});
await t.step("float", () => {
const value = python.float(42.0);
assertEquals(value.valueOf(), 42.0);
});
await t.step("str", () => {
const value = python.str("hello");
assertEquals(value.valueOf(), "hello");
const unicode = python.str("'δΈζ'");
assertEquals(unicode.valueOf(), "'δΈζ'");
});
await t.step("list", () => {
const value = python.list([1, 2, 3]);
assertEquals(value.valueOf(), [1, 2, 3]);
});
await t.step("dict", () => {
const value = python.dict({ a: 1, b: 2 });
assertEquals(
value.valueOf(),
new Map([
["a", 1],
["b", 2],
]),
);
});
await t.step("set", () => {
let value = python.set([1, 2, 3]);
assertEquals(value.valueOf(), new Set([1, 2, 3]));
value = PyObject.from(new Set([1, 2, 3]));
assertEquals(value.valueOf(), new Set([1, 2, 3]));
});
await t.step("tuple", () => {
const value = python.tuple([1, 2, 3]);
assertEquals(value.valueOf(), [1, 2, 3]);
});
});
Deno.test("object", async (t) => {
const { Person } = python.runModule(`
class Person:
def __init__(self, name):
self.name = name
`);
const person = new Person("John");
await t.step("get attr", () => {
assertEquals(person.name.valueOf(), "John");
});
await t.step("set attr", () => {
person.name = "Jane";
assertEquals(person.name.valueOf(), "Jane");
});
await t.step("has attr", () => {
assert("name" in person);
});
await t.step("dict item", () => {
const dict = python.dict({ prop: "value" });
assertEquals(dict.prop.valueOf(), "value");
});
await t.step("dict set item", () => {
const dict = python.dict({ prop: "value" });
dict.prop = "new value";
assertEquals(dict.prop.valueOf(), "new value");
});
await t.step("dict has item", () => {
const dict = python.dict({ prop: "value" });
assert("prop" in dict);
});
await t.step("dict not has item", () => {
const dict = python.dict({ prop: "value" });
assert(!("prop2" in dict));
});
await t.step("list index", () => {
const list = python.list([1, 2, 3]);
assertEquals(list[0].valueOf(), 1);
});
await t.step("list set index", () => {
const list = python.list([1, 2, 3]);
list[0] = 42;
assertEquals(list[0].valueOf(), 42);
});
await t.step("list iter", () => {
const array = [1, 2, 3];
const list = python.list(array);
let i = 0;
for (const v of list) {
assertEquals(v.valueOf(), array[i]);
i++;
}
});
});
Deno.test("named argument", async (t) => {
await t.step("single named argument", () => {
assertEquals(
python
.str("Hello, {name}!")
.format(kw`name=${"world"}`)
.valueOf(),
"Hello, world!",
);
});
await t.step(
"combination of positional parameters and named argument",
() => {
const { Test } = python.runModule(`
class Test:
def test(self, *args, **kwargs):
return all([len(args) == 3, "name" in kwargs])
`);
const t = new Test();
const d = python.dict({ a: 1, b: 2 });
const v = t.test(1, 2, new NamedArgument("name", "vampire"), d);
assertEquals(v.valueOf(), true);
},
);
});
Deno.test("numpy", () => {
const _np = python.import("numpy");
});
Deno.test("custom proxy", () => {
const np = python.import("numpy");
// We declare our own PythonProxy wrapper
const CustomProxy = class implements PythonProxy {
public readonly [ProxiedPyObject]: PyObject;
constructor(array: PythonProxy) {
this[ProxiedPyObject] = array[ProxiedPyObject];
}
};
// Wrap the result in our custom wrapper
const arr = new CustomProxy(np.array([1, 2, 3]));
// Then, we use the wrapped proxy as if it were an original PyObject
assertEquals(np.add(arr, 2).tolist().valueOf(), [3, 4, 5]);
});
Deno.test("slice", async (t) => {
await t.step("get", () => {
const list = python.list([1, 2, 3, 4, 5, 6, 7, 8, 9]);
assertEquals(list["1:"].valueOf(), [2, 3, 4, 5, 6, 7, 8, 9]);
assertEquals(list["1:2"].valueOf(), [2]);
assertEquals(list[":2"].valueOf(), [1, 2]);
assertEquals(list[":2:"].valueOf(), [1, 2]);
assertEquals(list["0:3:2"].valueOf(), [1, 3]);
assertEquals(list["-2:"].valueOf(), [8, 9]);
assertEquals(list["::2"].valueOf(), [1, 3, 5, 7, 9]);
});
await t.step("set", () => {
const np = python.import("numpy");
let list = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]);
list["1:"] = -5;
assertEquals(list.tolist().valueOf(), [1, -5, -5, -5, -5, -5, -5, -5, -5]);
list = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]);
list["1::3"] = -5;
assertEquals(list.tolist().valueOf(), [1, -5, 3, 4, -5, 6, 7, -5, 9]);
list = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]);
list["1:2:3"] = -5;
assertEquals(list.tolist().valueOf(), [1, -5, 3, 4, 5, 6, 7, 8, 9]);
});
});
Deno.test("slice list", async (t) => {
const np = python.import("numpy");
await t.step("get", () => {
const array = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]);
assertEquals(array["0, :"].tolist().valueOf(), [1, 2, 3]);
assertEquals(array["1:, ::2"].tolist().valueOf(), [
[4, 6],
[7, 9],
]);
assertEquals(array["1:, 0"].tolist().valueOf(), [4, 7]);
});
await t.step("set", () => {
const array = np.arange(15).reshape(3, 5);
array["1:, ::2"] = -99;
assertEquals(array.tolist().valueOf(), [
[0, 1, 2, 3, 4],
[-99, 6, -99, 8, -99],
[-99, 11, -99, 13, -99],
]);
});
await t.step("whitespaces", () => {
const array = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]);
assertEquals(array[" 1 : , : : 2 "].tolist().valueOf(), [
[4, 6],
[7, 9],
]);
});
await t.step("3d slicing", () => {
const a3 = np.array([[[10, 11, 12], [13, 14, 15], [16, 17, 18]], [
[20, 21, 22],
[23, 24, 25],
[26, 27, 28],
], [[30, 31, 32], [33, 34, 35], [36, 37, 38]]]);
assertEquals(a3["0, :, 1"].tolist().valueOf(), [11, 14, 17]);
});
await t.step("ellipsis", () => {
const a4 = np.arange(16).reshape(2, 2, 2, 2);
assertEquals(a4["1, ..., 1"].tolist().valueOf(), [[9, 11], [13, 15]]);
});
});
Deno.test("async", () => {
const { test } = python.runModule(
`
async def test():
return "ok"
`,
"async_test.py",
);
const aio = python.import("asyncio");
assertEquals(aio.run(test()).valueOf(), "ok");
});
Deno.test("callback", () => {
const { call } = python.runModule(
`
def call(cb):
return cb(61, reduce=1) + 1
`,
"cb_test.py",
);
const cb = python.callback((kw: { reduce: number }, num: number) => {
return num - kw.reduce + 8;
});
assertEquals(
call(cb).valueOf(),
69,
);
cb.destroy();
});
Deno.test("callback returns void", () => {
const { call } = python.runModule(
`
def call(cb):
cb()
`,
"cb_test.py",
);
const cb = python.callback(() => {
// return void
});
call(cb);
cb.destroy();
});
Deno.test("exceptions", async (t) => {
await t.step("simple exception", () => {
assertThrows(() => python.runModule("1 / 0"));
});
await t.step("exception with traceback", () => {
const np = python.import("numpy");
const array = np.zeros([2, 3, 4]);
assertThrows(() => array.shape = [3, 6]);
});
});
Deno.test("instance method", () => {
const { A } = python.runModule(
`
class A:
def b(self):
return 4
`,
"cb_test.py",
);
const [m, cb] = python.instanceMethod((_args, self) => {
return self.b();
});
// Modifying PyObject modifes A
PyObject.from(A).setAttr("a", m);
assertEquals(new A().a.call().valueOf(), 4);
cb.destroy();
});
Deno.test("callbacks have signature", async (t) => {
const inspect = python.import("inspect");
await t.step("empty arguments", () => {
const fn = python.callback(() => {});
assertEquals(inspect.signature(fn).toString(), "()");
fn.destroy();
});
await t.step("with no arguments", () => {
const fn = python.callback((_f, _b, _c) => {});
assertEquals(inspect.signature(fn).toString(), "(a, b, c)");
fn.destroy();
});
});
Deno.test("js exception inside python callback returns python exception", () => {
const pyCallback = python.callback(() => {
throw new Error("This is an intentional error from JS!");
});
const pyModule = python.runModule(
`
def call_the_callback(cb):
result = cb()
return result
`,
"test_module",
);
try {
pyModule.call_the_callback(pyCallback);
} catch (e) {
// deno-lint-ignore no-explicit-any
assertEquals((e as any).name, "PythonError");
} finally {
pyCallback.destroy();
}
});
Deno.test("None valueOf is null", () => {
assertEquals(python.None.valueOf(), null);
});