Skip to content

Commit

Permalink
test: Add tests for autoupdate and GitHub API
Browse files Browse the repository at this point in the history
  • Loading branch information
raulb committed May 26, 2022
1 parent be9bc93 commit 8224679
Show file tree
Hide file tree
Showing 7 changed files with 245 additions and 49 deletions.
40 changes: 0 additions & 40 deletions cmd/meroxa/builder/autoupdate.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,6 @@ limitations under the License.
package builder

import (
"context"
"encoding/json"
"io"
"net/http"
"time"

"github.com/meroxa/cli/cmd/meroxa/global"
Expand Down Expand Up @@ -53,39 +49,3 @@ func needToCheckNewerCLIVersion() bool {
func getCurrentCLIVersion() string {
return global.CurrentTag
}

// getLatestCLIVersion returns latest CLI available tag.
func getLatestCLIVersion(ctx context.Context) (string, error) {
client := &http.Client{}

// Fetches tags in GitHub
req, err := http.NewRequestWithContext(ctx, "GET", "https://api.github.com/repos/meroxa/cli/tags", http.NoBody)
if err != nil {
return "", err
}

req.Header.Add("Accept", "application/vnd.github.v3+json")
resp, err := client.Do(req)
if err != nil {
return "", err
}

if resp.Body != nil {
defer resp.Body.Close()
}

b, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}

var result []struct {
Name string `json:"name"`
}

if err := json.Unmarshal(b, &result); err != nil {
return "", nil
}

return result[0].Name, nil
}
76 changes: 76 additions & 0 deletions cmd/meroxa/builder/autoupdate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package builder

import (
"testing"
"time"

"github.com/meroxa/cli/cmd/meroxa/global"
"github.com/spf13/viper"
)

func TestNeedToCheckNewerCLIVersion(t *testing.T) {
oldConfig := global.Config

tests := []struct {
desc string
config func() *viper.Viper
expected bool
}{
{
desc: "Global config is nil",
config: func() *viper.Viper {
return nil
},
expected: false,
},
{
desc: "Notifications are disabled by the user",
config: func() *viper.Viper {
cfg := viper.New()
cfg.Set(global.DisableNotificationsUpdate, "true")
return cfg
},
expected: false,
},
{
desc: "Version has never been checked",
config: viper.New,
expected: true,
},
{
desc: "Version was recently checked",
config: func() *viper.Viper {
cfg := viper.New()
// Checked last time less than a week before
lastTimeChecked := time.Now().UTC().AddDate(0, 0, -7).Add(time.Minute * 1)
cfg.Set(global.LatestCLIVersionUpdatedAtEnv, lastTimeChecked)
return cfg
},
expected: false,
},
{
desc: "Version was checked more than a week before",
config: func() *viper.Viper {
cfg := viper.New()
// Checked last time more than a week before
lastTimeChecked := time.Now().UTC().AddDate(0, 0, -7).Add(-time.Minute * 1)
cfg.Set(global.LatestCLIVersionUpdatedAtEnv, lastTimeChecked)
return cfg
},
expected: true,
},
}

for _, tc := range tests {
t.Run(tc.desc, func(t *testing.T) {
global.Config = tc.config()
got := needToCheckNewerCLIVersion()

if tc.expected != got {
t.Fatalf("expected needToCheckNewerCLIVersion to be %v, got %v", tc.expected, got)
}
})
}

global.Config = oldConfig
}
8 changes: 6 additions & 2 deletions cmd/meroxa/builder/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,13 @@ import (
"context"
"errors"
"fmt"
"net/http"
"os"
"strings"
"time"

"github.com/meroxa/cli/cmd/meroxa/github"

"github.com/cased/cased-go"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
Expand Down Expand Up @@ -498,14 +501,15 @@ func buildCommandAutoUpdate(cmd *cobra.Command) {
return err
}

latestCLIVersion, err := getLatestCLIVersion(cmd.Context())
github.Client = &http.Client{}
latestCLIVersion, err := github.GetLatestCLITag(cmd.Context())
if err != nil {
return err
}

if getCurrentCLIVersion() != latestCLIVersion {
fmt.Printf("\n\n 🎁 meroxa %s is available! To update it run: `brew upgrade meroxa`", latestCLIVersion)
fmt.Printf("\n 🧐 Check out latest changes in https://github.com/meroxa/cli/releases/tag/%s", latestCLIVersion)
fmt.Printf("\n 🧐 Check out latest changes in https://github.com/meroxa/cli/releases/tag/v%s", latestCLIVersion)
fmt.Printf("\n 💡 To disable these warnings, run `meroxa config set %s=true`\n", global.DisableNotificationsUpdate)
}
}
Expand Down
88 changes: 88 additions & 0 deletions cmd/meroxa/github/github.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
Copyright © 2022 Meroxa Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package github

import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"regexp"
)

type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}

var (
Client HTTPClient
)

// getContentHomebrewFormula returns from GitHub the content of the formula file for Meroxa CLI.
func getContentHomebrewFormula(ctx context.Context) (string, error) {
url := "https://api.github.com/repos/meroxa/homebrew-taps/contents/Formula/meroxa.rb"
req, err := http.NewRequestWithContext(ctx, "GET", url, http.NoBody)
if err != nil {
return "", err
}

req.Header.Add("Accept", "application/vnd.github.v3+json")
resp, err := Client.Do(req)
if err != nil {
return "", err
}

if resp.Body != nil {
defer resp.Body.Close()
}

b, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}

type FormulaDefinition struct {
Content []byte `json:"content,omitempty"`
Encoding string `json:"encoding,omitempty"`
}

var f FormulaDefinition
if err := json.Unmarshal(b, &f); err != nil {
return "", err
}

return bytes.NewBuffer(f.Content).String(), nil
}

// parseVersionFromFormulaFile receives the content of a formula file such as the one in
// "https://api.github.com/repos/meroxa/homebrew-taps/contents/Formula/meroxa.rb"
// and extracts its version number.
func parseVersionFromFormulaFile(content string) string {
r := regexp.MustCompile(`version "(\d+.\d+.\d+)"`)
return r.FindStringSubmatch(content)[1]
}

// GetLatestCLITag fetches the content formula file from GitHub and then parses its version.
func GetLatestCLITag(ctx context.Context) (string, error) {
brewFormulaFile, err := getContentHomebrewFormula(ctx)
if err != nil {
return brewFormulaFile, err
}

return parseVersionFromFormulaFile(brewFormulaFile), nil
}
71 changes: 71 additions & 0 deletions cmd/meroxa/github/github_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package github

import (
"bytes"
"context"
"encoding/base64"
"fmt"
"io"
"net/http"
"reflect"
"testing"
)

type MockDoType func(req *http.Request) (*http.Response, error)

type MockClient struct {
MockDo MockDoType
}

func (m *MockClient) Do(req *http.Request) (*http.Response, error) {
return m.MockDo(req)
}

func TestGetLatestCLITag(t *testing.T) {
version := "2.2.0"

f := fmt.Sprintf(`
class Meroxa < Formula
desc "The Meroxa CLI"
homepage "https://meroxa.io"
version "%s"
end
`, version)

sEnc := base64.StdEncoding.EncodeToString([]byte(f))

jsonResponse := fmt.Sprintf(`
{
"content": "%s",
"encoding": "base64"
}
`, sEnc)

r := io.NopCloser(bytes.NewReader([]byte(jsonResponse)))
Client = &MockClient{
MockDo: func(*http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: 200,
Body: r,
}, nil
},
}

ctx := context.Background()
gotContent, err := getContentHomebrewFormula(ctx)

if err != nil {
t.Error("unexpected error, got: ", err)
return
}

if !reflect.DeepEqual(gotContent, f) {
t.Errorf("expected %v, got %v", f, gotContent)
}

gotVersion := parseVersionFromFormulaFile(gotContent)

if gotVersion != version {
t.Errorf("expected version %q, got %q", version, gotVersion)
}
}
2 changes: 1 addition & 1 deletion cmd/meroxa/root/config/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func (s *Set) Docs() builder.Docs {

func (s *Set) Execute(ctx context.Context) error {
for k, v := range s.args.keys {
s.logger.Infof(ctx, "Updating your Meroxa configuration file with %s=%s...", k, v)
s.logger.Infof(ctx, "Updating your Meroxa configuration file with \"%s=%s\"...", k, v)
s.config.Set(k, v)
}
s.logger.Info(ctx, "Done!")
Expand Down
9 changes: 3 additions & 6 deletions cmd/meroxa/root/config/set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,9 @@ func TestSetConfigExecution(t *testing.T) {
logger := log.NewTestLogger()

k1 := "MY_KEY"
k2 := "ANOTHER_KEY"

setKeys := map[string]string{
k1: "value",
k2: "anotherValue",
}

cfg := config.NewInMemoryConfig()
Expand All @@ -140,15 +138,14 @@ func TestSetConfigExecution(t *testing.T) {
}

gotLeveledOutput := logger.LeveledOutput()
wantLeveledOutput := fmt.Sprintf("Updating your Meroxa configuration file with %s=%s...\n"+
"Updating your Meroxa configuration file with %s=%s...\n"+
"Done!", k1, setKeys[k1], k2, setKeys[k2])
wantLeveledOutput := fmt.Sprintf("Updating your Meroxa configuration file with \"%s=%s\"...\n"+
"Done!", k1, setKeys[k1])

if !strings.Contains(gotLeveledOutput, wantLeveledOutput) {
t.Fatalf("expected output:\n%s\ngot:\n%s", wantLeveledOutput, gotLeveledOutput)
}

keys := []string{k1, k2}
keys := []string{k1}

for _, k := range keys {
if s.config.GetString(k) != setKeys[k] {
Expand Down

0 comments on commit 8224679

Please sign in to comment.