github.com/GGP1/kure@v0.8.4/commands/backup/backup_test.go (about) 1 package backup 2 3 import ( 4 "bytes" 5 "net/http" 6 "net/http/httptest" 7 "os" 8 "testing" 9 10 cmdutil "github.com/GGP1/kure/commands" 11 12 "github.com/stretchr/testify/assert" 13 ) 14 15 func TestBackupFile(t *testing.T) { 16 db := cmdutil.SetContext(t) 17 filename := "backup-test" 18 19 cmd := NewCmd(db) 20 f := cmd.Flags() 21 f.Set("path", filename) 22 23 err := cmd.Execute() 24 assert.NoError(t, err, "Failed creating the backup file") 25 26 err = os.Remove(filename) 27 assert.NoError(t, err, "Failed removing the backup file") 28 } 29 30 func TestBackupServer(t *testing.T) { 31 db := cmdutil.SetContext(t) 32 33 rec := httptest.NewRecorder() 34 req, err := http.NewRequest("GET", "localhost:4000/", nil) 35 assert.NoError(t, err, "Failed sending the request") 36 37 hf := httpBackup(db) 38 hf.ServeHTTP(rec, req) 39 40 res := rec.Result() 41 assert.Equal(t, http.StatusOK, res.StatusCode) 42 43 gotCt := res.Header.Get("Content-Type") 44 expectedCt := "application/octet-stream" 45 assert.Equal(t, expectedCt, gotCt) 46 } 47 48 func TestBackupErrors(t *testing.T) { 49 db := cmdutil.SetContext(t) 50 51 cases := []struct { 52 desc string 53 port string 54 http string 55 path string 56 }{ 57 { 58 desc: "HTTP", 59 http: "true", 60 port: "0", 61 }, 62 { 63 desc: "Invalid path", 64 path: "", 65 }, 66 { 67 desc: "Mkdir error", 68 path: "backup.go/", 69 }, 70 } 71 72 cmd := NewCmd(db) 73 74 for _, tc := range cases { 75 t.Run(tc.desc, func(t *testing.T) { 76 f := cmd.Flags() 77 f.Set("path", tc.path) 78 f.Set("http", tc.http) 79 f.Set("port", tc.port) 80 81 err := cmd.Execute() 82 assert.Error(t, err) 83 }) 84 } 85 } 86 87 func TestWriteTo(t *testing.T) { 88 db := cmdutil.SetContext(t) 89 90 var buf bytes.Buffer 91 err := writeTo(db, &buf) 92 assert.NoError(t, err, "Failed writing database") 93 94 assert.NotEqual(t, buf.Len(), 0) 95 } 96 97 func TestPostRun(t *testing.T) { 98 NewCmd(nil).PostRun(nil, nil) 99 }