walk_test.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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 http://mozilla.org/MPL/2.0/.
  6. package scanner
  7. import (
  8. "bytes"
  9. "crypto/rand"
  10. "fmt"
  11. "io"
  12. "os"
  13. "path/filepath"
  14. "runtime"
  15. rdebug "runtime/debug"
  16. "sort"
  17. "sync"
  18. "testing"
  19. "github.com/d4l3k/messagediff"
  20. "github.com/syncthing/syncthing/lib/ignore"
  21. "github.com/syncthing/syncthing/lib/osutil"
  22. "github.com/syncthing/syncthing/lib/protocol"
  23. "github.com/syncthing/syncthing/lib/symlinks"
  24. "golang.org/x/text/unicode/norm"
  25. )
  26. type testfile struct {
  27. name string
  28. size int
  29. hash string
  30. }
  31. type testfileList []testfile
  32. var testdata = testfileList{
  33. {"afile", 4, "b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c"},
  34. {"dir1", 128, ""},
  35. {filepath.Join("dir1", "dfile"), 5, "49ae93732fcf8d63fe1cce759664982dbd5b23161f007dba8561862adc96d063"},
  36. {"dir2", 128, ""},
  37. {filepath.Join("dir2", "cfile"), 4, "bf07a7fbb825fc0aae7bf4a1177b2b31fcf8a3feeaf7092761e18c859ee52a9c"},
  38. {"excludes", 37, "df90b52f0c55dba7a7a940affe482571563b1ac57bd5be4d8a0291e7de928e06"},
  39. {"further-excludes", 5, "7eb0a548094fa6295f7fd9200d69973e5f5ec5c04f2a86d998080ac43ecf89f1"},
  40. }
  41. func init() {
  42. // This test runs the risk of entering infinite recursion if it fails.
  43. // Limit the stack size to 10 megs to crash early in that case instead of
  44. // potentially taking down the box...
  45. rdebug.SetMaxStack(10 * 1 << 20)
  46. }
  47. func TestWalkSub(t *testing.T) {
  48. ignores := ignore.New(false)
  49. err := ignores.Load("testdata/.stignore")
  50. if err != nil {
  51. t.Fatal(err)
  52. }
  53. w := Walker{
  54. Dir: "testdata",
  55. Subs: []string{"dir2"},
  56. BlockSize: 128 * 1024,
  57. Matcher: ignores,
  58. Hashers: 2,
  59. }
  60. fchan, err := w.Walk()
  61. var files []protocol.FileInfo
  62. for f := range fchan {
  63. files = append(files, f)
  64. }
  65. if err != nil {
  66. t.Fatal(err)
  67. }
  68. // The directory contains two files, where one is ignored from a higher
  69. // level. We should see only the directory and one of the files.
  70. if len(files) != 2 {
  71. t.Fatalf("Incorrect length %d != 2", len(files))
  72. }
  73. if files[0].Name != "dir2" {
  74. t.Errorf("Incorrect file %v != dir2", files[0])
  75. }
  76. if files[1].Name != filepath.Join("dir2", "cfile") {
  77. t.Errorf("Incorrect file %v != dir2/cfile", files[1])
  78. }
  79. }
  80. func TestWalk(t *testing.T) {
  81. ignores := ignore.New(false)
  82. err := ignores.Load("testdata/.stignore")
  83. if err != nil {
  84. t.Fatal(err)
  85. }
  86. t.Log(ignores)
  87. w := Walker{
  88. Dir: "testdata",
  89. BlockSize: 128 * 1024,
  90. Matcher: ignores,
  91. Hashers: 2,
  92. }
  93. fchan, err := w.Walk()
  94. if err != nil {
  95. t.Fatal(err)
  96. }
  97. var tmp []protocol.FileInfo
  98. for f := range fchan {
  99. tmp = append(tmp, f)
  100. }
  101. sort.Sort(fileList(tmp))
  102. files := fileList(tmp).testfiles()
  103. if diff, equal := messagediff.PrettyDiff(testdata, files); !equal {
  104. t.Errorf("Walk returned unexpected data. Diff:\n%s", diff)
  105. }
  106. }
  107. func TestWalkError(t *testing.T) {
  108. w := Walker{
  109. Dir: "testdata-missing",
  110. BlockSize: 128 * 1024,
  111. Hashers: 2,
  112. }
  113. _, err := w.Walk()
  114. if err == nil {
  115. t.Error("no error from missing directory")
  116. }
  117. w = Walker{
  118. Dir: "testdata/bar",
  119. BlockSize: 128 * 1024,
  120. }
  121. _, err = w.Walk()
  122. if err == nil {
  123. t.Error("no error from non-directory")
  124. }
  125. }
  126. func TestVerify(t *testing.T) {
  127. blocksize := 16
  128. // data should be an even multiple of blocksize long
  129. data := []byte("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut e")
  130. buf := bytes.NewBuffer(data)
  131. progress := newByteCounter()
  132. defer progress.Close()
  133. blocks, err := Blocks(buf, blocksize, 0, progress)
  134. if err != nil {
  135. t.Fatal(err)
  136. }
  137. if exp := len(data) / blocksize; len(blocks) != exp {
  138. t.Fatalf("Incorrect number of blocks %d != %d", len(blocks), exp)
  139. }
  140. if int64(len(data)) != progress.Total() {
  141. t.Fatalf("Incorrect counter value %d != %d", len(data), progress.Total())
  142. }
  143. buf = bytes.NewBuffer(data)
  144. err = Verify(buf, blocksize, blocks)
  145. t.Log(err)
  146. if err != nil {
  147. t.Fatal("Unexpected verify failure", err)
  148. }
  149. buf = bytes.NewBuffer(append(data, '\n'))
  150. err = Verify(buf, blocksize, blocks)
  151. t.Log(err)
  152. if err == nil {
  153. t.Fatal("Unexpected verify success")
  154. }
  155. buf = bytes.NewBuffer(data[:len(data)-1])
  156. err = Verify(buf, blocksize, blocks)
  157. t.Log(err)
  158. if err == nil {
  159. t.Fatal("Unexpected verify success")
  160. }
  161. data[42] = 42
  162. buf = bytes.NewBuffer(data)
  163. err = Verify(buf, blocksize, blocks)
  164. t.Log(err)
  165. if err == nil {
  166. t.Fatal("Unexpected verify success")
  167. }
  168. }
  169. func TestNormalization(t *testing.T) {
  170. if runtime.GOOS == "darwin" {
  171. t.Skip("Normalization test not possible on darwin")
  172. return
  173. }
  174. os.RemoveAll("testdata/normalization")
  175. defer os.RemoveAll("testdata/normalization")
  176. tests := []string{
  177. "0-A", // ASCII A -- accepted
  178. "1-\xC3\x84", // NFC 'Ä' -- conflicts with the entry below, accepted
  179. "1-\x41\xCC\x88", // NFD 'Ä' -- conflicts with the entry above, ignored
  180. "2-\xC3\x85", // NFC 'Å' -- accepted
  181. "3-\x41\xCC\x83", // NFD 'Ã' -- converted to NFC
  182. "4-\xE2\x98\x95", // U+2615 HOT BEVERAGE (☕) -- accepted
  183. "5-\xCD\xE2", // EUC-CN "wài" (外) -- ignored (not UTF8)
  184. }
  185. numInvalid := 2
  186. if runtime.GOOS == "windows" {
  187. // On Windows, in case 5 the character gets replaced with a
  188. // replacement character \xEF\xBF\xBD at the point it's written to disk,
  189. // which means it suddenly becomes valid (sort of).
  190. numInvalid--
  191. }
  192. numValid := len(tests) - numInvalid
  193. for _, s1 := range tests {
  194. // Create a directory for each of the interesting strings above
  195. if err := osutil.MkdirAll(filepath.Join("testdata/normalization", s1), 0755); err != nil {
  196. t.Fatal(err)
  197. }
  198. for _, s2 := range tests {
  199. // Within each dir, create a file with each of the interesting
  200. // file names. Ensure that the file doesn't exist when it's
  201. // created. This detects and fails if there's file name
  202. // normalization stuff at the filesystem level.
  203. if fd, err := os.OpenFile(filepath.Join("testdata/normalization", s1, s2), os.O_CREATE|os.O_EXCL, 0644); err != nil {
  204. t.Fatal(err)
  205. } else {
  206. fd.WriteString("test")
  207. fd.Close()
  208. }
  209. }
  210. }
  211. // We can normalize a directory name, but we can't descend into it in the
  212. // same pass due to how filepath.Walk works. So we run the scan twice to
  213. // make sure it all gets done. In production, things will be correct
  214. // eventually...
  215. _, err := walkDir("testdata/normalization")
  216. if err != nil {
  217. t.Fatal(err)
  218. }
  219. tmp, err := walkDir("testdata/normalization")
  220. if err != nil {
  221. t.Fatal(err)
  222. }
  223. files := fileList(tmp).testfiles()
  224. // We should have one file per combination, plus the directories
  225. // themselves
  226. expectedNum := numValid*numValid + numValid
  227. if len(files) != expectedNum {
  228. t.Errorf("Expected %d files, got %d", expectedNum, len(files))
  229. }
  230. // The file names should all be in NFC form.
  231. for _, f := range files {
  232. t.Logf("%q (% x) %v", f.name, f.name, norm.NFC.IsNormalString(f.name))
  233. if !norm.NFC.IsNormalString(f.name) {
  234. t.Errorf("File name %q is not NFC normalized", f.name)
  235. }
  236. }
  237. }
  238. func TestIssue1507(t *testing.T) {
  239. w := Walker{}
  240. c := make(chan protocol.FileInfo, 100)
  241. fn := w.walkAndHashFiles(c, c)
  242. fn("", nil, protocol.ErrClosed)
  243. }
  244. func walkDir(dir string) ([]protocol.FileInfo, error) {
  245. w := Walker{
  246. Dir: dir,
  247. BlockSize: 128 * 1024,
  248. AutoNormalize: true,
  249. Hashers: 2,
  250. }
  251. fchan, err := w.Walk()
  252. if err != nil {
  253. return nil, err
  254. }
  255. var tmp []protocol.FileInfo
  256. for f := range fchan {
  257. tmp = append(tmp, f)
  258. }
  259. sort.Sort(fileList(tmp))
  260. return tmp, nil
  261. }
  262. type fileList []protocol.FileInfo
  263. func (l fileList) Len() int {
  264. return len(l)
  265. }
  266. func (l fileList) Less(a, b int) bool {
  267. return l[a].Name < l[b].Name
  268. }
  269. func (l fileList) Swap(a, b int) {
  270. l[a], l[b] = l[b], l[a]
  271. }
  272. func (l fileList) testfiles() testfileList {
  273. testfiles := make(testfileList, len(l))
  274. for i, f := range l {
  275. if len(f.Blocks) > 1 {
  276. panic("simple test case stuff only supports a single block per file")
  277. }
  278. testfiles[i] = testfile{name: f.Name, size: int(f.Size())}
  279. if len(f.Blocks) == 1 {
  280. testfiles[i].hash = fmt.Sprintf("%x", f.Blocks[0].Hash)
  281. }
  282. }
  283. return testfiles
  284. }
  285. func (l testfileList) String() string {
  286. var b bytes.Buffer
  287. b.WriteString("{\n")
  288. for _, f := range l {
  289. fmt.Fprintf(&b, " %s (%d bytes): %s\n", f.name, f.size, f.hash)
  290. }
  291. b.WriteString("}")
  292. return b.String()
  293. }
  294. func TestSymlinkTypeEqual(t *testing.T) {
  295. testcases := []struct {
  296. onDiskType symlinks.TargetType
  297. inIndexFlags uint32
  298. equal bool
  299. }{
  300. // File is only equal to file
  301. {symlinks.TargetFile, 0, true},
  302. {symlinks.TargetFile, protocol.FlagDirectory, false},
  303. {symlinks.TargetFile, protocol.FlagSymlinkMissingTarget, false},
  304. // Directory is only equal to directory
  305. {symlinks.TargetDirectory, 0, false},
  306. {symlinks.TargetDirectory, protocol.FlagDirectory, true},
  307. {symlinks.TargetDirectory, protocol.FlagSymlinkMissingTarget, false},
  308. // Unknown is equal to anything
  309. {symlinks.TargetUnknown, 0, true},
  310. {symlinks.TargetUnknown, protocol.FlagDirectory, true},
  311. {symlinks.TargetUnknown, protocol.FlagSymlinkMissingTarget, true},
  312. }
  313. for _, tc := range testcases {
  314. res := SymlinkTypeEqual(tc.onDiskType, protocol.FileInfo{Flags: tc.inIndexFlags})
  315. if res != tc.equal {
  316. t.Errorf("Incorrect result %v for %v, %v", res, tc.onDiskType, tc.inIndexFlags)
  317. }
  318. }
  319. }
  320. var initOnce sync.Once
  321. const (
  322. testdataSize = 17 << 20
  323. testdataName = "_random.data"
  324. )
  325. func BenchmarkHashFile(b *testing.B) {
  326. initOnce.Do(initTestFile)
  327. b.ResetTimer()
  328. for i := 0; i < b.N; i++ {
  329. if _, err := HashFile(testdataName, protocol.BlockSize, testdataSize, nil); err != nil {
  330. b.Fatal(err)
  331. }
  332. }
  333. b.ReportAllocs()
  334. }
  335. func initTestFile() {
  336. fd, err := os.Create(testdataName)
  337. if err != nil {
  338. panic(err)
  339. }
  340. lr := io.LimitReader(rand.Reader, testdataSize)
  341. if _, err := io.Copy(fd, lr); err != nil {
  342. panic(err)
  343. }
  344. if err := fd.Close(); err != nil {
  345. panic(err)
  346. }
  347. }