-
-
Notifications
You must be signed in to change notification settings - Fork 99
/
TemplatesTest.kt
72 lines (57 loc) · 2.44 KB
/
TemplatesTest.kt
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
package com.hexagonkt.templates.examples
import com.hexagonkt.core.text.Glob
import com.hexagonkt.core.urlOf
import com.hexagonkt.templates.SampleTemplateAdapter
import com.hexagonkt.templates.TemplateManager
import com.hexagonkt.templates.TemplatePort
import org.junit.jupiter.api.Test
import java.net.URL
import java.util.*
import kotlin.test.assertEquals
class TemplatesTest {
@Test fun registerEngine() {
// templateRegex
TemplateManager.adapters = mapOf(
Regex(".*\\.html") to SampleTemplateAdapter("html"),
Regex(".*\\.txt") to SampleTemplateAdapter("text"),
Regex(".*") to SampleTemplateAdapter("others"),
)
// templateRegex
checkRegisteredAdapters()
// templateGlob
TemplateManager.adapters = mapOf(
Glob("*.html").regex to SampleTemplateAdapter("html"),
Glob("*.txt").regex to SampleTemplateAdapter("text"),
Glob("*").regex to SampleTemplateAdapter("others"),
)
// templateGlob
checkRegisteredAdapters()
}
@Test fun renderPage() {
TemplateManager.adapters = mapOf(Glob("*").regex to EchoTemplateAdapter)
// templateUsage
val context = mapOf("key1" to "value1", "key2" to "value2")
val rendered = TemplateManager.render(urlOf("classpath:template.txt"), context)
// templateUsage
assert(rendered.startsWith("classpath:template.txt {key1=value1, key2=value2"))
assert(rendered.contains("_template_"))
assert(rendered.contains("_now_"))
}
private fun checkRegisteredAdapters() {
val context = mapOf<String, Any>()
val html = TemplateManager.render(urlOf("classpath:template.html"), context)
val plain = TemplateManager.render(urlOf("classpath:template.txt"), context)
val others = TemplateManager.render(urlOf("classpath:template.other"), context)
assertEquals("html:classpath:template.html", html)
assertEquals("text:classpath:template.txt", plain)
assertEquals("others:classpath:template.other", others)
}
private object EchoTemplateAdapter : TemplatePort {
override fun render(url: URL, context: Map<String, *>, locale: Locale): String =
"$url $context"
override fun render(
name: String, templates: Map<String, String>, context: Map<String, *>, locale: Locale
): String =
throw UnsupportedOperationException()
}
}