Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add timeout on github client #1290

Merged
merged 2 commits into from
Jul 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package cmd

import (
"fmt"
"net/http"
"os"
"time"

"github.com/astronomer/astro-cli/cmd/registry"

Expand Down Expand Up @@ -70,8 +72,8 @@ Welcome to the Astro CLI, the modern command line interface for data orchestrati
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
// Check for latest version
if config.CFG.UpgradeMessage.GetBool() {
// create github client
githubClient := github.NewClient(nil)
// create github client with 3 second timeout, setting an aggressive timeout since its not mandatory to get a response in each command execution
githubClient := github.NewClient(&http.Client{Timeout: 3 * time.Second})
// compare current version to latest
err = version.CompareVersions(githubClient, "astronomer", "astro-cli")
if err != nil {
Expand Down
36 changes: 36 additions & 0 deletions version/version_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package version

import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"

"github.com/google/go-github/v48/github"
"github.com/stretchr/testify/assert"
)

func TestGithubAPITimeout(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(5 * time.Second) // sleeping and doing nothing
}))
defer ts.Close()
githubURL, err := url.Parse(fmt.Sprintf("%s/", ts.URL))
assert.NoError(t, err)

githubClient := github.NewClient(&http.Client{Timeout: 1 * time.Second}) // client side timeout should be less than server side sleep defined above
githubClient.BaseURL = githubURL

start := time.Now()
release, err := getLatestRelease(githubClient, "test", "test")
elapsed := time.Since(start)
// assert time to get a response from the function is only slightly greater than client timeout
assert.GreaterOrEqual(t, elapsed, 1*time.Second)
assert.Less(t, elapsed, 2*time.Second)
// assert error returned is related to client timeout
assert.Nil(t, release)
assert.Error(t, err)
assert.Contains(t, err.Error(), "context deadline exceeded")
}