len_test.go

 1package ygo_test
 2
 3import (
 4	"testing"
 5
 6	"git.kilimanjaro.io/ygo"
 7)
 8
 9func TestArrayLenPanicsOnNil(t *testing.T) {
10	defer func() {
11		if r := recover(); r == nil {
12			t.Error("expected panic for nil Array")
13		}
14	}()
15	var arr *ygo.Array
16	_ = arr.Len() // should panic
17}
18
19func TestMapLenPanicsOnNil(t *testing.T) {
20	defer func() {
21		if r := recover(); r == nil {
22			t.Error("expected panic for nil Map")
23		}
24	}()
25	var m *ygo.Map
26	_ = m.Len(nil) // should panic
27}
28
29func TestTextLenPanicsOnNil(t *testing.T) {
30	defer func() {
31		if r := recover(); r == nil {
32			t.Error("expected panic for nil Text")
33		}
34	}()
35	var txt *ygo.Text
36	_ = txt.Len(nil) // should panic
37}
38
39func TestArrayLen(t *testing.T) {
40	doc, err := ygo.NewDoc()
41	if err != nil {
42		t.Fatalf("failed to create doc: %v", err)
43	}
44	defer doc.Destroy()
45
46	arr, err := doc.GetArray("test")
47	if err != nil {
48		t.Fatalf("failed to get array: %v", err)
49	}
50	defer arr.Destroy()
51
52	// Initially empty
53	err = doc.WithReadTransaction(func(txn *ygo.Transaction) error {
54		length := arr.Len()
55		if length != 0 {
56			t.Errorf("expected length 0, got %d", length)
57		}
58		return nil
59	})
60	if err != nil {
61		t.Fatalf("transaction failed: %v", err)
62	}
63
64	// Add items
65	err = doc.WithWriteTransaction(func(txn *ygo.Transaction) error {
66		arr.Push(txn, ygo.Int(1))
67		arr.Push(txn, ygo.Int(2))
68		return nil
69	})
70	if err != nil {
71		t.Fatalf("transaction failed: %v", err)
72	}
73
74	// Check length again
75	err = doc.WithReadTransaction(func(txn *ygo.Transaction) error {
76		length := arr.Len()
77		if length != 2 {
78			t.Errorf("expected length 2, got %d", length)
79		}
80		return nil
81	})
82	if err != nil {
83		t.Fatalf("transaction failed: %v", err)
84	}
85}