PrepareSession prepares a session for unit tests. It creates a temporary folder to save the session credentials in and does a login to the specified authorization server using test credentials. It is the responsibility of the caller to cleanup the temporary directory. This function will use asserts
(authPort uint16, authSrv *oauth2.AuthorizationServer, grpcURL string)
| 23 | // |
| 24 | // This function will use asserts and fail/panic if errors occurs. |
| 25 | func PrepareSession(authPort uint16, authSrv *oauth2.AuthorizationServer, grpcURL string) (dir string, err error) { |
| 26 | var ( |
| 27 | token *oauth2.Token |
| 28 | session *cli.Session |
| 29 | ) |
| 30 | |
| 31 | // Create a temporary folder |
| 32 | dir, err = os.MkdirTemp(os.TempDir(), ".clouditor") |
| 33 | if err != nil { |
| 34 | return "", err |
| 35 | } |
| 36 | |
| 37 | viper.Set("auth-server", fmt.Sprintf("http://localhost:%d", authPort)) |
| 38 | viper.Set(cli.SessionFolderFlag, dir) |
| 39 | |
| 40 | // Simulate a login by directly granting a token |
| 41 | token, err = authSrv.GenerateToken(testdata.MockAuthClientID, 0, 0) |
| 42 | if err != nil { |
| 43 | return "", err |
| 44 | } |
| 45 | |
| 46 | // TODO(oxisto): This is slightly duplicated code from the Login command. Extract it into the session struct |
| 47 | session, err = cli.NewSession(grpcURL, &oauth2.Config{ |
| 48 | ClientID: testdata.MockAuthClientID, |
| 49 | Endpoint: oauth2.Endpoint{ |
| 50 | AuthURL: testutil.AuthURL(authPort), |
| 51 | TokenURL: testutil.TokenURL(authPort), |
| 52 | }, |
| 53 | }, token) |
| 54 | if err != nil { |
| 55 | return "", err |
| 56 | } |
| 57 | |
| 58 | session.SetAuthorizer(api.NewOAuthAuthorizerFromConfig( |
| 59 | session.Config, |
| 60 | token, |
| 61 | )) |
| 62 | |
| 63 | err = session.Save() |
| 64 | if err != nil { |
| 65 | return "", err |
| 66 | } |
| 67 | |
| 68 | return dir, nil |
| 69 | } |
| 70 | |
| 71 | // RunCLITest can be used in a TestMain function for CLI tests. It takes care of launching |
| 72 | // an authorization server as well as a gRPC server with the selected services supplied as options. |
no test coverage detected