🔀 Merge branch 'release/v82'
[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
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.uri).thenReturn(mock())
53         }
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         private val translation = object : Translation {
79                 override val currentLocale = Locale.ENGLISH
80                 override fun translate(key: String) = translations[key] ?: key
81         }
82
83         init {
84                 setupCore()
85                 setupWebInterface()
86                 setupHttpRequest()
87                 setupFreenetRequest()
88         }
89
90         private fun setupCore() {
91                 whenever(core.preferences).thenReturn(preferences)
92                 whenever(core.identityManager.allOwnIdentities).then { ownIdentities }
93                 whenever(core.sones).then { allSones.values }
94                 whenever(core.getSone(anyString())).then { allSones[it[0]] }
95                 whenever(core.localSones).then { localSones.values }
96                 whenever(core.getLocalSone(anyString())).then { localSones[it[0]] }
97                 whenever(core.getPost(anyString())).then { allPosts[it[0]] }
98                 whenever(core.getPostReply(anyString())).then { allPostReplies[it[0]] }
99                 whenever(core.getReplies(anyString())).then { perPostReplies[it[0]].asList() }
100                 whenever(core.getAlbum(anyString())).then { allAlbums[it[0]] }
101                 whenever(core.getImage(anyString())).then { allImages[it[0]] }
102                 whenever(core.getImage(anyString(), anyBoolean())).then { allImages[it[0]] }
103                 whenever(core.getTemporaryImage(anyString())).thenReturn(null)
104         }
105
106         private fun setupWebInterface() {
107                 whenever(webInterface.getCurrentSone(eq(toadletContext))).thenReturn(currentSone)
108                 whenever(webInterface.getNotifications(currentSone)).then { notifications.values }
109                 whenever(webInterface.getNotification(anyString())).then { notifications[it[0]].asOptional() }
110                 whenever(webInterface.translation).thenReturn(translation)
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         fun setMethod(method: Method) {
151                 whenever(httpRequest.method).thenReturn(method.name)
152                 whenever(freenetRequest.method).thenReturn(method)
153         }
154
155         fun request(uri: String) {
156                 whenever(httpRequest.path).thenReturn(uri)
157                 whenever(freenetRequest.uri).thenReturn(URI(uri))
158         }
159
160         fun addHttpRequestHeader(name: String, value: String) {
161                 requestHeaders[name.toLowerCase()] = value
162         }
163
164         fun addHttpRequestParameter(name: String, value: String) {
165                 getRequestParameters[name] = getRequestParameters.getOrElse(name) { mutableListOf() }.apply { add(value) }
166         }
167
168         fun addHttpRequestPart(name: String, value: String) {
169                 postRequestParameters[name] = value.toByteArray(UTF_8)
170         }
171
172         fun unsetCurrentSone() {
173                 whenever(webInterface.getCurrentSone(eq(toadletContext))).thenReturn(null)
174         }
175
176         fun addOwnIdentity(ownIdentity: OwnIdentity) {
177                 ownIdentities += ownIdentity
178         }
179
180         fun addSone(id: String, sone: Sone) {
181                 allSones[id] = sone
182         }
183
184         fun addLocalSone(id: String, localSone: Sone) {
185                 localSones[id] = localSone
186         }
187
188         fun addPost(id: String, post: Post) {
189                 allPosts[id] = post
190         }
191
192         fun addPostReply(id: String, postReply: PostReply) {
193                 allPostReplies[id] = postReply
194                 postReply.postId?.also { perPostReplies[it] = postReply }
195         }
196
197         fun addAlbum(id: String, album: Album) {
198                 allAlbums[id] = album
199         }
200
201         fun addImage(id: String, image: Image) {
202                 allImages[id] = image
203         }
204
205         fun addTranslation(key: String, value: String) {
206                 translations[key] = value
207         }
208
209         fun addNotification(id: String, notification: Notification) {
210                 notifications[id] = notification
211         }
212
213         fun addTemporaryImage(id: String, temporaryImage: TemporaryImage) {
214                 whenever(core.getTemporaryImage(id)).thenReturn(temporaryImage)
215         }
216
217         fun addUploadedFile(name: String, filename: String, contentType: String, resource: String) {
218                 uploadedFileNames[name] = filename
219                 uploadedFileContentTypes[name] = contentType
220                 uploadedFileResources[name] = resource
221         }
222
223         fun verifyNoRedirect(assertions: () -> Unit) {
224                 var caughtException: Exception? = null
225                 try {
226                         page.handleRequest(freenetRequest, templateContext)
227                 } catch (e: Exception) {
228                         caughtException = e
229                 }
230                 caughtException?.run { throw this } ?: assertions()
231         }
232
233         fun verifyRedirect(target: String, assertions: () -> Unit = {}) {
234                 try {
235                         page.handleRequest(freenetRequest, templateContext)
236                         fail()
237                 } catch (re: RedirectException) {
238                         if (re.target != target) {
239                                 throw re
240                         }
241                         assertions()
242                 } catch (e: Exception) {
243                         throw e
244                 }
245         }
246
247 }