github.com/nuvolaris/nuv@v0.0.0-20240511174247-a74e3a52bfd8/auth/password_reader_test.go (about) 1 // Licensed to the Apache Software Foundation (ASF) under one 2 // or more contributor license agreements. See the NOTICE file 3 // distributed with this work for additional information 4 // regarding copyright ownership. The ASF licenses this file 5 // to you under the Apache License, Version 2.0 (the 6 // "License"); you may not use this file except in compliance 7 // with the License. You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, 12 // software distributed under the License is distributed on an 13 // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 // KIND, either express or implied. See the License for the 15 // specific language governing permissions and limitations 16 // under the License. 17 18 package auth 19 20 import ( 21 "errors" 22 "testing" 23 ) 24 25 type stubPasswordReader struct { 26 Password string 27 ReturnError bool 28 } 29 30 func (pr stubPasswordReader) ReadPassword() (string, error) { 31 if pr.ReturnError { 32 return "", errors.New("stubbed error") 33 } 34 return pr.Password, nil 35 } 36 37 func TestAskPassword(t *testing.T) { 38 t.Run("error: returns error when password reader returns error", func(t *testing.T) { 39 oldPwdReader := pwdReader 40 pwdReader = stubPasswordReader{ReturnError: true} 41 42 result, err := AskPassword() 43 44 pwdReader = oldPwdReader 45 if err == nil { 46 t.Error("Expected error, got nil") 47 } 48 49 if err.Error() != "stubbed error" { 50 t.Errorf("Expected error to be 'stubbed error', got %s", err.Error()) 51 } 52 53 if result != "" { 54 t.Errorf("Expected empty string, got %s", result) 55 } 56 }) 57 58 t.Run("success: returns password correctly", func(t *testing.T) { 59 oldPwdReader := pwdReader 60 pwdReader = stubPasswordReader{Password: "a password", ReturnError: false} 61 62 result, err := AskPassword() 63 64 pwdReader = oldPwdReader 65 66 if err != nil { 67 t.Errorf("Expected no error, got %s", err.Error()) 68 } 69 if result != "a password" { 70 t.Errorf("Expected 'a password', got %s", result) 71 } 72 }) 73 }