focus_test.go 17 KB
Newer Older
1 2 3 4 5 6 7 8
package traversal_test

import (
	"fmt"
	"testing"

	. "github.com/warpfork/go-wish"

Eric Myhre's avatar
Eric Myhre committed
9 10
	"github.com/ipfs/go-cid"
	"github.com/ipld/go-ipld-prime"
11
	_ "github.com/ipld/go-ipld-prime/codec/dagjson"
12 13
	"github.com/ipld/go-ipld-prime/fluent"
	cidlink "github.com/ipld/go-ipld-prime/linking/cid"
Eric Myhre's avatar
Eric Myhre committed
14
	"github.com/ipld/go-ipld-prime/must"
15
	basicnode "github.com/ipld/go-ipld-prime/node/basic"
Eric Myhre's avatar
Eric Myhre committed
16
	"github.com/ipld/go-ipld-prime/storage"
17 18 19 20 21 22
	"github.com/ipld/go-ipld-prime/traversal"
)

// Do some fixture fabrication.
// We assume all the builders and serialization must Just Work here.

Eric Myhre's avatar
Eric Myhre committed
23
var store = storage.Memory{}
24
var (
25 26
	leafAlpha, leafAlphaLnk         = encode(basicnode.NewString("alpha"))
	leafBeta, leafBetaLnk           = encode(basicnode.NewString("beta"))
27
	middleMapNode, middleMapNodeLnk = encode(fluent.MustBuildMap(basicnode.Prototype__Map{}, 3, func(na fluent.MapAssembler) {
28 29 30 31 32
		na.AssembleEntry("foo").AssignBool(true)
		na.AssembleEntry("bar").AssignBool(false)
		na.AssembleEntry("nested").CreateMap(2, func(na fluent.MapAssembler) {
			na.AssembleEntry("alink").AssignLink(leafAlphaLnk)
			na.AssembleEntry("nonlink").AssignString("zoo")
33
		})
34
	}))
35
	middleListNode, middleListNodeLnk = encode(fluent.MustBuildList(basicnode.Prototype__List{}, 4, func(na fluent.ListAssembler) {
36 37 38 39
		na.AssembleValue().AssignLink(leafAlphaLnk)
		na.AssembleValue().AssignLink(leafAlphaLnk)
		na.AssembleValue().AssignLink(leafBetaLnk)
		na.AssembleValue().AssignLink(leafAlphaLnk)
40
	}))
41
	rootNode, rootNodeLnk = encode(fluent.MustBuildMap(basicnode.Prototype__Map{}, 4, func(na fluent.MapAssembler) {
42 43 44 45
		na.AssembleEntry("plain").AssignString("olde string")
		na.AssembleEntry("linkedString").AssignLink(leafAlphaLnk)
		na.AssembleEntry("linkedMap").AssignLink(middleMapNodeLnk)
		na.AssembleEntry("linkedList").AssignLink(middleListNodeLnk)
46 47 48 49 50 51 52
	}))
)

// encode hardcodes some encoding choices for ease of use in fixture generation;
// just gimme a link and stuff the bytes in a map.
// (also return the node again for convenient assignment.)
func encode(n ipld.Node) (ipld.Node, ipld.Link) {
Eric Myhre's avatar
Eric Myhre committed
53
	lp := cidlink.LinkPrototype{cid.Prefix{
54 55
		Version:  1,
		Codec:    0x0129,
56
		MhType:   0x13,
57 58
		MhLength: 4,
	}}
Eric Myhre's avatar
Eric Myhre committed
59 60 61 62
	lsys := cidlink.DefaultLinkSystem()
	lsys.StorageWriteOpener = (&store).OpenWrite

	lnk, err := lsys.Store(ipld.LinkContext{}, lp, n)
63 64 65 66 67 68 69 70 71
	if err != nil {
		panic(err)
	}
	return n, lnk
}

// covers Focus used on one already-loaded Node; no link-loading exercised.
func TestFocusSingleTree(t *testing.T) {
	t.Run("empty path on scalar node returns start node", func(t *testing.T) {
72 73
		err := traversal.Focus(basicnode.NewString("x"), ipld.Path{}, func(prog traversal.Progress, n ipld.Node) error {
			Wish(t, n, ShouldEqual, basicnode.NewString("x"))
Eric Myhre's avatar
Eric Myhre committed
74
			Wish(t, prog.Path.String(), ShouldEqual, ipld.Path{}.String())
75 76 77 78 79
			return nil
		})
		Wish(t, err, ShouldEqual, nil)
	})
	t.Run("one step path on map node works", func(t *testing.T) {
Eric Myhre's avatar
Eric Myhre committed
80
		err := traversal.Focus(middleMapNode, ipld.ParsePath("foo"), func(prog traversal.Progress, n ipld.Node) error {
81
			Wish(t, n, ShouldEqual, basicnode.NewBool(true))
Eric Myhre's avatar
Eric Myhre committed
82
			Wish(t, prog.Path, ShouldEqual, ipld.ParsePath("foo"))
83 84 85 86 87
			return nil
		})
		Wish(t, err, ShouldEqual, nil)
	})
	t.Run("two step path on map node works", func(t *testing.T) {
Eric Myhre's avatar
Eric Myhre committed
88
		err := traversal.Focus(middleMapNode, ipld.ParsePath("nested/nonlink"), func(prog traversal.Progress, n ipld.Node) error {
89
			Wish(t, n, ShouldEqual, basicnode.NewString("zoo"))
Eric Myhre's avatar
Eric Myhre committed
90
			Wish(t, prog.Path, ShouldEqual, ipld.ParsePath("nested/nonlink"))
91 92 93 94 95 96
			return nil
		})
		Wish(t, err, ShouldEqual, nil)
	})
}

Eric Myhre's avatar
Eric Myhre committed
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
// covers Get used on one already-loaded Node; no link-loading exercised.
// same fixtures as the test for Focus; just has fewer assertions, since Get does no progress tracking.
func TestGetSingleTree(t *testing.T) {
	t.Run("empty path on scalar node returns start node", func(t *testing.T) {
		n, err := traversal.Get(basicnode.NewString("x"), ipld.Path{})
		Wish(t, err, ShouldEqual, nil)
		Wish(t, n, ShouldEqual, basicnode.NewString("x"))
	})
	t.Run("one step path on map node works", func(t *testing.T) {
		n, err := traversal.Get(middleMapNode, ipld.ParsePath("foo"))
		Wish(t, err, ShouldEqual, nil)
		Wish(t, n, ShouldEqual, basicnode.NewBool(true))
	})
	t.Run("two step path on map node works", func(t *testing.T) {
		n, err := traversal.Get(middleMapNode, ipld.ParsePath("nested/nonlink"))
		Wish(t, err, ShouldEqual, nil)
		Wish(t, n, ShouldEqual, basicnode.NewString("zoo"))
	})
}

117 118 119
func TestFocusWithLinkLoading(t *testing.T) {
	t.Run("link traversal with no configured loader should fail", func(t *testing.T) {
		t.Run("terminal link should fail", func(t *testing.T) {
Eric Myhre's avatar
Eric Myhre committed
120
			err := traversal.Focus(middleMapNode, ipld.ParsePath("nested/alink"), func(prog traversal.Progress, n ipld.Node) error {
121 122 123
				t.Errorf("should not be reached; no way to load this path")
				return nil
			})
124
			Wish(t, err.Error(), ShouldEqual, `error traversing node at "nested/alink": could not load link "`+leafAlphaLnk.String()+`": no LinkTargetNodePrototypeChooser configured`)
125 126
		})
		t.Run("mid-path link should fail", func(t *testing.T) {
Eric Myhre's avatar
Eric Myhre committed
127
			err := traversal.Focus(rootNode, ipld.ParsePath("linkedMap/nested/nonlink"), func(prog traversal.Progress, n ipld.Node) error {
128 129 130
				t.Errorf("should not be reached; no way to load this path")
				return nil
			})
131
			Wish(t, err.Error(), ShouldEqual, `error traversing node at "linkedMap": could not load link "`+middleMapNodeLnk.String()+`": no LinkTargetNodePrototypeChooser configured`)
132 133 134
		})
	})
	t.Run("link traversal with loader should work", func(t *testing.T) {
Eric Myhre's avatar
Eric Myhre committed
135 136
		lsys := cidlink.DefaultLinkSystem()
		lsys.StorageReadOpener = (&store).OpenRead
137 138
		err := traversal.Progress{
			Cfg: &traversal.Config{
Daniel Martí's avatar
Daniel Martí committed
139 140
				LinkSystem:                     lsys,
				LinkTargetNodePrototypeChooser: basicnode.Chooser,
141
			},
Eric Myhre's avatar
Eric Myhre committed
142
		}.Focus(rootNode, ipld.ParsePath("linkedMap/nested/nonlink"), func(prog traversal.Progress, n ipld.Node) error {
143
			Wish(t, n, ShouldEqual, basicnode.NewString("zoo"))
Eric Myhre's avatar
Eric Myhre committed
144 145 146
			Wish(t, prog.Path, ShouldEqual, ipld.ParsePath("linkedMap/nested/nonlink"))
			Wish(t, prog.LastBlock.Link, ShouldEqual, middleMapNodeLnk)
			Wish(t, prog.LastBlock.Path, ShouldEqual, ipld.ParsePath("linkedMap"))
147 148 149 150 151
			return nil
		})
		Wish(t, err, ShouldEqual, nil)
	})
}
152 153 154 155 156 157 158 159 160 161 162 163 164

func TestGetWithLinkLoading(t *testing.T) {
	t.Run("link traversal with no configured loader should fail", func(t *testing.T) {
		t.Run("terminal link should fail", func(t *testing.T) {
			_, err := traversal.Get(middleMapNode, ipld.ParsePath("nested/alink"))
			Wish(t, err.Error(), ShouldEqual, `error traversing node at "nested/alink": could not load link "`+leafAlphaLnk.String()+`": no LinkTargetNodePrototypeChooser configured`)
		})
		t.Run("mid-path link should fail", func(t *testing.T) {
			_, err := traversal.Get(rootNode, ipld.ParsePath("linkedMap/nested/nonlink"))
			Wish(t, err.Error(), ShouldEqual, `error traversing node at "linkedMap": could not load link "`+middleMapNodeLnk.String()+`": no LinkTargetNodePrototypeChooser configured`)
		})
	})
	t.Run("link traversal with loader should work", func(t *testing.T) {
Eric Myhre's avatar
Eric Myhre committed
165 166
		lsys := cidlink.DefaultLinkSystem()
		lsys.StorageReadOpener = (&store).OpenRead
167 168
		n, err := traversal.Progress{
			Cfg: &traversal.Config{
Daniel Martí's avatar
Daniel Martí committed
169 170
				LinkSystem:                     lsys,
				LinkTargetNodePrototypeChooser: basicnode.Chooser,
171 172 173 174 175 176
			},
		}.Get(rootNode, ipld.ParsePath("linkedMap/nested/nonlink"))
		Wish(t, err, ShouldEqual, nil)
		Wish(t, n, ShouldEqual, basicnode.NewString("zoo"))
	})
}
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

func TestFocusedTransform(t *testing.T) {
	t.Run("UpdateMapEntry", func(t *testing.T) {
		n, err := traversal.FocusedTransform(rootNode, ipld.ParsePath("plain"), func(progress traversal.Progress, prev ipld.Node) (ipld.Node, error) {
			Wish(t, progress.Path.String(), ShouldEqual, "plain")
			Wish(t, must.String(prev), ShouldEqual, "olde string")
			nb := prev.Prototype().NewBuilder()
			nb.AssignString("new string!")
			return nb.Build(), nil
		}, false)
		Wish(t, err, ShouldEqual, nil)
		Wish(t, n.Kind(), ShouldEqual, ipld.Kind_Map)
		// updated value should be there
		Wish(t, must.Node(n.LookupByString("plain")), ShouldEqual, basicnode.NewString("new string!"))
		// everything else should be there
		Wish(t, must.Node(n.LookupByString("linkedString")), ShouldEqual, must.Node(rootNode.LookupByString("linkedString")))
		Wish(t, must.Node(n.LookupByString("linkedMap")), ShouldEqual, must.Node(rootNode.LookupByString("linkedMap")))
		Wish(t, must.Node(n.LookupByString("linkedList")), ShouldEqual, must.Node(rootNode.LookupByString("linkedList")))
		// everything should still be in the same order
		Wish(t, keys(n), ShouldEqual, []string{"plain", "linkedString", "linkedMap", "linkedList"})
	})
	t.Run("UpdateDeeperMap", func(t *testing.T) {
		n, err := traversal.FocusedTransform(middleMapNode, ipld.ParsePath("nested/alink"), func(progress traversal.Progress, prev ipld.Node) (ipld.Node, error) {
			Wish(t, progress.Path.String(), ShouldEqual, "nested/alink")
			Wish(t, prev, ShouldEqual, basicnode.NewLink(leafAlphaLnk))
			return basicnode.NewString("new string!"), nil
		}, false)
		Wish(t, err, ShouldEqual, nil)
		Wish(t, n.Kind(), ShouldEqual, ipld.Kind_Map)
		// updated value should be there
		Wish(t, must.Node(must.Node(n.LookupByString("nested")).LookupByString("alink")), ShouldEqual, basicnode.NewString("new string!"))
		// everything else in the parent map should should be there!
		Wish(t, must.Node(n.LookupByString("foo")), ShouldEqual, must.Node(middleMapNode.LookupByString("foo")))
		Wish(t, must.Node(n.LookupByString("bar")), ShouldEqual, must.Node(middleMapNode.LookupByString("bar")))
		// everything should still be in the same order
		Wish(t, keys(n), ShouldEqual, []string{"foo", "bar", "nested"})
	})
	t.Run("AppendIfNotExists", func(t *testing.T) {
		n, err := traversal.FocusedTransform(rootNode, ipld.ParsePath("newpart"), func(progress traversal.Progress, prev ipld.Node) (ipld.Node, error) {
			Wish(t, progress.Path.String(), ShouldEqual, "newpart")
			Wish(t, prev, ShouldEqual, nil) // REVIEW: should ipld.Absent be used here?  I lean towards "no" but am unsure what's least surprising here.
			// An interesting thing to note about inserting a value this way is that you have no `prev.Prototype().NewBuilder()` to use if you wanted to.
			//  But if that's an issue, then what you do is a focus or walk (transforming or not) to the parent node, get its child prototypes, and go from there.
			return basicnode.NewString("new string!"), nil
		}, false)
		Wish(t, err, ShouldEqual, nil)
		Wish(t, n.Kind(), ShouldEqual, ipld.Kind_Map)
		// updated value should be there
		Wish(t, must.Node(n.LookupByString("newpart")), ShouldEqual, basicnode.NewString("new string!"))
		// everything should still be in the same order... with the new entry at the end.
		Wish(t, keys(n), ShouldEqual, []string{"plain", "linkedString", "linkedMap", "linkedList", "newpart"})
	})
	t.Run("CreateParents", func(t *testing.T) {
		n, err := traversal.FocusedTransform(rootNode, ipld.ParsePath("newsection/newpart"), func(progress traversal.Progress, prev ipld.Node) (ipld.Node, error) {
			Wish(t, progress.Path.String(), ShouldEqual, "newsection/newpart")
			Wish(t, prev, ShouldEqual, nil) // REVIEW: should ipld.Absent be used here?  I lean towards "no" but am unsure what's least surprising here.
			return basicnode.NewString("new string!"), nil
		}, true)
		Wish(t, err, ShouldEqual, nil)
		Wish(t, n.Kind(), ShouldEqual, ipld.Kind_Map)
		// a new map node in the middle should've been created
		n2 := must.Node(n.LookupByString("newsection"))
		Wish(t, n2.Kind(), ShouldEqual, ipld.Kind_Map)
		// updated value should in there
		Wish(t, must.Node(n2.LookupByString("newpart")), ShouldEqual, basicnode.NewString("new string!"))
		// everything in the root map should still be in the same order... with the new entry at the end.
		Wish(t, keys(n), ShouldEqual, []string{"plain", "linkedString", "linkedMap", "linkedList", "newsection"})
		// and the created intermediate map of course has just one entry.
		Wish(t, keys(n2), ShouldEqual, []string{"newpart"})
	})
	t.Run("CreateParentsRequiresPermission", func(t *testing.T) {
		_, err := traversal.FocusedTransform(rootNode, ipld.ParsePath("newsection/newpart"), func(progress traversal.Progress, prev ipld.Node) (ipld.Node, error) {
			Wish(t, true, ShouldEqual, false) // ought not be reached
			return nil, nil
		}, false)
		Wish(t, err, ShouldEqual, fmt.Errorf("transform: parent position at \"newsection\" did not exist (and createParents was false)"))
	})
	t.Run("UpdateListEntry", func(t *testing.T) {
		n, err := traversal.FocusedTransform(middleListNode, ipld.ParsePath("2"), func(progress traversal.Progress, prev ipld.Node) (ipld.Node, error) {
			Wish(t, progress.Path.String(), ShouldEqual, "2")
			Wish(t, prev, ShouldEqual, basicnode.NewLink(leafBetaLnk))
			return basicnode.NewString("new string!"), nil
		}, false)
		Wish(t, err, ShouldEqual, nil)
		Wish(t, n.Kind(), ShouldEqual, ipld.Kind_List)
		// updated value should be there
		Wish(t, must.Node(n.LookupByIndex(2)), ShouldEqual, basicnode.NewString("new string!"))
		// everything else should be there
		Wish(t, n.Length(), ShouldEqual, int64(4))
		Wish(t, must.Node(n.LookupByIndex(0)), ShouldEqual, basicnode.NewLink(leafAlphaLnk))
		Wish(t, must.Node(n.LookupByIndex(1)), ShouldEqual, basicnode.NewLink(leafAlphaLnk))
		Wish(t, must.Node(n.LookupByIndex(3)), ShouldEqual, basicnode.NewLink(leafAlphaLnk))
	})
	t.Run("AppendToList", func(t *testing.T) {
		n, err := traversal.FocusedTransform(middleListNode, ipld.ParsePath("-"), func(progress traversal.Progress, prev ipld.Node) (ipld.Node, error) {
			Wish(t, progress.Path.String(), ShouldEqual, "4")
			Wish(t, prev, ShouldEqual, nil)
			return basicnode.NewString("new string!"), nil
		}, false)
		Wish(t, err, ShouldEqual, nil)
		Wish(t, n.Kind(), ShouldEqual, ipld.Kind_List)
		// updated value should be there
		Wish(t, must.Node(n.LookupByIndex(4)), ShouldEqual, basicnode.NewString("new string!"))
		// everything else should be there
		Wish(t, n.Length(), ShouldEqual, int64(5))
	})
	t.Run("ListBounds", func(t *testing.T) {
		_, err := traversal.FocusedTransform(middleListNode, ipld.ParsePath("4"), func(progress traversal.Progress, prev ipld.Node) (ipld.Node, error) {
			Wish(t, true, ShouldEqual, false) // ought not be reached
			return nil, nil
		}, false)
		Wish(t, err, ShouldEqual, fmt.Errorf("transform: cannot navigate path segment \"4\" at \"\" because it is beyond the list bounds"))
	})
	t.Run("ReplaceRoot", func(t *testing.T) { // a fairly degenerate case and no reason to do this, but should work.
		n, err := traversal.FocusedTransform(middleListNode, ipld.ParsePath(""), func(progress traversal.Progress, prev ipld.Node) (ipld.Node, error) {
			Wish(t, progress.Path.String(), ShouldEqual, "")
			Wish(t, prev, ShouldEqual, middleListNode)
			nb := basicnode.Prototype.Any.NewBuilder()
			la, _ := nb.BeginList(0)
			la.Finish()
			return nb.Build(), nil
		}, false)
		Wish(t, err, ShouldEqual, nil)
		Wish(t, n.Kind(), ShouldEqual, ipld.Kind_List)
		Wish(t, n.Length(), ShouldEqual, int64(0))
	})
}

func TestFocusedTransformWithLinks(t *testing.T) {
Eric Myhre's avatar
Eric Myhre committed
306 307 308 309
	var store2 = storage.Memory{}
	lsys := cidlink.DefaultLinkSystem()
	lsys.StorageReadOpener = (&store).OpenRead
	lsys.StorageWriteOpener = (&store2).OpenWrite
310
	cfg := traversal.Config{
Daniel Martí's avatar
Daniel Martí committed
311 312
		LinkSystem:                     lsys,
		LinkTargetNodePrototypeChooser: basicnode.Chooser,
313 314 315 316 317 318 319 320
	}
	t.Run("UpdateMapBeyondLink", func(t *testing.T) {
		n, err := traversal.Progress{
			Cfg: &cfg,
		}.FocusedTransform(rootNode, ipld.ParsePath("linkedMap/nested/nonlink"), func(progress traversal.Progress, prev ipld.Node) (ipld.Node, error) {
			Wish(t, progress.Path.String(), ShouldEqual, "linkedMap/nested/nonlink")
			Wish(t, must.String(prev), ShouldEqual, "zoo")
			Wish(t, progress.LastBlock.Path.String(), ShouldEqual, "linkedMap")
321
			Wish(t, progress.LastBlock.Link.String(), ShouldEqual, "baguqeeye2opztzy")
322 323 324 325 326 327 328
			nb := prev.Prototype().NewBuilder()
			nb.AssignString("new string!")
			return nb.Build(), nil
		}, false)
		Wish(t, err, ShouldEqual, nil)
		Wish(t, n.Kind(), ShouldEqual, ipld.Kind_Map)
		// there should be a new object in our new storage!
Eric Myhre's avatar
Eric Myhre committed
329
		Wish(t, len(store2.Bag), ShouldEqual, 1)
330
		// cleanup for next test
Eric Myhre's avatar
Eric Myhre committed
331
		store2 = storage.Memory{}
332 333 334 335 336 337 338 339 340 341 342 343 344 345
	})
	t.Run("UpdateNotBeyondLink", func(t *testing.T) {
		// This is replacing a link with a non-link.  Doing so shouldn't hit storage.
		n, err := traversal.Progress{
			Cfg: &cfg,
		}.FocusedTransform(rootNode, ipld.ParsePath("linkedMap"), func(progress traversal.Progress, prev ipld.Node) (ipld.Node, error) {
			Wish(t, progress.Path.String(), ShouldEqual, "linkedMap")
			nb := prev.Prototype().NewBuilder()
			nb.AssignString("new string!")
			return nb.Build(), nil
		}, false)
		Wish(t, err, ShouldEqual, nil)
		Wish(t, n.Kind(), ShouldEqual, ipld.Kind_Map)
		// there should be no new objects in our new storage!
Eric Myhre's avatar
Eric Myhre committed
346
		Wish(t, len(store2.Bag), ShouldEqual, 0)
347
		// cleanup for next test
Eric Myhre's avatar
Eric Myhre committed
348
		store2 = storage.Memory{}
349 350 351 352 353 354 355 356 357 358 359 360 361
	})

	// link traverse to scalar // this is unspecifiable using the current path syntax!  you'll just end up replacing the link with the scalar!
}

func keys(n ipld.Node) []string {
	v := make([]string, 0, n.Length())
	for itr := n.MapIterator(); !itr.Done(); {
		k, _, _ := itr.Next()
		v = append(v, must.String(k))
	}
	return v
}