fileutils_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. package fileutils
  2. import (
  3. "io/ioutil"
  4. "os"
  5. "path"
  6. "path/filepath"
  7. "runtime"
  8. "strings"
  9. "testing"
  10. )
  11. // CopyFile with invalid src
  12. func TestCopyFileWithInvalidSrc(t *testing.T) {
  13. tempFolder, err := ioutil.TempDir("", "docker-fileutils-test")
  14. defer os.RemoveAll(tempFolder)
  15. if err != nil {
  16. t.Fatal(err)
  17. }
  18. bytes, err := CopyFile("/invalid/file/path", path.Join(tempFolder, "dest"))
  19. if err == nil {
  20. t.Fatal("Should have fail to copy an invalid src file")
  21. }
  22. if bytes != 0 {
  23. t.Fatal("Should have written 0 bytes")
  24. }
  25. }
  26. // CopyFile with invalid dest
  27. func TestCopyFileWithInvalidDest(t *testing.T) {
  28. tempFolder, err := ioutil.TempDir("", "docker-fileutils-test")
  29. defer os.RemoveAll(tempFolder)
  30. if err != nil {
  31. t.Fatal(err)
  32. }
  33. src := path.Join(tempFolder, "file")
  34. err = ioutil.WriteFile(src, []byte("content"), 0740)
  35. if err != nil {
  36. t.Fatal(err)
  37. }
  38. bytes, err := CopyFile(src, path.Join(tempFolder, "/invalid/dest/path"))
  39. if err == nil {
  40. t.Fatal("Should have fail to copy an invalid src file")
  41. }
  42. if bytes != 0 {
  43. t.Fatal("Should have written 0 bytes")
  44. }
  45. }
  46. // CopyFile with same src and dest
  47. func TestCopyFileWithSameSrcAndDest(t *testing.T) {
  48. tempFolder, err := ioutil.TempDir("", "docker-fileutils-test")
  49. defer os.RemoveAll(tempFolder)
  50. if err != nil {
  51. t.Fatal(err)
  52. }
  53. file := path.Join(tempFolder, "file")
  54. err = ioutil.WriteFile(file, []byte("content"), 0740)
  55. if err != nil {
  56. t.Fatal(err)
  57. }
  58. bytes, err := CopyFile(file, file)
  59. if err != nil {
  60. t.Fatal(err)
  61. }
  62. if bytes != 0 {
  63. t.Fatal("Should have written 0 bytes as it is the same file.")
  64. }
  65. }
  66. // CopyFile with same src and dest but path is different and not clean
  67. func TestCopyFileWithSameSrcAndDestWithPathNameDifferent(t *testing.T) {
  68. tempFolder, err := ioutil.TempDir("", "docker-fileutils-test")
  69. defer os.RemoveAll(tempFolder)
  70. if err != nil {
  71. t.Fatal(err)
  72. }
  73. testFolder := path.Join(tempFolder, "test")
  74. err = os.MkdirAll(testFolder, 0740)
  75. if err != nil {
  76. t.Fatal(err)
  77. }
  78. file := path.Join(testFolder, "file")
  79. sameFile := testFolder + "/../test/file"
  80. err = ioutil.WriteFile(file, []byte("content"), 0740)
  81. if err != nil {
  82. t.Fatal(err)
  83. }
  84. bytes, err := CopyFile(file, sameFile)
  85. if err != nil {
  86. t.Fatal(err)
  87. }
  88. if bytes != 0 {
  89. t.Fatal("Should have written 0 bytes as it is the same file.")
  90. }
  91. }
  92. func TestCopyFile(t *testing.T) {
  93. tempFolder, err := ioutil.TempDir("", "docker-fileutils-test")
  94. defer os.RemoveAll(tempFolder)
  95. if err != nil {
  96. t.Fatal(err)
  97. }
  98. src := path.Join(tempFolder, "src")
  99. dest := path.Join(tempFolder, "dest")
  100. ioutil.WriteFile(src, []byte("content"), 0777)
  101. ioutil.WriteFile(dest, []byte("destContent"), 0777)
  102. bytes, err := CopyFile(src, dest)
  103. if err != nil {
  104. t.Fatal(err)
  105. }
  106. if bytes != 7 {
  107. t.Fatalf("Should have written %d bytes but wrote %d", 7, bytes)
  108. }
  109. actual, err := ioutil.ReadFile(dest)
  110. if err != nil {
  111. t.Fatal(err)
  112. }
  113. if string(actual) != "content" {
  114. t.Fatalf("Dest content was '%s', expected '%s'", string(actual), "content")
  115. }
  116. }
  117. // Reading a symlink to a directory must return the directory
  118. func TestReadSymlinkedDirectoryExistingDirectory(t *testing.T) {
  119. var err error
  120. if err = os.Mkdir("/tmp/testReadSymlinkToExistingDirectory", 0777); err != nil {
  121. t.Errorf("failed to create directory: %s", err)
  122. }
  123. if err = os.Symlink("/tmp/testReadSymlinkToExistingDirectory", "/tmp/dirLinkTest"); err != nil {
  124. t.Errorf("failed to create symlink: %s", err)
  125. }
  126. var path string
  127. if path, err = ReadSymlinkedDirectory("/tmp/dirLinkTest"); err != nil {
  128. t.Fatalf("failed to read symlink to directory: %s", err)
  129. }
  130. if path != "/tmp/testReadSymlinkToExistingDirectory" {
  131. t.Fatalf("symlink returned unexpected directory: %s", path)
  132. }
  133. if err = os.Remove("/tmp/testReadSymlinkToExistingDirectory"); err != nil {
  134. t.Errorf("failed to remove temporary directory: %s", err)
  135. }
  136. if err = os.Remove("/tmp/dirLinkTest"); err != nil {
  137. t.Errorf("failed to remove symlink: %s", err)
  138. }
  139. }
  140. // Reading a non-existing symlink must fail
  141. func TestReadSymlinkedDirectoryNonExistingSymlink(t *testing.T) {
  142. var path string
  143. var err error
  144. if path, err = ReadSymlinkedDirectory("/tmp/test/foo/Non/ExistingPath"); err == nil {
  145. t.Fatalf("error expected for non-existing symlink")
  146. }
  147. if path != "" {
  148. t.Fatalf("expected empty path, but '%s' was returned", path)
  149. }
  150. }
  151. // Reading a symlink to a file must fail
  152. func TestReadSymlinkedDirectoryToFile(t *testing.T) {
  153. var err error
  154. var file *os.File
  155. if file, err = os.Create("/tmp/testReadSymlinkToFile"); err != nil {
  156. t.Fatalf("failed to create file: %s", err)
  157. }
  158. file.Close()
  159. if err = os.Symlink("/tmp/testReadSymlinkToFile", "/tmp/fileLinkTest"); err != nil {
  160. t.Errorf("failed to create symlink: %s", err)
  161. }
  162. var path string
  163. if path, err = ReadSymlinkedDirectory("/tmp/fileLinkTest"); err == nil {
  164. t.Fatalf("ReadSymlinkedDirectory on a symlink to a file should've failed")
  165. }
  166. if path != "" {
  167. t.Fatalf("path should've been empty: %s", path)
  168. }
  169. if err = os.Remove("/tmp/testReadSymlinkToFile"); err != nil {
  170. t.Errorf("failed to remove file: %s", err)
  171. }
  172. if err = os.Remove("/tmp/fileLinkTest"); err != nil {
  173. t.Errorf("failed to remove symlink: %s", err)
  174. }
  175. }
  176. func TestWildcardMatches(t *testing.T) {
  177. match, _ := Matches("fileutils.go", []string{"*"})
  178. if match != true {
  179. t.Errorf("failed to get a wildcard match, got %v", match)
  180. }
  181. }
  182. // A simple pattern match should return true.
  183. func TestPatternMatches(t *testing.T) {
  184. match, _ := Matches("fileutils.go", []string{"*.go"})
  185. if match != true {
  186. t.Errorf("failed to get a match, got %v", match)
  187. }
  188. }
  189. // An exclusion followed by an inclusion should return true.
  190. func TestExclusionPatternMatchesPatternBefore(t *testing.T) {
  191. match, _ := Matches("fileutils.go", []string{"!fileutils.go", "*.go"})
  192. if match != true {
  193. t.Errorf("failed to get true match on exclusion pattern, got %v", match)
  194. }
  195. }
  196. // A folder pattern followed by an exception should return false.
  197. func TestPatternMatchesFolderExclusions(t *testing.T) {
  198. match, _ := Matches("docs/README.md", []string{"docs", "!docs/README.md"})
  199. if match != false {
  200. t.Errorf("failed to get a false match on exclusion pattern, got %v", match)
  201. }
  202. }
  203. // A folder pattern followed by an exception should return false.
  204. func TestPatternMatchesFolderWithSlashExclusions(t *testing.T) {
  205. match, _ := Matches("docs/README.md", []string{"docs/", "!docs/README.md"})
  206. if match != false {
  207. t.Errorf("failed to get a false match on exclusion pattern, got %v", match)
  208. }
  209. }
  210. // A folder pattern followed by an exception should return false.
  211. func TestPatternMatchesFolderWildcardExclusions(t *testing.T) {
  212. match, _ := Matches("docs/README.md", []string{"docs/*", "!docs/README.md"})
  213. if match != false {
  214. t.Errorf("failed to get a false match on exclusion pattern, got %v", match)
  215. }
  216. }
  217. // A pattern followed by an exclusion should return false.
  218. func TestExclusionPatternMatchesPatternAfter(t *testing.T) {
  219. match, _ := Matches("fileutils.go", []string{"*.go", "!fileutils.go"})
  220. if match != false {
  221. t.Errorf("failed to get false match on exclusion pattern, got %v", match)
  222. }
  223. }
  224. // A filename evaluating to . should return false.
  225. func TestExclusionPatternMatchesWholeDirectory(t *testing.T) {
  226. match, _ := Matches(".", []string{"*.go"})
  227. if match != false {
  228. t.Errorf("failed to get false match on ., got %v", match)
  229. }
  230. }
  231. // A single ! pattern should return an error.
  232. func TestSingleExclamationError(t *testing.T) {
  233. _, err := Matches("fileutils.go", []string{"!"})
  234. if err == nil {
  235. t.Errorf("failed to get an error for a single exclamation point, got %v", err)
  236. }
  237. }
  238. // A string preceded with a ! should return true from Exclusion.
  239. func TestExclusion(t *testing.T) {
  240. exclusion := exclusion("!")
  241. if !exclusion {
  242. t.Errorf("failed to get true for a single !, got %v", exclusion)
  243. }
  244. }
  245. // Matches with no patterns
  246. func TestMatchesWithNoPatterns(t *testing.T) {
  247. matches, err := Matches("/any/path/there", []string{})
  248. if err != nil {
  249. t.Fatal(err)
  250. }
  251. if matches {
  252. t.Fatalf("Should not have match anything")
  253. }
  254. }
  255. // Matches with malformed patterns
  256. func TestMatchesWithMalformedPatterns(t *testing.T) {
  257. matches, err := Matches("/any/path/there", []string{"["})
  258. if err == nil {
  259. t.Fatal("Should have failed because of a malformed syntax in the pattern")
  260. }
  261. if matches {
  262. t.Fatalf("Should not have match anything")
  263. }
  264. }
  265. // Test lots of variants of patterns & strings
  266. func TestMatches(t *testing.T) {
  267. tests := []struct {
  268. pattern string
  269. text string
  270. pass bool
  271. }{
  272. {"**", "file", true},
  273. {"**", "file/", true},
  274. {"**/", "file", true}, // weird one
  275. {"**/", "file/", true},
  276. {"**", "/", true},
  277. {"**/", "/", true},
  278. {"**", "dir/file", true},
  279. {"**/", "dir/file", false},
  280. {"**", "dir/file/", true},
  281. {"**/", "dir/file/", true},
  282. {"**/**", "dir/file", true},
  283. {"**/**", "dir/file/", true},
  284. {"dir/**", "dir/file", true},
  285. {"dir/**", "dir/file/", true},
  286. {"dir/**", "dir/dir2/file", true},
  287. {"dir/**", "dir/dir2/file/", true},
  288. {"**/dir2/*", "dir/dir2/file", true},
  289. {"**/dir2/*", "dir/dir2/file/", false},
  290. {"**/dir2/**", "dir/dir2/dir3/file", true},
  291. {"**/dir2/**", "dir/dir2/dir3/file/", true},
  292. {"**file", "file", true},
  293. {"**file", "dir/file", true},
  294. {"**/file", "dir/file", true},
  295. {"**file", "dir/dir/file", true},
  296. {"**/file", "dir/dir/file", true},
  297. {"**/file*", "dir/dir/file", true},
  298. {"**/file*", "dir/dir/file.txt", true},
  299. {"**/file*txt", "dir/dir/file.txt", true},
  300. {"**/file*.txt", "dir/dir/file.txt", true},
  301. {"**/file*.txt*", "dir/dir/file.txt", true},
  302. {"**/**/*.txt", "dir/dir/file.txt", true},
  303. {"**/**/*.txt2", "dir/dir/file.txt", false},
  304. {"**/*.txt", "file.txt", true},
  305. {"**/**/*.txt", "file.txt", true},
  306. {"a**/*.txt", "a/file.txt", true},
  307. {"a**/*.txt", "a/dir/file.txt", true},
  308. {"a**/*.txt", "a/dir/dir/file.txt", true},
  309. {"a/*.txt", "a/dir/file.txt", false},
  310. {"a/*.txt", "a/file.txt", true},
  311. {"a/*.txt**", "a/file.txt", true},
  312. {"a[b-d]e", "ae", false},
  313. {"a[b-d]e", "ace", true},
  314. {"a[b-d]e", "aae", false},
  315. {"a[^b-d]e", "aze", true},
  316. {".*", ".foo", true},
  317. {".*", "foo", false},
  318. {"abc.def", "abcdef", false},
  319. {"abc.def", "abc.def", true},
  320. {"abc.def", "abcZdef", false},
  321. {"abc?def", "abcZdef", true},
  322. {"abc?def", "abcdef", false},
  323. {"a\\*b", "a*b", true},
  324. {"a\\", "a", false},
  325. {"a\\", "a\\", false},
  326. {"a\\\\", "a\\", true},
  327. {"**/foo/bar", "foo/bar", true},
  328. {"**/foo/bar", "dir/foo/bar", true},
  329. {"**/foo/bar", "dir/dir2/foo/bar", true},
  330. {"abc/**", "abc", false},
  331. {"abc/**", "abc/def", true},
  332. {"abc/**", "abc/def/ghi", true},
  333. }
  334. for _, test := range tests {
  335. res, _ := regexpMatch(test.pattern, test.text)
  336. if res != test.pass {
  337. t.Fatalf("Failed: %v - res:%v", test, res)
  338. }
  339. }
  340. }
  341. // An empty string should return true from Empty.
  342. func TestEmpty(t *testing.T) {
  343. empty := empty("")
  344. if !empty {
  345. t.Errorf("failed to get true for an empty string, got %v", empty)
  346. }
  347. }
  348. func TestCleanPatterns(t *testing.T) {
  349. cleaned, _, _, _ := CleanPatterns([]string{"docs", "config"})
  350. if len(cleaned) != 2 {
  351. t.Errorf("expected 2 element slice, got %v", len(cleaned))
  352. }
  353. }
  354. func TestCleanPatternsStripEmptyPatterns(t *testing.T) {
  355. cleaned, _, _, _ := CleanPatterns([]string{"docs", "config", ""})
  356. if len(cleaned) != 2 {
  357. t.Errorf("expected 2 element slice, got %v", len(cleaned))
  358. }
  359. }
  360. func TestCleanPatternsExceptionFlag(t *testing.T) {
  361. _, _, exceptions, _ := CleanPatterns([]string{"docs", "!docs/README.md"})
  362. if !exceptions {
  363. t.Errorf("expected exceptions to be true, got %v", exceptions)
  364. }
  365. }
  366. func TestCleanPatternsLeadingSpaceTrimmed(t *testing.T) {
  367. _, _, exceptions, _ := CleanPatterns([]string{"docs", " !docs/README.md"})
  368. if !exceptions {
  369. t.Errorf("expected exceptions to be true, got %v", exceptions)
  370. }
  371. }
  372. func TestCleanPatternsTrailingSpaceTrimmed(t *testing.T) {
  373. _, _, exceptions, _ := CleanPatterns([]string{"docs", "!docs/README.md "})
  374. if !exceptions {
  375. t.Errorf("expected exceptions to be true, got %v", exceptions)
  376. }
  377. }
  378. func TestCleanPatternsErrorSingleException(t *testing.T) {
  379. _, _, _, err := CleanPatterns([]string{"!"})
  380. if err == nil {
  381. t.Errorf("expected error on single exclamation point, got %v", err)
  382. }
  383. }
  384. func TestCleanPatternsFolderSplit(t *testing.T) {
  385. _, dirs, _, _ := CleanPatterns([]string{"docs/config/CONFIG.md"})
  386. if dirs[0][0] != "docs" {
  387. t.Errorf("expected first element in dirs slice to be docs, got %v", dirs[0][1])
  388. }
  389. if dirs[0][1] != "config" {
  390. t.Errorf("expected first element in dirs slice to be config, got %v", dirs[0][1])
  391. }
  392. }
  393. func TestCreateIfNotExistsDir(t *testing.T) {
  394. tempFolder, err := ioutil.TempDir("", "docker-fileutils-test")
  395. if err != nil {
  396. t.Fatal(err)
  397. }
  398. defer os.RemoveAll(tempFolder)
  399. folderToCreate := filepath.Join(tempFolder, "tocreate")
  400. if err := CreateIfNotExists(folderToCreate, true); err != nil {
  401. t.Fatal(err)
  402. }
  403. fileinfo, err := os.Stat(folderToCreate)
  404. if err != nil {
  405. t.Fatalf("Should have create a folder, got %v", err)
  406. }
  407. if !fileinfo.IsDir() {
  408. t.Fatalf("Should have been a dir, seems it's not")
  409. }
  410. }
  411. func TestCreateIfNotExistsFile(t *testing.T) {
  412. tempFolder, err := ioutil.TempDir("", "docker-fileutils-test")
  413. if err != nil {
  414. t.Fatal(err)
  415. }
  416. defer os.RemoveAll(tempFolder)
  417. fileToCreate := filepath.Join(tempFolder, "file/to/create")
  418. if err := CreateIfNotExists(fileToCreate, false); err != nil {
  419. t.Fatal(err)
  420. }
  421. fileinfo, err := os.Stat(fileToCreate)
  422. if err != nil {
  423. t.Fatalf("Should have create a file, got %v", err)
  424. }
  425. if fileinfo.IsDir() {
  426. t.Fatalf("Should have been a file, seems it's not")
  427. }
  428. }
  429. // These matchTests are stolen from go's filepath Match tests.
  430. type matchTest struct {
  431. pattern, s string
  432. match bool
  433. err error
  434. }
  435. var matchTests = []matchTest{
  436. {"abc", "abc", true, nil},
  437. {"*", "abc", true, nil},
  438. {"*c", "abc", true, nil},
  439. {"a*", "a", true, nil},
  440. {"a*", "abc", true, nil},
  441. {"a*", "ab/c", false, nil},
  442. {"a*/b", "abc/b", true, nil},
  443. {"a*/b", "a/c/b", false, nil},
  444. {"a*b*c*d*e*/f", "axbxcxdxe/f", true, nil},
  445. {"a*b*c*d*e*/f", "axbxcxdxexxx/f", true, nil},
  446. {"a*b*c*d*e*/f", "axbxcxdxe/xxx/f", false, nil},
  447. {"a*b*c*d*e*/f", "axbxcxdxexxx/fff", false, nil},
  448. {"a*b?c*x", "abxbbxdbxebxczzx", true, nil},
  449. {"a*b?c*x", "abxbbxdbxebxczzy", false, nil},
  450. {"ab[c]", "abc", true, nil},
  451. {"ab[b-d]", "abc", true, nil},
  452. {"ab[e-g]", "abc", false, nil},
  453. {"ab[^c]", "abc", false, nil},
  454. {"ab[^b-d]", "abc", false, nil},
  455. {"ab[^e-g]", "abc", true, nil},
  456. {"a\\*b", "a*b", true, nil},
  457. {"a\\*b", "ab", false, nil},
  458. {"a?b", "a☺b", true, nil},
  459. {"a[^a]b", "a☺b", true, nil},
  460. {"a???b", "a☺b", false, nil},
  461. {"a[^a][^a][^a]b", "a☺b", false, nil},
  462. {"[a-ζ]*", "α", true, nil},
  463. {"*[a-ζ]", "A", false, nil},
  464. {"a?b", "a/b", false, nil},
  465. {"a*b", "a/b", false, nil},
  466. {"[\\]a]", "]", true, nil},
  467. {"[\\-]", "-", true, nil},
  468. {"[x\\-]", "x", true, nil},
  469. {"[x\\-]", "-", true, nil},
  470. {"[x\\-]", "z", false, nil},
  471. {"[\\-x]", "x", true, nil},
  472. {"[\\-x]", "-", true, nil},
  473. {"[\\-x]", "a", false, nil},
  474. {"[]a]", "]", false, filepath.ErrBadPattern},
  475. {"[-]", "-", false, filepath.ErrBadPattern},
  476. {"[x-]", "x", false, filepath.ErrBadPattern},
  477. {"[x-]", "-", false, filepath.ErrBadPattern},
  478. {"[x-]", "z", false, filepath.ErrBadPattern},
  479. {"[-x]", "x", false, filepath.ErrBadPattern},
  480. {"[-x]", "-", false, filepath.ErrBadPattern},
  481. {"[-x]", "a", false, filepath.ErrBadPattern},
  482. {"\\", "a", false, filepath.ErrBadPattern},
  483. {"[a-b-c]", "a", false, filepath.ErrBadPattern},
  484. {"[", "a", false, filepath.ErrBadPattern},
  485. {"[^", "a", false, filepath.ErrBadPattern},
  486. {"[^bc", "a", false, filepath.ErrBadPattern},
  487. {"a[", "a", false, filepath.ErrBadPattern}, // was nil but IMO its wrong
  488. {"a[", "ab", false, filepath.ErrBadPattern},
  489. {"*x", "xxx", true, nil},
  490. }
  491. func errp(e error) string {
  492. if e == nil {
  493. return "<nil>"
  494. }
  495. return e.Error()
  496. }
  497. // TestMatch test's our version of filepath.Match, called regexpMatch.
  498. func TestMatch(t *testing.T) {
  499. for _, tt := range matchTests {
  500. pattern := tt.pattern
  501. s := tt.s
  502. if runtime.GOOS == "windows" {
  503. if strings.Index(pattern, "\\") >= 0 {
  504. // no escape allowed on windows.
  505. continue
  506. }
  507. pattern = filepath.Clean(pattern)
  508. s = filepath.Clean(s)
  509. }
  510. ok, err := regexpMatch(pattern, s)
  511. if ok != tt.match || err != tt.err {
  512. t.Fatalf("Match(%#q, %#q) = %v, %q want %v, %q", pattern, s, ok, errp(err), tt.match, errp(tt.err))
  513. }
  514. }
  515. }