fileutils_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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. // TODO Windows: Port this test
  120. if runtime.GOOS == "windows" {
  121. t.Skip("Needs porting to Windows")
  122. }
  123. var err error
  124. if err = os.Mkdir("/tmp/testReadSymlinkToExistingDirectory", 0777); err != nil {
  125. t.Errorf("failed to create directory: %s", err)
  126. }
  127. if err = os.Symlink("/tmp/testReadSymlinkToExistingDirectory", "/tmp/dirLinkTest"); err != nil {
  128. t.Errorf("failed to create symlink: %s", err)
  129. }
  130. var path string
  131. if path, err = ReadSymlinkedDirectory("/tmp/dirLinkTest"); err != nil {
  132. t.Fatalf("failed to read symlink to directory: %s", err)
  133. }
  134. if path != "/tmp/testReadSymlinkToExistingDirectory" {
  135. t.Fatalf("symlink returned unexpected directory: %s", path)
  136. }
  137. if err = os.Remove("/tmp/testReadSymlinkToExistingDirectory"); err != nil {
  138. t.Errorf("failed to remove temporary directory: %s", err)
  139. }
  140. if err = os.Remove("/tmp/dirLinkTest"); err != nil {
  141. t.Errorf("failed to remove symlink: %s", err)
  142. }
  143. }
  144. // Reading a non-existing symlink must fail
  145. func TestReadSymlinkedDirectoryNonExistingSymlink(t *testing.T) {
  146. var path string
  147. var err error
  148. if path, err = ReadSymlinkedDirectory("/tmp/test/foo/Non/ExistingPath"); err == nil {
  149. t.Fatalf("error expected for non-existing symlink")
  150. }
  151. if path != "" {
  152. t.Fatalf("expected empty path, but '%s' was returned", path)
  153. }
  154. }
  155. // Reading a symlink to a file must fail
  156. func TestReadSymlinkedDirectoryToFile(t *testing.T) {
  157. // TODO Windows: Port this test
  158. if runtime.GOOS == "windows" {
  159. t.Skip("Needs porting to Windows")
  160. }
  161. var err error
  162. var file *os.File
  163. if file, err = os.Create("/tmp/testReadSymlinkToFile"); err != nil {
  164. t.Fatalf("failed to create file: %s", err)
  165. }
  166. file.Close()
  167. if err = os.Symlink("/tmp/testReadSymlinkToFile", "/tmp/fileLinkTest"); err != nil {
  168. t.Errorf("failed to create symlink: %s", err)
  169. }
  170. var path string
  171. if path, err = ReadSymlinkedDirectory("/tmp/fileLinkTest"); err == nil {
  172. t.Fatalf("ReadSymlinkedDirectory on a symlink to a file should've failed")
  173. }
  174. if path != "" {
  175. t.Fatalf("path should've been empty: %s", path)
  176. }
  177. if err = os.Remove("/tmp/testReadSymlinkToFile"); err != nil {
  178. t.Errorf("failed to remove file: %s", err)
  179. }
  180. if err = os.Remove("/tmp/fileLinkTest"); err != nil {
  181. t.Errorf("failed to remove symlink: %s", err)
  182. }
  183. }
  184. func TestWildcardMatches(t *testing.T) {
  185. match, _ := Matches("fileutils.go", []string{"*"})
  186. if !match {
  187. t.Errorf("failed to get a wildcard match, got %v", match)
  188. }
  189. }
  190. // A simple pattern match should return true.
  191. func TestPatternMatches(t *testing.T) {
  192. match, _ := Matches("fileutils.go", []string{"*.go"})
  193. if !match {
  194. t.Errorf("failed to get a match, got %v", match)
  195. }
  196. }
  197. // An exclusion followed by an inclusion should return true.
  198. func TestExclusionPatternMatchesPatternBefore(t *testing.T) {
  199. match, _ := Matches("fileutils.go", []string{"!fileutils.go", "*.go"})
  200. if !match {
  201. t.Errorf("failed to get true match on exclusion pattern, got %v", match)
  202. }
  203. }
  204. // A folder pattern followed by an exception should return false.
  205. func TestPatternMatchesFolderExclusions(t *testing.T) {
  206. match, _ := Matches("docs/README.md", []string{"docs", "!docs/README.md"})
  207. if match {
  208. t.Errorf("failed to get a false match on exclusion pattern, got %v", match)
  209. }
  210. }
  211. // A folder pattern followed by an exception should return false.
  212. func TestPatternMatchesFolderWithSlashExclusions(t *testing.T) {
  213. match, _ := Matches("docs/README.md", []string{"docs/", "!docs/README.md"})
  214. if match {
  215. t.Errorf("failed to get a false match on exclusion pattern, got %v", match)
  216. }
  217. }
  218. // A folder pattern followed by an exception should return false.
  219. func TestPatternMatchesFolderWildcardExclusions(t *testing.T) {
  220. match, _ := Matches("docs/README.md", []string{"docs/*", "!docs/README.md"})
  221. if match {
  222. t.Errorf("failed to get a false match on exclusion pattern, got %v", match)
  223. }
  224. }
  225. // A pattern followed by an exclusion should return false.
  226. func TestExclusionPatternMatchesPatternAfter(t *testing.T) {
  227. match, _ := Matches("fileutils.go", []string{"*.go", "!fileutils.go"})
  228. if match {
  229. t.Errorf("failed to get false match on exclusion pattern, got %v", match)
  230. }
  231. }
  232. // A filename evaluating to . should return false.
  233. func TestExclusionPatternMatchesWholeDirectory(t *testing.T) {
  234. match, _ := Matches(".", []string{"*.go"})
  235. if match {
  236. t.Errorf("failed to get false match on ., got %v", match)
  237. }
  238. }
  239. // A single ! pattern should return an error.
  240. func TestSingleExclamationError(t *testing.T) {
  241. _, err := Matches("fileutils.go", []string{"!"})
  242. if err == nil {
  243. t.Errorf("failed to get an error for a single exclamation point, got %v", err)
  244. }
  245. }
  246. // Matches with no patterns
  247. func TestMatchesWithNoPatterns(t *testing.T) {
  248. matches, err := Matches("/any/path/there", []string{})
  249. if err != nil {
  250. t.Fatal(err)
  251. }
  252. if matches {
  253. t.Fatalf("Should not have match anything")
  254. }
  255. }
  256. // Matches with malformed patterns
  257. func TestMatchesWithMalformedPatterns(t *testing.T) {
  258. matches, err := Matches("/any/path/there", []string{"["})
  259. if err == nil {
  260. t.Fatal("Should have failed because of a malformed syntax in the pattern")
  261. }
  262. if matches {
  263. t.Fatalf("Should not have match anything")
  264. }
  265. }
  266. // Test lots of variants of patterns & strings
  267. func TestMatches(t *testing.T) {
  268. // TODO Windows: Port this test
  269. if runtime.GOOS == "windows" {
  270. t.Skip("Needs porting to Windows")
  271. }
  272. tests := []struct {
  273. pattern string
  274. text string
  275. pass bool
  276. }{
  277. {"**", "file", true},
  278. {"**", "file/", true},
  279. {"**/", "file", true}, // weird one
  280. {"**/", "file/", true},
  281. {"**", "/", true},
  282. {"**/", "/", true},
  283. {"**", "dir/file", true},
  284. {"**/", "dir/file", true},
  285. {"**", "dir/file/", true},
  286. {"**/", "dir/file/", true},
  287. {"**/**", "dir/file", true},
  288. {"**/**", "dir/file/", true},
  289. {"dir/**", "dir/file", true},
  290. {"dir/**", "dir/file/", true},
  291. {"dir/**", "dir/dir2/file", true},
  292. {"dir/**", "dir/dir2/file/", true},
  293. {"**/dir2/*", "dir/dir2/file", true},
  294. {"**/dir2/*", "dir/dir2/file/", true},
  295. {"**/dir2/**", "dir/dir2/dir3/file", true},
  296. {"**/dir2/**", "dir/dir2/dir3/file/", true},
  297. {"**file", "file", true},
  298. {"**file", "dir/file", true},
  299. {"**/file", "dir/file", true},
  300. {"**file", "dir/dir/file", true},
  301. {"**/file", "dir/dir/file", true},
  302. {"**/file*", "dir/dir/file", true},
  303. {"**/file*", "dir/dir/file.txt", true},
  304. {"**/file*txt", "dir/dir/file.txt", true},
  305. {"**/file*.txt", "dir/dir/file.txt", true},
  306. {"**/file*.txt*", "dir/dir/file.txt", true},
  307. {"**/**/*.txt", "dir/dir/file.txt", true},
  308. {"**/**/*.txt2", "dir/dir/file.txt", false},
  309. {"**/*.txt", "file.txt", true},
  310. {"**/**/*.txt", "file.txt", true},
  311. {"a**/*.txt", "a/file.txt", true},
  312. {"a**/*.txt", "a/dir/file.txt", true},
  313. {"a**/*.txt", "a/dir/dir/file.txt", true},
  314. {"a/*.txt", "a/dir/file.txt", false},
  315. {"a/*.txt", "a/file.txt", true},
  316. {"a/*.txt**", "a/file.txt", true},
  317. {"a[b-d]e", "ae", false},
  318. {"a[b-d]e", "ace", true},
  319. {"a[b-d]e", "aae", false},
  320. {"a[^b-d]e", "aze", true},
  321. {".*", ".foo", true},
  322. {".*", "foo", false},
  323. {"abc.def", "abcdef", false},
  324. {"abc.def", "abc.def", true},
  325. {"abc.def", "abcZdef", false},
  326. {"abc?def", "abcZdef", true},
  327. {"abc?def", "abcdef", false},
  328. {"a\\*b", "a*b", true},
  329. {"a\\", "a", false},
  330. {"a\\", "a\\", false},
  331. {"a\\\\", "a\\", true},
  332. {"**/foo/bar", "foo/bar", true},
  333. {"**/foo/bar", "dir/foo/bar", true},
  334. {"**/foo/bar", "dir/dir2/foo/bar", true},
  335. {"abc/**", "abc", false},
  336. {"abc/**", "abc/def", true},
  337. {"abc/**", "abc/def/ghi", true},
  338. {"**/.foo", ".foo", true},
  339. {"**/.foo", "bar.foo", false},
  340. }
  341. for _, test := range tests {
  342. pm, err := NewPatternMatcher([]string{test.pattern})
  343. if err != nil {
  344. t.Fatalf("invalid pattern %s", test.pattern)
  345. }
  346. res, _ := pm.Matches(test.text)
  347. if res != test.pass {
  348. t.Fatalf("Failed: %v - res:%v", test, res)
  349. }
  350. }
  351. }
  352. func TestCleanPatterns(t *testing.T) {
  353. patterns := []string{"docs", "config"}
  354. pm, err := NewPatternMatcher(patterns)
  355. if err != nil {
  356. t.Fatalf("invalid pattern %v", patterns)
  357. }
  358. cleaned := pm.Patterns()
  359. if len(cleaned) != 2 {
  360. t.Errorf("expected 2 element slice, got %v", len(cleaned))
  361. }
  362. }
  363. func TestCleanPatternsStripEmptyPatterns(t *testing.T) {
  364. patterns := []string{"docs", "config", ""}
  365. pm, err := NewPatternMatcher(patterns)
  366. if err != nil {
  367. t.Fatalf("invalid pattern %v", patterns)
  368. }
  369. cleaned := pm.Patterns()
  370. if len(cleaned) != 2 {
  371. t.Errorf("expected 2 element slice, got %v", len(cleaned))
  372. }
  373. }
  374. func TestCleanPatternsExceptionFlag(t *testing.T) {
  375. patterns := []string{"docs", "!docs/README.md"}
  376. pm, err := NewPatternMatcher(patterns)
  377. if err != nil {
  378. t.Fatalf("invalid pattern %v", patterns)
  379. }
  380. if !pm.Exclusions() {
  381. t.Errorf("expected exceptions to be true, got %v", pm.Exclusions())
  382. }
  383. }
  384. func TestCleanPatternsLeadingSpaceTrimmed(t *testing.T) {
  385. patterns := []string{"docs", " !docs/README.md"}
  386. pm, err := NewPatternMatcher(patterns)
  387. if err != nil {
  388. t.Fatalf("invalid pattern %v", patterns)
  389. }
  390. if !pm.Exclusions() {
  391. t.Errorf("expected exceptions to be true, got %v", pm.Exclusions())
  392. }
  393. }
  394. func TestCleanPatternsTrailingSpaceTrimmed(t *testing.T) {
  395. patterns := []string{"docs", "!docs/README.md "}
  396. pm, err := NewPatternMatcher(patterns)
  397. if err != nil {
  398. t.Fatalf("invalid pattern %v", patterns)
  399. }
  400. if !pm.Exclusions() {
  401. t.Errorf("expected exceptions to be true, got %v", pm.Exclusions())
  402. }
  403. }
  404. func TestCleanPatternsErrorSingleException(t *testing.T) {
  405. patterns := []string{"!"}
  406. _, err := NewPatternMatcher(patterns)
  407. if err == nil {
  408. t.Errorf("expected error on single exclamation point, got %v", err)
  409. }
  410. }
  411. func TestCreateIfNotExistsDir(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. folderToCreate := filepath.Join(tempFolder, "tocreate")
  418. if err := CreateIfNotExists(folderToCreate, true); err != nil {
  419. t.Fatal(err)
  420. }
  421. fileinfo, err := os.Stat(folderToCreate)
  422. if err != nil {
  423. t.Fatalf("Should have create a folder, got %v", err)
  424. }
  425. if !fileinfo.IsDir() {
  426. t.Fatalf("Should have been a dir, seems it's not")
  427. }
  428. }
  429. func TestCreateIfNotExistsFile(t *testing.T) {
  430. tempFolder, err := ioutil.TempDir("", "docker-fileutils-test")
  431. if err != nil {
  432. t.Fatal(err)
  433. }
  434. defer os.RemoveAll(tempFolder)
  435. fileToCreate := filepath.Join(tempFolder, "file/to/create")
  436. if err := CreateIfNotExists(fileToCreate, false); err != nil {
  437. t.Fatal(err)
  438. }
  439. fileinfo, err := os.Stat(fileToCreate)
  440. if err != nil {
  441. t.Fatalf("Should have create a file, got %v", err)
  442. }
  443. if fileinfo.IsDir() {
  444. t.Fatalf("Should have been a file, seems it's not")
  445. }
  446. }
  447. // These matchTests are stolen from go's filepath Match tests.
  448. type matchTest struct {
  449. pattern, s string
  450. match bool
  451. err error
  452. }
  453. var matchTests = []matchTest{
  454. {"abc", "abc", true, nil},
  455. {"*", "abc", true, nil},
  456. {"*c", "abc", true, nil},
  457. {"a*", "a", true, nil},
  458. {"a*", "abc", true, nil},
  459. {"a*", "ab/c", true, nil},
  460. {"a*/b", "abc/b", true, nil},
  461. {"a*/b", "a/c/b", false, nil},
  462. {"a*b*c*d*e*/f", "axbxcxdxe/f", true, nil},
  463. {"a*b*c*d*e*/f", "axbxcxdxexxx/f", true, nil},
  464. {"a*b*c*d*e*/f", "axbxcxdxe/xxx/f", false, nil},
  465. {"a*b*c*d*e*/f", "axbxcxdxexxx/fff", false, nil},
  466. {"a*b?c*x", "abxbbxdbxebxczzx", true, nil},
  467. {"a*b?c*x", "abxbbxdbxebxczzy", false, nil},
  468. {"ab[c]", "abc", true, nil},
  469. {"ab[b-d]", "abc", true, nil},
  470. {"ab[e-g]", "abc", false, nil},
  471. {"ab[^c]", "abc", false, nil},
  472. {"ab[^b-d]", "abc", false, nil},
  473. {"ab[^e-g]", "abc", true, nil},
  474. {"a\\*b", "a*b", true, nil},
  475. {"a\\*b", "ab", false, nil},
  476. {"a?b", "a☺b", true, nil},
  477. {"a[^a]b", "a☺b", true, nil},
  478. {"a???b", "a☺b", false, nil},
  479. {"a[^a][^a][^a]b", "a☺b", false, nil},
  480. {"[a-ζ]*", "α", true, nil},
  481. {"*[a-ζ]", "A", false, nil},
  482. {"a?b", "a/b", false, nil},
  483. {"a*b", "a/b", false, nil},
  484. {"[\\]a]", "]", true, nil},
  485. {"[\\-]", "-", true, nil},
  486. {"[x\\-]", "x", true, nil},
  487. {"[x\\-]", "-", true, nil},
  488. {"[x\\-]", "z", false, nil},
  489. {"[\\-x]", "x", true, nil},
  490. {"[\\-x]", "-", true, nil},
  491. {"[\\-x]", "a", false, nil},
  492. {"[]a]", "]", false, filepath.ErrBadPattern},
  493. {"[-]", "-", false, filepath.ErrBadPattern},
  494. {"[x-]", "x", false, filepath.ErrBadPattern},
  495. {"[x-]", "-", false, filepath.ErrBadPattern},
  496. {"[x-]", "z", false, filepath.ErrBadPattern},
  497. {"[-x]", "x", false, filepath.ErrBadPattern},
  498. {"[-x]", "-", false, filepath.ErrBadPattern},
  499. {"[-x]", "a", false, filepath.ErrBadPattern},
  500. {"\\", "a", false, filepath.ErrBadPattern},
  501. {"[a-b-c]", "a", false, filepath.ErrBadPattern},
  502. {"[", "a", false, filepath.ErrBadPattern},
  503. {"[^", "a", false, filepath.ErrBadPattern},
  504. {"[^bc", "a", false, filepath.ErrBadPattern},
  505. {"a[", "a", false, filepath.ErrBadPattern}, // was nil but IMO its wrong
  506. {"a[", "ab", false, filepath.ErrBadPattern},
  507. {"*x", "xxx", true, nil},
  508. }
  509. func errp(e error) string {
  510. if e == nil {
  511. return "<nil>"
  512. }
  513. return e.Error()
  514. }
  515. // TestMatch test's our version of filepath.Match, called regexpMatch.
  516. func TestMatch(t *testing.T) {
  517. for _, tt := range matchTests {
  518. pattern := tt.pattern
  519. s := tt.s
  520. if runtime.GOOS == "windows" {
  521. if strings.Contains(pattern, "\\") {
  522. // no escape allowed on windows.
  523. continue
  524. }
  525. pattern = filepath.Clean(pattern)
  526. s = filepath.Clean(s)
  527. }
  528. ok, err := Matches(s, []string{pattern})
  529. if ok != tt.match || err != tt.err {
  530. t.Fatalf("Match(%#q, %#q) = %v, %q want %v, %q", pattern, s, ok, errp(err), tt.match, errp(tt.err))
  531. }
  532. }
  533. }