unixfs.go 27.3 KB
Newer Older
1
package tests
2 3 4 5

import (
	"bytes"
	"context"
6
	"encoding/hex"
7
	"fmt"
8 9 10
	"io"
	"io/ioutil"
	"math"
11
	"math/rand"
12 13 14 15 16 17
	"os"
	"strconv"
	"strings"
	"sync"
	"testing"

Łukasz Magiera's avatar
Łukasz Magiera committed
18 19
	coreiface "github.com/ipfs/interface-go-ipfs-core"
	"github.com/ipfs/interface-go-ipfs-core/options"
20

Łukasz Magiera's avatar
Łukasz Magiera committed
21 22 23 24 25 26 27
	"github.com/ipfs/go-cid"
	"github.com/ipfs/go-ipfs-files"
	cbor "github.com/ipfs/go-ipld-cbor"
	mdag "github.com/ipfs/go-merkledag"
	"github.com/ipfs/go-unixfs"
	"github.com/ipfs/go-unixfs/importer/helpers"
	mh "github.com/multiformats/go-multihash"
28 29
)

30
func (tp *provider) TestUnixfs(t *testing.T) {
31 32 33 34 35 36 37
	tp.hasApi(t, func(api coreiface.CoreAPI) error {
		if api.Unixfs() == nil {
			return apiNotImplemented
		}
		return nil
	})

38 39 40 41 42 43 44 45 46 47 48
	t.Run("TestAdd", tp.TestAdd)
	t.Run("TestAddPinned", tp.TestAddPinned)
	t.Run("TestAddHashOnly", tp.TestAddHashOnly)
	t.Run("TestGetEmptyFile", tp.TestGetEmptyFile)
	t.Run("TestGetDir", tp.TestGetDir)
	t.Run("TestGetNonUnixfs", tp.TestGetNonUnixfs)
	t.Run("TestLs", tp.TestLs)
	t.Run("TestEntriesExpired", tp.TestEntriesExpired)
	t.Run("TestLsEmptyDir", tp.TestLsEmptyDir)
	t.Run("TestLsNonUnixfs", tp.TestLsNonUnixfs)
	t.Run("TestAddCloses", tp.TestAddCloses)
49
	t.Run("TestGetSeek", tp.TestGetSeek)
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
// `echo -n 'hello, world!' | ipfs add`
var hello = "/ipfs/QmQy2Dw4Wk7rdJKjThjYXzfFJNaRKRHhHP5gHHXroJMYxk"
var helloStr = "hello, world!"

// `echo -n | ipfs add`
var emptyFile = "/ipfs/QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH"

func strFile(data string) func() files.Node {
	return func() files.Node {
		return files.NewBytesFile([]byte(data))
	}
}

func twoLevelDir() func() files.Node {
	return func() files.Node {
		return files.NewMapDirectory(map[string]files.Node{
			"abc": files.NewMapDirectory(map[string]files.Node{
				"def": files.NewBytesFile([]byte("world")),
			}),

			"bar": files.NewBytesFile([]byte("hello2")),
			"foo": files.NewBytesFile([]byte("hello1")),
		})
	}
}

func flatDir() files.Node {
	return files.NewMapDirectory(map[string]files.Node{
		"bar": files.NewBytesFile([]byte("hello2")),
		"foo": files.NewBytesFile([]byte("hello1")),
	})
}

85
func wrapped(names ...string) func(f files.Node) files.Node {
86
	return func(f files.Node) files.Node {
87 88 89 90 91 92
		for i := range names {
			f = files.NewMapDirectory(map[string]files.Node{
				names[len(names)-i-1]: f,
			})
		}
		return f
93 94 95
	}
}

96
func (tp *provider) TestAdd(t *testing.T) {
97 98
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
99
	api, err := tp.makeAPI(ctx)
100 101 102 103 104 105 106 107 108 109 110 111
	if err != nil {
		t.Error(err)
	}

	p := func(h string) coreiface.ResolvedPath {
		c, err := cid.Parse(h)
		if err != nil {
			t.Fatal(err)
		}
		return coreiface.IpfsPath(c)
	}

Łukasz Magiera's avatar
Łukasz Magiera committed
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
	rf, err := ioutil.TempFile(os.TempDir(), "unixfs-add-real")
	if err != nil {
		t.Fatal(err)
	}
	rfp := rf.Name()

	if _, err := rf.Write([]byte(helloStr)); err != nil {
		t.Fatal(err)
	}

	stat, err := rf.Stat()
	if err != nil {
		t.Fatal(err)
	}

	if err := rf.Close(); err != nil {
		t.Fatal(err)
	}
	defer os.Remove(rfp)

	realFile := func() files.Node {
		n, err := files.NewReaderPathFile(rfp, ioutil.NopCloser(strings.NewReader(helloStr)), stat)
		if err != nil {
			t.Fatal(err)
		}
		return n
	}

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
	cases := []struct {
		name   string
		data   func() files.Node
		expect func(files.Node) files.Node

		apiOpts []options.ApiOption

		path string
		err  string

		wrap string

		events []coreiface.AddEvent

		opts []options.UnixfsAddOption
	}{
		// Simple cases
		{
			name: "simpleAdd",
			data: strFile(helloStr),
			path: hello,
			opts: []options.UnixfsAddOption{},
		},
		{
			name: "addEmpty",
			data: strFile(""),
			path: emptyFile,
		},
		// CIDv1 version / rawLeaves
		{
			name: "addCidV1",
			data: strFile(helloStr),
			path: "/ipfs/zb2rhdhmJjJZs9qkhQCpCQ7VREFkqWw3h1r8utjVvQugwHPFd",
			opts: []options.UnixfsAddOption{options.Unixfs.CidVersion(1)},
		},
		{
			name: "addCidV1NoLeaves",
			data: strFile(helloStr),
			path: "/ipfs/zdj7WY4GbN8NDbTW1dfCShAQNVovams2xhq9hVCx5vXcjvT8g",
			opts: []options.UnixfsAddOption{options.Unixfs.CidVersion(1), options.Unixfs.RawLeaves(false)},
		},
		// Non sha256 hash vs CID
		{
			name: "addCidSha3",
			data: strFile(helloStr),
			path: "/ipfs/zb2wwnYtXBxpndNABjtYxWAPt3cwWNRnc11iT63fvkYV78iRb",
			opts: []options.UnixfsAddOption{options.Unixfs.Hash(mh.SHA3_256)},
		},
		{
			name: "addCidSha3Cid0",
			data: strFile(helloStr),
			err:  "CIDv0 only supports sha2-256",
			opts: []options.UnixfsAddOption{options.Unixfs.CidVersion(0), options.Unixfs.Hash(mh.SHA3_256)},
		},
		// Inline
		{
			name: "addInline",
			data: strFile(helloStr),
			path: "/ipfs/zaYomJdLndMku8P9LHngHB5w2CQ7NenLbv",
			opts: []options.UnixfsAddOption{options.Unixfs.Inline(true)},
		},
		{
			name: "addInlineLimit",
			data: strFile(helloStr),
			path: "/ipfs/zaYomJdLndMku8P9LHngHB5w2CQ7NenLbv",
			opts: []options.UnixfsAddOption{options.Unixfs.InlineLimit(32), options.Unixfs.Inline(true)},
		},
		{
			name: "addInlineZero",
			data: strFile(""),
			path: "/ipfs/z2yYDV",
			opts: []options.UnixfsAddOption{options.Unixfs.InlineLimit(0), options.Unixfs.Inline(true), options.Unixfs.RawLeaves(true)},
		},
		{ //TODO: after coreapi add is used in `ipfs add`, consider making this default for inline
			name: "addInlineRaw",
			data: strFile(helloStr),
			path: "/ipfs/zj7Gr8AcBreqGEfrnR5kPFe",
			opts: []options.UnixfsAddOption{options.Unixfs.InlineLimit(32), options.Unixfs.Inline(true), options.Unixfs.RawLeaves(true)},
		},
		// Chunker / Layout
		{
			name: "addChunks",
			data: strFile(strings.Repeat("aoeuidhtns", 200)),
			path: "/ipfs/QmRo11d4QJrST47aaiGVJYwPhoNA4ihRpJ5WaxBWjWDwbX",
			opts: []options.UnixfsAddOption{options.Unixfs.Chunker("size-4")},
		},
		{
			name: "addChunksTrickle",
			data: strFile(strings.Repeat("aoeuidhtns", 200)),
			path: "/ipfs/QmNNhDGttafX3M1wKWixGre6PrLFGjnoPEDXjBYpTv93HP",
			opts: []options.UnixfsAddOption{options.Unixfs.Chunker("size-4"), options.Unixfs.Layout(options.TrickleLayout)},
		},
		// Local
		{
			name:    "addLocal", // better cases in sharness
			data:    strFile(helloStr),
			path:    hello,
			apiOpts: []options.ApiOption{options.Api.Offline(true)},
		},
		{
			name: "hashOnly", // test (non)fetchability
			data: strFile(helloStr),
			path: hello,
			opts: []options.UnixfsAddOption{options.Unixfs.HashOnly(true)},
		},
		// multi file
		{
247
			name: "simpleDirNoWrap",
248 249 250 251
			data: flatDir,
			path: "/ipfs/QmRKGpFfR32FVXdvJiHfo4WJ5TDYBsM1P9raAp1p6APWSp",
		},
		{
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
			name:   "simpleDirWrap",
			data:   flatDir,
			expect: wrapped("QmRKGpFfR32FVXdvJiHfo4WJ5TDYBsM1P9raAp1p6APWSp"),
			path:   "/ipfs/QmXxCaQkC8Z6Qws1nTkTQfCsL9y4XvWXnrPokp9bhmjC1L",
			opts:   []options.UnixfsAddOption{options.Unixfs.Wrap(true)},
		},
		{
			name:   "simpleDir",
			data:   flatDir,
			wrap:   "t",
			expect: wrapped("t"),
			path:   "/ipfs/Qmc3nGXm1HtUVCmnXLQHvWcNwfdZGpfg2SRm1CxLf7Q2Rm",
		},
		{
			name:   "twoLevelDir",
			data:   twoLevelDir(),
			wrap:   "t",
			expect: wrapped("t"),
			path:   "/ipfs/QmPwsL3T5sWhDmmAWZHAzyjKtMVDS9a11aHNRqb3xoVnmg",
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
		},
		// wrapped
		{
			name: "addWrapped",
			path: "/ipfs/QmVE9rNpj5doj7XHzp5zMUxD7BJgXEqx4pe3xZ3JBReWHE",
			data: func() files.Node {
				return files.NewBytesFile([]byte(helloStr))
			},
			wrap:   "foo",
			expect: wrapped("foo"),
		},
		{
			name: "stdinWrapped",
			path: "/ipfs/QmU3r81oZycjHS9oaSHw37ootMFuFUw1DvMLKXPsezdtqU",
			data: func() files.Node {
				return files.NewBytesFile([]byte(helloStr))
			},
			expect: func(files.Node) files.Node {
				return files.NewMapDirectory(map[string]files.Node{
					"QmQy2Dw4Wk7rdJKjThjYXzfFJNaRKRHhHP5gHHXroJMYxk": files.NewBytesFile([]byte(helloStr)),
				})
			},
			opts: []options.UnixfsAddOption{options.Unixfs.Wrap(true)},
		},
		{
			name: "stdinNamed",
			path: "/ipfs/QmQ6cGBmb3ZbdrQW1MRm1RJnYnaxCqfssz7CrTa9NEhQyS",
			data: func() files.Node {
				rf, err := files.NewReaderPathFile(os.Stdin.Name(), ioutil.NopCloser(strings.NewReader(helloStr)), nil)
				if err != nil {
					panic(err)
				}

				return rf
			},
			expect: func(files.Node) files.Node {
				return files.NewMapDirectory(map[string]files.Node{
					"test": files.NewBytesFile([]byte(helloStr)),
				})
			},
			opts: []options.UnixfsAddOption{options.Unixfs.Wrap(true), options.Unixfs.StdinName("test")},
		},
		{
			name:   "twoLevelDirWrapped",
			data:   twoLevelDir(),
			wrap:   "t",
317 318
			expect: wrapped("QmPwsL3T5sWhDmmAWZHAzyjKtMVDS9a11aHNRqb3xoVnmg", "t"),
			path:   "/ipfs/QmXzZwAh34pmNjuKsVGZfpbByis5S5qeZjCCUxa1ajZqzH",
319 320 321 322 323 324
			opts:   []options.UnixfsAddOption{options.Unixfs.Wrap(true)},
		},
		{
			name:   "twoLevelInlineHash",
			data:   twoLevelDir(),
			wrap:   "t",
325 326
			expect: wrapped("zBunoruKoyCHKkALNSWxDvj4L7yuQnMgQ4hUa9j1Z64tVcDEcu6Zdetyu7eeFCxMPfxb7YJvHeFHoFoHMkBUQf6vfdhmi", "t"),
			path:   "/ipfs/QmUX6GykDGHTMtLmDkfjqs48QwQK82vou51xwaY9TSU7Zo",
327 328 329 330 331 332 333 334 335 336 337 338
			opts:   []options.UnixfsAddOption{options.Unixfs.Wrap(true), options.Unixfs.Inline(true), options.Unixfs.RawLeaves(true), options.Unixfs.Hash(mh.SHA3)},
		},
		// hidden
		{
			name: "hiddenFiles",
			data: func() files.Node {
				return files.NewMapDirectory(map[string]files.Node{
					".bar": files.NewBytesFile([]byte("hello2")),
					"bar":  files.NewBytesFile([]byte("hello2")),
					"foo":  files.NewBytesFile([]byte("hello1")),
				})
			},
339 340 341 342
			wrap:   "t",
			expect: wrapped("t"),
			path:   "/ipfs/QmPXLSBX382vJDLrGakcbrZDkU3grfkjMox7EgSC9KFbtQ",
			opts:   []options.UnixfsAddOption{options.Unixfs.Hidden(true)},
343 344
		},
		{
345
			name: "topHiddenFileAdded",
346 347 348
			data: func() files.Node {
				return files.NewBytesFile([]byte(helloStr))
			},
349 350 351 352
			wrap:   ".foo",
			expect: wrapped(".foo"),
			path:   "/ipfs/QmciAVG3krCbvzUaK9gr6jUgfEjQtYmuuXi1n67teQ4Ni2",
			opts:   []options.UnixfsAddOption{options.Unixfs.TopHidden(true)},
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
		},
		{
			name: "hiddenFilesNotAdded",
			data: func() files.Node {
				return files.NewMapDirectory(map[string]files.Node{
					".bar": files.NewBytesFile([]byte("hello2")),
					"bar":  files.NewBytesFile([]byte("hello2")),
					"foo":  files.NewBytesFile([]byte("hello1")),
				})
			},
			expect: func(files.Node) files.Node {
				return flatDir()
			},
			path: "/ipfs/QmRKGpFfR32FVXdvJiHfo4WJ5TDYBsM1P9raAp1p6APWSp",
			opts: []options.UnixfsAddOption{options.Unixfs.Hidden(false)},
		},
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
		{
			name: "hiddenFilesWrappedNotAdded",
			data: func() files.Node {
				return files.NewMapDirectory(map[string]files.Node{
					".bar": files.NewBytesFile([]byte("hello2")),
					"bar":  files.NewBytesFile([]byte("hello2")),
					"foo":  files.NewBytesFile([]byte("hello1")),
				})
			},
			expect: func(files.Node) files.Node {
				return wrapped("t")(flatDir())
			},
			wrap: "t",
			path: "/ipfs/Qmc3nGXm1HtUVCmnXLQHvWcNwfdZGpfg2SRm1CxLf7Q2Rm",
			opts: []options.UnixfsAddOption{options.Unixfs.Hidden(false)},
		},
Łukasz Magiera's avatar
Łukasz Magiera committed
385 386 387 388 389 390 391 392 393 394 395 396 397 398
		// NoCopy
		{
			name: "simpleNoCopy",
			data: realFile,
			path: "/ipfs/zb2rhdhmJjJZs9qkhQCpCQ7VREFkqWw3h1r8utjVvQugwHPFd",
			opts: []options.UnixfsAddOption{options.Unixfs.Nocopy(true)},
		},
		{
			name: "noCopyNoRaw",
			data: realFile,
			path: "/ipfs/zb2rhdhmJjJZs9qkhQCpCQ7VREFkqWw3h1r8utjVvQugwHPFd",
			opts: []options.UnixfsAddOption{options.Unixfs.Nocopy(true), options.Unixfs.RawLeaves(false)},
			err:  "nocopy option requires '--raw-leaves' to be enabled as well",
		},
399 400 401 402 403 404 405
		{
			name: "noCopyNoPath",
			data: strFile(helloStr),
			path: "/ipfs/zb2rhdhmJjJZs9qkhQCpCQ7VREFkqWw3h1r8utjVvQugwHPFd",
			opts: []options.UnixfsAddOption{options.Unixfs.Nocopy(true)},
			err:  helpers.ErrMissingFsRef.Error(),
		},
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
		// Events / Progress
		{
			name: "simpleAddEvent",
			data: strFile(helloStr),
			path: "/ipfs/zb2rhdhmJjJZs9qkhQCpCQ7VREFkqWw3h1r8utjVvQugwHPFd",
			events: []coreiface.AddEvent{
				{Name: "zb2rhdhmJjJZs9qkhQCpCQ7VREFkqWw3h1r8utjVvQugwHPFd", Path: p("zb2rhdhmJjJZs9qkhQCpCQ7VREFkqWw3h1r8utjVvQugwHPFd"), Size: strconv.Itoa(len(helloStr))},
			},
			opts: []options.UnixfsAddOption{options.Unixfs.RawLeaves(true)},
		},
		{
			name: "silentAddEvent",
			data: twoLevelDir(),
			path: "/ipfs/QmVG2ZYCkV1S4TK8URA3a4RupBF17A8yAr4FqsRDXVJASr",
			events: []coreiface.AddEvent{
421 422
				{Name: "abc", Path: p("QmU7nuGs2djqK99UNsNgEPGh6GV4662p6WtsgccBNGTDxt"), Size: "62"},
				{Name: "", Path: p("QmVG2ZYCkV1S4TK8URA3a4RupBF17A8yAr4FqsRDXVJASr"), Size: "229"},
423 424 425 426 427 428 429 430
			},
			opts: []options.UnixfsAddOption{options.Unixfs.Silent(true)},
		},
		{
			name: "dirAddEvents",
			data: twoLevelDir(),
			path: "/ipfs/QmVG2ZYCkV1S4TK8URA3a4RupBF17A8yAr4FqsRDXVJASr",
			events: []coreiface.AddEvent{
431 432 433 434 435
				{Name: "abc/def", Path: p("QmNyJpQkU1cEkBwMDhDNFstr42q55mqG5GE5Mgwug4xyGk"), Size: "13"},
				{Name: "bar", Path: p("QmS21GuXiRMvJKHos4ZkEmQDmRBqRaF5tQS2CQCu2ne9sY"), Size: "14"},
				{Name: "foo", Path: p("QmfAjGiVpTN56TXi6SBQtstit5BEw3sijKj1Qkxn6EXKzJ"), Size: "14"},
				{Name: "abc", Path: p("QmU7nuGs2djqK99UNsNgEPGh6GV4662p6WtsgccBNGTDxt"), Size: "62"},
				{Name: "", Path: p("QmVG2ZYCkV1S4TK8URA3a4RupBF17A8yAr4FqsRDXVJASr"), Size: "229"},
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
			},
		},
		{
			name: "progress1M",
			data: func() files.Node {
				return files.NewReaderFile(bytes.NewReader(bytes.Repeat([]byte{0}, 1000000)))
			},
			path: "/ipfs/QmXXNNbwe4zzpdMg62ZXvnX1oU7MwSrQ3vAEtuwFKCm1oD",
			events: []coreiface.AddEvent{
				{Name: "", Bytes: 262144},
				{Name: "", Bytes: 524288},
				{Name: "", Bytes: 786432},
				{Name: "", Bytes: 1000000},
				{Name: "QmXXNNbwe4zzpdMg62ZXvnX1oU7MwSrQ3vAEtuwFKCm1oD", Path: p("QmXXNNbwe4zzpdMg62ZXvnX1oU7MwSrQ3vAEtuwFKCm1oD"), Size: "1000256"},
			},
			wrap: "",
			opts: []options.UnixfsAddOption{options.Unixfs.Progress(true)},
		},
	}

	for _, testCase := range cases {
		t.Run(testCase.name, func(t *testing.T) {
			ctx, cancel := context.WithCancel(ctx)
			defer cancel()

			// recursive logic

			data := testCase.data()
			if testCase.wrap != "" {
				data = files.NewMapDirectory(map[string]files.Node{
					testCase.wrap: data,
				})
			}

			// handle events if relevant to test case

			opts := testCase.opts
			eventOut := make(chan interface{})
			var evtWg sync.WaitGroup
			if len(testCase.events) > 0 {
				opts = append(opts, options.Unixfs.Events(eventOut))
				evtWg.Add(1)

				go func() {
					defer evtWg.Done()
					expected := testCase.events

					for evt := range eventOut {
						event, ok := evt.(*coreiface.AddEvent)
						if !ok {
							t.Fatal("unexpected event type")
						}

						if len(expected) < 1 {
							t.Fatal("got more events than expected")
						}

						if expected[0].Size != event.Size {
							t.Errorf("Event.Size didn't match, %s != %s", expected[0].Size, event.Size)
						}

						if expected[0].Name != event.Name {
							t.Errorf("Event.Name didn't match, %s != %s", expected[0].Name, event.Name)
						}

						if expected[0].Path != nil && event.Path != nil {
							if expected[0].Path.Cid().String() != event.Path.Cid().String() {
								t.Errorf("Event.Hash didn't match, %s != %s", expected[0].Path, event.Path)
							}
						} else if event.Path != expected[0].Path {
							t.Errorf("Event.Hash didn't match, %s != %s", expected[0].Path, event.Path)
						}
						if expected[0].Bytes != event.Bytes {
							t.Errorf("Event.Bytes didn't match, %d != %d", expected[0].Bytes, event.Bytes)
						}

						expected = expected[1:]
					}

					if len(expected) > 0 {
						t.Fatalf("%d event(s) didn't arrive", len(expected))
					}
				}()
			}

			tapi, err := api.WithOptions(testCase.apiOpts...)
			if err != nil {
				t.Fatal(err)
			}

			// Add!

			p, err := tapi.Unixfs().Add(ctx, data, opts...)
			close(eventOut)
			evtWg.Wait()
			if testCase.err != "" {
				if err == nil {
					t.Fatalf("expected an error: %s", testCase.err)
				}
				if err.Error() != testCase.err {
					t.Fatalf("expected an error: '%s' != '%s'", err.Error(), testCase.err)
				}
				return
			}
			if err != nil {
				t.Fatal(err)
			}

			if p.String() != testCase.path {
				t.Errorf("expected path %s, got: %s", testCase.path, p)
			}

			// compare file structure with Unixfs().Get

			var cmpFile func(origName string, orig files.Node, gotName string, got files.Node)
			cmpFile = func(origName string, orig files.Node, gotName string, got files.Node) {
				_, origDir := orig.(files.Directory)
				_, gotDir := got.(files.Directory)

				if origName != gotName {
					t.Errorf("file name mismatch, orig='%s', got='%s'", origName, gotName)
				}

559 560 561 562
				if origDir != gotDir {
					t.Fatalf("file type mismatch on %s", origName)
				}

563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
				if !gotDir {
					defer orig.Close()
					defer got.Close()

					do, err := ioutil.ReadAll(orig.(files.File))
					if err != nil {
						t.Fatal(err)
					}

					dg, err := ioutil.ReadAll(got.(files.File))
					if err != nil {
						t.Fatal(err)
					}

					if !bytes.Equal(do, dg) {
						t.Fatal("data not equal")
					}

					return
				}

				origIt := orig.(files.Directory).Entries()
				gotIt := got.(files.Directory).Entries()

				for {
					if origIt.Next() {
						if !gotIt.Next() {
							t.Fatal("gotIt out of entries before origIt")
						}
					} else {
						if gotIt.Next() {
							t.Fatal("origIt out of entries before gotIt")
						}
						break
					}

					cmpFile(origIt.Name(), origIt.Node(), gotIt.Name(), gotIt.Node())
				}
				if origIt.Err() != nil {
					t.Fatal(origIt.Err())
				}
				if gotIt.Err() != nil {
					t.Fatal(gotIt.Err())
				}
			}

			f, err := tapi.Unixfs().Get(ctx, p)
			if err != nil {
				t.Fatal(err)
			}

			orig := testCase.data()
			if testCase.expect != nil {
				orig = testCase.expect(orig)
			}

			cmpFile("", orig, "", f)
		})
	}
}

624
func (tp *provider) TestAddPinned(t *testing.T) {
625 626
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
627
	api, err := tp.makeAPI(ctx)
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
	if err != nil {
		t.Error(err)
	}

	_, err = api.Unixfs().Add(ctx, strFile(helloStr)(), options.Unixfs.Pin(true))
	if err != nil {
		t.Error(err)
	}

	pins, err := api.Pin().Ls(ctx)
	if len(pins) != 1 {
		t.Fatalf("expected 1 pin, got %d", len(pins))
	}

	if pins[0].Path().String() != "/ipld/QmQy2Dw4Wk7rdJKjThjYXzfFJNaRKRHhHP5gHHXroJMYxk" {
		t.Fatalf("got unexpected pin: %s", pins[0].Path().String())
	}
}

647
func (tp *provider) TestAddHashOnly(t *testing.T) {
648 649
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
650
	api, err := tp.makeAPI(ctx)
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
	if err != nil {
		t.Error(err)
	}

	p, err := api.Unixfs().Add(ctx, strFile(helloStr)(), options.Unixfs.HashOnly(true))
	if err != nil {
		t.Error(err)
	}

	if p.String() != hello {
		t.Errorf("unxepected path: %s", p.String())
	}

	_, err = api.Block().Get(ctx, p)
	if err == nil {
		t.Fatal("expected an error")
	}
668
	if !strings.Contains(err.Error(), "blockservice: key not found") {
669 670 671 672
		t.Errorf("unxepected error: %s", err.Error())
	}
}

673
func (tp *provider) TestGetEmptyFile(t *testing.T) {
674 675
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
676
	api, err := tp.makeAPI(ctx)
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
	if err != nil {
		t.Fatal(err)
	}

	_, err = api.Unixfs().Add(ctx, files.NewBytesFile([]byte{}))
	if err != nil {
		t.Fatal(err)
	}

	emptyFilePath, err := coreiface.ParsePath(emptyFile)
	if err != nil {
		t.Fatal(err)
	}

	r, err := api.Unixfs().Get(ctx, emptyFilePath)
	if err != nil {
		t.Fatal(err)
	}

	buf := make([]byte, 1) // non-zero so that Read() actually tries to read
	n, err := io.ReadFull(r.(files.File), buf)
	if err != nil && err != io.EOF {
		t.Error(err)
	}
	if !bytes.HasPrefix(buf, []byte{0x00}) {
		t.Fatalf("expected empty data, got [%s] [read=%d]", buf, n)
	}
}

706
func (tp *provider) TestGetDir(t *testing.T) {
707 708
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
709
	api, err := tp.makeAPI(ctx)
710 711 712 713
	if err != nil {
		t.Error(err)
	}
	edir := unixfs.EmptyDirNode()
714
	err = api.Dag().Add(ctx, edir)
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
	if err != nil {
		t.Error(err)
	}
	p := coreiface.IpfsPath(edir.Cid())

	emptyDir, err := api.Object().New(ctx, options.Object.Type("unixfs-dir"))
	if err != nil {
		t.Error(err)
	}

	if p.String() != coreiface.IpfsPath(emptyDir.Cid()).String() {
		t.Fatalf("expected path %s, got: %s", emptyDir.Cid(), p.String())
	}

	r, err := api.Unixfs().Get(ctx, coreiface.IpfsPath(emptyDir.Cid()))
	if err != nil {
		t.Error(err)
	}

	if _, ok := r.(files.Directory); !ok {
		t.Fatalf("expected a directory")
	}
}

739
func (tp *provider) TestGetNonUnixfs(t *testing.T) {
740 741
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
742
	api, err := tp.makeAPI(ctx)
743 744 745 746 747
	if err != nil {
		t.Error(err)
	}

	nd := new(mdag.ProtoNode)
748
	err = api.Dag().Add(ctx, nd)
749 750 751 752 753 754 755 756 757 758
	if err != nil {
		t.Error(err)
	}

	_, err = api.Unixfs().Get(ctx, coreiface.IpfsPath(nd.Cid()))
	if !strings.Contains(err.Error(), "proto: required field") {
		t.Fatalf("expected protobuf error, got: %s", err)
	}
}

759
func (tp *provider) TestLs(t *testing.T) {
760 761
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
762
	api, err := tp.makeAPI(ctx)
763
	if err != nil {
Steven Allen's avatar
Steven Allen committed
764
		t.Fatal(err)
765 766 767 768 769
	}

	r := strings.NewReader("content-of-file")
	p, err := api.Unixfs().Add(ctx, files.NewMapDirectory(map[string]files.Node{
		"0": files.NewMapDirectory(map[string]files.Node{
Steven Allen's avatar
Steven Allen committed
770 771
			"name-of-file":    files.NewReaderFile(r),
			"name-of-symlink": files.NewLinkFile("/foo/bar", nil),
772 773 774
		}),
	}))
	if err != nil {
Steven Allen's avatar
Steven Allen committed
775
		t.Fatal(err)
776 777
	}

Steven Allen's avatar
Steven Allen committed
778
	entries, err := api.Unixfs().Ls(ctx, p)
779
	if err != nil {
Steven Allen's avatar
Steven Allen committed
780
		t.Fatal(err)
781 782
	}

Steven Allen's avatar
Steven Allen committed
783 784 785
	entry := <-entries
	if entry.Err != nil {
		t.Fatal(entry.Err)
786
	}
Steven Allen's avatar
Steven Allen committed
787
	if entry.Size != 15 {
Steven Allen's avatar
Steven Allen committed
788
		t.Errorf("expected size = 15, got %d", entry.Size)
Łukasz Magiera's avatar
Łukasz Magiera committed
789
	}
Steven Allen's avatar
Steven Allen committed
790
	if entry.Name != "name-of-file" {
Steven Allen's avatar
Steven Allen committed
791 792 793 794
		t.Errorf("expected name = name-of-file, got %s", entry.Name)
	}
	if entry.Type != coreiface.TFile {
		t.Errorf("wrong type %s", entry.Type)
Łukasz Magiera's avatar
Łukasz Magiera committed
795
	}
Steven Allen's avatar
Steven Allen committed
796
	if entry.Cid.String() != "QmX3qQVKxDGz3URVC3861Z3CKtQKGBn6ffXRBBWGMFz9Lr" {
Steven Allen's avatar
Steven Allen committed
797 798 799 800 801 802 803 804 805 806 807 808
		t.Errorf("expected cid = QmX3qQVKxDGz3URVC3861Z3CKtQKGBn6ffXRBBWGMFz9Lr, got %s", entry.Cid)
	}
	entry = <-entries
	if entry.Err != nil {
		t.Fatal(entry.Err)
	}
	if entry.Type != coreiface.TSymlink {
		t.Errorf("wrong type %s", entry.Type)
	}
	if entry.Name != "name-of-symlink" {
		t.Errorf("expected name = name-of-symlink, got %s", entry.Name)
	}
809
	if entry.Target != "/foo/bar" {
Steven Allen's avatar
Steven Allen committed
810 811 812
		t.Errorf("expected symlink target to be /foo/bar, got %s", entry.Target)
	}

Steven Allen's avatar
Steven Allen committed
813
	if l, ok := <-entries; ok {
Łukasz Magiera's avatar
Łukasz Magiera committed
814
		t.Errorf("didn't expect a second link")
815 816 817
		if l.Err != nil {
			t.Error(l.Err)
		}
Łukasz Magiera's avatar
Łukasz Magiera committed
818
	}
819 820
}

821
func (tp *provider) TestEntriesExpired(t *testing.T) {
822 823
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
824
	api, err := tp.makeAPI(ctx)
825 826 827 828 829 830
	if err != nil {
		t.Error(err)
	}

	r := strings.NewReader("content-of-file")
	p, err := api.Unixfs().Add(ctx, files.NewMapDirectory(map[string]files.Node{
831
		"name-of-file": files.NewReaderFile(r),
832 833 834 835 836
	}))
	if err != nil {
		t.Error(err)
	}

837
	ctx, cancel = context.WithCancel(ctx)
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862

	nd, err := api.Unixfs().Get(ctx, p)
	if err != nil {
		t.Error(err)
	}
	cancel()

	it := files.ToDir(nd).Entries()
	if it == nil {
		t.Fatal("it was nil")
	}

	if it.Next() {
		t.Fatal("Next succeeded")
	}

	if it.Err() != context.Canceled {
		t.Fatalf("unexpected error %s", it.Err())
	}

	if it.Next() {
		t.Fatal("Next succeeded")
	}
}

863
func (tp *provider) TestLsEmptyDir(t *testing.T) {
864 865
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
866
	api, err := tp.makeAPI(ctx)
867 868 869 870
	if err != nil {
		t.Error(err)
	}

871
	_, err = api.Unixfs().Add(ctx, files.NewSliceDirectory([]files.DirEntry{}))
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
	if err != nil {
		t.Error(err)
	}

	emptyDir, err := api.Object().New(ctx, options.Object.Type("unixfs-dir"))
	if err != nil {
		t.Error(err)
	}

	links, err := api.Unixfs().Ls(ctx, coreiface.IpfsPath(emptyDir.Cid()))
	if err != nil {
		t.Error(err)
	}

	if len(links) != 0 {
		t.Fatalf("expected 0 links, got %d", len(links))
	}
}

// TODO(lgierth) this should test properly, with len(links) > 0
892
func (tp *provider) TestLsNonUnixfs(t *testing.T) {
893 894
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
895
	api, err := tp.makeAPI(ctx)
896 897 898 899 900 901 902 903 904
	if err != nil {
		t.Error(err)
	}

	nd, err := cbor.WrapObject(map[string]interface{}{"foo": "bar"}, math.MaxUint64, -1)
	if err != nil {
		t.Fatal(err)
	}

905
	err = api.Dag().Add(ctx, nd)
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
	if err != nil {
		t.Error(err)
	}

	links, err := api.Unixfs().Ls(ctx, coreiface.IpfsPath(nd.Cid()))
	if err != nil {
		t.Error(err)
	}

	if len(links) != 0 {
		t.Fatalf("expected 0 links, got %d", len(links))
	}
}

type closeTestF struct {
	files.File
	closed bool

	t *testing.T
}

type closeTestD struct {
	files.Directory
	closed bool

	t *testing.T
}

func (f *closeTestD) Close() error {
	if f.closed {
		f.t.Fatal("already closed")
	}
	f.closed = true
	return nil
}

func (f *closeTestF) Close() error {
	if f.closed {
		f.t.Fatal("already closed")
	}
	f.closed = true
	return nil
}

950
func (tp *provider) TestAddCloses(t *testing.T) {
951 952
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
953
	api, err := tp.makeAPI(ctx)
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
	if err != nil {
		t.Error(err)
	}

	n4 := &closeTestF{files.NewBytesFile([]byte("foo")), false, t}
	d3 := &closeTestD{files.NewMapDirectory(map[string]files.Node{
		"sub": n4,
	}), false, t}
	n2 := &closeTestF{files.NewBytesFile([]byte("bar")), false, t}
	n1 := &closeTestF{files.NewBytesFile([]byte("baz")), false, t}
	d0 := &closeTestD{files.NewMapDirectory(map[string]files.Node{
		"a": d3,
		"b": n1,
		"c": n2,
	}), false, t}

	_, err = api.Unixfs().Add(ctx, d0)
	if err != nil {
		t.Error(err)
	}

	d0.Close() // Adder doesn't close top-level file

	for i, n := range []*closeTestF{n1, n2, n4} {
		if !n.closed {
			t.Errorf("file %d not closed!", i)
		}
	}

	for i, n := range []*closeTestD{d0, d3} {
		if !n.closed {
			t.Errorf("dir %d not closed!", i)
		}
	}
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
}

func (tp *provider) TestGetSeek(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	api, err := tp.makeAPI(ctx)
	if err != nil {
		t.Error(err)
	}

	dataSize := int64(100000)
	tf := files.NewReaderFile(io.LimitReader(rand.New(rand.NewSource(1403768328)), dataSize))

	p, err := api.Unixfs().Add(ctx, tf, options.Unixfs.Chunker("size-100"))
	if err != nil {
		t.Fatal(err)
	}

	r, err := api.Unixfs().Get(ctx, p)
	if err != nil {
		t.Fatal(err)
	}

	f := files.ToFile(r)
	if f == nil {
		t.Fatal("not a file")
	}

	orig := make([]byte, dataSize)
1017
	if _, err := io.ReadFull(f, orig); err != nil {
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
		t.Fatal(err)
	}
	f.Close()

	origR := bytes.NewReader(orig)

	r, err = api.Unixfs().Get(ctx, p)
	if err != nil {
		t.Fatal(err)
	}

	f = files.ToFile(r)
	if f == nil {
		t.Fatal("not a file")
	}

	test := func(offset int64, whence int, read int, expect int64, shouldEof bool) {
		t.Run(fmt.Sprintf("seek%d+%d-r%d-%d", whence, offset, read, expect), func(t *testing.T) {
			n, err := f.Seek(offset, whence)
			if err != nil {
				t.Fatal(err)
			}
			origN, err := origR.Seek(offset, whence)
			if err != nil {
				t.Fatal(err)
			}

			if n != origN {
				t.Fatalf("offsets didn't match, expected %d, got %d", origN, n)
			}

			buf := make([]byte, read)
			origBuf := make([]byte, read)
			origRead, err := origR.Read(origBuf)
			if err != nil {
				t.Fatalf("orig: %s", err)
			}
1055
			r, err := io.ReadFull(f, buf)
1056
			switch {
1057
			case shouldEof && err != nil && err != io.ErrUnexpectedEOF:
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
				fallthrough
			case !shouldEof && err != nil:
				t.Fatalf("f: %s", err)
			case shouldEof:
				_, err := f.Read([]byte{0})
				if err != io.EOF {
					t.Fatal("expected EOF")
				}
				_, err = origR.Read([]byte{0})
				if err != io.EOF {
					t.Fatal("expected EOF (orig)")
				}
			}

			if int64(r) != expect {
				t.Fatal("read wrong amount of data")
			}
			if r != origRead {
				t.Fatal("read different amount of data than bytes.Reader")
			}
			if !bytes.Equal(buf, origBuf) {
1079 1080
				fmt.Fprintf(os.Stderr, "original:\n%s\n", hex.Dump(origBuf))
				fmt.Fprintf(os.Stderr, "got:\n%s\n", hex.Dump(buf))
1081 1082 1083 1084
				t.Fatal("data didn't match")
			}
		})
	}
1085

1086 1087 1088 1089 1090
	test(3, io.SeekCurrent, 10, 10, false)
	test(3, io.SeekCurrent, 10, 10, false)
	test(500, io.SeekCurrent, 10, 10, false)
	test(350, io.SeekStart, 100, 100, false)
	test(-123, io.SeekCurrent, 100, 100, false)
1091
	test(0, io.SeekStart, int(dataSize), dataSize, false)
1092 1093
	test(dataSize-50, io.SeekStart, 100, 50, true)
	test(-5, io.SeekEnd, 100, 5, true)
1094
}