tftp_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package tftp
  2. import (
  3. "fmt"
  4. "io"
  5. "reflect"
  6. "testing"
  7. )
  8. type mockClient struct {
  9. }
  10. type mockReceiver struct {
  11. }
  12. func (r mockReceiver) WriteTo(w io.Writer) (n int64, err error) {
  13. b := []byte("cloud-config file")
  14. w.Write(b)
  15. return int64(len(b)), nil
  16. }
  17. func (c mockClient) Receive(filename string, mode string) (io.WriterTo, error) {
  18. if filename == "does-not-exist" {
  19. return &mockReceiver{}, fmt.Errorf("does not exist")
  20. }
  21. return &mockReceiver{}, nil
  22. }
  23. var _ Client = (*mockClient)(nil)
  24. func TestNewDatasource(t *testing.T) {
  25. for _, tt := range []struct {
  26. root string
  27. expectHost string
  28. expectPath string
  29. }{
  30. {
  31. root: "127.0.0.1/test/file.yaml",
  32. expectHost: "127.0.0.1:69",
  33. expectPath: "test/file.yaml",
  34. },
  35. {
  36. root: "127.0.0.1/test/file.yaml",
  37. expectHost: "127.0.0.1:69",
  38. expectPath: "test/file.yaml",
  39. },
  40. } {
  41. ds := NewDatasource(tt.root)
  42. if ds.host != tt.expectHost || ds.path != tt.expectPath {
  43. t.Fatalf("bad host or path (%q): want host=%s, got %s, path=%s, got %s", tt.root, tt.expectHost, ds.host, tt.expectPath, ds.path)
  44. }
  45. }
  46. }
  47. func TestIsAvailable(t *testing.T) {
  48. for _, tt := range []struct {
  49. remoteFile *RemoteFile
  50. expect bool
  51. }{
  52. {
  53. remoteFile: &RemoteFile{"1.2.3.4", "test", &mockClient{}, nil, nil},
  54. expect: true,
  55. },
  56. {
  57. remoteFile: &RemoteFile{"1.2.3.4", "does-not-exist", &mockClient{}, nil, nil},
  58. expect: false,
  59. },
  60. } {
  61. if tt.remoteFile.IsAvailable() != tt.expect {
  62. t.Fatalf("expected remote file %s to be %v", tt.remoteFile.path, tt.expect)
  63. }
  64. }
  65. }
  66. func TestFetchUserdata(t *testing.T) {
  67. rf := &RemoteFile{"1.2.3.4", "test", &mockClient{}, &mockReceiver{}, nil}
  68. b, _ := rf.FetchUserdata()
  69. expect := []byte("cloud-config file")
  70. if len(b) != len(expect) || !reflect.DeepEqual(b, expect) {
  71. t.Fatalf("expected length of buffer to be %d was %d. Expected %s, got %s", len(expect), len(b), string(expect), string(b))
  72. }
  73. }
  74. func TestType(t *testing.T) {
  75. rf := &RemoteFile{"1.2.3.4", "test", &mockClient{}, nil, nil}
  76. if rf.Type() != "tftp" {
  77. t.Fatalf("expected remote file Type() to return %s got %s", "tftp", rf.Type())
  78. }
  79. }