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