func TestGetRealPath(t *testing.T) { if runtime.GOOS == "windows" && os.Getenv("CI") == "" { t.Skip("Skip TestGetRealPath as os.Symlink needs administrator rights on Windows") } d1, err := ioutil.TempDir("", "d1") defer os.Remove(d1) fs := afero.NewOsFs() rp1, err := GetRealPath(fs, d1) require.NoError(t, err) assert.Equal(t, d1, rp1) sym := filepath.Join(os.TempDir(), "d1sym") err = os.Symlink(d1, sym) require.NoError(t, err) defer os.Remove(sym) rp2, err := GetRealPath(fs, sym) require.NoError(t, err) // On OS X, the temp folder is itself a symbolic link (to /private...) // This has to do for now. assert.True(t, strings.HasSuffix(rp2, d1)) }
// Run the application, start http and scp server. func Run(appConfig Config) { config = appConfig // Connect to DB db, err := lib.Connect() if err != nil { fmt.Printf("Failed to connect to db") return } // Logging log := logrus.New() log.Level = logrus.DebugLevel log.Out = os.Stdout log.Formatter = &logrus.TextFormatter{} // Websockets ws := ws.NewServer() // Shared dependencies between all controller deps := dependencies.Dependencies{ Fs: afero.NewOsFs(), Logger: log, DB: db, WS: ws, } ws.Dependencies = &deps go ws.Start() // // Start SCP // scp := scp.Server{} // scp.DB = deps.DB // scp.Logger = deps.Logger // scp.CertPath = "certs/scp.rsa" // scp.BindAddr = config.SCPBindAddr // go scp.ListenAndServe() if config.Secure { c := autocert.DirCache("certs") m := autocert.Manager{ Cache: c, Prompt: autocert.AcceptTOS, HostPolicy: autocert.HostWhitelist("x.zqz.ca"), } s := &http.Server{ Addr: config.HTTPBindAddr, TLSConfig: &tls.Config{GetCertificate: m.GetCertificate}, } deps.Info("Listening for HTTP1.1 Connections", "addr", ":3001") deps.Info("Listening for HTTP2 Connections", "addr", config.HTTPBindAddr) go http.ListenAndServe(":3001", secureRedirect()) s.ListenAndServeTLS("", "") } else { deps.Info("Listening for HTTP1.1 Connections", "addr", config.HTTPBindAddr) http.ListenAndServe(config.HTTPBindAddr, Routes(deps)) } }
func New(config Config, provider Provider) *Exporter { return &Exporter{ Config: config, Fs: afero.NewOsFs(), provider: provider, } }
func TestFilename(t *testing.T) { fs := afero.NewOsFs() filename := "lazy_file_reader_test.go" rd, err := NewLazyFileReader(fs, filename) if err != nil { t.Fatalf("NewLazyFileReader %s: %v", filename, err) } if rd.Filename() != filename { t.Errorf("Filename: expected filename %q, got %q", filename, rd.Filename()) } }
func TestNewLazyFileReader(t *testing.T) { fs := afero.NewOsFs() filename := "itdoesnotexistfile" _, err := NewLazyFileReader(fs, filename) if err == nil { t.Errorf("NewLazyFileReader %s: error expected but no error is returned", filename) } filename = "lazy_file_reader_test.go" _, err = NewLazyFileReader(fs, filename) if err != nil { t.Errorf("NewLazyFileReader %s: %v", filename, err) } }
func TestStdlib(t *testing.T) { // We need to specify that we read from disk because other tests may have switched // the filesystem to MemMap. util.AppFs = afero.NewOsFs() checkMachines := func(code, expectedCode string, expected ...Machine) { ctx := parseTestImport(t, code, expectedCode, "../specs") machineResult := Stitch{"", ctx}.QueryMachines() if !reflect.DeepEqual(machineResult, expected) { t.Error(spew.Sprintf("test: %s, result: %v, expected: %v", code, machineResult, expected)) } } code := `(import "stdlib/machines") (machines.Boot 1 2 (list (provider "Amazon") (size "m4.large") (sshkey "key")))` expCode := `(module "machines" (list) (list) (list) (list)) (list (machine (provider "Amazon") (size "m4.large") (role "Master") (sshkey "key")) (machine (provider "Amazon") (size "m4.large") (role "Worker") (sshkey "key")) (machine (provider "Amazon") (size "m4.large") (role "Worker") (sshkey "key")))` expMachines := []Machine{ {Provider: "Amazon", Size: "m4.large", Role: "Master", SSHKeys: []string{"key"}, }, {Provider: "Amazon", Size: "m4.large", Role: "Worker", SSHKeys: []string{"key"}, }, {Provider: "Amazon", Size: "m4.large", Role: "Worker", SSHKeys: []string{"key"}, }, } checkMachines(code, expCode, expMachines...) }
func init() { // file system filesystem := afero.NewOsFs() // locate the home directory userHomeDir, homeDirError := homedir.Dir() if homeDirError != nil { fmt.Fprintf(os.Stderr, "Unable to determine home directory: %s\n", homeDirError.Error()) os.Exit(1) } // base folder baseFolder := getSettingsFolder(filesystem, userHomeDir) // credential store credentialFilePath := filepath.Join(baseFolder, "credentials.json") credentialStore := filesystemCredentialStore{filesystem, credentialFilePath} // DNS client factory dnsClientFactory := dnsimpleClientFactory{credentialStore} // create DNSimple info provider dnsInfoProviderFactory := dnsimpleInfoProviderFactory{dnsClientFactory} // create a DNS editor instance dnsEditorFactory := dnsEditorFactory{dnsClientFactory, dnsInfoProviderFactory} actions = []action{ loginAction{credentialStore}, logoutAction{credentialStore}, listAction{dnsInfoProviderFactory}, createAction{dnsEditorFactory, os.Stdin}, updateAction{dnsEditorFactory, os.Stdin}, deleteAction{dnsEditorFactory}, createOrUpdateAction{dnsEditorFactory, dnsInfoProviderFactory, os.Stdin}, } // override the help information printer // of the flag package executablePath := os.Args[0] executableName := path.Base(executablePath) usagePrinter := newUsagePrinter(executableName, version(), actions) flag.Usage = func() { usagePrinter.PrintUsageInformation(os.Stdout) } }
// Returns an initialized Viper instance. func New() *Viper { v := new(Viper) v.keyDelim = "." v.configName = "config" v.fs = afero.NewOsFs() v.config = make(map[string]interface{}) v.override = make(map[string]interface{}) v.defaults = make(map[string]interface{}) v.kvstore = make(map[string]interface{}) v.pflags = make(map[string]FlagValue) v.env = make(map[string]string) v.aliases = make(map[string]string) v.typeByDefValue = false return v }
func TestWriteTo(t *testing.T) { fs := afero.NewOsFs() filename := "lazy_file_reader_test.go" fi, err := fs.Stat(filename) if err != nil { t.Fatalf("os.Stat: %v", err) } b, err := afero.ReadFile(fs, filename) if err != nil { t.Fatalf("afero.ReadFile: %v", err) } rd, err := NewLazyFileReader(fs, filename) if err != nil { t.Fatalf("NewLazyFileReader %s: %v", filename, err) } tst := func(testcase string, expectedSize int64, checkEqual bool) { buf := bytes.NewBuffer(make([]byte, 0, bytes.MinRead)) n, err := rd.WriteTo(buf) if err != nil { t.Fatalf("WriteTo %s case: %v", testcase, err) } if n != expectedSize { t.Errorf("WriteTo %s case: written bytes length expected %d, got %d", testcase, expectedSize, n) } if checkEqual && !bytes.Equal(b, buf.Bytes()) { t.Errorf("WriteTo %s case: written bytes are different from expected", testcase) } } tst("No cache", fi.Size(), true) tst("No cache 2nd", 0, false) p := make([]byte, fi.Size()) _, err = rd.Read(p) if err != nil && err != io.EOF { t.Fatalf("Read: %v", err) } _, err = rd.Seek(0, 0) if err != nil { t.Fatalf("Seek: %v", err) } tst("Cache", fi.Size(), true) }
func TestRead(t *testing.T) { fs := afero.NewOsFs() filename := "lazy_file_reader_test.go" fi, err := fs.Stat(filename) if err != nil { t.Fatalf("os.Stat: %v", err) } b, err := afero.ReadFile(fs, filename) if err != nil { t.Fatalf("afero.ReadFile: %v", err) } rd, err := NewLazyFileReader(fs, filename) if err != nil { t.Fatalf("NewLazyFileReader %s: %v", filename, err) } tst := func(testcase string) { p := make([]byte, fi.Size()) n, err := rd.Read(p) if err != nil { t.Fatalf("Read %s case: %v", testcase, err) } if int64(n) != fi.Size() { t.Errorf("Read %s case: read bytes length expected %d, got %d", testcase, fi.Size(), n) } if !bytes.Equal(b, p) { t.Errorf("Read %s case: read bytes are different from expected", testcase) } } tst("No cache") _, err = rd.Seek(0, 0) if err != nil { t.Fatalf("Seek: %v", err) } tst("Cache") }
func TestSeek(t *testing.T) { type testcase struct { seek int offset int64 length int moveto int64 expected []byte } fs := afero.NewOsFs() filename := "lazy_file_reader_test.go" b, err := afero.ReadFile(fs, filename) if err != nil { t.Fatalf("afero.ReadFile: %v", err) } // no cache case for i, this := range []testcase{ {seek: os.SEEK_SET, offset: 0, length: 10, moveto: 0, expected: b[:10]}, {seek: os.SEEK_SET, offset: 5, length: 10, moveto: 5, expected: b[5:15]}, {seek: os.SEEK_CUR, offset: 5, length: 10, moveto: 5, expected: b[5:15]}, // current pos = 0 {seek: os.SEEK_END, offset: -1, length: 1, moveto: int64(len(b) - 1), expected: b[len(b)-1:]}, {seek: 3, expected: nil}, {seek: os.SEEK_SET, offset: -1, expected: nil}, } { rd, err := NewLazyFileReader(fs, filename) if err != nil { t.Errorf("[%d] NewLazyFileReader %s: %v", i, filename, err) continue } pos, err := rd.Seek(this.offset, this.seek) if this.expected == nil { if err == nil { t.Errorf("[%d] Seek didn't return an expected error", i) } } else { if err != nil { t.Errorf("[%d] Seek failed unexpectedly: %v", i, err) continue } if pos != this.moveto { t.Errorf("[%d] Seek failed to move the pointer: got %d, expected: %d", i, pos, this.moveto) } buf := make([]byte, this.length) n, err := rd.Read(buf) if err != nil { t.Errorf("[%d] Read failed unexpectedly: %v", i, err) } if !bytes.Equal(this.expected, buf[:n]) { t.Errorf("[%d] Seek and Read got %q but expected %q", i, buf[:n], this.expected) } } } // cache case rd, err := NewLazyFileReader(fs, filename) if err != nil { t.Fatalf("NewLazyFileReader %s: %v", filename, err) } dummy := make([]byte, len(b)) _, err = rd.Read(dummy) if err != nil { t.Fatalf("Read failed unexpectedly: %v", err) } for i, this := range []testcase{ {seek: os.SEEK_SET, offset: 0, length: 10, moveto: 0, expected: b[:10]}, {seek: os.SEEK_SET, offset: 5, length: 10, moveto: 5, expected: b[5:15]}, {seek: os.SEEK_CUR, offset: 1, length: 10, moveto: 16, expected: b[16:26]}, // current pos = 15 {seek: os.SEEK_END, offset: -1, length: 1, moveto: int64(len(b) - 1), expected: b[len(b)-1:]}, {seek: 3, expected: nil}, {seek: os.SEEK_SET, offset: -1, expected: nil}, } { pos, err := rd.Seek(this.offset, this.seek) if this.expected == nil { if err == nil { t.Errorf("[%d] Seek didn't return an expected error", i) } } else { if err != nil { t.Errorf("[%d] Seek failed unexpectedly: %v", i, err) continue } if pos != this.moveto { t.Errorf("[%d] Seek failed to move the pointer: got %d, expected: %d", i, pos, this.moveto) } buf := make([]byte, this.length) n, err := rd.Read(buf) if err != nil { t.Errorf("[%d] Read failed unexpectedly: %v", i, err) } if !bytes.Equal(this.expected, buf[:n]) { t.Errorf("[%d] Seek and Read got %q but expected %q", i, buf[:n], this.expected) } } } }
ed := 0 for _, label := range b { if _, ok := amap[label]; ok { delete(amap, label) } else { ed++ } } ed += len(amap) return ed } // AppFs is an aero filesystem. It is stored in a variable so that we can replace it // with in-memory filesystems for unit tests. var AppFs = afero.NewOsFs() // Open opens a new aero file. func Open(path string) (afero.File, error) { return AppFs.Open(path) } // WriteFile writes 'data' to the file 'filename' with the given permissions. func WriteFile(filename string, data []byte, perm os.FileMode) error { a := afero.Afero{ Fs: AppFs, } return a.WriteFile(filename, data, perm) } // ReadFile returns the contents of `filename`.
"errors" "fmt" "io/ioutil" "net/http" "os" "os/exec" "path/filepath" "time" "github.com/Sirupsen/logrus" "github.com/spf13/afero" ) // appFs is an aero filesystem. It is stored in a variable so that we can replace it // with in-memory filesystems for unit tests. var appFs = afero.NewOsFs() type logger struct { rootDir string cmdLogger fileLogger testerLogger fileLogger ip string } // Creates a new fileLogger for the given test, in the appropriate // "passed" or "failed" directory. func (l logger) testLogger(passed bool, testName string) fileLogger { filename := fmt.Sprintf("%s.txt", testName) folder := filepath.Join(l.rootDir, "passed") if !passed { folder = filepath.Join(l.rootDir, "failed")