test(random): add unit tests for random behavior
SonarQube Scan / SonarQube Trigger (push) Successful in 1m37s
SonarQube Scan / SonarQube Trigger (push) Successful in 1m37s
- Added unit tests to cover random string generation and error handling. - Introduced Random interface and random struct for better abstraction. - Updated server, session, and interaction packages to require Random interface for dependency injection.
This commit is contained in:
@@ -1,12 +1,35 @@
|
||||
package random
|
||||
|
||||
import "crypto/rand"
|
||||
import (
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
func GenerateRandomString(length int) (string, error) {
|
||||
var (
|
||||
ErrInvalidLength = fmt.Errorf("invalid length")
|
||||
)
|
||||
|
||||
type Random interface {
|
||||
String(length int) (string, error)
|
||||
}
|
||||
|
||||
type random struct {
|
||||
reader io.Reader
|
||||
}
|
||||
|
||||
func New() Random {
|
||||
return &random{reader: rand.Reader}
|
||||
}
|
||||
|
||||
func (ran *random) String(length int) (string, error) {
|
||||
if length < 0 {
|
||||
return "", ErrInvalidLength
|
||||
}
|
||||
const charset = "abcdefghijklmnopqrstuvwxyz0123456789"
|
||||
b := make([]byte, length)
|
||||
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
if _, err := ran.reader.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user