Skip to content

Commit

Permalink
feat(cipher/caesar): add fuzzy test to caesar cipher (#559)
Browse files Browse the repository at this point in the history
  • Loading branch information
VictorAssunc authored Oct 12, 2022
1 parent 44b39e0 commit 873b9ec
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
10 changes: 5 additions & 5 deletions cipher/caesar/caesar.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ func Encrypt(input string, key int) string {
key8 := byte(key%26+26) % 26

var outputBuffer []byte
// r is a rune, which is the equivalent of uint32.
for _, r := range input {
newByte := byte(r)
if 'A' <= r && r <= 'Z' {
// b is a byte, which is the equivalent of uint8.
for _, b := range []byte(input) {
newByte := b
if 'A' <= b && b <= 'Z' {
outputBuffer = append(outputBuffer, 'A'+(newByte-'A'+key8)%26)
} else if 'a' <= r && r <= 'z' {
} else if 'a' <= b && b <= 'z' {
outputBuffer = append(outputBuffer, 'a'+(newByte-'a'+key8)%26)
} else {
outputBuffer = append(outputBuffer, newByte)
Expand Down
13 changes: 13 additions & 0 deletions cipher/caesar/caesar_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package caesar

import (
"fmt"
"math/rand"
"testing"
"time"
)

func TestEncrypt(t *testing.T) {
Expand Down Expand Up @@ -152,3 +154,14 @@ func Example() {
// Encrypt=> key: 10, input: The Quick Brown Fox Jumps over the Lazy Dog., encryptedText: Dro Aesmu Lbygx Pyh Tewzc yfob dro Vkji Nyq.
// Decrypt=> key: 10, input: Dro Aesmu Lbygx Pyh Tewzc yfob dro Vkji Nyq., decryptedText: The Quick Brown Fox Jumps over the Lazy Dog.
}

func FuzzCaesar(f *testing.F) {
rand.Seed(time.Now().Unix())
f.Add("The Quick Brown Fox Jumps over the Lazy Dog.")
f.Fuzz(func(t *testing.T, input string) {
key := rand.Intn(26)
if result := Decrypt(Encrypt(input, key), key); result != input {
t.Fatalf("With input: '%s' and key: %d\n\tExpected: '%s'\n\tGot: '%s'", input, key, input, result)
}
})
}

0 comments on commit 873b9ec

Please sign in to comment.