walk_test.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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. "fmt"
  10. "os"
  11. "path/filepath"
  12. "reflect"
  13. "runtime"
  14. rdebug "runtime/debug"
  15. "sort"
  16. "testing"
  17. "github.com/syncthing/syncthing/lib/ignore"
  18. "github.com/syncthing/syncthing/lib/osutil"
  19. "github.com/syncthing/syncthing/lib/protocol"
  20. "github.com/syncthing/syncthing/lib/symlinks"
  21. "golang.org/x/text/unicode/norm"
  22. )
  23. type testfile struct {
  24. name string
  25. size int
  26. hash string
  27. }
  28. type testfileList []testfile
  29. var testdata = testfileList{
  30. {"afile", 4, "b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c"},
  31. {"dir1", 128, ""},
  32. {filepath.Join("dir1", "dfile"), 5, "49ae93732fcf8d63fe1cce759664982dbd5b23161f007dba8561862adc96d063"},
  33. {"dir2", 128, ""},
  34. {filepath.Join("dir2", "cfile"), 4, "bf07a7fbb825fc0aae7bf4a1177b2b31fcf8a3feeaf7092761e18c859ee52a9c"},
  35. {"excludes", 37, "df90b52f0c55dba7a7a940affe482571563b1ac57bd5be4d8a0291e7de928e06"},
  36. {"further-excludes", 5, "7eb0a548094fa6295f7fd9200d69973e5f5ec5c04f2a86d998080ac43ecf89f1"},
  37. }
  38. var correctIgnores = map[string][]string{
  39. ".": {".*", "quux"},
  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 !reflect.DeepEqual(files, testdata) {
  104. t.Errorf("Walk returned unexpected data\nExpected: %v\nActual: %v", testdata, files)
  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. var progress int64
  132. blocks, err := Blocks(buf, blocksize, 0, &progress)
  133. if err != nil {
  134. t.Fatal(err)
  135. }
  136. if exp := len(data) / blocksize; len(blocks) != exp {
  137. t.Fatalf("Incorrect number of blocks %d != %d", len(blocks), exp)
  138. }
  139. if int64(len(data)) != progress {
  140. t.Fatalf("Incorrect counter value %d != %d", len(data), progress)
  141. }
  142. buf = bytes.NewBuffer(data)
  143. err = Verify(buf, blocksize, blocks)
  144. t.Log(err)
  145. if err != nil {
  146. t.Fatal("Unexpected verify failure", err)
  147. }
  148. buf = bytes.NewBuffer(append(data, '\n'))
  149. err = Verify(buf, blocksize, blocks)
  150. t.Log(err)
  151. if err == nil {
  152. t.Fatal("Unexpected verify success")
  153. }
  154. buf = bytes.NewBuffer(data[:len(data)-1])
  155. err = Verify(buf, blocksize, blocks)
  156. t.Log(err)
  157. if err == nil {
  158. t.Fatal("Unexpected verify success")
  159. }
  160. data[42] = 42
  161. buf = bytes.NewBuffer(data)
  162. err = Verify(buf, blocksize, blocks)
  163. t.Log(err)
  164. if err == nil {
  165. t.Fatal("Unexpected verify success")
  166. }
  167. }
  168. func TestNormalization(t *testing.T) {
  169. if runtime.GOOS == "darwin" {
  170. t.Skip("Normalization test not possible on darwin")
  171. return
  172. }
  173. os.RemoveAll("testdata/normalization")
  174. defer os.RemoveAll("testdata/normalization")
  175. tests := []string{
  176. "0-A", // ASCII A -- accepted
  177. "1-\xC3\x84", // NFC 'Ä' -- conflicts with the entry below, accepted
  178. "1-\x41\xCC\x88", // NFD 'Ä' -- conflicts with the entry above, ignored
  179. "2-\xC3\x85", // NFC 'Å' -- accepted
  180. "3-\x41\xCC\x83", // NFD 'Ã' -- converted to NFC
  181. "4-\xE2\x98\x95", // U+2615 HOT BEVERAGE (☕) -- accepted
  182. "5-\xCD\xE2", // EUC-CN "wài" (外) -- ignored (not UTF8)
  183. }
  184. numInvalid := 2
  185. if runtime.GOOS == "windows" {
  186. // On Windows, in case 5 the character gets replaced with a
  187. // replacement character \xEF\xBF\xBD at the point it's written to disk,
  188. // which means it suddenly becomes valid (sort of).
  189. numInvalid--
  190. }
  191. numValid := len(tests) - numInvalid
  192. for _, s1 := range tests {
  193. // Create a directory for each of the interesting strings above
  194. if err := osutil.MkdirAll(filepath.Join("testdata/normalization", s1), 0755); err != nil {
  195. t.Fatal(err)
  196. }
  197. for _, s2 := range tests {
  198. // Within each dir, create a file with each of the interesting
  199. // file names. Ensure that the file doesn't exist when it's
  200. // created. This detects and fails if there's file name
  201. // normalization stuff at the filesystem level.
  202. if fd, err := os.OpenFile(filepath.Join("testdata/normalization", s1, s2), os.O_CREATE|os.O_EXCL, 0644); err != nil {
  203. t.Fatal(err)
  204. } else {
  205. fd.WriteString("test")
  206. fd.Close()
  207. }
  208. }
  209. }
  210. // We can normalize a directory name, but we can't descend into it in the
  211. // same pass due to how filepath.Walk works. So we run the scan twice to
  212. // make sure it all gets done. In production, things will be correct
  213. // eventually...
  214. _, err := walkDir("testdata/normalization")
  215. if err != nil {
  216. t.Fatal(err)
  217. }
  218. tmp, err := walkDir("testdata/normalization")
  219. if err != nil {
  220. t.Fatal(err)
  221. }
  222. files := fileList(tmp).testfiles()
  223. // We should have one file per combination, plus the directories
  224. // themselves
  225. expectedNum := numValid*numValid + numValid
  226. if len(files) != expectedNum {
  227. t.Errorf("Expected %d files, got %d", expectedNum, len(files))
  228. }
  229. // The file names should all be in NFC form.
  230. for _, f := range files {
  231. t.Logf("%q (% x) %v", f.name, f.name, norm.NFC.IsNormalString(f.name))
  232. if !norm.NFC.IsNormalString(f.name) {
  233. t.Errorf("File name %q is not NFC normalized", f.name)
  234. }
  235. }
  236. }
  237. func TestIssue1507(t *testing.T) {
  238. w := Walker{}
  239. c := make(chan protocol.FileInfo, 100)
  240. fn := w.walkAndHashFiles(c, c)
  241. fn("", nil, protocol.ErrClosed)
  242. }
  243. func walkDir(dir string) ([]protocol.FileInfo, error) {
  244. w := Walker{
  245. Dir: dir,
  246. BlockSize: 128 * 1024,
  247. AutoNormalize: true,
  248. Hashers: 2,
  249. }
  250. fchan, err := w.Walk()
  251. if err != nil {
  252. return nil, err
  253. }
  254. var tmp []protocol.FileInfo
  255. for f := range fchan {
  256. tmp = append(tmp, f)
  257. }
  258. sort.Sort(fileList(tmp))
  259. return tmp, nil
  260. }
  261. type fileList []protocol.FileInfo
  262. func (l fileList) Len() int {
  263. return len(l)
  264. }
  265. func (l fileList) Less(a, b int) bool {
  266. return l[a].Name < l[b].Name
  267. }
  268. func (l fileList) Swap(a, b int) {
  269. l[a], l[b] = l[b], l[a]
  270. }
  271. func (l fileList) testfiles() testfileList {
  272. testfiles := make(testfileList, len(l))
  273. for i, f := range l {
  274. if len(f.Blocks) > 1 {
  275. panic("simple test case stuff only supports a single block per file")
  276. }
  277. testfiles[i] = testfile{name: f.Name, size: int(f.Size())}
  278. if len(f.Blocks) == 1 {
  279. testfiles[i].hash = fmt.Sprintf("%x", f.Blocks[0].Hash)
  280. }
  281. }
  282. return testfiles
  283. }
  284. func (l testfileList) String() string {
  285. var b bytes.Buffer
  286. b.WriteString("{\n")
  287. for _, f := range l {
  288. fmt.Fprintf(&b, " %s (%d bytes): %s\n", f.name, f.size, f.hash)
  289. }
  290. b.WriteString("}")
  291. return b.String()
  292. }
  293. func TestSymlinkTypeEqual(t *testing.T) {
  294. testcases := []struct {
  295. onDiskType symlinks.TargetType
  296. inIndexFlags uint32
  297. equal bool
  298. }{
  299. // File is only equal to file
  300. {symlinks.TargetFile, 0, true},
  301. {symlinks.TargetFile, protocol.FlagDirectory, false},
  302. {symlinks.TargetFile, protocol.FlagSymlinkMissingTarget, false},
  303. // Directory is only equal to directory
  304. {symlinks.TargetDirectory, 0, false},
  305. {symlinks.TargetDirectory, protocol.FlagDirectory, true},
  306. {symlinks.TargetDirectory, protocol.FlagSymlinkMissingTarget, false},
  307. // Unknown is equal to anything
  308. {symlinks.TargetUnknown, 0, true},
  309. {symlinks.TargetUnknown, protocol.FlagDirectory, true},
  310. {symlinks.TargetUnknown, protocol.FlagSymlinkMissingTarget, true},
  311. }
  312. for _, tc := range testcases {
  313. res := SymlinkTypeEqual(tc.onDiskType, protocol.FileInfo{Flags: tc.inIndexFlags})
  314. if res != tc.equal {
  315. t.Errorf("Incorrect result %v for %v, %v", res, tc.onDiskType, tc.inIndexFlags)
  316. }
  317. }
  318. }