Skip to content

Instantly share code, notes, and snippets.

@nikialeksey
Last active November 2, 2018 18:27
Show Gist options
  • Save nikialeksey/39d6acdd63494cb94b47909d7a2d6f42 to your computer and use it in GitHub Desktop.
Save nikialeksey/39d6acdd63494cb94b47909d7a2d6f42 to your computer and use it in GitHub Desktop.
Android localization unit-test
dependencies {
testImplementation 'com.atlascopco:hunspell-bridj:1.0.4'
}
package com.example
import com.atlascopco.hunspell.Hunspell
import org.hamcrest.core.IsEqual
import org.junit.Assert
import org.junit.Test
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.util.*
class DictionaryTest {
@Test
fun allEnKeysPresent() {
val defaultKeys = default().keys
val enKeys = en().keys
val emptyKeys = mutableSetOf<String>()
for (key in defaultKeys) {
if (key !in enKeys) {
emptyKeys.add(key)
}
}
Assert.assertThat(emptyKeys.toString(), defaultKeys, IsEqual.equalTo(enKeys))
}
@Test
fun spellEn() {
spell(
localization = en(),
dict = "./src/test/assets/en-US/index.dic", // dicts and affixes from https://github.com/wooorm/dictionaries
affix = "./src/test/assets/en-US/index.aff",
ignoredKeys = setOf(<...>),
ignoredWords = setOf(
"%s", "%d", "%f", "%1\$d", "%2\$d", "%1\$s", "%2\$s"
)
)
}
@Test
fun spellDefault() {
spell(
localization = default(),
dict = "./src/test/assets/ru/index.dic",
affix = "./src/test/assets/ru/index.aff",
ignoredKeys = setOf(<...>),
ignoredWords = setOf(
"%s", "%d", "%f", "%1\$d", "%2\$d", "%1\$s", "%2\$s", "="
)
)
}
private fun en(): Map<String, String> {
return localization("./src/main/res/values-en/dictionary.xml")
}
private fun default(): Map<String, String> {
return localization("./src/main/res/values/dictionary.xml")
}
private fun spell(
localization: Map<String, String>,
dict: String,
affix: String,
ignoredKeys: Set<String>,
ignoredWords: Set<String>
) {
val hunspell = Hunspell(dict, affix)
for ((key, sentences) in localization) {
if (key !in ignoredKeys) {
for (sentence in sentences.split("\\n")) {
val words = StringTokenizer(sentence, " .,!?:-()_\\\"/…")
while (words.hasMoreTokens()) {
val word = words.nextToken()
if (word !in ignoredWords) {
val correct = hunspell.isCorrect(word)
val suggest = if (!correct) {
hunspell.suggest(word)
} else {
emptyList()
}
Assert.assertTrue("name=$key was=$word suggests=$suggest", correct)
}
}
}
}
}
}
private fun localization(file: String): Map<String, String> {
return BufferedReader(FileReader(File(file))).use { reader ->
var line = reader.readLine()
val localization = mutableMapOf<String, String>()
while (line != null) {
if (line.contains("<string name=\"")) {
localization.put(
line.split("\"")[1],
line.split("<|>".toRegex())[2]
)
}
line = reader.readLine()
}
localization
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment