🎨 Clean up imports
[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         val page by lazy { pageSupplier(webInterface, loaders, templateRenderer) }
47
48         val httpRequest = mock<HTTPRequest>()
49         val freenetRequest = mock<FreenetRequest>()
50         init {
51                 whenever(freenetRequest.l10n).thenReturn(l10n)
52                 whenever(freenetRequest.sessionManager).thenReturn(sessionManager)
53                 whenever(freenetRequest.uri).thenReturn(mock())
54         }
55         val soneRequest by lazy { freenetRequest.toSoneRequest(core, webInterface) }
56         val templateContext = TemplateContext()
57         val toadletContext = deepMock<ToadletContext>()
58         val responseContent = ByteArrayOutputStream()
59         val response = Response(responseContent)
60
61         private val requestHeaders = mutableMapOf<String, String>()
62         private val getRequestParameters = mutableMapOf<String, MutableList<String>>()
63         private val postRequestParameters = mutableMapOf<String, ByteArray>()
64         private val uploadedFileNames = mutableMapOf<String, String>()
65         private val uploadedFileContentTypes = mutableMapOf<String, String>()
66         private val uploadedFileResources = mutableMapOf<String, String>()
67         private val ownIdentities = mutableSetOf<OwnIdentity>()
68         private val allSones = mutableMapOf<String, Sone>()
69         private val localSones = mutableMapOf<String, Sone>()
70         private val allPosts = mutableMapOf<String, Post>()
71         private val allPostReplies = mutableMapOf<String, PostReply>()
72         private val perPostReplies = mutableMapOf<String, PostReply>()
73         private val allAlbums = mutableMapOf<String, Album>()
74         private val allImages = mutableMapOf<String, Image>()
75         private val notifications = mutableMapOf<String, Notification>()
76         private val translations = mutableMapOf<String, String>()
77
78         init {
79                 setupCore()
80                 setupWebInterface()
81                 setupHttpRequest()
82                 setupFreenetRequest()
83                 setupTranslations()
84         }
85
86         private fun setupCore() {
87                 whenever(core.preferences).thenReturn(preferences)
88                 whenever(core.identityManager.allOwnIdentities).then { ownIdentities }
89                 whenever(core.sones).then { allSones.values }
90                 whenever(core.getSone(anyString())).then { allSones[it[0]] }
91                 whenever(core.localSones).then { localSones.values }
92                 whenever(core.getLocalSone(anyString())).then { localSones[it[0]] }
93                 whenever(core.getPost(anyString())).then { allPosts[it[0]] }
94                 whenever(core.getPostReply(anyString())).then { allPostReplies[it[0]] }
95                 whenever(core.getReplies(anyString())).then { perPostReplies[it[0]].asList() }
96                 whenever(core.getAlbum(anyString())).then { allAlbums[it[0]] }
97                 whenever(core.getImage(anyString())).then { allImages[it[0]]}
98                 whenever(core.getImage(anyString(), anyBoolean())).then { allImages[it[0]]}
99                 whenever(core.getTemporaryImage(anyString())).thenReturn(null)
100         }
101
102         private fun setupWebInterface() {
103                 whenever(webInterface.sessionManager).thenReturn(sessionManager)
104                 whenever(webInterface.getCurrentSoneCreatingSession(eq(toadletContext))).thenReturn(currentSone)
105                 whenever(webInterface.getCurrentSone(eq(toadletContext), anyBoolean())).thenReturn(currentSone)
106                 whenever(webInterface.getCurrentSoneWithoutCreatingSession(eq(toadletContext))).thenReturn(currentSone)
107                 whenever(webInterface.getNotifications(currentSone)).then { notifications.values }
108                 whenever(webInterface.getNotification(anyString())).then { notifications[it[0]].asOptional() }
109         }
110
111         private fun setupHttpRequest() {
112                 whenever(httpRequest.method).thenReturn("GET")
113                 whenever(httpRequest.getHeader(anyString())).then { requestHeaders[it.get<String>(0).toLowerCase()] }
114                 whenever(httpRequest.hasParameters()).then { getRequestParameters.isNotEmpty() }
115                 whenever(httpRequest.parameterNames).then { getRequestParameters.keys }
116                 whenever(httpRequest.isParameterSet(anyString())).then { it[0] in getRequestParameters }
117                 whenever(httpRequest.getParam(anyString())).then { getRequestParameters[it[0]]?.firstOrNull() ?: "" }
118                 whenever(httpRequest.getParam(anyString(), anyString())).then { getRequestParameters[it[0]]?.firstOrNull() ?: it[1] }
119                 whenever(httpRequest.getIntParam(anyString())).then { getRequestParameters[it[0]]?.first()?.toIntOrNull() ?: 0 }
120                 whenever(httpRequest.getIntParam(anyString(), anyInt())).then { getRequestParameters[it[0]]?.first()?.toIntOrNull() ?: it[1] }
121                 whenever(httpRequest.getLongParam(anyString(), anyLong())).then { getRequestParameters[it[0]]?.first()?.toLongOrNull() ?: it[1] }
122                 whenever(httpRequest.getMultipleParam(anyString())).then { getRequestParameters[it[0]]?.toTypedArray() ?: emptyArray<String>() }
123                 whenever(httpRequest.getMultipleIntParam(anyString())).then { getRequestParameters[it[0]]?.map { it.toIntOrNull() ?: 0 } ?: emptyArray<Int>() }
124                 whenever(httpRequest.isPartSet(anyString())).then { it[0] in postRequestParameters }
125                 whenever(httpRequest.getPartAsStringFailsafe(anyString(), anyInt())).then { postRequestParameters[it[0]]?.decode()?.take(it[1]) ?: "" }
126                 whenever(httpRequest.getUploadedFile(anyString())).then {
127                         it.get<String>(0).takeIf { it in uploadedFileNames }
128                                         ?.let { name -> UploadedFile(uploadedFileNames[name]!!, uploadedFileContentTypes[name]!!, uploadedFileResources[name]!!)
129                         }
130                 }
131         }
132
133         private class UploadedFile(private val filename: String, private val contentType: String, private val resourceName: String): HTTPUploadedFile {
134                 override fun getFilename() = filename
135                 override fun getContentType() = contentType
136                 override fun getData() = javaClass.getResourceAsStream(resourceName).readBytes().let(::SimpleReadOnlyArrayBucket)
137         }
138
139         private fun ByteArray.decode(charset: Charset = UTF_8) = String(this, charset)
140
141         private fun setupFreenetRequest() {
142                 whenever(freenetRequest.method).thenReturn(GET)
143                 whenever(freenetRequest.httpRequest).thenReturn(httpRequest)
144                 whenever(freenetRequest.toadletContext).thenReturn(toadletContext)
145         }
146
147         private fun setupTranslations() {
148                 whenever(l10n.getString(anyString())).then { translations[it[0]] ?: it[0] }
149         }
150
151         fun setMethod(method: Method) {
152                 whenever(httpRequest.method).thenReturn(method.name)
153                 whenever(freenetRequest.method).thenReturn(method)
154         }
155
156         fun request(uri: String) {
157                 whenever(httpRequest.path).thenReturn(uri)
158                 whenever(freenetRequest.uri).thenReturn(URI(uri))
159         }
160
161         fun addHttpRequestHeader(name: String, value: String) {
162                 requestHeaders[name.toLowerCase()] = value
163         }
164
165         fun addHttpRequestParameter(name: String, value: String) {
166                 getRequestParameters[name] = getRequestParameters.getOrElse(name) { mutableListOf() }.apply { add(value) }
167         }
168
169         fun addHttpRequestPart(name: String, value: String) {
170                 postRequestParameters[name] = value.toByteArray(UTF_8)
171         }
172
173         fun unsetCurrentSone() {
174                 whenever(webInterface.getCurrentSoneCreatingSession(eq(toadletContext))).thenReturn(null)
175                 whenever(webInterface.getCurrentSone(eq(toadletContext), anyBoolean())).thenReturn(null)
176                 whenever(webInterface.getCurrentSoneWithoutCreatingSession(eq(toadletContext))).thenReturn(null)
177         }
178
179         fun addOwnIdentity(ownIdentity: OwnIdentity) {
180                 ownIdentities += ownIdentity
181         }
182
183         fun addSone(id: String, sone: Sone) {
184                 allSones[id] = sone
185         }
186
187         fun addLocalSone(id: String, localSone: Sone) {
188                 localSones[id] = localSone
189         }
190
191         fun addPost(id: String, post: Post) {
192                 allPosts[id] = post
193         }
194
195         fun addPostReply(id: String, postReply: PostReply) {
196                 allPostReplies[id] = postReply
197                 postReply.postId?.also { perPostReplies[it] = postReply }
198         }
199
200         fun addAlbum(id: String, album: Album) {
201                 allAlbums[id] = album
202         }
203
204         fun addImage(id: String, image: Image) {
205                 allImages[id] = image
206         }
207
208         fun addTranslation(key: String, value: String) {
209                 translations[key] = value
210         }
211
212         fun addNotification(id: String, notification: Notification) {
213                 notifications[id] = notification
214         }
215
216         fun addTemporaryImage(id: String, temporaryImage: TemporaryImage) {
217                 whenever(core.getTemporaryImage(id)).thenReturn(temporaryImage)
218         }
219
220         fun addUploadedFile(name: String, filename: String, contentType: String, resource: String) {
221                 uploadedFileNames[name] = filename
222                 uploadedFileContentTypes[name] = contentType
223                 uploadedFileResources[name] = resource
224         }
225
226         fun verifyNoRedirect(assertions: () -> Unit) {
227                 var caughtException: Exception? = null
228                 try {
229                         page.handleRequest(freenetRequest, templateContext)
230                 } catch (e: Exception) {
231                         caughtException = e
232                 }
233                 caughtException?.run { throw this } ?: assertions()
234         }
235
236         fun verifyRedirect(target: String, assertions: () -> Unit = {}) {
237                 try {
238                         page.handleRequest(freenetRequest, templateContext)
239                         fail()
240                 } catch (re: RedirectException) {
241                         if (re.target != target) {
242                                 throw re
243                         }
244                         assertions()
245                 } catch (e: Exception) {
246                         throw e
247                 }
248         }
249
250 }