Implement a unit test case for parsing trans output

This commit is contained in:
Kristóf Tóth 2019-10-09 21:05:12 +02:00
parent 8b8f0e94b0
commit ce24100bf8
2 changed files with 61 additions and 13 deletions

View File

@ -7,29 +7,30 @@ import (
"log" "log"
) )
type Translator interface {
Translate() []string type Translation struct {
job TransJob
Executor func(TransJob) ([]byte, error)
} }
type transJob struct { type TransJob struct {
word string word string
fromLang string fromLang string
toLang string toLang string
} }
func New(word, fromLang, toLang string) Translator { func New(word, fromLang, toLang string) Translation {
return transJob{word: word, fromLang: fromLang, toLang: toLang} return Translation{
} job: TransJob{
word: word,
func (tj transJob) Translate() []string { fromLang: fromLang,
outBytes, err := tj.execTrans() toLang: toLang,
if err != nil { },
log.Fatalf("Failed to execute command 'trans': %v", err) Executor: executeTransShell,
} }
return uniqueSlice(parseTransOutput(string(outBytes)))
} }
func (tj transJob) execTrans() ([]byte, error) { func executeTransShell(tj TransJob) ([]byte, error) {
config := []string{ config := []string{
"-no-ansi", "-no-ansi",
"-show-original", "n", "-show-original", "n",
@ -43,6 +44,14 @@ func (tj transJob) execTrans() ([]byte, error) {
return exec.Command("trans", config...).Output() return exec.Command("trans", config...).Output()
} }
func (t Translation) Translate() []string {
outBytes, err := t.Executor(t.job)
if err != nil {
log.Fatalf("Failed to execute command 'trans': %v", err)
}
return uniqueSlice(parseTransOutput(string(outBytes)))
}
func parseTransOutput(out string) []string { func parseTransOutput(out string) []string {
outLines := strings.Split(out, "\n") outLines := strings.Split(out, "\n")
translation := outLines[0] translation := outLines[0]

39
trans/trans_test.go Normal file
View File

@ -0,0 +1,39 @@
package trans_test
import (
"testing"
"."
"reflect"
)
type testData struct {
job []string
transOutput []byte
expectedResults []string
}
func TestTranslation(t *testing.T) {
cases := []testData{
testData{
[]string{"actuator", "en", "hu"},
[]byte(`működtető
actuator
működtető, beavatkozó, hajtómű, aktuátor, hajtás
`),
[]string{"működtető", "beavatkozó", "hajtómű", "aktuátor", "hajtás"},
},
}
for _, data := range cases {
j := trans.New(data.job[0], data.job[1], data.job[2])
j.Executor = func(tj trans.TransJob) ([]byte, error) {
return data.transOutput, nil
}
r := j.Translate()
if (!reflect.DeepEqual(r, data.expectedResults)) {
t.Error()
}
}
}