File: syllables_test.go

package info (click to toggle)
golang-github-jdkato-prose 1.1.0%2Bgit20171031.e27abfd-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 12,848 kB
  • sloc: python: 115; makefile: 55; sh: 21
file content (92 lines) | stat: -rw-r--r-- 2,134 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package summarize

import (
	"bufio"
	"encoding/json"
	"os"
	"path/filepath"
	"testing"

	"github.com/jdkato/prose/internal/util"
	"github.com/montanaflynn/stats"
	"github.com/stretchr/testify/assert"
)

func TestSyllables(t *testing.T) {
	cases := util.ReadDataFile(filepath.Join(testdata, "syllables.json"))
	tests := make(map[string]int)
	util.CheckError(json.Unmarshal(cases, &tests))

	for word, count := range tests {
		assert.Equal(t, count, Syllables(word), word)
	}

	total := 9462.0
	right := 0.0
	p := filepath.Join(testdata, "1-syllable-words.txt")
	right += testNSyllables(t, p, 1)

	p = filepath.Join(testdata, "2-syllable-words.txt")
	right += testNSyllables(t, p, 2)

	p = filepath.Join(testdata, "3-syllable-words.txt")
	right += testNSyllables(t, p, 3)

	p = filepath.Join(testdata, "4-syllable-words.txt")
	right += testNSyllables(t, p, 4)

	p = filepath.Join(testdata, "5-syllable-words.txt")
	right += testNSyllables(t, p, 5)

	p = filepath.Join(testdata, "6-syllable-words.txt")
	right += testNSyllables(t, p, 6)

	p = filepath.Join(testdata, "7-syllable-words.txt")
	right += testNSyllables(t, p, 7)

	ratio, _ := stats.Round(right/total, 2)
	assert.True(t, ratio >= 0.93, "Less than 93% accurate on NSyllables!")
}

func testNSyllables(t *testing.T, fpath string, n int) float64 {
	file, err := os.Open(fpath)
	util.CheckError(err)

	right := 0.0
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		word := scanner.Text()
		if n == Syllables(word) {
			right++
		}
	}

	util.CheckError(scanner.Err())
	util.CheckError(file.Close())

	return right
}

func BenchmarkSyllables(b *testing.B) {
	cases := util.ReadDataFile(filepath.Join(testdata, "syllables.json"))
	tests := make(map[string]int)
	util.CheckError(json.Unmarshal(cases, &tests))

	for n := 0; n < b.N; n++ {
		for word := range tests {
			Syllables(word)
		}
	}
}

func BenchmarkSyllablesIn(b *testing.B) {
	cases := util.ReadDataFile(filepath.Join(testdata, "syllables.json"))
	tests := make(map[string]int)
	util.CheckError(json.Unmarshal(cases, &tests))

	for n := 0; n < b.N; n++ {
		for word := range tests {
			Syllables(word)
		}
	}
}