Exemplo n.º 1
0
func TestArgs_Words(t *testing.T) {
	args := NewArgs([]string{"--no-ff", "master"})
	a := args.Words()

	assert.Equal(t, 1, len(a))
	assert.Equal(t, "master", a[0])
}
Exemplo n.º 2
0
func TestDecode(t *testing.T) {
	input := `
{ "Login": "******"
, "Url": "/foo/bar{/arg}"
, "_links":
  { "self": { "href": "/foo/bar{/arg}" }
  }
}`

	user := &HypermediaUser{}
	decode(t, input, user)

	assert.Equal(t, "bob", user.Login)
	assert.Equal(t, 1, len(user.Links))

	hl := user.Url
	url, err := hl.Expand(M{"arg": "baz"})
	if err != nil {
		t.Errorf("Errors parsing %s: %s", hl, err)
	}

	assert.Equal(t, "/foo/bar/baz", url.String())

	hl = user.Links["self"].Href
	url, err = hl.Expand(M{"arg": "baz"})
	if err != nil {
		t.Errorf("Errors parsing %s: %s", hl, err)
	}
	assert.Equal(t, "/foo/bar/baz", url.String())
}
Exemplo n.º 3
0
func TestEditor_openAndEdit_deleteFileWhenOpeningEditorFails(t *testing.T) {
	tempFile, _ := ioutil.TempFile("", "editor-test")
	tempFile.Close()

	ioutil.WriteFile(tempFile.Name(), []byte("hello"), 0644)
	editor := Editor{
		Program: "memory",
		File:    tempFile.Name(),
		Topic:   "test",
		openEditor: func(program string, file string) error {
			assert.Equal(t, "memory", program)
			assert.Equal(t, tempFile.Name(), file)
			return fmt.Errorf("error")
		},
	}

	_, err := os.Stat(tempFile.Name())
	assert.Equal(t, nil, err)

	_, err = editor.openAndEdit()
	assert.Equal(t, "error using text editor for test message", fmt.Sprintf("%s", err))

	// file is removed if there's error
	_, err = os.Stat(tempFile.Name())
	assert.T(t, os.IsNotExist(err))
}
Exemplo n.º 4
0
func TestConfigService_TomlSave(t *testing.T) {
	file, _ := ioutil.TempFile("", "test-gh-config-")
	defer os.RemoveAll(file.Name())

	host := &Host{
		Host:        "github.com",
		User:        "******",
		AccessToken: "123",
		Protocol:    "https",
	}
	c := &Config{Hosts: []*Host{host}}

	cs := &configService{
		Encoder: &tomlConfigEncoder{},
		Decoder: &tomlConfigDecoder{},
	}
	err := cs.Save(file.Name(), c)
	assert.Equal(t, nil, err)

	b, _ := ioutil.ReadFile(file.Name())
	content := `[[hosts]]
  host = "github.com"
  user = "******"
  access_token = "123"
  protocol = "https"`
	assert.Equal(t, content, strings.TrimSpace(string(b)))
}
Exemplo n.º 5
0
func TestSuccessfulGetWithoutOutput(t *testing.T) {
	setup := Setup(t)
	defer setup.Teardown()

	setup.Mux.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
		assert.Equal(t, "GET", r.Method)
		head := w.Header()
		head.Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write([]byte(`{"id": 1, "login": "******"}`))
	})

	client := setup.Client
	user := &TestUser{}

	req, err := client.NewRequest("user")
	assert.Equal(t, nil, err)

	res := req.Get()
	assert.Equal(t, false, res.IsError())
	assert.Equal(t, false, res.IsApiError())

	assert.Tf(t, !res.IsError(), "Response shouldn't have error")
	assert.Equal(t, 200, res.StatusCode)
	assert.Equal(t, false, res.BodyClosed)
	assert.Equal(t, 0, user.Id)
	assert.Equal(t, "", user.Login)

	dec := json.NewDecoder(res.Body)
	dec.Decode(user)
	assert.Equal(t, 1, user.Id)
	assert.Equal(t, "sawyer", user.Login)
}
Exemplo n.º 6
0
func TestEditor_EditTitleAndBody(t *testing.T) {
	tempFile, _ := ioutil.TempFile("", "PULLREQ")
	tempFile.Close()

	editor := Editor{
		Program: "memory",
		File:    tempFile.Name(),
		CS:      "#",
		openEditor: func(program string, file string) error {
			assert.Equal(t, "memory", program)
			assert.Equal(t, tempFile.Name(), file)

			message := `A title
A title continues

A body
A body continues
# comment
`
			return ioutil.WriteFile(file, []byte(message), 0644)
		},
	}

	title, body, err := editor.EditTitleAndBody()
	assert.Equal(t, nil, err)
	assert.Equal(t, "A title A title continues", title)
	assert.Equal(t, "A body\nA body continues", body)
}
Exemplo n.º 7
0
func TestSuccessfulGet(t *testing.T) {
	setup := Setup(t)
	defer setup.Teardown()

	setup.Mux.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
		assert.Equal(t, "GET", r.Method)
		head := w.Header()
		head.Set("Content-Type", "application/json")
		link := `<https://api.github.com/user/repos?page=3&per_page=100>; rel="next", <https://api.github.com/user/repos?page=50&per_page=100>; rel="last"`
		head.Set("Link", link)
		w.WriteHeader(http.StatusOK)
		w.Write([]byte(`{"id": 1, "login": "******"}`))
	})

	client := setup.Client
	user := &TestUser{}

	req, err := client.NewRequest("user")
	assert.Equal(t, nil, err)

	res := req.Get()
	assert.Equal(t, false, res.IsError())
	assert.Equal(t, false, res.IsApiError())

	assert.Equal(t, nil, res.Decode(user))
	assert.Equal(t, 200, res.StatusCode)
	assert.Equal(t, 1, user.Id)
	assert.Equal(t, "sawyer", user.Login)

	mheader := res.MediaHeader
	assert.Equal(t, "https://api.github.com/user/repos?page=3&per_page=100", string(mheader.Relations["next"]))
	assert.Equal(t, "https://api.github.com/user/repos?page=50&per_page=100", string(mheader.Relations["last"]))
}
Exemplo n.º 8
0
func TestResolveRequestQuery(t *testing.T) {
	setup := Setup(t)
	defer setup.Teardown()

	setup.Mux.HandleFunc("/q", func(w http.ResponseWriter, r *http.Request) {
		q := r.URL.Query()
		assert.Equal(t, "1", q.Get("a"))
		assert.Equal(t, "4", q.Get("b"))
		assert.Equal(t, "3", q.Get("c"))
		assert.Equal(t, "2", q.Get("d"))
		assert.Equal(t, "1", q.Get("e"))
		w.WriteHeader(123)
		w.Write([]byte("ok"))
	})

	assert.Equal(t, "1", setup.Client.Query.Get("a"))
	assert.Equal(t, "1", setup.Client.Query.Get("b"))

	setup.Client.Query.Set("b", "2")
	setup.Client.Query.Set("c", "3")

	req, err := setup.Client.NewRequest("/q?d=4")
	assert.Equal(t, nil, err)

	req.Query.Set("b", "4")
	req.Query.Set("c", "3")
	req.Query.Set("d", "2")
	req.Query.Set("e", "1")

	res := req.Get()
	assert.Equal(t, nil, err)
	assert.Equal(t, 123, res.StatusCode)
}
Exemplo n.º 9
0
func TestGitTreesService_One_Recursive(t *testing.T) {
	setup()
	defer tearDown()

	mux.HandleFunc("/repos/pengwynn/flint/git/trees/master", func(w http.ResponseWriter, r *http.Request) {
		testMethod(t, r, "GET")
		respondWithJSON(w, loadFixture("tree_recursive.json"))
	})

	url, err := GitTreesURL.Expand(M{
		"owner":     "pengwynn",
		"repo":      "flint",
		"sha":       "master",
		"recursive": "1",
	})
	assert.Equal(t, nil, err)
	tree, result := client.GitTrees(url).One()

	assert.T(t, !result.HasError())
	assert.Equal(t, "9c1337e761bbd517f3cc1b5acb9373b17f4810e8", tree.Sha)
	assert.Equal(t, "https://api.github.com/repos/pengwynn/flint/git/trees/9c1337e761bbd517f3cc1b5acb9373b17f4810e8", tree.URL)

	entries := tree.Tree
	assert.Equal(t, 15, len(entries))
}
Exemplo n.º 10
0
func TestUploadsService_UploadAsset(t *testing.T) {
	setup()
	defer tearDown()

	file, err := ioutil.TempFile("", "octokit-test-upload-")
	assert.Equal(t, nil, err)
	file.WriteString("this is a test")

	fi, err := file.Stat()
	assert.Equal(t, nil, err)
	file.Close()

	mux.HandleFunc("/repos/octokit/Hello-World/releases/123/assets", func(w http.ResponseWriter, r *http.Request) {
		testMethod(t, r, "POST")
		testHeader(t, r, "Content-Type", "text/plain")
		assert.Equal(t, fi.Size(), r.ContentLength)
		respondWithStatus(w, 201)
	})

	link := Hyperlink("/repos/octokit/Hello-World/releases/123/assets{?name}")
	url, err := link.Expand(M{"name": fi.Name()})
	assert.Equal(t, nil, err)

	open, _ := os.Open(file.Name())
	result := client.Uploads(url).UploadAsset(open, "text/plain", fi.Size())
	fmt.Println(result)
	assert.T(t, !result.HasError())

	assert.Equal(t, 201, result.Response.StatusCode)
}
Exemplo n.º 11
0
func TestAuthorizationsService_Create(t *testing.T) {
	setup()
	defer tearDown()

	params := AuthorizationParams{Scopes: []string{"public_repo"}}

	mux.HandleFunc("/authorizations", func(w http.ResponseWriter, r *http.Request) {
		var authParams AuthorizationParams
		json.NewDecoder(r.Body).Decode(&authParams)
		assert.T(t, reflect.DeepEqual(authParams, params))

		testMethod(t, r, "POST")
		respondWithJSON(w, loadFixture("create_authorization.json"))
	})

	url, err := AuthorizationsURL.Expand(nil)
	assert.Equal(t, nil, err)

	auth, _ := client.Authorizations(url).Create(params)

	assert.Equal(t, 3844190, auth.ID)
	assert.Equal(t, "https://api.github.com/authorizations/3844190", auth.URL)
	assert.Equal(t, "123", auth.Token)
	assert.Equal(t, "", auth.Note)
	assert.Equal(t, "", auth.NoteURL)
	assert.Equal(t, "2013-09-28 18:44:39 +0000 UTC", auth.CreatedAt.String())
	assert.Equal(t, "2013-09-28 18:44:39 +0000 UTC", auth.UpdatedAt.String())

	app := App{ClientID: "00000000000000000000", URL: "http://developer.github.com/v3/oauth/#oauth-authorizations-api", Name: "GitHub API"}
	assert.Equal(t, app, auth.App)

	assert.Equal(t, 1, len(auth.Scopes))
	scopes := []string{"public_repo"}
	assert.T(t, reflect.DeepEqual(auth.Scopes, scopes))
}
Exemplo n.º 12
0
func TestAuthorizationsService_All(t *testing.T) {
	setup()
	defer tearDown()

	mux.HandleFunc("/authorizations", func(w http.ResponseWriter, r *http.Request) {
		testMethod(t, r, "GET")
		respondWithJSON(w, loadFixture("authorizations.json"))
	})

	url, err := AuthorizationsURL.Expand(nil)
	assert.Equal(t, nil, err)

	auths, result := client.Authorizations(url).All()
	assert.T(t, !result.HasError())

	firstAuth := auths[0]
	assert.Equal(t, 1, firstAuth.ID)
	assert.Equal(t, "https://api.github.com/authorizations/1", firstAuth.URL)
	assert.Equal(t, "456", firstAuth.Token)
	assert.Equal(t, "", firstAuth.Note)
	assert.Equal(t, "", firstAuth.NoteURL)
	assert.Equal(t, "2012-11-16 01:05:51 +0000 UTC", firstAuth.CreatedAt.String())
	assert.Equal(t, "2013-08-21 03:29:51 +0000 UTC", firstAuth.UpdatedAt.String())

	app := App{ClientID: "123", URL: "http://localhost:8080", Name: "Test"}
	assert.Equal(t, app, firstAuth.App)

	assert.Equal(t, 2, len(firstAuth.Scopes))
	scopes := []string{"repo", "user"}
	assert.T(t, reflect.DeepEqual(firstAuth.Scopes, scopes))
}
Exemplo n.º 13
0
func TestRepositoresService_One(t *testing.T) {
	setup()
	defer tearDown()

	mux.HandleFunc("/repos/jingweno/octokat", func(w http.ResponseWriter, r *http.Request) {
		testMethod(t, r, "GET")
		respondWithJSON(w, loadFixture("repository.json"))
	})

	url, err := RepositoryURL.Expand(M{"owner": "jingweno", "repo": "octokat"})
	assert.Equal(t, nil, err)

	repo, result := client.Repositories(url).One()

	assert.T(t, !result.HasError())
	assert.Equal(t, 10575811, repo.ID)
	assert.Equal(t, "octokat", repo.Name)
	assert.Equal(t, "jingweno/octokat", repo.FullName)
	assert.T(t, !repo.Private)
	assert.T(t, !repo.Fork)
	assert.Equal(t, "https://api.github.com/repos/jingweno/octokat", repo.URL)
	assert.Equal(t, "https://github.com/jingweno/octokat", repo.HTMLURL)
	assert.Equal(t, "https://github.com/jingweno/octokat.git", repo.CloneURL)
	assert.Equal(t, "git://github.com/jingweno/octokat.git", repo.GitURL)
	assert.Equal(t, "[email protected]:jingweno/octokat.git", repo.SSHURL)
	assert.Equal(t, "master", repo.MasterBranch)
	assert.T(t, !repo.Permissions.Admin)
	assert.T(t, !repo.Permissions.Push)
	assert.T(t, repo.Permissions.Pull)
}
Exemplo n.º 14
0
func TestUsersService_All(t *testing.T) {
	setup()
	defer tearDown()

	mux.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
		testMethod(t, r, "GET")

		rr := regexp.MustCompile(`users\?since=\d+`)
		assert.Tf(t, rr.MatchString(r.URL.String()), "Regexp should match users?since=\\d+")

		header := w.Header()
		link := fmt.Sprintf(`<%s>; rel="next", <%s>; rel="first"`, testURLOf("users?since=135"), testURLOf("users{?since}"))
		header.Set("Link", link)
		respondWithJSON(w, loadFixture("users.json"))
	})

	url, err := UserURL.Expand(M{"since": 1})
	assert.Equal(t, nil, err)

	q := url.Query()
	q.Set("since", "1")
	url.RawQuery = q.Encode()
	allUsers, result := client.Users(url).All()

	assert.T(t, !result.HasError())
	assert.Equal(t, 1, len(allUsers))
	assert.Equal(t, testURLStringOf("users?since=135"), string(*result.NextPage))

	nextPageURL, err := result.NextPage.Expand(nil)
	assert.Equal(t, nil, err)

	allUsers, result = client.Users(nextPageURL).All()
	assert.T(t, !result.HasError())
	assert.Equal(t, 1, len(allUsers))
}
Exemplo n.º 15
0
func TestArgs_GlobalFlags_Repeated(t *testing.T) {
	args := NewArgs([]string{"-C", "mydir", "-c", "a=b", "--bare", "-c", "c=d", "-c", "e=f", "status"})
	assert.Equal(t, "status", args.Command)
	assert.Equal(t, []string{"-C", "mydir", "-c", "a=b", "--bare", "-c", "c=d", "-c", "e=f"}, args.GlobalFlags)
	assert.Equal(t, 0, len(args.Params))
	assert.Equal(t, false, args.Noop)
}
Exemplo n.º 16
0
func TestSuccessfulGet_BasicAuth(t *testing.T) {
	setup()
	defer tearDown()

	mux.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
		testMethod(t, r, "GET")
		testHeader(t, r, "Accept", defaultMediaType)
		testHeader(t, r, "User-Agent", userAgent)
		testHeader(t, r, "Authorization", "Basic amluZ3dlbm86cGFzc3dvcmQ=")
		testHeader(t, r, "X-GitHub-OTP", "OTP")
		respondWithJSON(w, `{"login": "******"}`)
	})

	client = NewClientWith(
		server.URL,
		userAgent,
		BasicAuth{
			Login:           "******",
			Password:        "******",
			OneTimePassword: "******",
		},
		nil)
	req, err := client.NewRequest("foo")
	assert.Equal(t, nil, err)

	var output map[string]interface{}
	_, err = req.Get(&output)
	assert.Equal(t, nil, err)
	assert.Equal(t, "octokit", output["login"])
}
Exemplo n.º 17
0
func TestParseRange(t *testing.T) {
	s := "1.0..2.0"
	assert.Equal(t, "1.0...2.0", parseCompareRange(s))

	s = "1.0...2.0"
	assert.Equal(t, "1.0...2.0", parseCompareRange(s))
}
Exemplo n.º 18
0
func TestSearchBrowserLauncher(t *testing.T) {
	browser := searchBrowserLauncher("darwin")
	assert.Equal(t, "open", browser)

	browser = searchBrowserLauncher("windows")
	assert.Equal(t, "cmd /c start", browser)
}
Exemplo n.º 19
0
func TestConfigService_YamlSave(t *testing.T) {
	file, _ := ioutil.TempFile("", "test-gh-config-")
	defer os.RemoveAll(file.Name())

	host := Host{
		Host:        "github.com",
		User:        "******",
		AccessToken: "123",
		Protocol:    "https",
	}
	c := Config{Hosts: []Host{host}}

	cs := &configService{
		Encoder: &yamlConfigEncoder{},
		Decoder: &yamlConfigDecoder{},
	}
	err := cs.Save(file.Name(), &c)
	assert.Equal(t, nil, err)

	b, _ := ioutil.ReadFile(file.Name())
	content := `github.com:
- user: jingweno
  oauth_token: "123"
  protocol: https`
	assert.Equal(t, content, strings.TrimSpace(string(b)))
}
Exemplo n.º 20
0
func TestAssetUploader_detectContentType(t *testing.T) {
	u := &assetUploader{}
	ct, err := u.detectContentType(fixtures.Path("release_dir", "file1"))

	assert.Equal(t, nil, err)
	assert.Equal(t, "text/plain", ct)
}
Exemplo n.º 21
0
func TestResponseError_Error_401(t *testing.T) {
	setup()
	defer tearDown()

	mux.HandleFunc("/error", func(w http.ResponseWriter, r *http.Request) {
		head := w.Header()
		head.Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusUnauthorized)
		respondWith(w, `{"message":"Unauthorized"}`)
	})

	req, _ := client.NewRequest("error")
	_, err := req.Get(nil)
	assert.Tf(t, strings.Contains(err.Error(), "401 - Unauthorized"), "%s", err.Error())

	e := err.(*ResponseError)
	assert.Equal(t, ErrorUnauthorized, e.Type)

	mux.HandleFunc("/error_2fa", func(w http.ResponseWriter, r *http.Request) {
		head := w.Header()
		head.Set("Content-Type", "application/json")
		head.Set("X-GitHub-OTP", "required; app")
		w.WriteHeader(http.StatusUnauthorized)
		respondWith(w, `{"message":"Unauthorized"}`)
	})

	req, _ = client.NewRequest("error_2fa")
	_, err = req.Get(nil)
	assert.Tf(t, strings.Contains(err.Error(), "401 - Unauthorized"), "%s", err.Error())

	e = err.(*ResponseError)
	assert.Equal(t, ErrorOneTimePasswordRequired, e.Type)
}
Exemplo n.º 22
0
func TestArgs_GlobalFlags_NoopTwice(t *testing.T) {
	args := NewArgs([]string{"--noop", "--bare", "--noop", "status"})
	assert.Equal(t, "status", args.Command)
	assert.Equal(t, []string{"--bare"}, args.GlobalFlags)
	assert.Equal(t, 0, len(args.Params))
	assert.Equal(t, true, args.Noop)
}
Exemplo n.º 23
0
func TestArgs_GlobalFlags_Noop(t *testing.T) {
	args := NewArgs([]string{"-c", "key=value", "--noop", "--literal-pathspecs", "status", "-s", "-b"})
	assert.Equal(t, "status", args.Command)
	assert.Equal(t, []string{"-c", "key=value", "--literal-pathspecs"}, args.GlobalFlags)
	assert.Equal(t, []string{"-s", "-b"}, args.Params)
	assert.Equal(t, true, args.Noop)
}
Exemplo n.º 24
0
func TestArgs_GlobalFlags(t *testing.T) {
	args := NewArgs([]string{"-c", "key=value", "status", "-s", "-b"})
	assert.Equal(t, "status", args.Command)
	assert.Equal(t, []string{"-c", "key=value"}, args.GlobalFlags)
	assert.Equal(t, []string{"-s", "-b"}, args.Params)
	assert.Equal(t, false, args.Noop)
}
Exemplo n.º 25
0
func TestGitShow(t *testing.T) {
	repo := fixtures.SetupTestRepo()
	defer repo.TearDown()

	output, err := Show("9b5a719a3d76ac9dc2fa635d9b1f34fd73994c06")
	assert.Equal(t, nil, err)
	assert.Equal(t, "First comment\n\nMore comment", output)
}
Exemplo n.º 26
0
func TestArgs_Words(t *testing.T) {
	args := NewArgs([]string{"merge", "--no-ff", "master", "-m", "message"})
	a := args.Words()

	assert.Equal(t, 2, len(a))
	assert.Equal(t, "master", a[0])
	assert.Equal(t, "message", a[1])
}
Exemplo n.º 27
0
func TestGitRef(t *testing.T) {
	repo := fixtures.SetupTestRepo()
	defer repo.TearDown()

	ref := "08f4b7b6513dffc6245857e497cfd6101dc47818"
	gitRef, err := Ref(ref)
	assert.Equal(t, nil, err)
	assert.Equal(t, ref, gitRef)
}
Exemplo n.º 28
0
func TestGitEditor(t *testing.T) {
	repo := fixtures.SetupTestRepo()
	defer repo.TearDown()

	SetGlobalConfig("core.editor", "foo")
	gitEditor, err := Editor()
	assert.Equal(t, nil, err)
	assert.Equal(t, "foo", gitEditor)
}
Exemplo n.º 29
0
func TestParseRepoNameOwner(t *testing.T) {
	owner, repo := parseRepoNameOwner("jingweno")
	assert.Equal(t, "jingweno", owner)
	assert.Equal(t, "", repo)

	owner, repo = parseRepoNameOwner("jingweno/gh")
	assert.Equal(t, "jingweno", owner)
	assert.Equal(t, "gh", repo)
}
Exemplo n.º 30
0
func TestArgs_Remove(t *testing.T) {
	args := NewArgs([]string{"1", "2", "3", "4"})

	item := args.RemoveParam(1)
	assert.Equal(t, "3", item)
	assert.Equal(t, 2, args.ParamsSize())
	assert.Equal(t, "2", args.FirstParam())
	assert.Equal(t, "4", args.GetParam(1))
}