Skip to content

Commit

Permalink
Merge pull request #949 from aziontech/test/cmd_login
Browse files Browse the repository at this point in the history
test: command login
  • Loading branch information
maxwelbm authored Sep 17, 2024
2 parents cad0af3 + 680aff5 commit 7a0a1c0
Show file tree
Hide file tree
Showing 27 changed files with 523 additions and 328 deletions.
5 changes: 1 addition & 4 deletions pkg/cmd/deploy/requests.go
Original file line number Diff line number Diff line change
Expand Up @@ -565,13 +565,10 @@ func (cmd *DeployCmd) updateInstance(ctx context.Context, client *apiapp.Client,
func checkToken(f *cmdutil.Factory) error {
configureToken := f.Config.GetString("token")

t, err := token.New(&token.Config{
t := token.New(&token.Config{
Client: f.HttpClient,
Out: f.IOStreams.Out,
})
if err != nil {
return fmt.Errorf("%s: %w", utils.ErrorTokenManager, err)
}

if configureToken == "" {
return utils.ErrorTokenNotProvided
Expand Down
5 changes: 1 addition & 4 deletions pkg/cmd/deploy_remote/requests.go
Original file line number Diff line number Diff line change
Expand Up @@ -569,13 +569,10 @@ func (cmd *DeployCmd) updateInstance(ctx context.Context, client *apiapp.Client,
func checkToken(f *cmdutil.Factory) error {
configureToken := f.Config.GetString("token")

t, err := token.New(&token.Config{
t := token.New(&token.Config{
Client: f.HttpClient,
Out: f.IOStreams.Out,
})
if err != nil {
return fmt.Errorf("%s: %w", utils.ErrorTokenManager, err)
}

if configureToken == "" {
return utils.ErrorTokenNotProvided
Expand Down
7 changes: 2 additions & 5 deletions pkg/cmd/init/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ type initCmd struct {
changeDir func(dir string) error
askOne func(p survey.Prompt, response interface{}, opts ...survey.AskOpt) error
load func(filenames ...string) (err error)
dir func() (config.DirPath, error)
dir func() config.DirPath
mkdirTemp func(dir, pattern string) (string, error)
readAll func(r io.Reader) ([]byte, error)
get func(url string) (resp *http.Response, err error)
Expand Down Expand Up @@ -211,10 +211,7 @@ func (cmd *initCmd) Run(c *cobra.Command, _ []string) error {
return err
}

dirPath, err := cmd.dir()
if err != nil {
return err
}
dirPath := cmd.dir()

// Create a temporary directory
tempDir, err := cmd.mkdirTemp(dirPath.Dir, "tempclonesamples")
Expand Down
164 changes: 2 additions & 162 deletions pkg/cmd/init/init_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ func Test_initCmd_Run(t *testing.T) {
changeDir func(dir string) error
askOne func(p survey.Prompt, response interface{}, opts ...survey.AskOpt) error
load func(filenames ...string) (err error)
dir func() (config.DirPath, error)
dir func() config.DirPath
mkdirTemp func(dir, pattern string) (string, error)
readAll func(r io.Reader) ([]byte, error)
get func(url string) (resp *http.Response, err error)
Expand Down Expand Up @@ -712,166 +712,6 @@ func Test_initCmd_Run(t *testing.T) {
},
wantErr: true,
},
{
name: "error dir",
fields: fields{
fileReader: func(filename string) ([]byte, error) {
return nil, nil
},
auto: true,
f: &cmdutil.Factory{
Flags: cmdutil.Flags{
GlobalFlagAll: false,
Format: "",
Out: "",
NoColor: false,
},
IOStreams: iostreams.System(),
},
globalFlagAll: false,
name: "",
preset: "vite",
mode: "deliver",
getWorkDir: func() (string, error) {
return "/path/full", nil
},
get: func(url string) (resp *http.Response, err error) {
b, err := os.ReadFile("./.fixtures/project_samples.json")
if err != nil {
return nil, err
}

responseBody := io.NopCloser(bytes.NewReader(b))
resp = &http.Response{
StatusCode: 200,
Body: responseBody,
Header: make(http.Header),
}
return resp, nil
},
readAll: io.ReadAll,
unmarshal: json.Unmarshal,
askOne: func(p survey.Prompt,
response interface{},
opts ...survey.AskOpt,
) error {
return nil
},
dir: func() (config.DirPath, error) {
return config.DirPath{}, errors.New("error dir")
},
mkdirTemp: func(dir, pattern string) (string, error) {
return "", nil
},
removeAll: os.RemoveAll,
rename: func(oldpath, newpath string) error {
return nil
},
mkdir: func(path string, perm os.FileMode) error { return nil },
marshalIndent: json.MarshalIndent,
writeFile: func(filename string, data []byte, perm fs.FileMode) error {
return nil
},
changeDir: func(dir string) error { return nil },
commandRunnerOutput: func(f *cmdutil.Factory, comm string, envVars []string) (string, error) {
return "3.2.1", nil
},
commandRunInteractive: func(f *cmdutil.Factory, comm string) error {
return nil
},
load: func(filenames ...string) (err error) {
os.Setenv("preset", "vite")
os.Setenv("mode", "deliver")
return nil
},
git: github.Github{
Clone: func(url, path string) error {
return nil
},
},
},
wantErr: true,
},
{
name: "error mkdirTemp",
fields: fields{
fileReader: func(filename string) ([]byte, error) {
return nil, nil
},
auto: true,
f: &cmdutil.Factory{
Flags: cmdutil.Flags{
GlobalFlagAll: false,
Format: "",
Out: "",
NoColor: false,
},
IOStreams: iostreams.System(),
},
globalFlagAll: false,
name: "",
preset: "vite",
mode: "deliver",
getWorkDir: func() (string, error) {
return "/path/full", nil
},
get: func(url string) (resp *http.Response, err error) {
b, err := os.ReadFile("./.fixtures/project_samples.json")
if err != nil {
return nil, err
}

responseBody := io.NopCloser(bytes.NewReader(b))
resp = &http.Response{
StatusCode: 200,
Body: responseBody,
Header: make(http.Header),
}
return resp, nil
},
readAll: io.ReadAll,
unmarshal: json.Unmarshal,
askOne: func(p survey.Prompt,
response interface{},
opts ...survey.AskOpt,
) error {
return nil
},
dir: func() (config.DirPath, error) {
return config.DirPath{}, errors.New("error dir")
},
mkdirTemp: func(dir, pattern string) (string, error) {
return "", nil
},
removeAll: os.RemoveAll,
rename: func(oldpath, newpath string) error {
return nil
},
mkdir: func(path string, perm os.FileMode) error { return nil },
marshalIndent: json.MarshalIndent,
writeFile: func(filename string, data []byte, perm fs.FileMode) error {
return nil
},
changeDir: func(dir string) error { return nil },
commandRunnerOutput: func(f *cmdutil.Factory, comm string, envVars []string) (string, error) {
return "3.2.1", nil
},
commandRunInteractive: func(f *cmdutil.Factory, comm string) error {
return nil
},
load: func(filenames ...string) (err error) {
os.Setenv("preset", "vite")
os.Setenv("mode", "deliver")
return nil
},
git: github.Github{
Clone: func(url, path string) error {
return nil
},
},
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down Expand Up @@ -952,7 +792,7 @@ func Test_initCmd_deps(t *testing.T) {
changeDir func(dir string) error
askOne func(p survey.Prompt, response interface{}, opts ...survey.AskOpt) error
load func(filenames ...string) (err error)
dir func() (config.DirPath, error)
dir func() config.DirPath
mkdirTemp func(dir, pattern string) (string, error)
readAll func(r io.Reader) ([]byte, error)
get func(url string) (resp *http.Response, err error)
Expand Down
9 changes: 9 additions & 0 deletions pkg/cmd/login/.fixtures/response.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"uuid": "5b8934cf-3561-4b48-aceb-7ba52a227b6c",
"name": "One day token",
"key": "tokenazion",
"user_id": 23192,
"created": "2023-08-29T15:23:41.878136Z",
"expires_at": "2024-07-26T00:00:00Z",
"description": "example"
}
59 changes: 41 additions & 18 deletions pkg/cmd/login/browser.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,42 +6,65 @@ import (
"net/http"

msg "github.com/aziontech/azion-cli/messages/login"
"github.com/aziontech/azion-cli/pkg/cmdutil"
"github.com/aziontech/azion-cli/pkg/logger"
"github.com/skratchdot/open-golang/open"
"go.uber.org/zap"
)

const (
urlSsoNext = "https://sso.azion.com/login?next=cli"
)

func browserLogin(f *cmdutil.Factory) error {
// when it's a single test set true
var enableHandlerRouter = true

ctx, cancel := context.WithCancel(context.Background())
type Server interface {
ListenAndServe() error
Shutdown(ctx context.Context) error
}

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
paramValue := r.URL.Query().Get("c")
_, _ = io.WriteString(w, msg.BrowserMsg)
if paramValue != "" {
tokenValue = paramValue
}
cancel()
})
var (
globalCtx context.Context
globalCancel context.CancelFunc
)

func initializeContext() {
globalCtx, globalCancel = context.WithCancel(context.Background())
}

func shutdownContext() {
if globalCancel != nil {
globalCancel()
}
}

func (l *login) browserLogin(srv Server) error {
initializeContext()
defer shutdownContext()

srv := &http.Server{Addr: ":8080"}
err := openBrowser(f)
if enableHandlerRouter {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
paramValue := r.URL.Query().Get("c")
_, _ = io.WriteString(w, msg.BrowserMsg)
if paramValue != "" {
tokenValue = paramValue
}
globalCancel()
})
}

err := l.openBrowser()
if err != nil {
return err
}

go func() {
err := srv.ListenAndServe()
if err != http.ErrServerClosed {
logger.Error(msg.ErrorServerClosed.Error(), zap.Error(err))
}
}()

<-ctx.Done() // wait for the signal to gracefully shutdown the server
<-globalCtx.Done() // wait for the signal to gracefully shutdown the server

// gracefully shutdown the server:
// waiting indefinitely for connections to return to idle and then shut down.
Expand All @@ -53,9 +76,9 @@ func browserLogin(f *cmdutil.Factory) error {
return nil
}

func openBrowser(f *cmdutil.Factory) error {
logger.FInfo(f.IOStreams.Out, msg.VisitMsg)
err := open.Run(urlSsoNext)
func (l *login) openBrowser() error {
logger.FInfo(l.factory.IOStreams.Out, msg.VisitMsg)
err := l.run(urlSsoNext)
if err != nil {
return err
}
Expand Down
Loading

0 comments on commit 7a0a1c0

Please sign in to comment.