walk_test.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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/protocol"
  18. "github.com/syncthing/syncthing/internal/ignore"
  19. "golang.org/x/text/unicode/norm"
  20. )
  21. type testfile struct {
  22. name string
  23. size int
  24. hash string
  25. }
  26. type testfileList []testfile
  27. var testdata = testfileList{
  28. {"afile", 4, "b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c"},
  29. {"dir1", 128, ""},
  30. {filepath.Join("dir1", "dfile"), 5, "49ae93732fcf8d63fe1cce759664982dbd5b23161f007dba8561862adc96d063"},
  31. {"dir2", 128, ""},
  32. {filepath.Join("dir2", "cfile"), 4, "bf07a7fbb825fc0aae7bf4a1177b2b31fcf8a3feeaf7092761e18c859ee52a9c"},
  33. {"excludes", 37, "df90b52f0c55dba7a7a940affe482571563b1ac57bd5be4d8a0291e7de928e06"},
  34. {"further-excludes", 5, "7eb0a548094fa6295f7fd9200d69973e5f5ec5c04f2a86d998080ac43ecf89f1"},
  35. }
  36. var correctIgnores = map[string][]string{
  37. ".": {".*", "quux"},
  38. }
  39. func init() {
  40. // This test runs the risk of entering infinite recursion if it fails.
  41. // Limit the stack size to 10 megs to crash early in that case instead of
  42. // potentially taking down the box...
  43. rdebug.SetMaxStack(10 * 1 << 20)
  44. }
  45. func TestWalkSub(t *testing.T) {
  46. ignores := ignore.New(false)
  47. err := ignores.Load("testdata/.stignore")
  48. if err != nil {
  49. t.Fatal(err)
  50. }
  51. w := Walker{
  52. Dir: "testdata",
  53. Subs: []string{"dir2"},
  54. BlockSize: 128 * 1024,
  55. Matcher: ignores,
  56. Hashers: 2,
  57. }
  58. fchan, err := w.Walk()
  59. var files []protocol.FileInfo
  60. for f := range fchan {
  61. files = append(files, f)
  62. }
  63. if err != nil {
  64. t.Fatal(err)
  65. }
  66. // The directory contains two files, where one is ignored from a higher
  67. // level. We should see only the directory and one of the files.
  68. if len(files) != 2 {
  69. t.Fatalf("Incorrect length %d != 2", len(files))
  70. }
  71. if files[0].Name != "dir2" {
  72. t.Errorf("Incorrect file %v != dir2", files[0])
  73. }
  74. if files[1].Name != filepath.Join("dir2", "cfile") {
  75. t.Errorf("Incorrect file %v != dir2/cfile", files[1])
  76. }
  77. }
  78. func TestWalk(t *testing.T) {
  79. ignores := ignore.New(false)
  80. err := ignores.Load("testdata/.stignore")
  81. if err != nil {
  82. t.Fatal(err)
  83. }
  84. t.Log(ignores)
  85. w := Walker{
  86. Dir: "testdata",
  87. BlockSize: 128 * 1024,
  88. Matcher: ignores,
  89. Hashers: 2,
  90. }
  91. fchan, err := w.Walk()
  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 !reflect.DeepEqual(files, testdata) {
  102. t.Errorf("Walk returned unexpected data\nExpected: %v\nActual: %v", testdata, files)
  103. }
  104. }
  105. func TestWalkError(t *testing.T) {
  106. w := Walker{
  107. Dir: "testdata-missing",
  108. BlockSize: 128 * 1024,
  109. Hashers: 2,
  110. }
  111. _, err := w.Walk()
  112. if err == nil {
  113. t.Error("no error from missing directory")
  114. }
  115. w = Walker{
  116. Dir: "testdata/bar",
  117. BlockSize: 128 * 1024,
  118. }
  119. _, err = w.Walk()
  120. if err == nil {
  121. t.Error("no error from non-directory")
  122. }
  123. }
  124. func TestVerify(t *testing.T) {
  125. blocksize := 16
  126. // data should be an even multiple of blocksize long
  127. data := []byte("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut e")
  128. buf := bytes.NewBuffer(data)
  129. blocks, err := Blocks(buf, blocksize, 0)
  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. buf = bytes.NewBuffer(data)
  137. err = Verify(buf, blocksize, blocks)
  138. t.Log(err)
  139. if err != nil {
  140. t.Fatal("Unexpected verify failure", err)
  141. }
  142. buf = bytes.NewBuffer(append(data, '\n'))
  143. err = Verify(buf, blocksize, blocks)
  144. t.Log(err)
  145. if err == nil {
  146. t.Fatal("Unexpected verify success")
  147. }
  148. buf = bytes.NewBuffer(data[:len(data)-1])
  149. err = Verify(buf, blocksize, blocks)
  150. t.Log(err)
  151. if err == nil {
  152. t.Fatal("Unexpected verify success")
  153. }
  154. data[42] = 42
  155. buf = bytes.NewBuffer(data)
  156. err = Verify(buf, blocksize, blocks)
  157. t.Log(err)
  158. if err == nil {
  159. t.Fatal("Unexpected verify success")
  160. }
  161. }
  162. func TestNormalization(t *testing.T) {
  163. if runtime.GOOS == "darwin" {
  164. t.Skip("Normalization test not possible on darwin")
  165. return
  166. }
  167. os.RemoveAll("testdata/normalization")
  168. defer os.RemoveAll("testdata/normalization")
  169. tests := []string{
  170. "0-A", // ASCII A -- accepted
  171. "1-\xC3\x84", // NFC 'Ä' -- conflicts with the entry below, accepted
  172. "1-\x41\xCC\x88", // NFD 'Ä' -- conflicts with the entry above, ignored
  173. "2-\xC3\x85", // NFC 'Å' -- accepted
  174. "3-\x41\xCC\x83", // NFD 'Ã' -- converted to NFC
  175. "4-\xE2\x98\x95", // U+2615 HOT BEVERAGE (☕) -- accepted
  176. "5-\xCD\xE2", // EUC-CN "wài" (外) -- ignored (not UTF8)
  177. }
  178. numInvalid := 2
  179. if runtime.GOOS == "windows" {
  180. // On Windows, in case 5 the character gets replaced with a
  181. // replacement character \xEF\xBF\xBD at the point it's written to disk,
  182. // which means it suddenly becomes valid (sort of).
  183. numInvalid--
  184. }
  185. numValid := len(tests) - numInvalid
  186. for _, s1 := range tests {
  187. // Create a directory for each of the interesting strings above
  188. if err := os.MkdirAll(filepath.Join("testdata/normalization", s1), 0755); err != nil {
  189. t.Fatal(err)
  190. }
  191. for _, s2 := range tests {
  192. // Within each dir, create a file with each of the interesting
  193. // file names. Ensure that the file doesn't exist when it's
  194. // created. This detects and fails if there's file name
  195. // normalization stuff at the filesystem level.
  196. if fd, err := os.OpenFile(filepath.Join("testdata/normalization", s1, s2), os.O_CREATE|os.O_EXCL, 0644); err != nil {
  197. t.Fatal(err)
  198. } else {
  199. fd.WriteString("test")
  200. fd.Close()
  201. }
  202. }
  203. }
  204. // We can normalize a directory name, but we can't descend into it in the
  205. // same pass due to how filepath.Walk works. So we run the scan twice to
  206. // make sure it all gets done. In production, things will be correct
  207. // eventually...
  208. _, err := walkDir("testdata/normalization")
  209. if err != nil {
  210. t.Fatal(err)
  211. }
  212. tmp, err := walkDir("testdata/normalization")
  213. if err != nil {
  214. t.Fatal(err)
  215. }
  216. files := fileList(tmp).testfiles()
  217. // We should have one file per combination, plus the directories
  218. // themselves
  219. expectedNum := numValid*numValid + numValid
  220. if len(files) != expectedNum {
  221. t.Errorf("Expected %d files, got %d", expectedNum, len(files))
  222. }
  223. // The file names should all be in NFC form.
  224. for _, f := range files {
  225. t.Logf("%q (% x) %v", f.name, f.name, norm.NFC.IsNormalString(f.name))
  226. if !norm.NFC.IsNormalString(f.name) {
  227. t.Errorf("File name %q is not NFC normalized", f.name)
  228. }
  229. }
  230. }
  231. func TestIssue1507(t *testing.T) {
  232. w := Walker{}
  233. c := make(chan protocol.FileInfo, 100)
  234. fn := w.walkAndHashFiles(c)
  235. fn("", nil, protocol.ErrClosed)
  236. }
  237. func walkDir(dir string) ([]protocol.FileInfo, error) {
  238. w := Walker{
  239. Dir: dir,
  240. BlockSize: 128 * 1024,
  241. AutoNormalize: true,
  242. Hashers: 2,
  243. }
  244. fchan, err := w.Walk()
  245. if err != nil {
  246. return nil, err
  247. }
  248. var tmp []protocol.FileInfo
  249. for f := range fchan {
  250. tmp = append(tmp, f)
  251. }
  252. sort.Sort(fileList(tmp))
  253. return tmp, nil
  254. }
  255. type fileList []protocol.FileInfo
  256. func (l fileList) Len() int {
  257. return len(l)
  258. }
  259. func (l fileList) Less(a, b int) bool {
  260. return l[a].Name < l[b].Name
  261. }
  262. func (l fileList) Swap(a, b int) {
  263. l[a], l[b] = l[b], l[a]
  264. }
  265. func (l fileList) testfiles() testfileList {
  266. testfiles := make(testfileList, len(l))
  267. for i, f := range l {
  268. if len(f.Blocks) > 1 {
  269. panic("simple test case stuff only supports a single block per file")
  270. }
  271. testfiles[i] = testfile{name: f.Name, size: int(f.Size())}
  272. if len(f.Blocks) == 1 {
  273. testfiles[i].hash = fmt.Sprintf("%x", f.Blocks[0].Hash)
  274. }
  275. }
  276. return testfiles
  277. }
  278. func (l testfileList) String() string {
  279. var b bytes.Buffer
  280. b.WriteString("{\n")
  281. for _, f := range l {
  282. fmt.Fprintf(&b, " %s (%d bytes): %s\n", f.name, f.size, f.hash)
  283. }
  284. b.WriteString("}")
  285. return b.String()
  286. }