Browse Source

Added TestDeserializeEncodedText

Piotr Czajkowski 3 years ago
parent
commit
67596f708b
2 changed files with 46 additions and 9 deletions
  1. 28 6
      app_test.go
  2. 18 3
      encodedText.go

+ 28 - 6
app_test.go

@@ -17,18 +17,18 @@ func TestDecodeEncode(t *testing.T) {
 
 	for _, item := range testCases {
 		encoded := EncodeText(item.text)
-		if encoded.text == item.text {
-			t.Errorf("Encoded text '%s' should be different than provided text '%s'!", encoded.text, item.text)
+		if encoded.Text == item.text {
+			t.Errorf("Encoded text '%s' should be different than provided text '%s'!", encoded.Text, item.text)
 		}
 
-		count := len(encoded.encodedWords)
+		count := len(encoded.EncodedWords)
 		if count != item.count {
-			t.Errorf("There should be %d encoded words instead of %d! %v", item.count, count, encoded.encodedWords)
+			t.Errorf("There should be %d encoded words instead of %d! %v", item.count, count, encoded.EncodedWords)
 		}
 
-		decodedText := DecodeText(encoded.text, encoded.encodedWords)
+		decodedText := DecodeText(encoded.Text, encoded.EncodedWords)
 		if decodedText != item.text {
-			t.Errorf("Decoded text '%s' should be same as provided text '%s'!", decodedText, item.text)
+			t.Errorf("Decoded text '%s' should be same as expected text '%s'!", decodedText, item.text)
 		}
 	}
 }
@@ -46,3 +46,25 @@ This long looong sentence some test with words`
 		t.Errorf("Serialization error!\nShould be:%s\nIs:%s", expected, encoded.String())
 	}
 }
+
+func TestDeserializeEncodedText(t *testing.T) {
+	serialized := `
+---weird---
+Tihs is a lnog loonog tset sneetcne,
+wtih smoe big (biiiiig) wodrs!
+---weird---
+This long looong sentence some test with words`
+
+	expected := "This is a long looong test sentence,\nwith some big (biiiiig) words!"
+
+	encoded := EncodedText{}
+	err := encoded.FromString(serialized)
+	if err != nil {
+		t.Errorf("Error deserializing encoded text: %s", err)
+	}
+
+	decodedText := DecodeText(encoded.Text, encoded.EncodedWords)
+	if decodedText != expected {
+		t.Errorf("Decoded text '%s' should be same as expected text '%s'!", decodedText, expected)
+	}
+}

+ 18 - 3
encodedText.go

@@ -6,10 +6,25 @@ import (
 )
 
 type EncodedText struct {
-	text         string
-	encodedWords []string
+	Text         string
+	EncodedWords []string
 }
 
 func (e EncodedText) String() string {
-	return fmt.Sprintf("\n---weird---\n%s\n---weird---\n%v", e.text, strings.Join(e.encodedWords, " "))
+	return fmt.Sprintf("\n---weird---\n%s\n---weird---\n%v", e.Text, strings.Join(e.EncodedWords, " "))
+}
+
+func (e *EncodedText) FromString(serialized string) error {
+	if !strings.HasPrefix(serialized, "\n---weird---\n") {
+		return fmt.Errorf("Invalid prefix: %s", serialized)
+	}
+
+	parts := strings.Split(serialized, "\n---weird---\n")
+	if len(parts) != 3 {
+		return fmt.Errorf("Invalid string: %s", serialized)
+	}
+
+	e.Text = parts[1]
+	e.EncodedWords = strings.Split(parts[2], " ")
+	return nil
 }