Created
December 18, 2019 17:45
-
-
Save bentranter/105b446292ea3f2f07e057baf3bf5faa to your computer and use it in GitHub Desktop.
An attempt to recreate the race condition in godo.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package race_test | |
import ( | |
"context" | |
"fmt" | |
"log" | |
"math/rand" | |
"os" | |
"sync" | |
"testing" | |
"github.com/digitalocean/godo" | |
"golang.org/x/oauth2" | |
) | |
type TokenSource struct { | |
AccessToken string | |
} | |
func (t *TokenSource) Token() (*oauth2.Token, error) { | |
return &oauth2.Token{AccessToken: os.Getenv("DIGITALOCEAN_API_TOKEN")}, nil | |
} | |
var client = godo.NewClient(oauth2.NewClient(context.TODO(), &TokenSource{})) | |
func randomAPICall() error { | |
funcs := [](func() error){ | |
func() error { | |
_, _, err := client.Droplets.List(context.TODO(), &godo.ListOptions{}) | |
return err | |
}, | |
func() error { | |
_, _, err := client.Droplets.Get(context.TODO(), 1) | |
return err | |
}, | |
func() error { | |
_, _, err := client.DropletActions.Get(context.TODO(), 1, 1) | |
return err | |
}, | |
} | |
n := rand.Intn(3) | |
fmt.Println(n) | |
return funcs[n]() | |
} | |
func TestRace(t *testing.T) { | |
var wg sync.WaitGroup | |
runs := 20 | |
// Start 20 goroutines so fire off random requests. | |
wg.Add(runs) | |
for i := 0; i < runs; i++ { | |
go func(w *sync.WaitGroup) { | |
defer w.Done() | |
if err := randomAPICall(); err != nil { | |
log.Println(err) | |
} | |
}(&wg) | |
} | |
wg.Wait() | |
log.Println("DONE") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment