}
@Subscribe
- fun strictFilteringActivated(event: StrictFilteringActivatedEvent) {
+ fun StrictFilteringActivatedEvent.strictFilteringActivated() {
strictFiltering.set(true)
}
@Subscribe
- fun strictFilteringDeactivated(event: StrictFilteringDeactivatedEvent) {
+ fun StrictFilteringDeactivatedEvent.strictFilteringDeactivated() {
strictFiltering.set(false)
}
bind(SessionProvider::class.java).to(FreenetSessionProvider::class.java).`in`(Singleton::class.java)
bindListener(Matchers.any(), object : TypeListener {
- override fun <I> hear(typeLiteral: TypeLiteral<I>, typeEncounter: TypeEncounter<I>) {
+ override fun <I : Any> hear(typeLiteral: TypeLiteral<I>, typeEncounter: TypeEncounter<I>) {
typeEncounter.register(InjectionListener { injectee ->
logger.fine { "Injecting $injectee..." }
eventBus.register(injectee)
import com.codahale.metrics.*
import net.pterodactylus.sone.utils.*
import net.pterodactylus.util.template.*
+import java.util.Locale
/**
* [Filter] that renders a [Histogram] as a table row.
</tr>""".asTemplate()
private fun String.dotToCamel() =
- split(".").joinToString("", transform = String::capitalize)
+ split(".").joinToString("", transform = { it.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() } })
import net.pterodactylus.util.web.Method.GET
import net.pterodactylus.util.web.Method.POST
import net.pterodactylus.util.web.Request
+import java.util.Locale
val Request.isGET get() = this.method == GET
val Request.isPOST get() = this.method == POST
val HTTPRequest.headers get() = Headers(this)
class Headers(private val request: HTTPRequest) {
- operator fun get(name: String): String? = request.getHeader(name.toLowerCase())
+ operator fun get(name: String): String? = request.getHeader(name.lowercase(Locale.US))
}
.flatMap(ListNotification<PostReply>::elements)
.filter { replyVisibilityFilter.isReplyVisible(null, it) }
}
-
-private fun <R> Collection<*>.cast(): List<R> = map { it as R }
import net.pterodactylus.util.template.*
import java.util.logging.*
import javax.inject.*
+import java.util.Locale
/**
* The ācreate Soneā page lets the user create a new Sone.
override fun handleRequest(soneRequest: SoneRequest, templateContext: TemplateContext) {
templateContext["sones"] = soneRequest.core.localSones.sortedWith(niceNameComparator)
- templateContext["identitiesWithoutSone"] = soneRequest.core.identityManager.allOwnIdentities.filterNot { "Sone" in it.contexts }.sortedBy { "${it.nickname}@${it.id}".toLowerCase() }
+ templateContext["identitiesWithoutSone"] = soneRequest.core.identityManager.allOwnIdentities.filterNot { "Sone" in it.contexts }.sortedBy { "${it.nickname}@${it.id}".lowercase(Locale.US) }
if (soneRequest.isPOST) {
val identity = soneRequest.httpRequest.getPartAsStringFailsafe("identity", 43)
soneRequest.core.identityManager.allOwnIdentities.firstOrNull { it.id == identity }?.let { ownIdentity ->
SoneTemplatePage(webInterface, loaders, templateRenderer, pageTitleKey = pageTitleKey, requiresLogin = true) {
final override fun handleRequest(soneRequest: SoneRequest, templateContext: TemplateContext) {
- handleRequest(soneRequest, getCurrentSone(soneRequest.toadletContext, false)!!, templateContext)
+ handleRequest(soneRequest, getCurrentSone(soneRequest.toadletContext)!!, templateContext)
}
protected abstract fun handleRequest(soneRequest: SoneRequest, currentSone: Sone, templateContext: TemplateContext)
override fun isEnabled(soneRequest: SoneRequest) = when {
soneRequest.core.preferences.requireFullAccess && !soneRequest.toadletContext.isAllowedFullAccess -> false
- else -> getCurrentSone(soneRequest.toadletContext, false) == null
+ else -> getCurrentSone(soneRequest.toadletContext) == null
}
}
SoneTemplatePage(webInterface, loaders, templateRenderer, pageTitleKey = "Page.New.Title") {
override fun handleRequest(soneRequest: SoneRequest, templateContext: TemplateContext) =
- getCurrentSone(soneRequest.toadletContext).let { currentSone ->
+ getCurrentSone(soneRequest.toadletContext).let { _ ->
(newElements.newPosts + newElements.newReplies.mapPresent { it.post })
.distinct()
.sortedByDescending { it.time }
import net.pterodactylus.util.text.*
import java.util.concurrent.TimeUnit.*
import javax.inject.*
+import java.util.Locale
/**
* This page lets the user search for posts and replies that contain certain
}
private fun Sone.allText(soneNameCache: (Sone) -> String) =
- (soneNameCache(this) + profile.fields.map { "${it.name} ${it.value}" }.joinToString(" ", " ")).toLowerCase()
+ (soneNameCache(this) + profile.fields.map { "${it.name} ${it.value}" }.joinToString(" ", " ")).lowercase(Locale.US)
private fun Post.allText(soneNameCache: (Sone) -> String, getReplies: (String) -> Collection<PostReply>) =
(text + recipient.orNull()?.let { " ${soneNameCache(it)}" } + getReplies(id)
.filter(noFutureReply)
- .map { "${soneNameCache(it.sone)} ${it.text}" }.joinToString(" ", " ")).toLowerCase()
+ .map { "${soneNameCache(it.sone)} ${it.text}" }.joinToString(" ", " ")).lowercase(Locale.US)
private fun Iterable<Phrase>.indicesFor(text: String, predicate: (Phrase) -> Boolean) =
- filter(predicate).map(Phrase::phrase).map(String::toLowerCase).flatMap { text.findAll(it) }
+ filter(predicate).map(Phrase::phrase).map { it.lowercase(Locale.US) }.flatMap { text.findAll(it) }
private fun score(text: String, phrases: Iterable<Phrase>): Double {
val requiredPhrases = phrases.count { it.required }
private val sessionProvider: SessionProvider = webInterface
protected val translation: Translation = webInterface.translation
- protected fun getCurrentSone(toadletContext: ToadletContext, createSession: Boolean = true) =
+ protected fun getCurrentSone(toadletContext: ToadletContext) =
sessionProvider.getCurrentSone(toadletContext)
protected fun setCurrentSone(toadletContext: ToadletContext, sone: Sone?) =
package net.pterodactylus.sone.main;
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static java.nio.file.Files.write;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import net.pterodactylus.sone.web.page.FreenetRequest;
import net.pterodactylus.util.template.Template;
import freenet.clients.http.ToadletContext;
import freenet.support.api.HTTPRequest;
-import com.google.common.base.Charsets;
-import com.google.common.io.Files;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
public void setupLoader() throws IOException {
String templatePath = temporaryFolder.newFolder("temps").getPath();
loaders = new DebugLoaders(templatePath);
- File templateFile = new File(templatePath, "template.txt");
- Files.write("<%if foo>foo<%else>bar<%/if>", templateFile, Charsets.UTF_8);
+ Path templateFile = Paths.get(templatePath, "template.txt");
+ write(templateFile, "<%if foo>foo<%else>bar<%/if>".getBytes(UTF_8));
new File(templatePath, "templates").mkdir();
- File secondTemplateFile = new File(templatePath, "templates/template.txt");
- Files.write("<%if foo>foo<%else>bar<%/if>", secondTemplateFile, Charsets.UTF_8);
+ Path secondTemplateFile = Paths.get(templatePath, "templates/template.txt");
+ write(secondTemplateFile, "<%if foo>foo<%else>bar<%/if>".getBytes(UTF_8));
}
@Test
import org.hamcrest.MatcherAssert.*
import org.hamcrest.Matchers.*
import org.junit.*
-import org.junit.rules.*
+import org.junit.Assert.assertThrows
import org.mockito.ArgumentMatchers.*
import org.mockito.ArgumentMatchers.eq
*/
class ConfigurationSoneParserTest {
- @Rule
- @JvmField
- val expectedException = ExpectedException.none()!!
-
private val configuration = mock<Configuration>()
private val sone = mock<Sone>().apply {
whenever(this.id).thenReturn("1")
@Test
fun postWithoutTimeIsRecognized() {
setupPostWithoutTime()
- expectedException.expect<InvalidPostFound>()
- configurationSoneParser.parsePosts(createPostBuilderFactory())
+ assertThrows(InvalidPostFound::class.java) {
+ configurationSoneParser.parsePosts(createPostBuilderFactory())
+ }
}
private fun setupPostWithoutTime() {
@Test
fun postWithoutTextIsRecognized() {
setupPostWithoutText()
- expectedException.expect<InvalidPostFound>()
- configurationSoneParser.parsePosts(createPostBuilderFactory())
+ assertThrows(InvalidPostFound::class.java) {
+ configurationSoneParser.parsePosts(createPostBuilderFactory())
+ }
}
private fun setupPostWithoutText() {
@Test
fun missingPostIdIsRecognized() {
setupPostReplyWithMissingPostId()
- expectedException.expect<InvalidPostReplyFound>()
- configurationSoneParser.parsePostReplies(null)
+ assertThrows(InvalidPostReplyFound::class.java) {
+ configurationSoneParser.parsePostReplies(null)
+ }
}
private fun setupPostReplyWithMissingPostId() {
@Test
fun missingPostReplyTimeIsRecognized() {
setupPostReplyWithMissingPostReplyTime()
- expectedException.expect<InvalidPostReplyFound>()
- configurationSoneParser.parsePostReplies(null)
+ assertThrows(InvalidPostReplyFound::class.java) {
+ configurationSoneParser.parsePostReplies(null)
+ }
}
private fun setupPostReplyWithMissingPostReplyTime() {
@Test
fun missingPostReplyTextIsRecognized() {
setupPostReplyWithMissingPostReplyText()
- expectedException.expect<InvalidPostReplyFound>()
- configurationSoneParser.parsePostReplies(null)
+ assertThrows(InvalidPostReplyFound::class.java) {
+ configurationSoneParser.parsePostReplies(null)
+ }
}
private fun setupPostReplyWithMissingPostReplyText() {
@Test
fun albumWithInvalidTitleIsRecognized() {
setupAlbum(0, "A1", null, null, "D1", "I1")
- expectedException.expect<InvalidAlbumFound>()
- configurationSoneParser.parseTopLevelAlbums(createAlbumBuilderFactory())
+ assertThrows(InvalidAlbumFound::class.java) {
+ configurationSoneParser.parseTopLevelAlbums(createAlbumBuilderFactory())
+ }
}
@Test
fun albumWithInvalidDescriptionIsRecognized() {
setupAlbum(0, "A1", null, "T1", null, "I1")
- expectedException.expect<InvalidAlbumFound>()
- configurationSoneParser.parseTopLevelAlbums(createAlbumBuilderFactory())
+ assertThrows(InvalidAlbumFound::class.java) {
+ configurationSoneParser.parseTopLevelAlbums(createAlbumBuilderFactory())
+ }
}
@Test
fun albumWithInvalidParentIsRecognized() {
setupAlbum(0, "A1", "A0", "T1", "D1", "I1")
- expectedException.expect<InvalidParentAlbumFound>()
- configurationSoneParser.parseTopLevelAlbums(createAlbumBuilderFactory())
+ assertThrows(InvalidParentAlbumFound::class.java) {
+ configurationSoneParser.parseTopLevelAlbums(createAlbumBuilderFactory())
+ }
}
@Test
setupTopLevelAlbums()
configurationSoneParser.parseTopLevelAlbums(createAlbumBuilderFactory())
setupImage(0, "I1", null, 1000L, "K1", "T1", "D1", 16, 9)
- expectedException.expect<InvalidImageFound>()
- configurationSoneParser.parseImages(createImageBuilderFactory())
+ assertThrows(InvalidImageFound::class.java) {
+ configurationSoneParser.parseImages(createImageBuilderFactory())
+ }
}
@Test
setupTopLevelAlbums()
configurationSoneParser.parseTopLevelAlbums(createAlbumBuilderFactory())
setupImage(0, "I1", "A4", 1000L, "K1", "T1", "D1", 16, 9)
- expectedException.expect<InvalidParentAlbumFound>()
- configurationSoneParser.parseImages(createImageBuilderFactory())
+ assertThrows(InvalidParentAlbumFound::class.java) {
+ configurationSoneParser.parseImages(createImageBuilderFactory())
+ }
}
@Test
setupTopLevelAlbums()
configurationSoneParser.parseTopLevelAlbums(createAlbumBuilderFactory())
setupImage(0, "I1", "A1", null, "K1", "T1", "D1", 16, 9)
- expectedException.expect<InvalidImageFound>()
- configurationSoneParser.parseImages(createImageBuilderFactory())
+ assertThrows(InvalidImageFound::class.java) {
+ configurationSoneParser.parseImages(createImageBuilderFactory())
+ }
}
@Test
setupTopLevelAlbums()
configurationSoneParser.parseTopLevelAlbums(createAlbumBuilderFactory())
setupImage(0, "I1", "A1", 1000L, null, "T1", "D1", 16, 9)
- expectedException.expect<InvalidImageFound>()
- configurationSoneParser.parseImages(createImageBuilderFactory())
+ assertThrows(InvalidImageFound::class.java) {
+ configurationSoneParser.parseImages(createImageBuilderFactory())
+ }
}
@Test
setupTopLevelAlbums()
configurationSoneParser.parseTopLevelAlbums(createAlbumBuilderFactory())
setupImage(0, "I1", "A1", 1000L, "K1", null, "D1", 16, 9)
- expectedException.expect<InvalidImageFound>()
- configurationSoneParser.parseImages(createImageBuilderFactory())
+ assertThrows(InvalidImageFound::class.java) {
+ configurationSoneParser.parseImages(createImageBuilderFactory())
+ }
}
@Test
setupTopLevelAlbums()
configurationSoneParser.parseTopLevelAlbums(createAlbumBuilderFactory())
setupImage(0, "I1", "A1", 1000L, "K1", "T1", null, 16, 9)
- expectedException.expect<InvalidImageFound>()
- configurationSoneParser.parseImages(createImageBuilderFactory())
+ assertThrows(InvalidImageFound::class.java) {
+ configurationSoneParser.parseImages(createImageBuilderFactory())
+ }
}
@Test
setupTopLevelAlbums()
configurationSoneParser.parseTopLevelAlbums(createAlbumBuilderFactory())
setupImage(0, "I1", "A1", 1000L, "K1", "T1", "D1", null, 9)
- expectedException.expect<InvalidImageFound>()
- configurationSoneParser.parseImages(createImageBuilderFactory())
+ assertThrows(InvalidImageFound::class.java) {
+ configurationSoneParser.parseImages(createImageBuilderFactory())
+ }
}
@Test
setupTopLevelAlbums()
configurationSoneParser.parseTopLevelAlbums(createAlbumBuilderFactory())
setupImage(0, "I1", "A1", 1000L, "K1", "T1", "D1", 16, null)
- expectedException.expect<InvalidImageFound>()
- configurationSoneParser.parseImages(createImageBuilderFactory())
+ assertThrows(InvalidImageFound::class.java) {
+ configurationSoneParser.parseImages(createImageBuilderFactory())
+ }
}
}
import org.hamcrest.Matchers.notNullValue
import org.hamcrest.Matchers.nullValue
import org.junit.*
-import org.junit.rules.*
import org.mockito.*
import org.mockito.ArgumentCaptor.*
import org.mockito.ArgumentMatchers.eq
import java.io.*
import java.util.*
import kotlin.test.Test
+import org.junit.Assert.assertThrows
/**
* Unit test for [FreenetInterface].
@Rule
@JvmField
- val expectionException: ExpectedException = ExpectedException.none()
-
- @Rule
- @JvmField
val silencedLogging = silencedLogging()
@Suppress("UnstableApiUsage")
whenever(highLevelSimpleClient.getInsertContext(anyBoolean())).thenReturn(insertContext)
val insertBlockCaptor = forClass(InsertBlock::class.java)
whenever(highLevelSimpleClient.insert(insertBlockCaptor.capture(), eq(null as String?), eq(false), eq(insertContext), eq(insertToken), anyShort())).thenThrow(InsertException::class.java)
- expectionException.expect(SoneInsertException::class.java)
- freenetInterface.insertImage(temporaryImage, image, insertToken)
+ assertThrows(SoneInsertException::class.java) {
+ freenetInterface.insertImage(temporaryImage, image, insertToken)
+ }
}
@Test
@Test
fun `insert exception is forwarded as sone exception`() {
whenever(highLevelSimpleClient.insertManifest(any(), any(), any())).thenThrow(InsertException::class.java)
- expectionException.expect(SoneException::class.java)
- freenetInterface.insertDirectory(null, null, null)
+ assertThrows(SoneException::class.java) {
+ freenetInterface.insertDirectory(null, null, null)
+ }
}
@Test
val sone1Id = setupStringValue("SoneFollowingTimes/0/Sone", "Sone1")
val sone1Time = setupLongValue("SoneFollowingTimes/0/Time", 1000L)
val sone2Id = setupStringValue("SoneFollowingTimes/1/Sone", "Sone2")
- val sone2Time = setupLongValue("SoneFollowingTimes/1/Time", 2000L)
+ setupLongValue("SoneFollowingTimes/1/Time", 2000L)
setupStringValue("SoneFollowingTimes/2/Sone")
configurationLoader.removeSoneFollowingTime("Sone1")
assertThat(sone1Id.value, equalTo("Sone2"))
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.hamcrest.Matchers.nullValue
+import org.junit.Assert.assertThrows
import org.junit.Test
/**
whenever(localSone.id).thenReturn("RemoteSone")
parameters += "Sone" to "SoneId"
parameters += "LocalSone" to "RemoteSone"
- expectedException.expect(FcpException::class.java)
- command.execute(parameters)
+ assertThrows(FcpException::class.java) {
+ command.execute(parameters)
+ }
}
}
import org.hamcrest.MatcherAssert.*
import org.hamcrest.Matchers.*
import org.junit.*
+import org.junit.Assert.assertThrows
import org.mockito.Mockito.*
/**
@Test
fun `request with invalid post id results in FCP exception`() {
parameters += "Post" to "InvalidPostId"
- expectedException.expect(FcpException::class.java)
- command.execute(parameters)
+ assertThrows(FcpException::class.java) {
+ command.execute(parameters)
+ }
}
@Test
fun `request with missing local sone results in FCP exception`() {
parameters += "Post" to "PostId"
- expectedException.expect(FcpException::class.java)
- command.execute(parameters)
+ assertThrows(FcpException::class.java) {
+ command.execute(parameters)
+ }
}
@Test
fun `request with invalid sone results in FCP exception`() {
parameters += "Post" to "PostId"
parameters += "Sone" to "InvalidSoneId"
- expectedException.expect(FcpException::class.java)
- command.execute(parameters)
+ assertThrows(FcpException::class.java) {
+ command.execute(parameters)
+ }
}
@Test
fun `request with valid remote sone results in FCP exception`() {
parameters += "Post" to "PostId"
parameters += "Sone" to "RemoteSoneId"
- expectedException.expect(FcpException::class.java)
- command.execute(parameters)
+ assertThrows(FcpException::class.java) {
+ command.execute(parameters)
+ }
}
@Test
import org.hamcrest.MatcherAssert.*
import org.hamcrest.Matchers.*
import org.junit.*
+import org.junit.Assert.assertThrows
import org.mockito.Mockito.*
/**
@Test
fun `request with invalid reply results in FCP exception`() {
parameters += "Reply" to "InvalidReplyId"
- expectedException.expect(FcpException::class.java)
- command.execute(parameters)
+ assertThrows(FcpException::class.java) {
+ command.execute(parameters)
+ }
}
@Test
fun `request without sone results in FCP exception`() {
parameters += "Reply" to "ReplyId"
- expectedException.expect(FcpException::class.java)
- command.execute(parameters)
+ assertThrows(FcpException::class.java) {
+ command.execute(parameters)
+ }
}
@Test
fun `request with invalid sone results in FCP exception`() {
parameters += "Reply" to "ReplyId"
parameters += "Sone" to "InvalidSoneId"
- expectedException.expect(FcpException::class.java)
- command.execute(parameters)
+ assertThrows(FcpException::class.java) {
+ command.execute(parameters)
+ }
}
@Test
fun `request with remote sone results in FCP exception`() {
parameters += "Reply" to "ReplyId"
parameters += "Sone" to "RemoteSoneId"
- expectedException.expect(FcpException::class.java)
- command.execute(parameters)
+ assertThrows(FcpException::class.java) {
+ command.execute(parameters)
+ }
}
@Test
import net.pterodactylus.sone.test.*
import net.pterodactylus.sone.utils.*
import org.junit.*
-import org.junit.rules.*
+import org.junit.Assert.assertThrows
import org.mockito.ArgumentMatchers.*
/**
*/
abstract class SoneCommandTest {
- @Rule @JvmField val expectedException = ExpectedException.none()!!
-
protected val core = mock<Core>()
protected val command: AbstractSoneCommand by lazy { createCommand(core) }
}
protected fun executeCommandAndExpectFcpException() {
- expectedException.expect(FcpException::class.java)
- command.execute(parameters)
+ assertThrows(FcpException::class.java) {
+ command.execute(parameters)
+ }
}
protected fun requestWithoutAnyParameterResultsInFcpException() {
- expectedException.expect(FcpException::class.java)
- command.execute(parameters)
+ assertThrows(FcpException::class.java) {
+ command.execute(parameters)
+ }
}
protected fun requestWithEmptySoneParameterResultsInFcpException() {
import org.hamcrest.MatcherAssert.*
import org.hamcrest.Matchers.*
import org.junit.*
-import org.junit.rules.*
+import org.junit.Assert.assertThrows
import org.mockito.*
import org.mockito.Mockito.*
*/
class FreenetModuleTest {
- @Rule
- @JvmField
- val expectedException = ExpectedException.none()!!
-
private val sessionManager = mock<SessionManager>()
private val uskManager = mock<USKManager>()
private val clientContext = mock<ClientContext>()
@Test
fun `plugin respirator is not bound`() {
- expectedException.expect(Exception::class.java)
- injector.getInstance<PluginRespirator>()
+ assertThrows(Exception::class.java) {
+ injector.getInstance<PluginRespirator>()
+ }
}
@Test
}
@Test
+ @Suppress("DEPRECATION")
fun `plugin respirator facade is returned correctly`() {
val pluginRespiratorFacade = injector.getInstance<PluginRespiratorFacade>()
pluginRespiratorFacade.getPluginTalker(mock(), "test.plugin", "test-request-1")
assertThat(shutdownReceived.get(), equalTo(true))
}
+ @Suppress("UNCHECKED_CAST")
private fun <T> getInjected(clazz: Class<T>, annotation: Annotation? = null): T? =
injected[TypeLiteral.get(clazz) to annotation] as? T
newPostNotification.add(createPost())
val listNotificationFilter = DefaultListNotificationFilter(matchThisPost(newPostNotification.elements[1]), showAllReplies)
val filteredNotifications = listNotificationFilter.filterNotifications(listOf(newPostNotification), localSone)
- assertThat((filteredNotifications[0] as ListNotification<Post>).elements, contains(newPostNotification.elements[1]))
+ assertThat((filteredNotifications[0] as ListNotification<*>).elements, contains(newPostNotification.elements[1]))
}
@Test
val listNotificationFilter = DefaultListNotificationFilter(showAllPosts, matchThisReply(newReplyNotification.elements[1]))
val filteredNotifications = listNotificationFilter.filterNotifications(listOf(newReplyNotification), localSone)
assertThat(filteredNotifications, hasSize(1))
- assertThat((filteredNotifications[0] as ListNotification<PostReply?>).elements[0], equalTo(newReplyNotification.elements[1]))
+ assertThat((filteredNotifications[0] as ListNotification<*>).elements[0], equalTo(newReplyNotification.elements[1]))
}
@Test
newReplyNotification.add(createPostReply())
newReplyNotification.add(createPostReply())
val filteredNotifications = listNotificationFilter.filterNotifications(listOf(newReplyNotification), localSone)
- assertThat(filteredNotifications, contains<Notification>(newReplyNotification))
+ assertThat(filteredNotifications, contains(newReplyNotification))
}
@Test
val listNotificationFilter = DefaultListNotificationFilter(matchThisPost(mentionNotification.elements[1]), showAllReplies)
val filteredNotifications = listNotificationFilter.filterNotifications(listOf(mentionNotification), null)
assertThat(filteredNotifications, hasSize(1))
- assertThat((filteredNotifications[0] as ListNotification<Post?>).elements[0], equalTo(mentionNotification.elements[1]))
+ assertThat((filteredNotifications[0] as ListNotification<*>).elements[0], equalTo(mentionNotification.elements[1]))
}
@Test
import org.hamcrest.MatcherAssert.*
import org.hamcrest.Matchers.*
import org.junit.*
-import org.junit.rules.*
import java.io.*
import java.lang.Thread.*
import kotlin.test.Test
+import net.pterodactylus.sone.template.FilesystemTemplate.TemplateFileNotFoundException
+import org.junit.Assert.assertThrows
/**
* Unit test for [FilesystemTemplate].
*/
class FilesystemTemplateTest() {
- @Rule
- @JvmField
- val expectedException: ExpectedException = ExpectedException.none()
-
private val tempFile = File.createTempFile("template-", ".dat")
private val filesystemTemplate: FilesystemTemplate
private val templateContext = TemplateContext()
@Test
fun `loading template from non existing file throws exception`() {
val filesystemTemplate = FilesystemTemplate("/a/b/c.dat")
- expectedException.expect(FilesystemTemplate.TemplateFileNotFoundException::class.java)
- filesystemTemplate.initialContext
+ assertThrows(TemplateFileNotFoundException::class.java) {
+ filesystemTemplate.initialContext
+ }
}
@Test
createPostReply(-4000)
)
whenever(core.getReplies("post-id")).thenReturn(replies)
- val repliesForPost = accessor[null, post, "replies"] as Collection<PostReply>
+ val repliesForPost = accessor[null, post, "replies"] as Collection<*>
assertThat(repliesForPost, contains(
replies[1],
replies[2],
fun `accessor returns the liking sones`() {
val sones = setOf<Sone>()
whenever(core.getLikes(post)).thenReturn(sones)
- val likingSones = accessor[null, post, "likes"] as Set<Sone>
+ val likingSones = accessor[null, post, "likes"] as Set<*>
assertThat(likingSones, equalTo(sones))
}
private fun setupPost(sone: Sone, value: String) =
mock<Post>().apply {
whenever(id).thenReturn(POST_ID)
- whenever(this.sone).thenReturn(this@RenderFilterTest.sone)
+ whenever(this.sone).thenReturn(sone)
whenever(text).thenReturn(value)
}
fun <T> eq(t: T): T {
ArgumentMatchers.eq(t)
+ @Suppress("UNCHECKED_CAST")
return null as T
}
@Test
fun `exception is thrown for null and true condition`() {
assertFailsWith(IllegalArgumentException::class) {
- null.throwOnNullIf(true) { IllegalArgumentException() }
+ null.throwOnNullIf<Unit>(true) { IllegalArgumentException() }
}
}
@Test
fun `exception is not thrown for null and false condition`() {
- assertThat(null.throwOnNullIf(false) { IllegalArgumentException() }, nullValue())
+ assertThat(null.throwOnNullIf<Unit>(false) { IllegalArgumentException() }, nullValue())
}
@Test
@Test
fun `onNull is executed on null`() {
val called = CountDownLatch(1)
- null.onNull { called.countDown() }
+ null.onNull<Unit> { called.countDown() }
assertThat(called.count, equalTo(0L))
}
@Test
fun `onNull returns null when called on null`() {
- assertThat(null.onNull {}, nullValue())
+ assertThat(null.onNull<Unit> {}, nullValue())
}
@Test
import net.pterodactylus.sone.main.*
import net.pterodactylus.sone.test.*
import net.pterodactylus.sone.web.page.*
-import org.junit.*
-import org.junit.rules.*
import org.mockito.Mockito.*
import kotlin.test.Test
+import org.junit.Assert.assertThrows
class PageToadletRegistryTest {
SonePlugin::class.isProvidedBy(sonePlugin)
)
- @JvmField
- @Rule
- val expectedException: ExpectedException = ExpectedException.none()
private val pageToadletRegistry = injector.getInstance<PageToadletRegistry>()
@Test
val toadletWithMenuname = createPageToadlet("Test")
whenever(pageToadletFactory.createPageToadlet(page)).thenReturn(toadletWithMenuname)
pageToadletRegistry.registerToadlets()
- expectedException.expect(IllegalStateException::class.java)
- pageToadletRegistry.addPage(page)
+ assertThrows(IllegalStateException::class.java) {
+ pageToadletRegistry.addPage(page)
+ }
}
@Test
val toadlet = createPageToadlet()
whenever(pageToadletFactory.createPageToadlet(page)).thenReturn(toadlet)
pageToadletRegistry.registerToadlets()
- expectedException.expect(IllegalStateException::class.java)
- pageToadletRegistry.addDebugPage(page)
+ assertThrows(IllegalStateException::class.java) {
+ pageToadletRegistry.addDebugPage(page)
+ }
}
private fun createPageToadlet(menuName: String? = null) =
assertThat(page.isPrefixPage, equalTo(false))
}
- private fun String.asJson() = objectMapper.readValue(this, Map::class.java) as Map<String, Any>
+ private fun String.asJson() = objectMapper.readValue(this, Map::class.java) as Map<*, *>
}
whenever(freenetRequest.httpRequest).thenReturn(httpRequest)
whenever(httpRequest.method).thenReturn("GET")
- whenever(httpRequest.getHeader(ArgumentMatchers.anyString())).thenAnswer { requestHeaders[it.get<String>(0).toLowerCase()] }
+ whenever(httpRequest.getHeader(ArgumentMatchers.anyString())).thenAnswer { requestHeaders[it.get<String>(0).lowercase(Locale.US)] }
whenever(httpRequest.getParam(ArgumentMatchers.anyString())).thenAnswer { requestParameters[it.getArgument(0)] ?: "" }
whenever(httpRequest.getParam(ArgumentMatchers.anyString(), ArgumentMatchers.anyString())).thenAnswer { requestParameters[it.getArgument(0)] ?: it.getArgument(1) }
whenever(httpRequest.getParam(ArgumentMatchers.anyString(), ArgumentMatchers.isNull())).thenAnswer { requestParameters[it.getArgument(0)] }
}
protected fun addRequestHeader(key: String, value: String) {
- requestHeaders += key.toLowerCase() to value
+ requestHeaders += key.lowercase(Locale.US) to value
}
protected fun addRequestParameter(key: String, value: String) {
import org.hamcrest.MatcherAssert.*
import org.hamcrest.Matchers.*
import org.junit.*
-import org.junit.rules.*
+import org.junit.Assert.assertThrows
class TemplateRendererTest {
- @Rule
- @JvmField
- val expectedException: ExpectedException = ExpectedException.none()
private val templateContextFactory = TemplateContextFactory()
private val templateRenderer = TemplateRenderer(templateContextFactory)
@Test
fun `redirect exceptions are thrown`() {
- expectedException.expect(RedirectException::class.java)
- templateRenderer.render(Template()) { _ -> throw RedirectException("foo") }
+ assertThrows(RedirectException::class.java) {
+ templateRenderer.render(Template()) { _ -> throw RedirectException("foo") }
+ }
}
@Test
import net.pterodactylus.sone.web.page.FreenetTemplatePage.*
import org.hamcrest.MatcherAssert.*
import org.hamcrest.Matchers.*
-import org.junit.Rule
-import org.junit.rules.*
-import org.junit.rules.ExpectedException.*
import org.mockito.Mockito.*
import kotlin.test.*
+import org.junit.Assert.assertThrows
class DebugPageTest : WebPageTest(::DebugPage) {
- @Rule
- @JvmField
- val expectedException: ExpectedException = none()
-
@Test
fun `page returns correct path`() {
assertThat(page.path, equalTo("debug"))
@Test
fun `get request redirects to index`() {
- expectedException.expect(redirectsTo("./"))
- page.handleRequest(soneRequest, templateContext)
+ val redirect = assertThrows(RedirectException::class.java) {
+ page.handleRequest(soneRequest, templateContext)
+ }
+ assertThat(redirect, redirectsTo("./"))
}
}
-
import org.hamcrest.MatcherAssert.*
import org.hamcrest.Matchers.*
import org.junit.*
+import java.util.Locale
/**
* Unit test for [KnownSonesPage].
val rootAlbum = AlbumImpl(this).also { it.addAlbum(album) }
whenever(this.rootAlbum).thenReturn(rootAlbum)
whenever(this.profile).thenReturn(mock())
- whenever(id).thenReturn(name.toLowerCase())
+ whenever(id).thenReturn(name.lowercase(Locale.US))
whenever(this.name).thenReturn(name)
}
createSoneWithPost("without-match", "no match")
addHttpRequestParameter("query", "recipient")
verifyNoRedirect {
- assertThat(this["postHits"], contains<Post>(postWithMatch))
+ assertThat(get<Iterable<Post>>("postHits"), contains(postWithMatch))
}
}
createSoneWithPost("without-match", "no match")
addHttpRequestParameter("query", "value")
verifyNoRedirect {
- assertThat(this["soneHits"], contains(soneWithProfileField))
+ assertThat(get<Iterable<Sone>>("soneHits"), contains(soneWithProfileField))
}
}
addHttpRequestParameter("query", "sone")
verifyNoRedirect {
assertThat(this["sonePagination"], isOnPage(0).hasPages(2))
- assertThat(this["soneHits"], contains(sones[0], sones[2]))
+ assertThat(get<Iterable<Sone>>("soneHits"), contains(sones[0], sones[2]))
}
}
addHttpRequestParameter("sonePage", "1")
verifyNoRedirect {
assertThat(this["sonePagination"], isOnPage(1).hasPages(2))
- assertThat(this["soneHits"], contains(sones[3]))
+ assertThat(get<Iterable<Sone>>("soneHits"), contains(sones[3]))
}
}
addHttpRequestParameter("query", "sone")
verifyNoRedirect {
assertThat(this["postPagination"], isOnPage(0).hasPages(2))
- assertThat(this["postHits"], contains(sones[0], sones[2]))
+ assertThat(get<Iterable<Post>>("postHits"), contains(sones[0], sones[2]))
}
}
addHttpRequestParameter("postPage", "1")
verifyNoRedirect {
assertThat(this["postPagination"], isOnPage(1).hasPages(2))
- assertThat(this["postHits"], contains(sones[3]))
+ assertThat(get<Iterable<Sone>>("postHits"), contains(sones[3]))
}
}
addSone("sone", sone)
addHttpRequestParameter("query", "text")
verifyNoRedirect {
- assertThat(this["postHits"], contains(post))
+ assertThat(get<Iterable<Post>>("postHits"), contains(post))
}
verifyNoRedirect {
assertThat(callCounter.get(), equalTo(1))
addSone("sone", sone)
addHttpRequestParameter("query", "text")
verifyNoRedirect {
- assertThat(this["postHits"], contains(post))
+ assertThat(get<Iterable<Post>>("postHits"), contains(post))
}
whenever(ticker.read()).thenReturn(TimeUnit.MINUTES.toNanos(5) + 1)
verifyNoRedirect {
private fun setupHttpRequest() {
whenever(httpRequest.method).thenReturn("GET")
- whenever(httpRequest.getHeader(anyString())).then { requestHeaders[it.get<String>(0).toLowerCase()] }
+ whenever(httpRequest.getHeader(anyString())).then { requestHeaders[it.get<String>(0).lowercase(Locale.US)] }
whenever(httpRequest.hasParameters()).then { getRequestParameters.isNotEmpty() }
whenever(httpRequest.parameterNames).then { getRequestParameters.keys }
whenever(httpRequest.isParameterSet(anyString())).then { it[0] in getRequestParameters }
}
fun addHttpRequestHeader(name: String, value: String) {
- requestHeaders[name.toLowerCase()] = value
+ requestHeaders[name.lowercase(Locale.US)] = value
}
fun addHttpRequestParameter(name: String, value: String) {