How to use Constraints.or method of io.kotest.property.Constraints class

Best Kotest code snippet using io.kotest.property.Constraints.Constraints.or

ExceptionMapperTests.kt

Source:ExceptionMapperTests.kt Github

copy

Full Screen

1package org.backstage.error2import com.fasterxml.jackson.databind.JsonMappingException3import com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException4import io.kotest.core.spec.style.BehaviorSpec5import io.kotest.core.spec.style.DescribeSpec6import io.kotest.matchers.collections.shouldHaveSize7import io.kotest.matchers.maps.shouldContainAll8import io.kotest.matchers.nulls.shouldBeNull9import io.kotest.matchers.nulls.shouldNotBeNull10import io.kotest.matchers.shouldBe11import io.kotest.matchers.types.shouldBeTypeOf12import org.backstage.http.HttpHeaders13import java.sql.SQLException14import javax.persistence.EntityNotFoundException15import javax.ws.rs.NotAllowedException16import javax.ws.rs.core.MediaType17import javax.ws.rs.core.Response18import javax.ws.rs.core.Response.Status.*19import javax.ws.rs.core.Response.StatusType20import kotlin.reflect.KClassifier21import kotlin.reflect.KParameter22import kotlin.reflect.KType23import kotlin.reflect.KTypeProjection24import org.hibernate.exception.ConstraintViolationException as HibernateConstraintViolationException25class ExceptionHandlerTests : BehaviorSpec() {26 init {27 Given("a missing parameter exception") {28 val exception = MissingKotlinParameterException(29 parameter = object : KParameter {30 override val annotations: List<Annotation>31 get() = emptyList()32 override val index: Int33 get() = 134 override val isOptional: Boolean35 get() = false36 override val isVararg: Boolean37 get() = false38 override val kind: KParameter.Kind39 get() = KParameter.Kind.VALUE40 override val name: String?41 get() = "name"42 override val type: KType43 get() = object : KType {44 override val annotations: List<Annotation>45 get() = emptyList()46 override val arguments: List<KTypeProjection>47 get() = emptyList()48 override val classifier: KClassifier?49 get() = null50 override val isMarkedNullable: Boolean51 get() = false52 }53 },54 processor = null,55 msg = "Message"56 )57 When("building the response") {58 val response = ExceptionResponseFactory.handleThrownException(exception)59 Then("the status code should be correct") {60 response.status shouldBe UnprocessableEntityStatus.statusCode61 }62 Then("the response should have the content type") {63 response.shouldHaveContentTypeHeader()64 }65 Then("the body should have the correct information") {66 response.shouldBeValidationErrorWith(67 field = "",68 value = null,69 messageKey = ErrorCode.NOT_MISSING,70 messageParams = mapOf("value" to null)71 )72 }73 }74 }75 Given("an illegal argument exception") {76 val exception = IllegalArgumentException()77 When("building the response") {78 val response = ExceptionResponseFactory.handleThrownException(exception)79 Then("the status code should be correct") {80 response.status shouldBe BAD_REQUEST.statusCode81 }82 Then("the response should have the content type") {83 response.shouldHaveContentTypeHeader()84 }85 Then("The response should have the correct message") {86 response.shouldBeGeneralErrorWith(87 status = BAD_REQUEST,88 message = null89 )90 }91 }92 }93 Given("a HttpException") {94 val exception = HttpException(BAD_GATEWAY, "Message")95 When("building the response") {96 val response = ExceptionResponseFactory.handleThrownException(exception)97 Then("the response should match the extension function") {98 with(exception.buildGeneralErrorResponse()) {99 response.status shouldBe this.status100 response.headers shouldBe this.headers101 }102 }103 }104 }105 Given("a not allowed exception") {106 val exception = NotAllowedException(Throwable(), "GET")107 When("building the response") {108 val response = ExceptionResponseFactory.handleThrownException(exception)109 Then("the status code should be correct") {110 response.status shouldBe METHOD_NOT_ALLOWED.statusCode111 }112 }113 }114 Given("a not implemented error") {115 val exception = NotImplementedError()116 When("building the response") {117 val response = ExceptionResponseFactory.handleThrownException(exception)118 Then("the status code should be correct") {119 response.status shouldBe NOT_IMPLEMENTED.statusCode120 }121 Then("the response should have the content type") {122 response.shouldHaveContentTypeHeader()123 }124 Then("The response should have the correct message") {125 response.shouldBeGeneralErrorWith(126 status = NOT_IMPLEMENTED,127 message = "Method not implemented"128 )129 }130 }131 }132 Given("a general Throwable") {133 val exception = Throwable("Message")134 When("building the response") {135 val response = ExceptionResponseFactory.handleThrownException(exception)136 Then("the status code should be correct") {137 response.status shouldBe INTERNAL_SERVER_ERROR.statusCode138 }139 Then("the response should have the content type") {140 response.shouldHaveContentTypeHeader()141 }142 }143 }144 Given("no exception") {145 val exception: Throwable? = null146 When("building the response") {147 val response = ExceptionResponseFactory.handleThrownException(exception)148 Then("the status code should be correct") {149 response.status shouldBe INTERNAL_SERVER_ERROR.statusCode150 }151 Then("the response should have the content type") {152 response.shouldHaveContentTypeHeader()153 }154 Then("the body should have the expected message") {155 response.shouldBeGeneralErrorWith(156 status = INTERNAL_SERVER_ERROR,157 message = "An unknown and unhandled error has occurred"158 )159 }160 }161 }162 }163}164class PersistenceExceptionHandlerTests : BehaviorSpec() {165 init {166 Given("a hibernate constraint violation exception") {167 val exception = HibernateConstraintViolationException("Message", SQLException(), "Constraint")168 When("building the response") {169 val response = ExceptionResponseFactory.handleThrownException(exception)170 Then("the response should have the correct status code") {171 response.status shouldBe UnprocessableEntityStatus.statusCode172 }173 Then("the response should have the content type") {174 response.shouldHaveContentTypeHeader()175 }176 Then("the response should have the correct body") {177 response.shouldBeGeneralErrorWith(178 status = UnprocessableEntityStatus,179 message = exception.message180 )181 }182 }183 }184 Given("an entity not found exception") {185 val exception = EntityNotFoundException()186 When("building the response") {187 val response = ExceptionResponseFactory.handleThrownException(exception)188 Then("the response should have the correct status code") {189 response.status shouldBe NOT_FOUND.statusCode190 }191 Then("the response should have the content type") {192 response.shouldHaveContentTypeHeader()193 }194 Then("the response should have the correct body") {195 response.shouldBeGeneralErrorWith(196 status = NOT_FOUND,197 message = null198 )199 }200 }201 }202 }203}204class BuildErrorResponseTests : DescribeSpec() {205 init {206 describe("building a validation error response from an unprocessable entity status") {207 val response = UnprocessableEntityStatus.buildValidationErrorResponse(208 field = "FIELD",209 value = "VALUE",210 messageKey = "KEY",211 messageParams = mapOf("value" to "VALUE")212 )213 it("the response should contain the correct status code") {214 response.status shouldBe UnprocessableEntityStatus.statusCode215 }216 it("the response should include the content type header") {217 response.shouldHaveContentTypeHeader()218 }219 it("the body should be correct") {220 response.shouldBeValidationErrorWith(221 field = "FIELD",222 value = "VALUE",223 messageKey = "KEY",224 messageParams = mapOf("value" to "VALUE")225 )226 }227 }228 describe("building a validation error response from an unprocessable entity status with no message key") {229 val response = UnprocessableEntityStatus.buildValidationErrorResponse(230 field = "FIELD",231 value = "VALUE",232 messageKey = null233 )234 it("the constraint should be null") {235 response.shouldBeValidationErrorWith(236 field = "FIELD",237 value = "VALUE",238 messageKey = null,239 messageParams = emptyMap()240 )241 }242 }243 describe("building an error response from any status") {244 val status = NOT_FOUND245 val response = status.buildResponse(246 message = "The error message"247 )248 it("the response should have the correct status code") {249 response.status shouldBe status.statusCode250 }251 it("the response should include the content type header") {252 response.shouldHaveContentTypeHeader()253 }254 it("the body should contain the correct information") {255 response.shouldBeGeneralErrorWith(256 status = status,257 message = "The error message"258 )259 }260 }261 describe("building an error response from a status with no message") {262 val response = NOT_FOUND.buildResponse()263 it("the message should be null") {264 response.entity.shouldBeTypeOf<GeneralError> { error ->265 error.message.shouldBeNull()266 }267 }268 }269 describe("building an error response from a general Throwable and status code") {270 val status = NOT_FOUND271 val exception = Throwable("A test exception")272 val response = exception.buildGeneralErrorResponse(status)273 it("the response should have the correct status code") {274 response.status shouldBe status.statusCode275 }276 it("the response should include the content type header") {277 response.shouldHaveContentTypeHeader()278 }279 it("the body should contain the correct information") {280 response.shouldBeGeneralErrorWith(281 status = status,282 message = exception.message283 )284 }285 }286 describe("building an error response from a HttpException") {287 val exception = HttpException(BAD_REQUEST, "Bad Request")288 val response = exception.buildGeneralErrorResponse()289 it("the response should have the correct status code") {290 response.status shouldBe exception.status.statusCode291 }292 it("the response should include the content type header") {293 response.shouldHaveContentTypeHeader()294 }295 it("the body should contain the correct information") {296 response.shouldBeGeneralErrorWith(297 status = exception.status,298 message = exception.message299 )300 }301 }302 }303}304class PathBuildingTests : BehaviorSpec() {305 init {306 Given("a list of paths, with and without field names") {307 val paths = listOf(308 JsonMappingException.Reference("from", "field"),309 JsonMappingException.Reference("from", 1),310 JsonMappingException.Reference("from", "second"),311 JsonMappingException.Reference("from", "third"),312 JsonMappingException.Reference("from", 6)313 )314 When("building to a string") {315 val path = paths.buildPath()316 Then("the result should be correct") {317 path shouldBe "field[1].second.third[6]"318 }319 }320 }321 }322}323fun Response.shouldHaveContentTypeHeader(headerValue: String = MediaType.APPLICATION_JSON) {324 this.headers[HttpHeaders.CONTENT_TYPE]?.firstOrNull() shouldBe headerValue325}326fun Response.shouldBeValidationErrorWith(327 field: String,328 value: Any? = null,329 messageKey: String? = null,330 messageParams: Map<String, Any?> = emptyMap()331) {332 (this.entity as List<*>).let { errors ->333 errors shouldHaveSize 1334 errors.first().shouldBeTypeOf<ValidationError> { error ->335 error.property shouldBe field336 when (value) {337 null -> error.value.shouldBeNull()338 else -> {339 error.value.shouldNotBeNull()340 error.value shouldBe value341 }342 }343 when (messageKey) {344 null -> error.constraint.shouldBeNull()345 else -> {346 error.constraint.shouldNotBeNull()347 error.constraint?.messageKey?.shouldBe("org.backstage.constraints.$messageKey.message")348 error.constraint?.messageBundle?.shouldBe("org/backstage/messages")349 error.constraint?.messageParams?.shouldContainAll(messageParams)350 }351 }352 }353 }354}355fun Response.shouldBeGeneralErrorWith(status: StatusType, message: String?) {356 this.entity.shouldBeTypeOf<GeneralError> { error ->357 error.code shouldBe status.statusCode358 when (message) {359 null -> error.message.shouldBeNull()360 else -> {361 error.message.shouldNotBeNull()362 error.message shouldBe message363 }364 }365 error.timestamp.shouldNotBeNull()366 }367}...

Full Screen

Full Screen

ThreadControllerTest.kt

Source:ThreadControllerTest.kt Github

copy

Full Screen

1package com.github.njuro.jard.thread2import com.github.njuro.jard.MockMvcTest3import com.github.njuro.jard.TEST_ATTACHMENT_PNG4import com.github.njuro.jard.WithContainerDatabase5import com.github.njuro.jard.WithMockJardUser6import com.github.njuro.jard.ban.UserBannedException7import com.github.njuro.jard.board8import com.github.njuro.jard.board.BoardFacade9import com.github.njuro.jard.board.dto.BoardDto10import com.github.njuro.jard.common.InputConstraints.MAX_ATTACHMENT_SIZE11import com.github.njuro.jard.common.InputConstraints.MAX_NAME_LENGTH12import com.github.njuro.jard.common.InputConstraints.MAX_POST_LENGTH13import com.github.njuro.jard.common.InputConstraints.MAX_SUBJECT_LENGTH14import com.github.njuro.jard.common.InputConstraints.MAX_TRIPCODE_PASSWORD_LENGTH15import com.github.njuro.jard.common.Mappings16import com.github.njuro.jard.multipartFile17import com.github.njuro.jard.post18import com.github.njuro.jard.post.PostFacade19import com.github.njuro.jard.post.dto.DeleteOwnPostDto20import com.github.njuro.jard.post.dto.PostDto21import com.github.njuro.jard.post.dto.PostForm22import com.github.njuro.jard.randomString23import com.github.njuro.jard.thread24import com.github.njuro.jard.thread.dto.ThreadDto25import com.github.njuro.jard.thread.dto.ThreadForm26import com.github.njuro.jard.toForm27import com.github.njuro.jard.user.UserAuthority28import com.github.njuro.jard.utils.HttpUtils29import com.github.njuro.jard.utils.validation.PropertyValidationException30import com.ninjasquad.springmockk.MockkBean31import io.kotest.matchers.collections.shouldHaveSize32import io.kotest.matchers.collections.shouldNotBeEmpty33import io.kotest.matchers.nulls.shouldNotBeNull34import io.kotest.matchers.should35import io.kotest.matchers.shouldBe36import io.kotest.matchers.string.shouldStartWith37import io.mockk.Runs38import io.mockk.every39import io.mockk.just40import io.mockk.mockkStatic41import io.mockk.slot42import io.mockk.unmockkStatic43import org.junit.jupiter.api.AfterEach44import org.junit.jupiter.api.BeforeEach45import org.junit.jupiter.api.DisplayName46import org.junit.jupiter.api.Nested47import org.junit.jupiter.api.Test48import org.springframework.mock.web.MockMultipartFile49import org.springframework.test.web.servlet.delete50import org.springframework.test.web.servlet.get51import org.springframework.test.web.servlet.multipart52import org.springframework.test.web.servlet.patch53import java.io.IOException54@WithContainerDatabase55internal class ThreadControllerTest : MockMvcTest() {56 @MockkBean57 private lateinit var threadFacade: ThreadFacade58 @MockkBean59 private lateinit var boardFacade: BoardFacade60 @MockkBean61 private lateinit var postFacade: PostFacade62 private val board = board(label = "r")63 private val thread = thread(board)64 private val post = post(thread)65 @BeforeEach66 fun initMocks() {67 mockkStatic(HttpUtils::class)68 every { HttpUtils.getClientIp(any()) } returns "0.0.0.0"69 every { boardFacade.resolveBoard(board.label) } returns board.toDto()70 every { threadFacade.resolveThread(board.label, thread.threadNumber) } returns thread.toDto()71 every { postFacade.resolvePost(board.label, post.postNumber) } returns post.toDto()72 }73 @AfterEach74 fun clearMocks() {75 unmockkStatic(HttpUtils::class)76 }77 @Nested78 @DisplayName("create thread")79 inner class CreateThread {80 private fun createThread(81 threadForm: ThreadForm,82 attachment: MockMultipartFile? = multipartFile("attachment", TEST_ATTACHMENT_PNG)83 ) =84 mockMvc.multipart(Mappings.API_ROOT_THREADS, board.label) {85 part("threadForm", threadForm)86 if (attachment != null) file(attachment)87 }88 @Test89 fun `create valid thread`() {90 val thread = thread(board, subject = "Test thread")91 val threadForm = slot<ThreadForm>()92 every { threadFacade.createThread(capture(threadForm), ofType(BoardDto::class)) } returns thread.toDto()93 val response =94 createThread(thread.toForm()).andExpect { status { isCreated() } }.andReturnConverted<ThreadDto>()95 response.threadNumber shouldBe thread.threadNumber96 threadForm.captured.should {97 it.postForm.ip shouldStartWith "0"98 it.postForm.attachment.originalFilename shouldBe TEST_ATTACHMENT_PNG99 }100 }101 @Test102 fun `create thread with embedded attachment in original post`() {103 val thread = thread(board, subject = "Test thread")104 every {105 threadFacade.createThread(106 ofType(ThreadForm::class),107 ofType(BoardDto::class)108 )109 } answers { thread.toDto() }110 createThread(111 thread.toForm().apply { postForm.embedUrl = "some_url" },112 attachment = null113 ).andExpect { status { isCreated() } }114 .andReturnConverted<ThreadDto>().shouldNotBeNull()115 }116 @Test117 fun `don't create thread when user is banned`() {118 val thread = thread(board, subject = "Test thread")119 every {120 threadFacade.createThread(121 ofType(ThreadForm::class),122 ofType(BoardDto::class)123 )124 } throws UserBannedException()125 createThread(thread.toForm()).andExpect { status { isForbidden() } }126 }127 @Test128 fun `don't create thread with invalid subject`() {129 createThread(130 thread(131 board,132 subject = randomString(MAX_SUBJECT_LENGTH + 1)133 ).toForm()134 ).andExpectValidationError("subject")135 }136 @Test137 fun `don't create thread without subject and body`() {138 createThread(thread(board).toForm()).andExpectValidationError("emptySubjectAndComment")139 }140 @Test141 fun `don't create thread without attachment`() {142 createThread(thread(board).toForm(), attachment = null).andExpectValidationError("uploadedAttachment")143 }144 }145 @Nested146 @DisplayName("reply to thread")147 inner class ReplyToThread {148 private fun replyToThread(149 postForm: PostForm,150 attachment: MockMultipartFile? = multipartFile("attachment", TEST_ATTACHMENT_PNG)151 ) =152 mockMvc.multipart(153 "${Mappings.API_ROOT_THREADS}/${Mappings.PATH_VARIABLE_THREAD}",154 board.label,155 thread.threadNumber156 ) {157 part("postForm", postForm)158 if (attachment != null) file(attachment)159 }160 @Test161 fun `create valid reply`() {162 val post = post(thread)163 val postForm = slot<PostForm>()164 every { threadFacade.replyToThread(capture(postForm), ofType(ThreadDto::class)) } returns post.toDto()165 val response = replyToThread(post.toForm()).andExpect {166 status { isCreated() }167 jsonPath("$.thread") { doesNotExist() }168 }.andReturnConverted<PostDto>()169 response.postNumber shouldBe post.postNumber170 postForm.captured.should {171 it.ip shouldStartWith "0"172 it.attachment.originalFilename shouldBe TEST_ATTACHMENT_PNG173 }174 }175 @Test176 fun `create valid reply without attachment`() {177 val post = post(thread, body = "test")178 every { threadFacade.replyToThread(ofType(PostForm::class), ofType(ThreadDto::class)) } returns post.toDto()179 replyToThread(post.toForm()).andExpect { status { isCreated() } }.andReturnConverted<PostDto>()180 .shouldNotBeNull()181 }182 @Test183 fun `don't create reply with invalid name`() {184 replyToThread(post(thread, name = randomString(MAX_NAME_LENGTH + 1)).toForm())185 .andExpectValidationError("name")186 }187 @Test188 fun `don't create reply when user is banned`() {189 val post = post(thread, body = "test")190 every {191 threadFacade.replyToThread(192 ofType(PostForm::class),193 ofType(ThreadDto::class)194 )195 } throws UserBannedException()196 replyToThread(post.toForm()).andExpect { status { isForbidden() } }197 }198 @Test199 fun `don't create reply with invalid password`() {200 replyToThread(201 post(thread).toForm().apply {202 password = randomString(203 MAX_TRIPCODE_PASSWORD_LENGTH + 1204 )205 }206 ).andExpectValidationError("password")207 }208 @Test209 fun `don't create reply with invalid body`() {210 replyToThread(post(thread, body = randomString(MAX_POST_LENGTH + 1)).toForm())211 .andExpectValidationError("body")212 }213 @Test214 fun `don't create reply with invalid ip`() {215 every { HttpUtils.getClientIp(any()) } returns "a.b.c.d"216 replyToThread(post(thread).toForm()).andExpectValidationError("ip")217 }218 @Test219 fun `don't create reply with attachment too big`() {220 replyToThread(221 post(thread).toForm(),222 attachment = multipartFile("attachment", MAX_ATTACHMENT_SIZE + 1)223 ).andExpectValidationError("attachmentTooBig", message = MAX_ATTACHMENT_SIZE.toString())224 }225 @Test226 fun `don't create reply without attachment and body`() {227 replyToThread(post(thread).toForm(), attachment = null)228 .andExpectValidationError("attachmentOrNonEmptyBody")229 }230 }231 @Nested232 @DisplayName("get thread")233 inner class GetThread {234 private fun getThread() = mockMvc.get(235 "${Mappings.API_ROOT_THREADS}/${Mappings.PATH_VARIABLE_THREAD}",236 board.label,237 thread.threadNumber238 ) { setUp() }239 @Test240 fun `get existing thread`() {241 every { threadFacade.getThread(ofType(ThreadDto::class)) } returns thread.toDto()242 .apply {243 replies = listOf(post(thread, postNumber = 2L).toDto(), post(thread, postNumber = 3L).toDto())244 }245 val response = getThread().andExpect {246 status { isOk() }247 jsonPath("$.originalPost.thread") { doesNotExist() }248 jsonPath("$.originalPost.ip") { doesNotExist() }249 jsonPath("$.replies[*].thread") { doesNotExist() }250 jsonPath("$.replies[*].ip") { doesNotExist() }251 }.andReturnConverted<ThreadDto>()252 response.replies.shouldNotBeEmpty()253 }254 @Test255 fun `don't get non-existing thread`() {256 every { threadFacade.resolveThread(board.label, thread.threadNumber) } throws ThreadNotFoundException()257 getThread().andExpect { status { isNotFound() } }258 }259 }260 @Test261 fun `get new replies for thread`() {262 val lastPostNumber = slot<Long>()263 every {264 threadFacade.getNewReplies(265 ofType(ThreadDto::class),266 capture(lastPostNumber)267 )268 } returns listOf(post(thread).toDto(), post(thread).toDto())269 mockMvc.get(270 "${Mappings.API_ROOT_THREADS}/${Mappings.PATH_VARIABLE_THREAD}/new-replies?lastPost=3",271 board.label,272 thread.threadNumber273 ) { setUp() }.andExpect {274 status { isOk() }275 jsonPath("$[*].thread") { doesNotExist() }276 jsonPath("$[*].ip") { doesNotExist() }277 }.andReturnConverted<List<PostDto>>() shouldHaveSize 2278 lastPostNumber.captured shouldBe 3279 }280 @Test281 @WithMockJardUser(UserAuthority.TOGGLE_STICKY_THREAD)282 fun `toggle sticky on thread`() {283 every { threadFacade.toggleStickyOnThread(ofType(ThreadDto::class)) } just Runs284 mockMvc.patch(285 "${Mappings.API_ROOT_THREADS}/${Mappings.PATH_VARIABLE_THREAD}/sticky",286 board.label,287 thread.threadNumber288 ) { setUp() }.andExpect { status { isOk() } }289 }290 @Test291 @WithMockJardUser(UserAuthority.TOGGLE_LOCK_THREAD)292 fun `toggle lock on thread`() {293 every { threadFacade.toggleLockOnThread(ofType(ThreadDto::class)) } just Runs294 mockMvc.patch(295 "${Mappings.API_ROOT_THREADS}/${Mappings.PATH_VARIABLE_THREAD}/lock",296 board.label,297 thread.threadNumber298 ) { setUp() }.andExpect { status { isOk() } }299 }300 @Nested301 @DisplayName("delete post")302 @WithMockJardUser(UserAuthority.DELETE_POST)303 inner class DeletePost {304 private fun deletePost(postNumber: Long) = mockMvc.delete(305 "${Mappings.API_ROOT_THREADS}/${Mappings.PATH_VARIABLE_THREAD}/${Mappings.PATH_VARIABLE_POST}",306 board.label,307 thread.threadNumber,308 postNumber309 ) { setUp() }310 @Test311 fun `delete post`() {312 every { threadFacade.deletePost(ofType(ThreadDto::class), ofType(PostDto::class)) } just Runs313 deletePost(post.postNumber).andExpect { status { isOk() } }314 }315 @Test316 fun `don't delete post on IO exception`() {317 every { threadFacade.deletePost(ofType(ThreadDto::class), ofType(PostDto::class)) } throws IOException()318 deletePost(post.postNumber).andExpect { status { isBadRequest() } }319 }320 }321 @Nested322 @DisplayName("delete own post")323 inner class DeleteOwnPost {324 private fun deleteOwnPost(postNumber: Long, deletionCode: String = "abcde") = mockMvc.delete(325 "${Mappings.API_ROOT_THREADS}/${Mappings.PATH_VARIABLE_THREAD}/${Mappings.PATH_VARIABLE_POST}/delete-own",326 board.label,327 thread.threadNumber,328 postNumber329 ) { body(DeleteOwnPostDto(deletionCode)) }330 @Test331 fun `delete own post`() {332 val deletionCode = slot<String>()333 every { postFacade.deleteOwnPost(ofType(PostDto::class), capture(deletionCode)) } just Runs334 deleteOwnPost(post.postNumber).andExpect { status { isOk() } }335 deletionCode.captured shouldBe "abcde"336 }337 @Test338 fun `don't delete own post with incorrect deletion code`() {339 every {340 postFacade.deleteOwnPost(341 ofType(PostDto::class),342 ofType(String::class)343 )344 } throws PropertyValidationException("")345 deleteOwnPost(post.postNumber).andExpect { status { isBadRequest() } }346 }347 @Test348 fun `don't delete own post on IO exception`() {349 every { postFacade.deleteOwnPost(ofType(PostDto::class), ofType(String::class)) } throws IOException()350 deleteOwnPost(post.postNumber).andExpect { status { isBadRequest() } }351 }352 }353}...

Full Screen

Full Screen

EntitySerializerTest.kt

Source:EntitySerializerTest.kt Github

copy

Full Screen

1/*Copyright 2021 Mecharex Kft.2This file is part of the logikaldb library.3The logikaldb library is free software: you can redistribute it and/or modify4it under the terms of the GNU Lesser General Public License as published by5the Free Software Foundation, either version 3 of the License, or6(at your option) any later version.7The logikaldb library is distributed in the hope that it will be useful,8but WITHOUT ANY WARRANTY; without even the implied warranty of9MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the10GNU Lesser General Public License for more details.11You should have received a copy of the GNU Lesser General Public License12along with the logikaldb library. If not, see <http://www.gnu.org/licenses/>.*/13package com.logikaldb.serializer14import com.logikaldb.entity.AndEntity15import com.logikaldb.entity.ConstraintEntity16import com.logikaldb.entity.ConstraintFunEntity17import com.logikaldb.entity.EqualEntity18import com.logikaldb.entity.FieldEntity19import com.logikaldb.entity.OrEntity20import com.logikaldb.entity.ValueEntity21import com.logikaldb.logikal.Logikal.equal22import io.kotest.core.spec.style.StringSpec23import io.kotest.property.Arb24import io.kotest.property.RandomSource25import io.kotest.property.Sample26import io.kotest.property.arbitrary.arb27import io.kotest.property.arbitrary.double28import io.kotest.property.arbitrary.int29import io.kotest.property.arbitrary.list30import io.kotest.property.arbitrary.map31import io.kotest.property.arbitrary.string32import io.kotest.property.forAll33class EntitySerializerTest : StringSpec({34 val underTest = EntitySerializer()35 fun createEqualEntity(randomPair: Pair<Sample<String>, Sample<Any>>): EqualEntity {36 return EqualEntity(FieldEntity(randomPair.first.value, String::class.java), ValueEntity(randomPair.second.value))37 }38 fun anyRandomValues(randomSource: RandomSource): Sequence<Sample<Any>> {39 val randomStrings = Arb.string().values(randomSource)40 val randomIntegers = Arb.int().values(randomSource)41 val randomDoubles = Arb.double().values(randomSource)42 return randomStrings + randomIntegers + randomDoubles43 }44 "A serialized and deserialized EqualEntity must be the same as the original entity" {45 val equalConstraintEntityArb = arb { randomSource ->46 val randomFields = Arb.string().values(randomSource)47 val randomValues = anyRandomValues(randomSource)48 randomFields.zip(randomValues)49 .map(::createEqualEntity)50 .map { ConstraintEntity(it) }51 }52 forAll(equalConstraintEntityArb) { equalConstraintEntity ->53 underTest.deserialize(underTest.serialize(equalConstraintEntity)) == equalConstraintEntity54 }55 }56 "A serialized and deserialized ConstraintEntity is not the same when the constraint fun is defined" {57 val constraintConstraintEntityArb = arb { randomSource ->58 val randomConstraints = Arb.string().values(randomSource)59 val randomParameters = Arb.list(Arb.string())60 .map { parameterNames -> parameterNames.map { FieldEntity(it, String::class.java) } }61 .values(randomSource)62 randomConstraints.zip(randomParameters)63 .map { ConstraintFunEntity(equal(1, 1)) }64 .map { ConstraintEntity(it) }65 }66 forAll(constraintConstraintEntityArb) { constraintConstraintEntity ->67 val convertedConstraintConstraintEntity = underTest.deserialize(underTest.serialize(constraintConstraintEntity))68 convertedConstraintConstraintEntity != constraintConstraintEntity69 }70 }71 "A serialized and deserialized AndEntity must be the same as the original entity" {72 val equalEntityArb = arb { randomSource ->73 val randomFields = Arb.string().values(randomSource)74 val randomValues = anyRandomValues(randomSource)75 randomFields.zip(randomValues)76 .map(::createEqualEntity)77 }78 val andConstraintEntityArb = arb { randomSource ->79 Arb.list(equalEntityArb, IntRange(0, 100)).values(randomSource)80 .map { AndEntity(it.value) }81 .map { ConstraintEntity(it) }82 }83 forAll(andConstraintEntityArb) { andConstraintEntity ->84 underTest.deserialize(underTest.serialize(andConstraintEntity)) == andConstraintEntity85 }86 }87 "A serialized and deserialized OrEntity must be the same as the original entity" {88 val equalEntityArb = arb { randomSource ->89 val randomFields = Arb.string().values(randomSource)90 val randomValues = anyRandomValues(randomSource)91 randomFields.zip(randomValues)92 .map(::createEqualEntity)93 }94 val orConstraintEntityArb = arb { randomSource ->95 Arb.list(equalEntityArb, IntRange(0, 100)).values(randomSource)96 .map { OrEntity(it.value) }97 .map { ConstraintEntity(it) }98 }99 forAll(orConstraintEntityArb) { orConstraintEntity ->100 underTest.deserialize(underTest.serialize(orConstraintEntity)) == orConstraintEntity101 }102 }103})...

Full Screen

Full Screen

config.kt

Source:config.kt Github

copy

Full Screen

1package io.kotest.property2import io.kotest.common.ExperimentalKotest3import io.kotest.mpp.atomics.AtomicProperty4import io.kotest.mpp.sysprop5import io.kotest.property.classifications.LabelsReporter6import io.kotest.property.classifications.StandardLabelsReporter7/**8 * Global object containing settings for property testing.9 */10object PropertyTesting {11 var maxFilterAttempts: Int by AtomicProperty {12 1013 }14 var shouldPrintShrinkSteps: Boolean by AtomicProperty {15 sysprop("kotest.proptest.output.shrink-steps", true)16 }17 var shouldPrintGeneratedValues: Boolean by AtomicProperty {18 sysprop("kotest.proptest.output.generated-values", false)19 }20 var edgecasesBindDeterminism: Double by AtomicProperty {21 sysprop("kotest.proptest.arb.edgecases-bind-determinism", 0.9)22 }23 var defaultSeed: Long? by AtomicProperty {24 sysprop("kotest.proptest.default.seed", null) { it.toLong() }25 }26 var defaultMinSuccess: Int by AtomicProperty {27 sysprop("kotest.proptest.default.min-success", Int.MAX_VALUE)28 }29 var defaultMaxFailure: Int by AtomicProperty {30 sysprop("kotest.proptest.default.max-failure", 0)31 }32 var defaultIterationCount: Int by AtomicProperty {33 sysprop("kotest.proptest.default.iteration.count", 1000)34 }35 var defaultShrinkingMode: ShrinkingMode by AtomicProperty {36 ShrinkingMode.Bounded(1000)37 }38 var defaultListeners: List<PropTestListener> by AtomicProperty {39 listOf()40 }41 var defaultEdgecasesGenerationProbability: Double by AtomicProperty {42 sysprop("kotest.proptest.arb.edgecases-generation-probability", 0.02)43 }44 var defaultOutputClassifications: Boolean by AtomicProperty {45 sysprop("kotest.proptest.arb.output.classifications", false)46 }47 var failOnSeed: Boolean by AtomicProperty {48 sysprop("kotest.proptest.seed.fail-if-set", false)49 }50 var writeFailedSeed: Boolean by AtomicProperty {51 sysprop("kotest.proptest.seed.write-failed", true)52 }53}54fun EdgeConfig.Companion.default(): EdgeConfig = EdgeConfig(55 edgecasesGenerationProbability = PropertyTesting.defaultEdgecasesGenerationProbability56)57data class PropTest(58 val seed: Long? = PropertyTesting.defaultSeed,59 val minSuccess: Int = PropertyTesting.defaultMinSuccess,60 val maxFailure: Int = PropertyTesting.defaultMaxFailure,61 val shrinkingMode: ShrinkingMode = PropertyTesting.defaultShrinkingMode,62 val iterations: Int? = null,63 val listeners: List<PropTestListener> = PropertyTesting.defaultListeners,64 val edgeConfig: EdgeConfig = EdgeConfig.default(),65 val constraints: Constraints? = null,66)67fun PropTest.toPropTestConfig() =68 PropTestConfig(69 seed = seed,70 minSuccess = minSuccess,71 maxFailure = maxFailure,72 iterations = iterations,73 shrinkingMode = shrinkingMode,74 listeners = listeners,75 edgeConfig = edgeConfig76 )77/**78 * Property Test Configuration to be used by the underlying property test runner79 *80 * @param iterations The number of iterations to run. If null either the global [PropertyTesting]'s default value81 * will be used, or the minimum iterations required for the supplied generations. Whichever is82 * greater.83 *84 * @param constraints controls the loop for properties. See [Constraints].85 */86@OptIn(ExperimentalKotest::class)87data class PropTestConfig(88 val seed: Long? = PropertyTesting.defaultSeed,89 val minSuccess: Int = PropertyTesting.defaultMinSuccess,90 val maxFailure: Int = PropertyTesting.defaultMaxFailure,91 val shrinkingMode: ShrinkingMode = PropertyTesting.defaultShrinkingMode,92 val iterations: Int? = null,93 val listeners: List<PropTestListener> = PropertyTesting.defaultListeners,94 val edgeConfig: EdgeConfig = EdgeConfig.default(),95 val outputClassifications: Boolean = PropertyTesting.defaultOutputClassifications,96 val labelsReporter: LabelsReporter = StandardLabelsReporter,97 val constraints: Constraints? = null,98)99interface PropTestListener {100 suspend fun beforeTest(): Unit = Unit101 suspend fun afterTest(): Unit = Unit102}...

Full Screen

Full Screen

Constraints.kt

Source:Constraints.kt Github

copy

Full Screen

1package io.kotest.property2import kotlin.time.Duration3import kotlin.time.TimeSource4/**5 * Controls iterations of a property test.6 */7fun interface Constraints {8 fun evaluate(): Boolean9 companion object {10 /**11 * Returns a [Constraints] that executes the property test for a fixed number of iterations.12 */13 fun iterations(k: Int) = object : Constraints {14 var count = 015 override fun evaluate(): Boolean {16 val result = count < k17 count++18 return result19 }20 }21 /**22 * Returns a [Constraints] that executes the property test for a certain duration.23 */24 fun duration(duration: Duration) = object : Constraints {25 val mark = TimeSource.Monotonic.markNow().plus(duration)26 override fun evaluate(): Boolean {27 return mark.hasNotPassedNow()28 }29 }30 }31}32fun Constraints.and(other: Constraints) = Constraints { this@and.evaluate() && other.evaluate() }33fun Constraints.or(other: Constraints) = Constraints { this@or.evaluate() || other.evaluate() }...

Full Screen

Full Screen

MinimumTest.kt

Source:MinimumTest.kt Github

copy

Full Screen

1package com.github.kommodus.constraints.definitions2import io.kotest.core.spec.style.StringSpec3import io.kotest.property.Arb4import io.kotest.property.arbitrary.int5import io.kotest.property.forAll6class MinimumTest : StringSpec({7 "detects correctly whether number is greater than expected" {8 forAll(Arb.int(), Arb.int()) { value, limit ->9 Minimum(limit, inclusive = false).check(value) == (value > limit)10 }11 }12 "detects correctly whether number is greater or equal to expected" {13 forAll(Arb.int(), Arb.int()) { value, limit ->14 Minimum(limit, inclusive = true).check(value) == (value >= limit)15 }16 }17})...

Full Screen

Full Screen

MaximumTest.kt

Source:MaximumTest.kt Github

copy

Full Screen

1package com.github.kommodus.constraints.definitions2import io.kotest.core.spec.style.StringSpec3import io.kotest.property.Arb4import io.kotest.property.arbitrary.int5import io.kotest.property.forAll6class MaximumTest : StringSpec({7 "detects correctly whether number is less than expected" {8 forAll(Arb.int(), Arb.int()) { value, limit ->9 Maximum(limit, inclusive = false).check(value) == (value < limit)10 }11 }12 "detects correctly whether number is less or equal to expected" {13 forAll(Arb.int(), Arb.int()) { value, limit ->14 Maximum(limit, inclusive = true).check(value) == (value <= limit)15 }16 }17})...

Full Screen

Full Screen

RequiredTest.kt

Source:RequiredTest.kt Github

copy

Full Screen

1package com.github.kommodus.constraints.definitions2import io.kotest.core.spec.style.StringSpec3import io.kotest.property.Arb4import io.kotest.property.arbitrary.choice5import io.kotest.property.arbitrary.long6import io.kotest.property.arbitrary.orNull7import io.kotest.property.arbitrary.string8import io.kotest.property.forAll9class RequiredTest : StringSpec({10 "detects correctly whether arbitrary value is not null" {11 forAll(Arb.choice(Arb.string().orNull(0.5), Arb.long().orNull(0.5))) { value ->12 Required<Any>().check(value) == (value != null)13 }14 }15})...

Full Screen

Full Screen

Constraints.or

Using AI Code Generation

copy

Full Screen

1val constraints = Constraints.or(constraint1, constraint2, constraint3)2val constraints = Constraints.and(constraint1, constraint2, constraint3)3val constraints = Constraints.not(constraint1)4val constraints = Constraints.all(constraint1, constraint2, constraint3)5val constraints = Constraints.any(constraint1, constraint2, constraint3)6val constraints = Constraints.never()7val constraints = Constraints.always()8val constraints = constraint1.not()9val constraints = constraint1.all(constraint2, constraint3)10val constraints = constraint1.any(constraint2, constraint3)11val constraints = Constraints.never()12val constraints = Constraints.always()13val constraints = constraint1.not()14val constraints = constraint1.all(constraint2, constraint3)

Full Screen

Full Screen

Constraints.or

Using AI Code Generation

copy

Full Screen

1val constraint1 = Constraints.between(1, 100)2val constraint2 = Constraints.between(200, 300)3val constraint3 = Constraints.between(400, 500)4val constraint4 = Constraints.between(600, 700)5val constraint5 = Constraints.between(800, 900)6val constraint6 = Constraints.between(1000, 1100)7val constraint7 = Constraints.between(1200, 1300)8val constraint8 = Constraints.between(1400, 1500)9val constraint9 = Constraints.between(1600, 1700)10val constraint10 = Constraints.between(1800, 1900)11val constraint11 = Constraints.between(2000, 2100)12val constraint12 = Constraints.between(2200, 2300)13val constraint13 = Constraints.between(2400, 2500)14val constraint14 = Constraints.between(2600, 2700)15val constraint15 = Constraints.between(2800, 2900)16val constraint16 = Constraints.between(3000, 3100)17val constraint17 = Constraints.between(3200, 3300)18val constraint18 = Constraints.between(3400, 3500)19val constraint19 = Constraints.between(3600, 3700)20val constraint20 = Constraints.between(3800, 3900)21val constraint21 = Constraints.between(4000, 4100)22val constraint22 = Constraints.between(4200, 4300)23val constraint23 = Constraints.between(4400, 4500)24val constraint24 = Constraints.between(4600, 4700)25val constraint25 = Constraints.between(4800, 4900)26val constraint26 = Constraints.between(5000, 5100)27val constraint27 = Constraints.between(5200, 5300)28val constraint28 = Constraints.between(5400, 5500)29val constraint29 = Constraints.between(5600, 5700)30val constraint30 = Constraints.between(5800, 5900)31val constraint31 = Constraints.between(6000, 6100)32val constraint32 = Constraints.between(6200, 6300)33val constraint33 = Constraints.between(6400, 6500)34val constraint34 = Constraints.between(6600, 6700)35val constraint35 = Constraints.between(6800, 6900)36val constraint36 = Constraints.between(7000, 7100)

Full Screen

Full Screen

Constraints.or

Using AI Code Generation

copy

Full Screen

1 "or" {2 forAll<Int, Int> { a, b ->3 (a > 0 || b > 0) shouldBe (Constraints.or(a > 0, b > 0))4 }5 }6 "and" {7 forAll<Int, Int> { a, b ->8 (a > 0 && b > 0) shouldBe (Constraints.and(a > 0, b > 0))9 }10 }11})12"or" {13 forAll<Int, Int> { a, b ->14 (a > 0 || b > 0) shouldBe (Constraints.or(a > 0, b > 0))15 }16}17"and" {18 forAll<Int, Int> { a, b ->19 (a > 0 && b > 0) shouldBe (Constraints.and(a > 0, b > 0))20 }21}

Full Screen

Full Screen

Constraints.or

Using AI Code Generation

copy

Full Screen

1val orConstraint = Constraint<Int> { it > 0 } or Constraint<Int> { it < 0 }2forAll(orConstraint) { i: Int -> i > 0 || i < 0 }3val andConstraint = Constraint<Int> { it > 0 } and Constraint<Int> { it < 0 }4forAll(andConstraint) { i: Int -> i > 0 && i < 0 }5val notConstraint = Constraint<Int> { it > 0 }.not()6forAll(notConstraint) { i: Int -> i < 0 }7val allConstraint = Constraints.all<Int>(Constraint<Int> { it > 0 }, Constraint<Int> { it < 0 })8forAll(allConstraint) { i: Int -> i > 0 && i < 0 }9val anyConstraint = Constraints.any<Int>(Constraint<Int> { it > 0 }, Constraint<Int> { it < 0 })10forAll(anyConstraint) { i: Int -> i > 0 || i < 0 }11val noneConstraint = Constraints.none<Int>(Constraint<Int> { it > 0 }, Constraint<Int> { it < 0 })12forAll(noneConstraint) { i: Int -> i > 0 && i < 0 }13val combinationsConstraint = Constraints.combinations<Int>(Constraint<Int> { it > 0 }, Constraint<Int> { it < 0 })14forAll(combinationsConstraint) { i: Int -> i > 0 && i < 0 }15val bothConstraint = Constraints.both(Constraint<Int> { it > 0 }, Constraint<Int> { it < 0 })16forAll(bothConstraint) { i: Int -> i > 0 && i < 0 }17val anyConstraint = Constraints.any(Constraint<Int>

Full Screen

Full Screen

Constraints.or

Using AI Code Generation

copy

Full Screen

1val config = PropertyTestingConfig(invocations = 1000)2property(config) {3forAll { a: Int, b: Int ->4}5}6val config = PropertyTestingConfig(invocations = 1000)7property(config) {8forAll { a: Int, b: Int ->9}10}11val config = PropertyTestingConfig(invocations = 1000)12property(config) {13forAll { a: Int, b: Int ->14}15}16val config = PropertyTestingConfig(invocations = 1000)17property(config) {18forAll { a: Int, b: Int ->19}20}21val config = PropertyTestingConfig(invocations = 1000)22property(config) {23forAll { a: Int, b: Int ->24}25}26val config = PropertyTestingConfig(invocations = 1000)27property(config) {28forAll { a: Int, b: Int ->29}30}31val config = PropertyTestingConfig(invocations = 1000)32property(config) {33forAll { a: Int, b: Int ->34}35}36val config = PropertyTestingConfig(invocations = 1000)37property(config) {38forAll { a: Int, b: Int ->39}40}41val config = PropertyTestingConfig(invocations = 1000)42property(config) {43forAll { a: Int, b: Int ->44}45}

Full Screen

Full Screen

Constraints.or

Using AI Code Generation

copy

Full Screen

1val intGen = Gen.int().filter { it > 0 }2val stringGen = Gen.string().filter { it.length > 0 }3val constraint = Constraints.or(intGen, stringGen)4val gen = Gen.create(constraint)5gen.generate()6gen.generate()7gen.generate()8gen.generate()9gen.generate()10gen.generate()11gen.generate()12gen.generate()

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Kotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful