1
0

walk_test.go 9.9 KB

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