walk_test.go 10.0 KB

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