-
Notifications
You must be signed in to change notification settings - Fork 1
/
object_test.go
431 lines (377 loc) · 9.94 KB
/
object_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
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
package gp
import (
"bytes"
"reflect"
"testing"
)
func TestObjectCreation(t *testing.T) {
setupTest(t)
// Test From() with different Go types
tests := []struct {
name string
input interface{}
checkFn func(Object) bool
expected interface{}
}{
{"int", 42, func(o Object) bool { return o.IsLong() }, 42},
{"float64", 3.14, func(o Object) bool { return o.IsFloat() }, 3.14},
{"string", "hello", func(o Object) bool { return o.IsStr() }, "hello"},
{"bool", true, func(o Object) bool { return o.IsBool() }, true},
{"[]byte", []byte("bytes"), func(o Object) bool { return o.IsBytes() }, []byte("bytes")},
{"slice", []int{1, 2, 3}, func(o Object) bool { return o.IsList() }, []int{1, 2, 3}},
{"map", map[string]int{"a": 1}, func(o Object) bool { return o.IsDict() }, map[string]int{"a": 1}},
}
for _, tt := range tests {
obj := From(tt.input)
if !tt.checkFn(obj) {
t.Errorf("From(%v) created wrong type", tt.input)
}
// Test conversion back to Go value
switch expected := tt.expected.(type) {
case int:
if got := obj.AsLong().Int64(); got != int64(expected) {
t.Errorf("Expected %v, got %v", expected, got)
}
case float64:
if got := obj.AsFloat().Float64(); got != expected {
t.Errorf("Expected %v, got %v", expected, got)
}
case string:
if got := obj.AsStr().String(); got != expected {
t.Errorf("Expected %v, got %v", expected, got)
}
case bool:
if got := obj.AsBool().Bool(); got != expected {
t.Errorf("Expected %v, got %v", expected, got)
}
case []byte:
if got := obj.AsBytes().Bytes(); !reflect.DeepEqual(got, expected) {
t.Errorf("Expected %v, got %v", expected, got)
}
}
}
}
func TestObjectAttributes(t *testing.T) {
setupTest(t)
// Test attributes using Python's built-in object type
builtins := ImportModule("builtins")
obj := builtins.AttrFunc("object").Call()
// Get built-in attribute
cls := obj.Attr("__class__")
if cls.Nil() {
t.Error("Failed to get __class__ attribute")
}
// Test Dir() method
dir := obj.Dir()
if dir.Len() == 0 {
t.Error("Dir() returned empty list")
}
// Create a custom class to test attribute setting
pyCode := `
class TestClass:
pass
`
locals := MakeDict(nil)
globals := MakeDict(nil)
globals.Set(MakeStr("__builtins__"), builtins.Object)
code, err := CompileString(pyCode, "<string>", FileInput)
if err != nil {
t.Errorf("CompileString() error = %v", err)
}
EvalCode(code, globals, locals).AsModule()
testClass := locals.Get(MakeStr("TestClass")).AsFunc()
instance := testClass.Call()
// Now we can set attributes
instance.SetAttr("new_attr", "test_value")
value := instance.Attr("new_attr")
if value.AsStr().String() != "test_value" {
t.Error("SetAttr failed to set new attribute")
}
}
func TestDictOperations(t *testing.T) {
setupTest(t)
// Test dictionary operations
pyDict := MakeDict(nil)
pyDict.Set(MakeStr("key1"), From(42))
pyDict.Set(MakeStr("key2"), From("value"))
value := pyDict.Get(MakeStr("key1"))
if value.AsLong().Int64() != 42 {
t.Error("Failed to get dictionary item")
}
func() {
pyDict.Set(MakeStr("key3"), From("new_value"))
value := pyDict.Get(MakeStr("key3"))
if value.AsStr().String() != "new_value" {
t.Error("Failed to set dictionary item")
}
}()
}
func TestObjectConversion(t *testing.T) {
setupTest(t)
type Person struct {
Name string
Age int
}
person := Person{Name: "Alice", Age: 30}
obj := From(person)
if !obj.IsDict() {
t.Error("Struct should be converted to Python dict")
}
dict := obj.AsDict()
if dict.Get(From("name")).AsStr().String() != "Alice" {
t.Error("Failed to convert struct field 'Name'")
}
if dict.Get(From("age")).AsLong().Int64() != 30 {
t.Error("Failed to convert struct field 'Age'")
}
func() {
slice := []int{1, 2, 3}
obj := From(slice)
if !obj.IsList() {
t.Error("Slice should be converted to Python list")
}
list := obj.AsList()
if list.Len() != 3 {
t.Error("Wrong length after conversion")
}
if list.GetItem(0).AsLong().Int64() != 1 {
t.Error("Wrong value at index 0")
}
}()
}
func TestObjectString(t *testing.T) {
setupTest(t)
tests := []struct {
name string
input interface{}
expected string
}{
{"int", 42, "42"},
{"string", "hello", "hello"},
{"bool", true, "True"},
}
for _, tt := range tests {
obj := From(tt.input)
str := obj.String()
if str != tt.expected {
t.Errorf("String() = %v, want %v", str, tt.expected)
}
}
}
func TestPyObjectMethods(t *testing.T) {
setupTest(t)
// Test pyObject.cpyObj()
obj := From(42)
if obj.pyObject.cpyObj() == nil {
t.Error("pyObject.cpyObj() returned nil for valid object")
}
func() {
var nilObj *pyObject
if nilObj.cpyObj() != nil {
t.Error("pyObject.cpyObj() should return nil for nil object")
}
}()
func() {
// Test pyObject.Ensure()
obj := From(42)
obj.Ensure() // Should not panic
}()
func() {
var nilObj Object
defer func() {
if r := recover(); r == nil {
t.Error("Ensure() should panic for nil object")
}
}()
nilObj.Ensure()
}()
}
func TestObjectMethods(t *testing.T) {
setupTest(t)
// Test Object.object()
obj := From(42)
if obj.object() != obj {
t.Error("object() should return the same object")
}
// Test Object.Attr* methods
// Create a test class with various attribute types
pyCode := `
class TestClass:
def __init__(self):
self.int_val = 42
self.float_val = 3.14
self.str_val = "test"
self.bool_val = True
self.list_val = [1, 2, 3]
self.dict_val = {"key": "value"}
self.tuple_val = (1, 2, 3)
`
locals := MakeDict(nil)
globals := MakeDict(nil)
builtins := ImportModule("builtins")
globals.Set(MakeStr("__builtins__"), builtins.Object)
code, err := CompileString(pyCode, "<string>", FileInput)
if err != nil {
t.Errorf("CompileString() error = %v", err)
}
EvalCode(code, globals, locals)
testClass := locals.Get(MakeStr("TestClass")).AsFunc()
instance := testClass.Call()
// Test each Attr* method
if instance.AttrLong("int_val").Int64() != 42 {
t.Error("AttrLong failed")
}
if instance.AttrFloat("float_val").Float64() != 3.14 {
t.Error("AttrFloat failed")
}
if instance.AttrString("str_val").String() != "test" {
t.Error("AttrString failed")
}
if !instance.AttrBool("bool_val").Bool() {
t.Error("AttrBool failed")
}
if instance.AttrList("list_val").Len() != 3 {
t.Error("AttrList failed")
}
if instance.AttrDict("dict_val").Get(MakeStr("key")).AsStr().String() != "value" {
t.Error("AttrDict failed")
}
if instance.AttrTuple("tuple_val").Len() != 3 {
t.Error("AttrTuple failed")
}
func() {
// Test Object.IsTuple and AsTuple
// Create a Python tuple using Python code to ensure proper tuple creation
pyCode := `
def make_tuple():
return (1, 2, 3)
`
locals := MakeDict(nil)
globals := MakeDict(nil)
builtins := ImportModule("builtins")
globals.Set(MakeStr("__builtins__"), builtins.Object)
code, err := CompileString(pyCode, "<string>", FileInput)
if err != nil {
t.Errorf("CompileString() error = %v", err)
}
EvalCode(code, globals, locals)
makeTuple := locals.Get(MakeStr("make_tuple")).AsFunc()
tuple := makeTuple.Call()
// Test IsTuple
if !tuple.IsTuple() {
t.Error("IsTuple failed to identify tuple")
}
// Test AsTuple
pythonTuple := tuple.AsTuple()
if pythonTuple.Len() != 3 {
t.Error("AsTuple conversion failed")
}
// Verify tuple contents
if pythonTuple.Get(0).AsLong().Int64() != 1 {
t.Error("Incorrect value at index 0")
}
if pythonTuple.Get(1).AsLong().Int64() != 2 {
t.Error("Incorrect value at index 1")
}
if pythonTuple.Get(2).AsLong().Int64() != 3 {
t.Error("Incorrect value at index 2")
}
}()
func() {
// Test Object.Repr and Type
obj := From(42)
if obj.Repr() != "42" {
t.Error("Repr failed")
}
}()
func() {
typeObj := obj.Type()
if typeObj.Repr() != "<class 'int'>" {
t.Error("Type failed")
}
}()
func() {
// Test From with various numeric types
tests := []struct {
input interface{}
expected int64
}{
{int8(42), 42},
{int16(42), 42},
{int32(42), 42},
{int64(42), 42},
{uint8(42), 42},
{uint16(42), 42},
{uint32(42), 42},
{uint64(42), 42},
}
for _, tt := range tests {
obj := From(tt.input)
if obj.AsLong().Int64() != tt.expected {
t.Errorf("From(%T) = %v, want %v", tt.input, obj.AsLong().Int64(), tt.expected)
}
}
}()
func() {
// Test From with false boolean
obj := From(false)
if obj.AsBool().Bool() != false {
t.Error("From(false) failed")
}
}()
func() {
// Test Object.cpyObj()
obj := From(42)
if obj.cpyObj() == nil {
t.Error("Object.cpyObj() returned nil for valid object")
}
}()
func() {
var nilObj Object
if nilObj.cpyObj() != nil {
t.Error("Object.cpyObj() should return nil for nil object")
}
}()
func() {
// Test AttrBytes
builtins := ImportModule("types")
objType := builtins.AttrFunc("SimpleNamespace")
obj := objType.Call()
// Create a simple object with bytes attribute
obj.SetAttr("bytes_val", From([]byte("hello")))
if !bytes.Equal(obj.AttrBytes("bytes_val").Bytes(), []byte("hello")) {
t.Error("AttrBytes failed")
}
}()
func() {
// Test Object.Call with kwargs
pyCode := `
def test_func(a, b=10, c="default"):
return (a, b, c)
`
locals := MakeDict(nil)
globals := MakeDict(nil)
globals.Set(MakeStr("__builtins__"), builtins.Object)
code, err := CompileString(pyCode, "<string>", FileInput)
if err != nil {
t.Errorf("CompileString() error = %v", err)
}
EvalCode(code, globals, locals)
testFunc := locals.Get(MakeStr("test_func"))
// Call with positional and keyword arguments
result := testFunc.Call("__call__", 1, KwArgs{
"b": 20,
"c": "custom",
})
tuple := result.AsTuple()
if tuple.Get(0).AsLong().Int64() != 1 {
t.Error("Wrong value for first argument")
}
if tuple.Get(1).AsLong().Int64() != 20 {
t.Error("Wrong value for keyword argument b")
}
if tuple.Get(2).AsStr().String() != "custom" {
t.Error("Wrong value for keyword argument c")
}
}()
}