• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang afero.NewMemMapFs函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/spf13/afero.NewMemMapFs函数的典型用法代码示例。如果您正苦于以下问题:Golang NewMemMapFs函数的具体用法?Golang NewMemMapFs怎么用?Golang NewMemMapFs使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了NewMemMapFs函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: TestErrorMetadata

func TestErrorMetadata(t *testing.T) {
	var checkParseErr = func(path string, expErr string) {
		sc := scanner.Scanner{
			Position: scanner.Position{
				Filename: path,
			},
		}
		f, err := util.Open(path)
		if err != nil {
			t.Errorf("Couldn't open %s", path)
		}
		_, err = parse(*sc.Init(f))
		if err.Error() != expErr {
			t.Errorf("Expected \"%s\"\ngot \"%s\"", expErr, err)
			return
		}
	}
	var checkEvalErr = func(path string, expErr string) {
		sc := scanner.Scanner{
			Position: scanner.Position{
				Filename: path,
			},
		}
		f, err := util.Open(path)
		if err != nil {
			t.Errorf("Couldn't open %s", path)
		}
		parsed, err := parse(*sc.Init(f))
		if err != nil {
			t.Errorf("Unexpected parse error: %s", parsed)
		}

		_, _, err = eval(astRoot(parsed))
		if err.Error() != expErr {
			t.Errorf("Expected \"%s\"\ngot \"%s\"", expErr, err)
			return
		}
	}

	util.AppFs = afero.NewMemMapFs()
	util.WriteFile("paren.spec", []byte(`
// This is a comment.
(define Test "abc"`), 0644)
	checkParseErr("paren.spec", "paren.spec:3: unbalanced Parenthesis")

	util.WriteFile("undefined.spec", []byte(`
(+ 1 b)`), 0644)
	checkEvalErr("undefined.spec", "undefined.spec:2: unassigned variable: b")

	util.WriteFile("bad_type.spec", []byte(`
(define a "1")
(+ 1 a)`), 0644)
	checkEvalErr("bad_type.spec", `bad_type.spec:3: bad arithmetic argument: "1"`)

	// Test that functions which evaluate generated S-expressions still have proper
	// error messages.
	util.WriteFile("generated_sexp.spec", []byte(`(apply + (list 1 "1"))`), 0644)
	checkEvalErr("generated_sexp.spec",
		`generated_sexp.spec:1: bad arithmetic argument: "1"`)
}
开发者ID:yuenmeiwan,项目名称:quilt,代码行数:60,代码来源:stitch_test.go


示例2: TestPromptsUser

func TestPromptsUser(t *testing.T) {
	oldConfirm := confirm
	defer func() {
		confirm = oldConfirm
	}()

	util.AppFs = afero.NewMemMapFs()
	for _, confirmResp := range []bool{true, false} {
		confirm = func(in io.Reader, prompt string) (bool, error) {
			return confirmResp, nil
		}

		mockGetter := new(testutils.Getter)
		c := &clientMock.Client{
			ClusterReturn: []db.Cluster{
				{
					Spec: `{"old":"spec"}`,
				},
			},
		}
		mockGetter.On("Client", mock.Anything).Return(c, nil)

		util.WriteFile("test.js", []byte(""), 0644)
		runCmd := NewRunCommand()
		runCmd.clientGetter = mockGetter
		runCmd.stitch = "test.js"
		runCmd.Run()
		assert.Equal(t, confirmResp, c.DeployArg != "")
	}
}
开发者ID:NetSys,项目名称:quilt,代码行数:30,代码来源:run_test.go


示例3: testCheckSpec

func testCheckSpec(t *testing.T) {
	initVCSFunc()
	os.Setenv("QUILT_PATH", ".")
	util.AppFs = afero.NewMemMapFs()
	util.AppFs.Mkdir("test", 777)
	util.WriteFile("test/noDownload.spec",
		[]byte(`(import "nextimport/nextimport")`), 0644)
	util.AppFs.Mkdir("nextimport", 777)
	util.WriteFile("nextimport/nextimport.spec", []byte("(define dummy 1)"), 0644)
	if err := checkSpec("test/noDownload.spec", nil, nil); err != nil {
		t.Error(err)
	}

	if len(created) != 0 {
		t.Errorf("should not have downloaded, but downloaded %s", created)
	}

	// Verify that call is made to GetSpec
	util.WriteFile("test/toDownload.spec",
		[]byte(`(import "github.com/NetSys/quilt/specs/example")`), 0644)
	expected := "unable to open import github.com/NetSys/quilt/specs/example"
	if err := checkSpec("test/toDownload.spec", nil, nil); err.Error() != expected {
		t.Errorf("expected %s \n but got %s", expected, err.Error())
	}

	if len(created) == 0 {
		t.Error("did not download dependency!")
	}

	expected = "github.com/NetSys/quilt"
	if created[0] != expected {
		t.Errorf("expected to download %s \n but got %s", expected, created[0])
	}
}
开发者ID:yuenmeiwan,项目名称:quilt,代码行数:34,代码来源:stitch_test.go


示例4: TestAutoDownload

func TestAutoDownload(t *testing.T) {
	util.AppFs = afero.NewMemMapFs()

	repoName := "autodownload"
	importPath := filepath.Join(repoName, "foo")
	util.WriteFile("test.js", []byte(fmt.Sprintf("require(%q);", importPath)), 0644)

	logger := newRepoLogger()
	getter := ImportGetter{
		Path:        ".",
		repoFactory: logger.newRepoFactory(nil),
	}

	expErr := "StitchError: unable to open import autodownload/foo: no loadable file"
	err := getter.checkSpec("test.js", nil, nil)
	if err == nil || err.Error() != expErr {
		t.Errorf("Wrong error, expected %q, got %v", expErr, err)
		return
	}

	assert.Equal(t, map[string][]string{
		importPath: {repoName},
	}, logger.created, "Should autodownload the repo")
	assert.Empty(t, logger.updated, "Shouldn't update any repos")
}
开发者ID:NetSys,项目名称:quilt,代码行数:25,代码来源:get_test.go


示例5: Test_filesystemCredentialStore_GetCredentials_SavedCredentialsAreValid_CredentialsAreReturned

func Test_filesystemCredentialStore_GetCredentials_SavedCredentialsAreValid_CredentialsAreReturned(t *testing.T) {

	// arrange
	fs := afero.NewMemMapFs()
	credentialFilePath := "/home/user/.dee/credentials.json"

	// create the initial file
	f1, _ := fs.Create(credentialFilePath)
	f1.WriteString(`{"Email":"[email protected]","Token":"123456"}`)
	f1.Close()

	credentialStore := filesystemCredentialStore{fs, credentialFilePath}

	// act
	credentials, err := credentialStore.GetCredentials()

	// assert
	if err != nil {
		t.Fail()
		t.Logf("GetCredentials returned an error: %s", err.Error())
	}

	if credentials.Email != "[email protected]" || credentials.Token != "123456" {
		t.Fail()
		t.Logf("GetCredentials did not return the correct credentials. Email: %q, Token: %q", credentials.Email, credentials.Token)
	}
}
开发者ID:andreaskoch,项目名称:dee-cli,代码行数:27,代码来源:credentials_test.go


示例6: TestCmdExec

func TestCmdExec(t *testing.T) {
	appFs = afero.NewMemMapFs()

	outputPath := "output.log"
	log = logger{
		cmdLogger: fileLogger(outputPath),
	}

	expStdout := "standard out"
	expStderr := "standard error"
	cmd := exec.Command("sh", "-c",
		fmt.Sprintf("echo %s ; echo %s 1>&2", expStdout, expStderr))
	stdout, stderr, err := execCmd(cmd, "PREFIX")

	if err != nil {
		t.Errorf("Unexpected error: %s", err.Error())
		return
	}
	if stdout != expStdout {
		t.Errorf("Stdout didn't match: expected %s, got %s", expStdout, stdout)
	}
	if stderr != expStderr {
		t.Errorf("Stderr didn't match: expected %s, got %s", expStderr, stderr)
	}
}
开发者ID:NetSys,项目名称:quilt,代码行数:25,代码来源:tester_test.go


示例7: TestUpdateNamespace

func TestUpdateNamespace(t *testing.T) {
	appFs = afero.NewMemMapFs()

	specPath := "/test.spec"
	err := overwrite(specPath, `require("spark");
var deployment = createDeployment({namespace: "replace"});
deployment.deploy(new Machine({}));`)
	if err != nil {
		t.Errorf("Unexpected error: %s", err.Error())
	}
	updateNamespace(specPath, "test-namespace")

	res, err := fileContents(specPath)
	exp := `require("spark");
var deployment = createDeployment({namespace: "replace"});
deployment.deploy(new Machine({}));; deployment.namespace = "test-namespace";`
	if err != nil {
		t.Errorf("Unexpected error: %s", err.Error())
		return
	}
	if res != exp {
		t.Errorf("Namespace didn't properly update, expected %s, got %s",
			exp, res)
	}
}
开发者ID:NetSys,项目名称:quilt,代码行数:25,代码来源:tester_test.go


示例8: TestDefaultKeys

func TestDefaultKeys(t *testing.T) {
	util.AppFs = afero.NewMemMapFs()

	// Don't pull in keys from the host OS. Setting this environment variable
	// is safe because it won't affect the parent shell.
	os.Setenv("SSH_AUTH_SOCK", "")

	dir, err := homedir.Dir()
	if err != nil {
		t.Errorf("Failed to get homedir: %q", err.Error())
		return
	}

	sshDir := filepath.Join(dir, ".ssh")
	if err := util.AppFs.MkdirAll(sshDir, 0600); err != nil {
		t.Errorf("Failed to create SSH directory: %q", err.Error())
		return
	}

	for _, key := range []string{"id_rsa", "id_dsa", "ignored"} {
		if err := writeRandomKey(filepath.Join(sshDir, key)); err != nil {
			t.Errorf("Failed to write key: %q", err.Error())
			return
		}
	}

	signers := defaultSigners()
	if len(signers) != 2 {
		t.Errorf("Expected two default signers, but got %v", signers)
	}
}
开发者ID:NetSys,项目名称:quilt,代码行数:31,代码来源:native_test.go


示例9: TestCompileAndRun

func TestCompileAndRun(t *testing.T) {
	var testProgram = "/$/ {}\n"
	store := metrics.NewStore()
	lines := make(chan string)
	w := watcher.NewFakeWatcher()
	fs := afero.NewMemMapFs()
	o := LoaderOptions{store, lines, w, fs, false, false, true}
	l, err := NewLoader(o)
	if err != nil {
		t.Fatalf("couldn't create loader: %s", err)
	}
	if err := l.CompileAndRun("Test", strings.NewReader(testProgram)); err != nil {
		t.Errorf("CompileAndRun returned error: %s", err)
	}
	l.handleMu.Lock()
	if len(l.handles) < 1 {
		t.Errorf("no vm handles: %v", l.handles)
	}
	l.handleMu.Unlock()
	l.handleMu.Lock()
	c := l.handles["Test"].done
	if c == nil {
		t.Errorf("No done channel in handles: %v", l.handles)
	}
	l.handleMu.Unlock()
	close(lines)
	<-c
	{
		l.handleMu.Lock()
		defer l.handleMu.Unlock()
		if len(l.handles) != 0 {
			t.Errorf("some vm handles: %v", l.handles)
		}
	}
}
开发者ID:yanghongkjxy,项目名称:mtail,代码行数:35,代码来源:loader_test.go


示例10: TestMain

func TestMain(t *testing.T) {
	util.AppFs = afero.NewMemMapFs()
	util.WriteFile("test.js", []byte(testStitch), 0644)

	exitCode := Main([]string{"test.js", "graphviz"})

	assert.Zero(t, exitCode)
	res, err := util.ReadFile("test.dot")
	assert.Nil(t, err)
	assert.True(t, isGraphEqual(expGraph, res))
}
开发者ID:NetSys,项目名称:quilt,代码行数:11,代码来源:inspect_test.go


示例11: makeTestTail

func makeTestTail(t *testing.T) (*Tailer, chan string, *watcher.FakeWatcher, afero.Fs) {
	fs := afero.NewMemMapFs()
	w := watcher.NewFakeWatcher()
	lines := make(chan string, 1)
	o := Options{lines, w, fs}
	ta, err := New(o)
	if err != nil {
		t.Fatal(err)
	}
	return ta, lines, w, fs
}
开发者ID:yanghongkjxy,项目名称:mtail,代码行数:11,代码来源:tail_test.go


示例12: TestSyncKeysError

func TestSyncKeysError(t *testing.T) {
	util.AppFs = afero.NewMemMapFs()

	conn := db.New()
	err := runOnce(conn)
	assert.EqualError(t, err, "no self minion")

	fs := afero.NewMemMapFs()
	util.AppFs = afero.NewReadOnlyFs(fs)
	conn.Transact(func(view db.Database) error {
		m := view.InsertMinion()
		m.Self = true
		m.AuthorizedKeys = "keys"
		view.Commit(m)
		return nil
	})
	err = runOnce(conn)
	assert.EqualError(t, err, "open /home/quilt/.ssh/authorized_keys: "+
		"file does not exist")

	fs.Create(authorizedKeysFile)
	err = runOnce(conn)
	assert.EqualError(t, err, "operation not permitted")
}
开发者ID:NetSys,项目名称:quilt,代码行数:24,代码来源:keys_test.go


示例13: Test_filesystemCredentialStore_SaveCredentials_CredentialsAreValid_NoErrorIsReturned

func Test_filesystemCredentialStore_SaveCredentials_CredentialsAreValid_NoErrorIsReturned(t *testing.T) {

	// arrange
	fs := afero.NewMemMapFs()
	credentialFilePath := "/home/user/.dee/credentials.json"
	credentialStore := filesystemCredentialStore{fs, credentialFilePath}

	// act
	err := credentialStore.SaveCredentials(deens.APICredentials{"[email protected]", "123456"})

	// assert
	if err != nil {
		t.Fail()
		t.Logf("SaveCredentials should not return an error (%q)", err.Error())
	}
}
开发者ID:andreaskoch,项目名称:dee-cli,代码行数:16,代码来源:credentials_test.go


示例14: Test_filesystemCredentialStore_WithoutSourceFile_DeleteCredentials_credentialsNotFoundErrorIsReturned

func Test_filesystemCredentialStore_WithoutSourceFile_DeleteCredentials_credentialsNotFoundErrorIsReturned(t *testing.T) {

	// arrange
	fs := afero.NewMemMapFs()
	credentialFilePath := "/home/user/.dee/credentials.json"
	credentialStore := filesystemCredentialStore{fs, credentialFilePath}

	// act
	err := credentialStore.DeleteCredentials()

	// assert
	if !isNoCredentialsError(err) {
		t.Fail()
		t.Logf("DeleteCredentials should return a noCredentials-error if the credential store has no source file.")
	}
}
开发者ID:andreaskoch,项目名称:dee-cli,代码行数:16,代码来源:credentials_test.go


示例15: TestSyncKeys

func TestSyncKeys(t *testing.T) {
	tests := []keyTest{
		{
			dbKeys:     "key1\nkey2",
			expKeyFile: "key1\nkey2",
		},
		{
			dbKeys:     "key1\nkey2",
			keyFile:    "key1",
			expKeyFile: "key1\nkey2",
		},
		{
			dbKeys:     "key1\nkey2",
			keyFile:    "key1\nkey2",
			expKeyFile: "key1\nkey2",
		},
		{
			keyFile:    "key1\nkey2",
			expKeyFile: "",
		},
	}
	for _, test := range tests {
		util.AppFs = afero.NewMemMapFs()
		if test.keyFile != "" {
			err := util.WriteFile(
				authorizedKeysFile, []byte(test.keyFile), 0644)
			assert.NoError(t, err)
		}

		conn := db.New()
		conn.Transact(func(view db.Database) error {
			m := view.InsertMinion()
			m.Self = true
			m.AuthorizedKeys = test.dbKeys
			view.Commit(m)
			return nil
		})

		err := runOnce(conn)
		assert.NoError(t, err)

		actual, err := util.ReadFile(authorizedKeysFile)
		assert.NoError(t, err)
		assert.Equal(t, test.expKeyFile, actual)
	}
}
开发者ID:NetSys,项目名称:quilt,代码行数:46,代码来源:keys_test.go


示例16: Test_filesystemCredentialStore_WithoutFilePath_SaveCredentials_ErrorIsReturned

func Test_filesystemCredentialStore_WithoutFilePath_SaveCredentials_ErrorIsReturned(t *testing.T) {

	// arrange
	filesystem := afero.NewMemMapFs()
	credentialStore := filesystemCredentialStore{
		fs: filesystem,
	}

	// act
	err := credentialStore.SaveCredentials(deens.APICredentials{"[email protected]", "123456"})

	// assert
	if err == nil {
		t.Fail()
		t.Logf("SaveCredentials should return an error if the credential store file path configured.")
	}
}
开发者ID:andreaskoch,项目名称:dee-cli,代码行数:17,代码来源:credentials_test.go


示例17: Test_filesystemCredentialStore_SaveCredentials_CredentialsAreValid_JSONIsWrittenToFile

func Test_filesystemCredentialStore_SaveCredentials_CredentialsAreValid_JSONIsWrittenToFile(t *testing.T) {

	// arrange
	fs := afero.NewMemMapFs()
	credentialFilePath := "/home/user/.dee/credentials.json"
	credentialStore := filesystemCredentialStore{fs, credentialFilePath}

	// act
	credentialStore.SaveCredentials(deens.APICredentials{"[email protected]", "123456"})

	// assert
	expectedResult := `{"Email":"[email protected]","Token":"123456"}`
	content, _ := afero.ReadFile(fs, credentialFilePath)
	if string(content) != expectedResult {
		t.Fail()
		t.Logf("SaveCredentials should have written the credentials as JSON to %q. Expected: %q, Actual: %q", credentialFilePath, expectedResult, string(content))
	}
}
开发者ID:andreaskoch,项目名称:dee-cli,代码行数:18,代码来源:credentials_test.go


示例18: TestImportExists

func TestImportExists(t *testing.T) {
	util.AppFs = afero.NewMemMapFs()

	util.WriteFile("test.js", []byte(`require("existingImport")`), 0644)
	util.WriteFile("existingImport.js", []byte(""), 0644)

	logger := newRepoLogger()
	getter := ImportGetter{
		Path:        ".",
		repoFactory: logger.newRepoFactory(nil),
	}
	if err := getter.checkSpec("test.js", nil, nil); err != nil {
		t.Error(err)
		return
	}

	assert.Empty(t, logger.created, "Shouldn't create any repos")
	assert.Empty(t, logger.updated, "Shouldn't update any repos")
}
开发者ID:NetSys,项目名称:quilt,代码行数:19,代码来源:get_test.go


示例19: TestGetWalk

func TestGetWalk(t *testing.T) {
	util.AppFs = afero.NewMemMapFs()

	quiltPath := "getspecs"

	repoOne := "repoOne"
	importOne := filepath.Join(repoOne, "file")

	repoTwo := "anotherRepo"
	fileTwo := "importTwo"
	importTwo := filepath.Join(repoTwo, fileTwo)

	logger := newRepoLogger()
	getter := ImportGetter{
		Path: quiltPath,
		repoFactory: logger.newRepoFactory(map[string][]file{
			importOne: {
				{
					name:     "foo.js",
					contents: fmt.Sprintf("require(%q);", importTwo),
				},
			},
			importTwo: {
				{
					name: fmt.Sprintf("%s.js", fileTwo),
				},
			},
		}),
	}

	if err := getter.Get(importOne); err != nil {
		t.Error(err)
		return
	}

	assert.Equal(t, map[string][]string{
		importOne: {filepath.Join(quiltPath, repoOne)},
		importTwo: {filepath.Join(quiltPath, repoTwo)},
	}, logger.created, "Should autodownload the imported repo")
	assert.Empty(t, logger.updated, "Shouldn't update any repos")
}
开发者ID:NetSys,项目名称:quilt,代码行数:41,代码来源:get_test.go


示例20: getFileWithContent

// getFileWithContent returns an afero.File with the given name and content.
func getFileWithContent(name, content string) (afero.File, error) {
	fs := afero.NewMemMapFs()
	fs.MkdirAll(path.Base(name), 0755)
	f, createFileError := fs.OpenFile(name, os.O_CREATE|os.O_RDWR, 0744)
	if createFileError != nil {
		return nil, createFileError
	}

	_, writeError := f.WriteString(content)
	if writeError != nil {
		return nil, writeError
	}
	f.Close()

	f2, openFileError := fs.OpenFile(name, os.O_CREATE|os.O_RDWR, 0744)
	if openFileError != nil {
		return nil, openFileError
	}

	return f2, nil
}
开发者ID:andreaskoch,项目名称:dee-cli,代码行数:22,代码来源:credentials_test.go



注:本文中的github.com/spf13/afero.NewMemMapFs函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang afero.ReadFile函数代码示例发布时间:2022-05-28
下一篇:
Golang test.RunTestServer函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap