walk_test.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package scanner
  7. import (
  8. "bytes"
  9. "context"
  10. "crypto/rand"
  11. "fmt"
  12. "io"
  13. "io/ioutil"
  14. "os"
  15. "path/filepath"
  16. "runtime"
  17. rdebug "runtime/debug"
  18. "sort"
  19. "sync"
  20. "testing"
  21. "github.com/d4l3k/messagediff"
  22. "github.com/syncthing/syncthing/lib/events"
  23. "github.com/syncthing/syncthing/lib/fs"
  24. "github.com/syncthing/syncthing/lib/ignore"
  25. "github.com/syncthing/syncthing/lib/osutil"
  26. "github.com/syncthing/syncthing/lib/protocol"
  27. "github.com/syncthing/syncthing/lib/sha256"
  28. "golang.org/x/text/unicode/norm"
  29. )
  30. type testfile struct {
  31. name string
  32. length int64
  33. hash string
  34. }
  35. type testfileList []testfile
  36. var testFs fs.Filesystem
  37. var testdata = testfileList{
  38. {"afile", 4, "b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c"},
  39. {"dir1", 128, ""},
  40. {filepath.Join("dir1", "dfile"), 5, "49ae93732fcf8d63fe1cce759664982dbd5b23161f007dba8561862adc96d063"},
  41. {"dir2", 128, ""},
  42. {filepath.Join("dir2", "cfile"), 4, "bf07a7fbb825fc0aae7bf4a1177b2b31fcf8a3feeaf7092761e18c859ee52a9c"},
  43. {"excludes", 37, "df90b52f0c55dba7a7a940affe482571563b1ac57bd5be4d8a0291e7de928e06"},
  44. {"further-excludes", 5, "7eb0a548094fa6295f7fd9200d69973e5f5ec5c04f2a86d998080ac43ecf89f1"},
  45. }
  46. func init() {
  47. // This test runs the risk of entering infinite recursion if it fails.
  48. // Limit the stack size to 10 megs to crash early in that case instead of
  49. // potentially taking down the box...
  50. rdebug.SetMaxStack(10 * 1 << 20)
  51. testFs = fs.NewFilesystem(fs.FilesystemTypeBasic, "testdata")
  52. }
  53. func TestWalkSub(t *testing.T) {
  54. ignores := ignore.New(testFs)
  55. err := ignores.Load(".stignore")
  56. if err != nil {
  57. t.Fatal(err)
  58. }
  59. cfg := testConfig()
  60. cfg.Subs = []string{"dir2"}
  61. cfg.Matcher = ignores
  62. fchan := Walk(context.TODO(), cfg)
  63. var files []protocol.FileInfo
  64. for f := range fchan {
  65. if f.Err != nil {
  66. t.Errorf("Error while scanning %v: %v", f.Err, f.Path)
  67. }
  68. files = append(files, f.File)
  69. }
  70. // The directory contains two files, where one is ignored from a higher
  71. // level. We should see only the directory and one of the files.
  72. if len(files) != 2 {
  73. t.Fatalf("Incorrect length %d != 2", len(files))
  74. }
  75. if files[0].Name != "dir2" {
  76. t.Errorf("Incorrect file %v != dir2", files[0])
  77. }
  78. if files[1].Name != filepath.Join("dir2", "cfile") {
  79. t.Errorf("Incorrect file %v != dir2/cfile", files[1])
  80. }
  81. }
  82. func TestWalk(t *testing.T) {
  83. ignores := ignore.New(testFs)
  84. err := ignores.Load(".stignore")
  85. if err != nil {
  86. t.Fatal(err)
  87. }
  88. t.Log(ignores)
  89. cfg := testConfig()
  90. cfg.Matcher = ignores
  91. fchan := Walk(context.TODO(), cfg)
  92. var tmp []protocol.FileInfo
  93. for f := range fchan {
  94. if f.Err != nil {
  95. t.Errorf("Error while scanning %v: %v", f.Err, f.Path)
  96. }
  97. tmp = append(tmp, f.File)
  98. }
  99. sort.Sort(fileList(tmp))
  100. files := fileList(tmp).testfiles()
  101. if diff, equal := messagediff.PrettyDiff(testdata, files); !equal {
  102. t.Errorf("Walk returned unexpected data. Diff:\n%s", diff)
  103. }
  104. }
  105. func TestVerify(t *testing.T) {
  106. blocksize := 16
  107. // data should be an even multiple of blocksize long
  108. data := []byte("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut e")
  109. buf := bytes.NewBuffer(data)
  110. progress := newByteCounter()
  111. defer progress.Close()
  112. blocks, err := Blocks(context.TODO(), buf, blocksize, -1, progress, false)
  113. if err != nil {
  114. t.Fatal(err)
  115. }
  116. if exp := len(data) / blocksize; len(blocks) != exp {
  117. t.Fatalf("Incorrect number of blocks %d != %d", len(blocks), exp)
  118. }
  119. if int64(len(data)) != progress.Total() {
  120. t.Fatalf("Incorrect counter value %d != %d", len(data), progress.Total())
  121. }
  122. buf = bytes.NewBuffer(data)
  123. err = verify(buf, blocksize, blocks)
  124. t.Log(err)
  125. if err != nil {
  126. t.Fatal("Unexpected verify failure", err)
  127. }
  128. buf = bytes.NewBuffer(append(data, '\n'))
  129. err = verify(buf, blocksize, blocks)
  130. t.Log(err)
  131. if err == nil {
  132. t.Fatal("Unexpected verify success")
  133. }
  134. buf = bytes.NewBuffer(data[:len(data)-1])
  135. err = verify(buf, blocksize, blocks)
  136. t.Log(err)
  137. if err == nil {
  138. t.Fatal("Unexpected verify success")
  139. }
  140. data[42] = 42
  141. buf = bytes.NewBuffer(data)
  142. err = verify(buf, blocksize, blocks)
  143. t.Log(err)
  144. if err == nil {
  145. t.Fatal("Unexpected verify success")
  146. }
  147. }
  148. func TestNormalization(t *testing.T) {
  149. if runtime.GOOS == "darwin" {
  150. t.Skip("Normalization test not possible on darwin")
  151. return
  152. }
  153. os.RemoveAll("testdata/normalization")
  154. defer os.RemoveAll("testdata/normalization")
  155. tests := []string{
  156. "0-A", // ASCII A -- accepted
  157. "1-\xC3\x84", // NFC 'Ä' -- conflicts with the entry below, accepted
  158. "1-\x41\xCC\x88", // NFD 'Ä' -- conflicts with the entry above, ignored
  159. "2-\xC3\x85", // NFC 'Å' -- accepted
  160. "3-\x41\xCC\x83", // NFD 'Ã' -- converted to NFC
  161. "4-\xE2\x98\x95", // U+2615 HOT BEVERAGE (☕) -- accepted
  162. "5-\xCD\xE2", // EUC-CN "wài" (外) -- ignored (not UTF8)
  163. }
  164. numInvalid := 2
  165. if runtime.GOOS == "windows" {
  166. // On Windows, in case 5 the character gets replaced with a
  167. // replacement character \xEF\xBF\xBD at the point it's written to disk,
  168. // which means it suddenly becomes valid (sort of).
  169. numInvalid--
  170. }
  171. numValid := len(tests) - numInvalid
  172. for _, s1 := range tests {
  173. // Create a directory for each of the interesting strings above
  174. if err := testFs.MkdirAll(filepath.Join("normalization", s1), 0755); err != nil {
  175. t.Fatal(err)
  176. }
  177. for _, s2 := range tests {
  178. // Within each dir, create a file with each of the interesting
  179. // file names. Ensure that the file doesn't exist when it's
  180. // created. This detects and fails if there's file name
  181. // normalization stuff at the filesystem level.
  182. if fd, err := testFs.OpenFile(filepath.Join("normalization", s1, s2), os.O_CREATE|os.O_EXCL, 0644); err != nil {
  183. t.Fatal(err)
  184. } else {
  185. fd.Write([]byte("test"))
  186. fd.Close()
  187. }
  188. }
  189. }
  190. // We can normalize a directory name, but we can't descend into it in the
  191. // same pass due to how filepath.Walk works. So we run the scan twice to
  192. // make sure it all gets done. In production, things will be correct
  193. // eventually...
  194. walkDir(testFs, "normalization", nil, nil, 0)
  195. tmp := walkDir(testFs, "normalization", nil, nil, 0)
  196. files := fileList(tmp).testfiles()
  197. // We should have one file per combination, plus the directories
  198. // themselves, plus the "testdata/normalization" directory
  199. expectedNum := numValid*numValid + numValid + 1
  200. if len(files) != expectedNum {
  201. t.Errorf("Expected %d files, got %d", expectedNum, len(files))
  202. }
  203. // The file names should all be in NFC form.
  204. for _, f := range files {
  205. t.Logf("%q (% x) %v", f.name, f.name, norm.NFC.IsNormalString(f.name))
  206. if !norm.NFC.IsNormalString(f.name) {
  207. t.Errorf("File name %q is not NFC normalized", f.name)
  208. }
  209. }
  210. }
  211. func TestIssue1507(t *testing.T) {
  212. w := &walker{}
  213. w.Matcher = ignore.New(w.Filesystem)
  214. h := make(chan protocol.FileInfo, 100)
  215. f := make(chan ScanResult, 100)
  216. fn := w.walkAndHashFiles(context.TODO(), h, f)
  217. fn("", nil, protocol.ErrClosed)
  218. }
  219. func TestWalkSymlinkUnix(t *testing.T) {
  220. if runtime.GOOS == "windows" {
  221. t.Skip("skipping unsupported symlink test")
  222. return
  223. }
  224. // Create a folder with a symlink in it
  225. os.RemoveAll("_symlinks")
  226. os.Mkdir("_symlinks", 0755)
  227. defer os.RemoveAll("_symlinks")
  228. os.Symlink("../testdata", "_symlinks/link")
  229. fs := fs.NewFilesystem(fs.FilesystemTypeBasic, "_symlinks")
  230. for _, path := range []string{".", "link"} {
  231. // Scan it
  232. files := walkDir(fs, path, nil, nil, 0)
  233. // Verify that we got one symlink and with the correct attributes
  234. if len(files) != 1 {
  235. t.Errorf("expected 1 symlink, not %d", len(files))
  236. }
  237. if len(files[0].Blocks) != 0 {
  238. t.Errorf("expected zero blocks for symlink, not %d", len(files[0].Blocks))
  239. }
  240. if files[0].SymlinkTarget != "../testdata" {
  241. t.Errorf("expected symlink to have target destination, not %q", files[0].SymlinkTarget)
  242. }
  243. }
  244. }
  245. func TestWalkSymlinkWindows(t *testing.T) {
  246. if runtime.GOOS != "windows" {
  247. t.Skip("skipping unsupported symlink test")
  248. }
  249. // Create a folder with a symlink in it
  250. name := "_symlinks-win"
  251. os.RemoveAll(name)
  252. os.Mkdir(name, 0755)
  253. defer os.RemoveAll(name)
  254. fs := fs.NewFilesystem(fs.FilesystemTypeBasic, name)
  255. if err := osutil.DebugSymlinkForTestsOnly("../testdata", "_symlinks/link"); err != nil {
  256. // Probably we require permissions we don't have.
  257. t.Skip(err)
  258. }
  259. for _, path := range []string{".", "link"} {
  260. // Scan it
  261. files := walkDir(fs, path, nil, nil, 0)
  262. // Verify that we got zero symlinks
  263. if len(files) != 0 {
  264. t.Errorf("expected zero symlinks, not %d", len(files))
  265. }
  266. }
  267. }
  268. func TestWalkRootSymlink(t *testing.T) {
  269. // Create a folder with a symlink in it
  270. tmp, err := ioutil.TempDir("", "")
  271. if err != nil {
  272. t.Fatal(err)
  273. }
  274. defer os.RemoveAll(tmp)
  275. link := tmp + "/link"
  276. dest, _ := filepath.Abs("testdata/dir1")
  277. if err := osutil.DebugSymlinkForTestsOnly(dest, link); err != nil {
  278. if runtime.GOOS == "windows" {
  279. // Probably we require permissions we don't have.
  280. t.Skip("Need admin permissions or developer mode to run symlink test on Windows: " + err.Error())
  281. } else {
  282. t.Fatal(err)
  283. }
  284. }
  285. // Scan it
  286. files := walkDir(fs.NewFilesystem(fs.FilesystemTypeBasic, link), ".", nil, nil, 0)
  287. // Verify that we got two files
  288. if len(files) != 2 {
  289. t.Errorf("expected two files, not %d", len(files))
  290. }
  291. }
  292. func TestBlocksizeHysteresis(t *testing.T) {
  293. // Verify that we select the right block size in the presence of old
  294. // file information.
  295. if testing.Short() {
  296. t.Skip("long and hard test")
  297. }
  298. sf := fs.NewWalkFilesystem(&singleFileFS{
  299. name: "testfile.dat",
  300. filesize: 500 << 20, // 500 MiB
  301. })
  302. current := make(fakeCurrentFiler)
  303. runTest := func(expectedBlockSize int) {
  304. files := walkDir(sf, ".", current, nil, 0)
  305. if len(files) != 1 {
  306. t.Fatalf("expected one file, not %d", len(files))
  307. }
  308. if s := files[0].BlockSize(); s != expectedBlockSize {
  309. t.Fatalf("incorrect block size %d != expected %d", s, expectedBlockSize)
  310. }
  311. }
  312. // Scan with no previous knowledge. We should get a 512 KiB block size.
  313. runTest(512 << 10)
  314. // Scan on the assumption that previous size was 256 KiB. Retain 256 KiB
  315. // block size.
  316. current["testfile.dat"] = protocol.FileInfo{
  317. Name: "testfile.dat",
  318. Size: 500 << 20,
  319. RawBlockSize: 256 << 10,
  320. }
  321. runTest(256 << 10)
  322. // Scan on the assumption that previous size was 1 MiB. Retain 1 MiB
  323. // block size.
  324. current["testfile.dat"] = protocol.FileInfo{
  325. Name: "testfile.dat",
  326. Size: 500 << 20,
  327. RawBlockSize: 1 << 20,
  328. }
  329. runTest(1 << 20)
  330. // Scan on the assumption that previous size was 128 KiB. Move to 512
  331. // KiB because the difference is large.
  332. current["testfile.dat"] = protocol.FileInfo{
  333. Name: "testfile.dat",
  334. Size: 500 << 20,
  335. RawBlockSize: 128 << 10,
  336. }
  337. runTest(512 << 10)
  338. // Scan on the assumption that previous size was 2 MiB. Move to 512
  339. // KiB because the difference is large.
  340. current["testfile.dat"] = protocol.FileInfo{
  341. Name: "testfile.dat",
  342. Size: 500 << 20,
  343. RawBlockSize: 2 << 20,
  344. }
  345. runTest(512 << 10)
  346. }
  347. func TestWalkReceiveOnly(t *testing.T) {
  348. sf := fs.NewWalkFilesystem(&singleFileFS{
  349. name: "testfile.dat",
  350. filesize: 1024,
  351. })
  352. current := make(fakeCurrentFiler)
  353. // Initial scan, no files in the CurrentFiler. Should pick up the file and
  354. // set the ReceiveOnly flag on it, because that's the flag we give the
  355. // walker to set.
  356. files := walkDir(sf, ".", current, nil, protocol.FlagLocalReceiveOnly)
  357. if len(files) != 1 {
  358. t.Fatal("Should have scanned one file")
  359. }
  360. if files[0].LocalFlags != protocol.FlagLocalReceiveOnly {
  361. t.Fatal("Should have set the ReceiveOnly flag")
  362. }
  363. // Update the CurrentFiler and scan again. It should not return
  364. // anything, because the file has not changed. This verifies that the
  365. // ReceiveOnly flag is properly ignored and doesn't trigger a rescan
  366. // every time.
  367. cur := files[0]
  368. current[cur.Name] = cur
  369. files = walkDir(sf, ".", current, nil, protocol.FlagLocalReceiveOnly)
  370. if len(files) != 0 {
  371. t.Fatal("Should not have scanned anything")
  372. }
  373. // Now pretend the file was previously ignored instead. We should pick up
  374. // the difference in flags and set just the LocalReceive flags.
  375. cur.LocalFlags = protocol.FlagLocalIgnored
  376. current[cur.Name] = cur
  377. files = walkDir(sf, ".", current, nil, protocol.FlagLocalReceiveOnly)
  378. if len(files) != 1 {
  379. t.Fatal("Should have scanned one file")
  380. }
  381. if files[0].LocalFlags != protocol.FlagLocalReceiveOnly {
  382. t.Fatal("Should have set the ReceiveOnly flag")
  383. }
  384. }
  385. func walkDir(fs fs.Filesystem, dir string, cfiler CurrentFiler, matcher *ignore.Matcher, localFlags uint32) []protocol.FileInfo {
  386. cfg := testConfig()
  387. cfg.Filesystem = fs
  388. cfg.Subs = []string{dir}
  389. cfg.AutoNormalize = true
  390. cfg.CurrentFiler = cfiler
  391. cfg.Matcher = matcher
  392. cfg.LocalFlags = localFlags
  393. fchan := Walk(context.TODO(), cfg)
  394. var tmp []protocol.FileInfo
  395. for f := range fchan {
  396. if f.Err == nil {
  397. tmp = append(tmp, f.File)
  398. }
  399. }
  400. sort.Sort(fileList(tmp))
  401. return tmp
  402. }
  403. type fileList []protocol.FileInfo
  404. func (l fileList) Len() int {
  405. return len(l)
  406. }
  407. func (l fileList) Less(a, b int) bool {
  408. return l[a].Name < l[b].Name
  409. }
  410. func (l fileList) Swap(a, b int) {
  411. l[a], l[b] = l[b], l[a]
  412. }
  413. func (l fileList) testfiles() testfileList {
  414. testfiles := make(testfileList, len(l))
  415. for i, f := range l {
  416. if len(f.Blocks) > 1 {
  417. panic("simple test case stuff only supports a single block per file")
  418. }
  419. testfiles[i] = testfile{name: f.Name, length: f.FileSize()}
  420. if len(f.Blocks) == 1 {
  421. testfiles[i].hash = fmt.Sprintf("%x", f.Blocks[0].Hash)
  422. }
  423. }
  424. return testfiles
  425. }
  426. func (l testfileList) String() string {
  427. var b bytes.Buffer
  428. b.WriteString("{\n")
  429. for _, f := range l {
  430. fmt.Fprintf(&b, " %s (%d bytes): %s\n", f.name, f.length, f.hash)
  431. }
  432. b.WriteString("}")
  433. return b.String()
  434. }
  435. var initOnce sync.Once
  436. const (
  437. testdataSize = 17 << 20
  438. testdataName = "_random.data"
  439. )
  440. func BenchmarkHashFile(b *testing.B) {
  441. initOnce.Do(initTestFile)
  442. b.ResetTimer()
  443. for i := 0; i < b.N; i++ {
  444. if _, err := HashFile(context.TODO(), fs.NewFilesystem(fs.FilesystemTypeBasic, ""), testdataName, protocol.MinBlockSize, nil, true); err != nil {
  445. b.Fatal(err)
  446. }
  447. }
  448. b.SetBytes(testdataSize)
  449. b.ReportAllocs()
  450. }
  451. func initTestFile() {
  452. fd, err := os.Create(testdataName)
  453. if err != nil {
  454. panic(err)
  455. }
  456. lr := io.LimitReader(rand.Reader, testdataSize)
  457. if _, err := io.Copy(fd, lr); err != nil {
  458. panic(err)
  459. }
  460. if err := fd.Close(); err != nil {
  461. panic(err)
  462. }
  463. }
  464. func TestStopWalk(t *testing.T) {
  465. // Create tree that is 100 levels deep, with each level containing 100
  466. // files (each 1 MB) and 100 directories (in turn containing 100 files
  467. // and 100 directories, etc). That is, in total > 100^100 files and as
  468. // many directories. It'll take a while to scan, giving us time to
  469. // cancel it and make sure the scan stops.
  470. // Use an errorFs as the backing fs for the rest of the interface
  471. // The way we get it is a bit hacky tho.
  472. errorFs := fs.NewFilesystem(fs.FilesystemType(-1), ".")
  473. fs := fs.NewWalkFilesystem(&infiniteFS{errorFs, 100, 100, 1e6})
  474. const numHashers = 4
  475. ctx, cancel := context.WithCancel(context.Background())
  476. cfg := testConfig()
  477. cfg.Filesystem = fs
  478. cfg.Hashers = numHashers
  479. cfg.ProgressTickIntervalS = -1 // Don't attempt to build the full list of files before starting to scan...
  480. fchan := Walk(ctx, cfg)
  481. // Receive a few entries to make sure the walker is up and running,
  482. // scanning both files and dirs. Do some quick sanity tests on the
  483. // returned file entries to make sure we are not just reading crap from
  484. // a closed channel or something.
  485. dirs := 0
  486. files := 0
  487. for {
  488. res := <-fchan
  489. if res.Err != nil {
  490. t.Errorf("Error while scanning %v: %v", res.Err, res.Path)
  491. }
  492. f := res.File
  493. t.Log("Scanned", f)
  494. if f.IsDirectory() {
  495. if len(f.Name) == 0 || f.Permissions == 0 {
  496. t.Error("Bad directory entry", f)
  497. }
  498. dirs++
  499. } else {
  500. if len(f.Name) == 0 || len(f.Blocks) == 0 || f.Permissions == 0 {
  501. t.Error("Bad file entry", f)
  502. }
  503. files++
  504. }
  505. if dirs > 5 && files > 5 {
  506. break
  507. }
  508. }
  509. // Cancel the walker.
  510. cancel()
  511. // Empty out any waiting entries and wait for the channel to close.
  512. // Count them, they should be zero or very few - essentially, each
  513. // hasher has the choice of returning a fully handled entry or
  514. // cancelling, but they should not start on another item.
  515. extra := 0
  516. for range fchan {
  517. extra++
  518. }
  519. t.Log("Extra entries:", extra)
  520. if extra > numHashers {
  521. t.Error("unexpected extra entries received after cancel")
  522. }
  523. }
  524. func TestIssue4799(t *testing.T) {
  525. tmp, err := ioutil.TempDir("", "")
  526. if err != nil {
  527. t.Fatal(err)
  528. }
  529. defer os.RemoveAll(tmp)
  530. fs := fs.NewFilesystem(fs.FilesystemTypeBasic, tmp)
  531. fd, err := fs.Create("foo")
  532. if err != nil {
  533. t.Fatal(err)
  534. }
  535. fd.Close()
  536. files := walkDir(fs, "/foo", nil, nil, 0)
  537. if len(files) != 1 || files[0].Name != "foo" {
  538. t.Error(`Received unexpected file infos when walking "/foo"`, files)
  539. }
  540. }
  541. func TestRecurseInclude(t *testing.T) {
  542. stignore := `
  543. !/dir1/cfile
  544. !efile
  545. !ffile
  546. *
  547. `
  548. ignores := ignore.New(testFs, ignore.WithCache(true))
  549. if err := ignores.Parse(bytes.NewBufferString(stignore), ".stignore"); err != nil {
  550. t.Fatal(err)
  551. }
  552. files := walkDir(testFs, ".", nil, ignores, 0)
  553. expected := []string{
  554. filepath.Join("dir1"),
  555. filepath.Join("dir1", "cfile"),
  556. filepath.Join("dir2"),
  557. filepath.Join("dir2", "dir21"),
  558. filepath.Join("dir2", "dir21", "dir22"),
  559. filepath.Join("dir2", "dir21", "dir22", "dir23"),
  560. filepath.Join("dir2", "dir21", "dir22", "dir23", "efile"),
  561. filepath.Join("dir2", "dir21", "dir22", "efile"),
  562. filepath.Join("dir2", "dir21", "dir22", "efile", "efile"),
  563. filepath.Join("dir2", "dir21", "dira"),
  564. filepath.Join("dir2", "dir21", "dira", "efile"),
  565. filepath.Join("dir2", "dir21", "dira", "ffile"),
  566. filepath.Join("dir2", "dir21", "efile"),
  567. filepath.Join("dir2", "dir21", "efile", "ign"),
  568. filepath.Join("dir2", "dir21", "efile", "ign", "efile"),
  569. }
  570. if len(files) != len(expected) {
  571. t.Fatalf("Got %d files %v, expected %d files at %v", len(files), files, len(expected), expected)
  572. }
  573. for i := range files {
  574. if files[i].Name != expected[i] {
  575. t.Errorf("Got %v, expected file at %v", files[i], expected[i])
  576. }
  577. }
  578. }
  579. func TestIssue4841(t *testing.T) {
  580. tmp, err := ioutil.TempDir("", "")
  581. if err != nil {
  582. t.Fatal(err)
  583. }
  584. defer os.RemoveAll(tmp)
  585. fs := fs.NewFilesystem(fs.FilesystemTypeBasic, tmp)
  586. fd, err := fs.Create("foo")
  587. if err != nil {
  588. panic(err)
  589. }
  590. fd.Close()
  591. cfg := testConfig()
  592. cfg.Filesystem = fs
  593. cfg.AutoNormalize = true
  594. cfg.CurrentFiler = fakeCurrentFiler{"foo": {
  595. Name: "foo",
  596. Type: protocol.FileInfoTypeFile,
  597. LocalFlags: protocol.FlagLocalIgnored,
  598. Version: protocol.Vector{}.Update(1),
  599. }}
  600. cfg.ShortID = protocol.LocalDeviceID.Short()
  601. fchan := Walk(context.TODO(), cfg)
  602. var files []protocol.FileInfo
  603. for f := range fchan {
  604. if f.Err != nil {
  605. t.Errorf("Error while scanning %v: %v", f.Err, f.Path)
  606. }
  607. files = append(files, f.File)
  608. }
  609. sort.Sort(fileList(files))
  610. if len(files) != 1 {
  611. t.Fatalf("Expected 1 file, got %d: %v", len(files), files)
  612. }
  613. if expected := (protocol.Vector{}.Update(protocol.LocalDeviceID.Short())); !files[0].Version.Equal(expected) {
  614. t.Fatalf("Expected Version == %v, got %v", expected, files[0].Version)
  615. }
  616. }
  617. // TestNotExistingError reproduces https://github.com/syncthing/syncthing/issues/5385
  618. func TestNotExistingError(t *testing.T) {
  619. sub := "notExisting"
  620. if _, err := testFs.Lstat(sub); !fs.IsNotExist(err) {
  621. t.Fatalf("Lstat returned error %v, while nothing should exist there.", err)
  622. }
  623. cfg := testConfig()
  624. cfg.Subs = []string{sub}
  625. fchan := Walk(context.TODO(), cfg)
  626. for f := range fchan {
  627. t.Fatalf("Expected no result from scan, got %v", f)
  628. }
  629. }
  630. // Verify returns nil or an error describing the mismatch between the block
  631. // list and actual reader contents
  632. func verify(r io.Reader, blocksize int, blocks []protocol.BlockInfo) error {
  633. hf := sha256.New()
  634. // A 32k buffer is used for copying into the hash function.
  635. buf := make([]byte, 32<<10)
  636. for i, block := range blocks {
  637. lr := &io.LimitedReader{R: r, N: int64(blocksize)}
  638. _, err := io.CopyBuffer(hf, lr, buf)
  639. if err != nil {
  640. return err
  641. }
  642. hash := hf.Sum(nil)
  643. hf.Reset()
  644. if !bytes.Equal(hash, block.Hash) {
  645. return fmt.Errorf("hash mismatch %x != %x for block %d", hash, block.Hash, i)
  646. }
  647. }
  648. // We should have reached the end now
  649. bs := make([]byte, 1)
  650. n, err := r.Read(bs)
  651. if n != 0 || err != io.EOF {
  652. return fmt.Errorf("file continues past end of blocks")
  653. }
  654. return nil
  655. }
  656. type fakeCurrentFiler map[string]protocol.FileInfo
  657. func (fcf fakeCurrentFiler) CurrentFile(name string) (protocol.FileInfo, bool) {
  658. f, ok := fcf[name]
  659. return f, ok
  660. }
  661. func testConfig() Config {
  662. evLogger := events.NewLogger()
  663. go evLogger.Serve()
  664. return Config{
  665. Filesystem: testFs,
  666. Hashers: 2,
  667. EvLogger: evLogger,
  668. }
  669. }