You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.4 KiB

  1. package common
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "testing"
  8. "time"
  9. )
  10. func TestWriteFileAtomic(t *testing.T) {
  11. data := []byte("Becatron")
  12. fname := fmt.Sprintf("/tmp/write-file-atomic-test-%v.txt", time.Now().UnixNano())
  13. err := WriteFileAtomic(fname, data, 0664)
  14. if err != nil {
  15. t.Fatal(err)
  16. }
  17. rData, err := ioutil.ReadFile(fname)
  18. if err != nil {
  19. t.Fatal(err)
  20. }
  21. if !bytes.Equal(data, rData) {
  22. t.Fatalf("data mismatch: %v != %v", data, rData)
  23. }
  24. if err := os.Remove(fname); err != nil {
  25. t.Fatal(err)
  26. }
  27. }
  28. func TestGoPath(t *testing.T) {
  29. // restore original gopath upon exit
  30. path := os.Getenv("GOPATH")
  31. defer func() {
  32. _ = os.Setenv("GOPATH", path)
  33. }()
  34. err := os.Setenv("GOPATH", "~/testgopath")
  35. if err != nil {
  36. t.Fatal(err)
  37. }
  38. path = GoPath()
  39. if path != "~/testgopath" {
  40. t.Fatalf("should get GOPATH env var value, got %v", path)
  41. }
  42. os.Unsetenv("GOPATH")
  43. path = GoPath()
  44. if path != "~/testgopath" {
  45. t.Fatalf("subsequent calls should return the same value, got %v", path)
  46. }
  47. }
  48. func TestGoPathWithoutEnvVar(t *testing.T) {
  49. // restore original gopath upon exit
  50. path := os.Getenv("GOPATH")
  51. defer func() {
  52. _ = os.Setenv("GOPATH", path)
  53. }()
  54. os.Unsetenv("GOPATH")
  55. // reset cache
  56. gopath = ""
  57. path = GoPath()
  58. if path == "" || path == "~/testgopath" {
  59. t.Fatalf("should get nonempty result of calling go env GOPATH, got %v", path)
  60. }
  61. }