🔥 Replace BaseL10n with Translation
[Sone.git] / src / test / kotlin / net / pterodactylus / sone / web / pages / WebPageTest.kt
1 package net.pterodactylus.sone.web.pages
2
3 import com.google.common.eventbus.*
4 import freenet.clients.http.*
5 import freenet.support.*
6 import freenet.support.api.*
7 import net.pterodactylus.sone.core.*
8 import net.pterodactylus.sone.data.*
9 import net.pterodactylus.sone.freenet.*
10 import net.pterodactylus.sone.freenet.wot.*
11 import net.pterodactylus.sone.main.*
12 import net.pterodactylus.sone.test.deepMock
13 import net.pterodactylus.sone.test.get
14 import net.pterodactylus.sone.test.mock
15 import net.pterodactylus.sone.test.whenever
16 import net.pterodactylus.sone.utils.*
17 import net.pterodactylus.sone.web.*
18 import net.pterodactylus.sone.web.page.*
19 import net.pterodactylus.sone.web.page.FreenetTemplatePage.RedirectException
20 import net.pterodactylus.util.notify.*
21 import net.pterodactylus.util.template.*
22 import net.pterodactylus.util.web.*
23 import net.pterodactylus.util.web.Method.*
24 import org.junit.Assert.*
25 import org.mockito.ArgumentMatchers.*
26 import org.mockito.ArgumentMatchers.eq
27 import java.io.*
28 import java.net.*
29 import java.nio.charset.*
30 import java.util.*
31 import kotlin.text.Charsets.UTF_8
32
33 /**
34  * Base class for web page tests.
35  */
36 open class WebPageTest(pageSupplier: (WebInterface, Loaders, TemplateRenderer) -> SoneTemplatePage = { _, _, _ -> mock() }) {
37
38         val currentSone = mock<Sone>()
39         val loaders = mock<Loaders>()
40         val templateRenderer = mock<TemplateRenderer>()
41         val webInterface = deepMock<WebInterface>()
42         val core = webInterface.core
43         val eventBus = mock<EventBus>()
44         val preferences = Preferences(eventBus)
45         val sessionManager = mock<SessionManager>()
46
47         open val page by lazy { pageSupplier(webInterface, loaders, templateRenderer) }
48
49         val httpRequest = mock<HTTPRequest>()
50         val freenetRequest = mock<FreenetRequest>()
51
52         init {
53                 whenever(freenetRequest.sessionManager).thenReturn(sessionManager)
54                 whenever(freenetRequest.uri).thenReturn(mock())
55         }
56
57         val soneRequest by lazy { freenetRequest.toSoneRequest(core, webInterface) }
58         val templateContext = TemplateContext()
59         val toadletContext = deepMock<ToadletContext>()
60         val responseContent = ByteArrayOutputStream()
61         val response = Response(responseContent)
62
63         private val requestHeaders = mutableMapOf<String, String>()
64         private val getRequestParameters = mutableMapOf<String, MutableList<String>>()
65         private val postRequestParameters = mutableMapOf<String, ByteArray>()
66         private val uploadedFileNames = mutableMapOf<String, String>()
67         private val uploadedFileContentTypes = mutableMapOf<String, String>()
68         private val uploadedFileResources = mutableMapOf<String, String>()
69         private val ownIdentities = mutableSetOf<OwnIdentity>()
70         private val allSones = mutableMapOf<String, Sone>()
71         private val localSones = mutableMapOf<String, Sone>()
72         private val allPosts = mutableMapOf<String, Post>()
73         private val allPostReplies = mutableMapOf<String, PostReply>()
74         private val perPostReplies = mutableMapOf<String, PostReply>()
75         private val allAlbums = mutableMapOf<String, Album>()
76         private val allImages = mutableMapOf<String, Image>()
77         private val notifications = mutableMapOf<String, Notification>()
78         private val translations = mutableMapOf<String, String>()
79
80         private val translation = object : Translation {
81                 override val currentLocale = Locale.ENGLISH
82                 override fun translate(key: String) = translations[key] ?: key
83         }
84
85         init {
86                 setupCore()
87                 setupWebInterface()
88                 setupHttpRequest()
89                 setupFreenetRequest()
90         }
91
92         private fun setupCore() {
93                 whenever(core.preferences).thenReturn(preferences)
94                 whenever(core.identityManager.allOwnIdentities).then { ownIdentities }
95                 whenever(core.sones).then { allSones.values }
96                 whenever(core.getSone(anyString())).then { allSones[it[0]] }
97                 whenever(core.localSones).then { localSones.values }
98                 whenever(core.getLocalSone(anyString())).then { localSones[it[0]] }
99                 whenever(core.getPost(anyString())).then { allPosts[it[0]] }
100                 whenever(core.getPostReply(anyString())).then { allPostReplies[it[0]] }
101                 whenever(core.getReplies(anyString())).then { perPostReplies[it[0]].asList() }
102                 whenever(core.getAlbum(anyString())).then { allAlbums[it[0]] }
103                 whenever(core.getImage(anyString())).then { allImages[it[0]] }
104                 whenever(core.getImage(anyString(), anyBoolean())).then { allImages[it[0]] }
105                 whenever(core.getTemporaryImage(anyString())).thenReturn(null)
106         }
107
108         private fun setupWebInterface() {
109                 whenever(webInterface.sessionManager).thenReturn(sessionManager)
110                 whenever(webInterface.getCurrentSoneCreatingSession(eq(toadletContext))).thenReturn(currentSone)
111                 whenever(webInterface.getCurrentSone(eq(toadletContext), anyBoolean())).thenReturn(currentSone)
112                 whenever(webInterface.getCurrentSoneWithoutCreatingSession(eq(toadletContext))).thenReturn(currentSone)
113                 whenever(webInterface.getNotifications(currentSone)).then { notifications.values }
114                 whenever(webInterface.getNotification(anyString())).then { notifications[it[0]].asOptional() }
115                 whenever(webInterface.translation).thenReturn(translation)
116         }
117
118         private fun setupHttpRequest() {
119                 whenever(httpRequest.method).thenReturn("GET")
120                 whenever(httpRequest.getHeader(anyString())).then { requestHeaders[it.get<String>(0).toLowerCase()] }
121                 whenever(httpRequest.hasParameters()).then { getRequestParameters.isNotEmpty() }
122                 whenever(httpRequest.parameterNames).then { getRequestParameters.keys }
123                 whenever(httpRequest.isParameterSet(anyString())).then { it[0] in getRequestParameters }
124                 whenever(httpRequest.getParam(anyString())).then { getRequestParameters[it[0]]?.firstOrNull() ?: "" }
125                 whenever(httpRequest.getParam(anyString(), anyString())).then { getRequestParameters[it[0]]?.firstOrNull() ?: it[1] }
126                 whenever(httpRequest.getIntParam(anyString())).then { getRequestParameters[it[0]]?.first()?.toIntOrNull() ?: 0 }
127                 whenever(httpRequest.getIntParam(anyString(), anyInt())).then { getRequestParameters[it[0]]?.first()?.toIntOrNull() ?: it[1] }
128                 whenever(httpRequest.getLongParam(anyString(), anyLong())).then { getRequestParameters[it[0]]?.first()?.toLongOrNull() ?: it[1] }
129                 whenever(httpRequest.getMultipleParam(anyString())).then { getRequestParameters[it[0]]?.toTypedArray() ?: emptyArray<String>() }
130                 whenever(httpRequest.getMultipleIntParam(anyString())).then { getRequestParameters[it[0]]?.map { it.toIntOrNull() ?: 0 } ?: emptyArray<Int>() }
131                 whenever(httpRequest.isPartSet(anyString())).then { it[0] in postRequestParameters }
132                 whenever(httpRequest.getPartAsStringFailsafe(anyString(), anyInt())).then { postRequestParameters[it[0]]?.decode()?.take(it[1]) ?: "" }
133                 whenever(httpRequest.getUploadedFile(anyString())).then {
134                         it.get<String>(0).takeIf { it in uploadedFileNames }
135                                         ?.let { name ->
136                                                 UploadedFile(uploadedFileNames[name]!!, uploadedFileContentTypes[name]!!, uploadedFileResources[name]!!)
137                                         }
138                 }
139         }
140
141         private class UploadedFile(private val filename: String, private val contentType: String, private val resourceName: String) : HTTPUploadedFile {
142                 override fun getFilename() = filename
143                 override fun getContentType() = contentType
144                 override fun getData() = javaClass.getResourceAsStream(resourceName).readBytes().let(::SimpleReadOnlyArrayBucket)
145         }
146
147         private fun ByteArray.decode(charset: Charset = UTF_8) = String(this, charset)
148
149         private fun setupFreenetRequest() {
150                 whenever(freenetRequest.method).thenReturn(GET)
151                 whenever(freenetRequest.httpRequest).thenReturn(httpRequest)
152                 whenever(freenetRequest.toadletContext).thenReturn(toadletContext)
153         }
154
155         fun setMethod(method: Method) {
156                 whenever(httpRequest.method).thenReturn(method.name)
157                 whenever(freenetRequest.method).thenReturn(method)
158         }
159
160         fun request(uri: String) {
161                 whenever(httpRequest.path).thenReturn(uri)
162                 whenever(freenetRequest.uri).thenReturn(URI(uri))
163         }
164
165         fun addHttpRequestHeader(name: String, value: String) {
166                 requestHeaders[name.toLowerCase()] = value
167         }
168
169         fun addHttpRequestParameter(name: String, value: String) {
170                 getRequestParameters[name] = getRequestParameters.getOrElse(name) { mutableListOf() }.apply { add(value) }
171         }
172
173         fun addHttpRequestPart(name: String, value: String) {
174                 postRequestParameters[name] = value.toByteArray(UTF_8)
175         }
176
177         fun unsetCurrentSone() {
178                 whenever(webInterface.getCurrentSoneCreatingSession(eq(toadletContext))).thenReturn(null)
179                 whenever(webInterface.getCurrentSone(eq(toadletContext), anyBoolean())).thenReturn(null)
180                 whenever(webInterface.getCurrentSoneWithoutCreatingSession(eq(toadletContext))).thenReturn(null)
181         }
182
183         fun addOwnIdentity(ownIdentity: OwnIdentity) {
184                 ownIdentities += ownIdentity
185         }
186
187         fun addSone(id: String, sone: Sone) {
188                 allSones[id] = sone
189         }
190
191         fun addLocalSone(id: String, localSone: Sone) {
192                 localSones[id] = localSone
193         }
194
195         fun addPost(id: String, post: Post) {
196                 allPosts[id] = post
197         }
198
199         fun addPostReply(id: String, postReply: PostReply) {
200                 allPostReplies[id] = postReply
201                 postReply.postId?.also { perPostReplies[it] = postReply }
202         }
203
204         fun addAlbum(id: String, album: Album) {
205                 allAlbums[id] = album
206         }
207
208         fun addImage(id: String, image: Image) {
209                 allImages[id] = image
210         }
211
212         fun addTranslation(key: String, value: String) {
213                 translations[key] = value
214         }
215
216         fun addNotification(id: String, notification: Notification) {
217                 notifications[id] = notification
218         }
219
220         fun addTemporaryImage(id: String, temporaryImage: TemporaryImage) {
221                 whenever(core.getTemporaryImage(id)).thenReturn(temporaryImage)
222         }
223
224         fun addUploadedFile(name: String, filename: String, contentType: String, resource: String) {
225                 uploadedFileNames[name] = filename
226                 uploadedFileContentTypes[name] = contentType
227                 uploadedFileResources[name] = resource
228         }
229
230         fun verifyNoRedirect(assertions: () -> Unit) {
231                 var caughtException: Exception? = null
232                 try {
233                         page.handleRequest(freenetRequest, templateContext)
234                 } catch (e: Exception) {
235                         caughtException = e
236                 }
237                 caughtException?.run { throw this } ?: assertions()
238         }
239
240         fun verifyRedirect(target: String, assertions: () -> Unit = {}) {
241                 try {
242                         page.handleRequest(freenetRequest, templateContext)
243                         fail()
244                 } catch (re: RedirectException) {
245                         if (re.target != target) {
246                                 throw re
247                         }
248                         assertions()
249                 } catch (e: Exception) {
250                         throw e
251                 }
252         }
253
254 }