From ce24100bf84c7bdc82b2ff4174adc8f1e9c45926 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krist=C3=B3f=20T=C3=B3th?= Date: Wed, 9 Oct 2019 21:05:12 +0200 Subject: [PATCH] Implement a unit test case for parsing trans output --- trans/trans.go | 35 ++++++++++++++++++++++------------- trans/trans_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 13 deletions(-) create mode 100644 trans/trans_test.go diff --git a/trans/trans.go b/trans/trans.go index 39ed8c7..784877b 100644 --- a/trans/trans.go +++ b/trans/trans.go @@ -7,29 +7,30 @@ import ( "log" ) -type Translator interface { - Translate() []string + +type Translation struct { + job TransJob + Executor func(TransJob) ([]byte, error) } -type transJob struct { +type TransJob struct { word string fromLang string toLang string } -func New(word, fromLang, toLang string) Translator { - return transJob{word: word, fromLang: fromLang, toLang: toLang} -} - -func (tj transJob) Translate() []string { - outBytes, err := tj.execTrans() - if err != nil { - log.Fatalf("Failed to execute command 'trans': %v", err) +func New(word, fromLang, toLang string) Translation { + return Translation{ + job: TransJob{ + word: word, + fromLang: fromLang, + toLang: toLang, + }, + Executor: executeTransShell, } - return uniqueSlice(parseTransOutput(string(outBytes))) } -func (tj transJob) execTrans() ([]byte, error) { +func executeTransShell(tj TransJob) ([]byte, error) { config := []string{ "-no-ansi", "-show-original", "n", @@ -43,6 +44,14 @@ func (tj transJob) execTrans() ([]byte, error) { 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 { outLines := strings.Split(out, "\n") translation := outLines[0] diff --git a/trans/trans_test.go b/trans/trans_test.go new file mode 100644 index 0000000..ae4defc --- /dev/null +++ b/trans/trans_test.go @@ -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() + } + } +}