Skip to content

Commit b30f959

Browse files
committed
Add simple example
1 parent 5f6ce0c commit b30f959

2 files changed

Lines changed: 85 additions & 0 deletions

File tree

example/embed-interface/main.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Copyright 2021 The go-github AUTHORS. All rights reserved.
2+
//
3+
// Use of this source code is governed by a BSD-style
4+
// license that can be found in the LICENSE file.
5+
6+
// This embed-interface example is a copy of the "simple" example
7+
// and its purpose is to demonstrate how embedding an interface
8+
// in a struct makes it easy to mock one or more methods.
9+
package main
10+
11+
import (
12+
"context"
13+
"fmt"
14+
15+
"github.com/google/go-github/v34/github"
16+
)
17+
18+
// Fetch all the public organizations' membership of a user.
19+
//
20+
func fetchOrganizations(orgService github.OrganizationsServiceInterface, username string) ([]*github.Organization, error) {
21+
orgs, _, err := orgService.List(context.Background(), username, nil)
22+
return orgs, err
23+
}
24+
25+
func main() {
26+
var username string
27+
fmt.Print("Enter GitHub username: ")
28+
fmt.Scanf("%s", &username)
29+
30+
client := github.NewClient(nil)
31+
organizations, err := fetchOrganizations(client.Organizations, username)
32+
if err != nil {
33+
fmt.Printf("Error: %v\n", err)
34+
return
35+
}
36+
37+
for i, organization := range organizations {
38+
fmt.Printf("%v. %v\n", i+1, organization.GetLogin())
39+
}
40+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Copyright 2021 The go-github AUTHORS. All rights reserved.
2+
//
3+
// Use of this source code is governed by a BSD-style
4+
// license that can be found in the LICENSE file.
5+
6+
package main
7+
8+
import (
9+
"context"
10+
"errors"
11+
"reflect"
12+
"testing"
13+
14+
"github.com/google/go-github/v34/github"
15+
)
16+
17+
type fakeOrgSvc struct {
18+
github.OrganizationsServiceInterface
19+
20+
orgs []*github.Organization
21+
}
22+
23+
func (f *fakeOrgSvc) List(ctx context.Context, org string, opts *github.ListOptions) ([]*github.Organization, *github.Response, error) {
24+
if org != "octocat" {
25+
return nil, nil, errors.New("unexpected org")
26+
}
27+
28+
return f.orgs, nil, nil
29+
}
30+
31+
func TestFetchOrganizations(t *testing.T) {
32+
want := []*github.Organization{
33+
{Name: github.String("octocat")},
34+
}
35+
36+
orgService := &fakeOrgSvc{orgs: want}
37+
got, err := fetchOrganizations(orgService, "octocat")
38+
if err != nil {
39+
t.Fatal(err)
40+
}
41+
42+
if !reflect.DeepEqual(got, want) {
43+
t.Errorf("got = %#v, want = %#v", got, want)
44+
}
45+
}

0 commit comments

Comments
 (0)