How to use String.shouldBeUUID method of io.kotest.matchers.string.matchers class

Best Kotest code snippet using io.kotest.matchers.string.matchers.String.shouldBeUUID

matchers.kt

Source:matchers.kt Github

copy

Full Screen

1package io.kotest.matchers.string2import io.kotest.assertions.failure3import io.kotest.assertions.show.show4import io.kotest.matchers.Matcher5import io.kotest.matchers.MatcherResult6import io.kotest.matchers.neverNullMatcher7import io.kotest.matchers.should8import io.kotest.matchers.shouldNot9import io.kotest.matchers.string.UUIDVersion.ANY10import kotlin.contracts.ExperimentalContracts11import kotlin.contracts.contract12import kotlin.text.RegexOption.IGNORE_CASE13fun String?.shouldContainOnlyDigits() = this should containOnlyDigits()14fun String?.shouldNotContainOnlyDigits() = this shouldNot containOnlyDigits()15fun containOnlyDigits() = neverNullMatcher<String> { value ->16 MatcherResult(17 value.toCharArray().all { it in '0'..'9' },18 "${value.show().value} should contain only digits",19 "${value.show().value} should not contain only digits")20}21fun String?.shouldContainADigit() = this should containADigit()22fun String?.shouldNotContainADigit() = this shouldNot containADigit()23fun containADigit() = neverNullMatcher<String> { value ->24 MatcherResult(25 value.toCharArray().any { it in '0'..'9' },26 "${value.show().value} should contain at least one digit",27 "${value.show().value} should not contain any digits")28}29infix fun String?.shouldContainOnlyOnce(substr: String) = this should containOnlyOnce(substr)30infix fun String?.shouldNotContainOnlyOnce(substr: String) = this shouldNot containOnlyOnce(substr)31fun containOnlyOnce(substring: String) = neverNullMatcher<String> { value ->32 MatcherResult(33 value.indexOf(substring) >= 0 && value.indexOf(substring) == value.lastIndexOf(substring),34 "${value.show().value} should contain the substring ${substring.show().value} exactly once",35 "${value.show().value} should not contain the substring ${substring.show().value} exactly once"36 )37}38fun String?.shouldBeLowerCase() = this should beLowerCase()39fun String?.shouldNotBeLowerCase() = this shouldNot beLowerCase()40fun beLowerCase() = neverNullMatcher<String> { value ->41 MatcherResult(42 value.toLowerCase() == value,43 "${value.show().value} should be lower case",44 "${value.show().value} should not should be lower case")45}46fun String?.shouldBeUpperCase() = this should beUpperCase()47fun String?.shouldNotBeUpperCase() = this shouldNot beUpperCase()48fun beUpperCase() = neverNullMatcher<String> { value ->49 MatcherResult(50 value.toUpperCase() == value,51 "${value.show().value} should be upper case",52 "${value.show().value} should not should be upper case")53}54fun String?.shouldBeEmpty() = this should beEmpty()55fun String?.shouldNotBeEmpty() = this shouldNot beEmpty()56fun beEmpty() = neverNullMatcher<String> { value ->57 MatcherResult(58 value.isEmpty(),59 "${value.show().value} should be empty",60 "${value.show().value} should not be empty")61}62infix fun String?.shouldHaveSameLengthAs(other: String) = this should haveSameLengthAs(other)63infix fun String?.shouldNotHaveSameLengthAs(other: String) = this shouldNot haveSameLengthAs(other)64fun haveSameLengthAs(other: String) = neverNullMatcher<String> { value ->65 MatcherResult(66 value.length == other.length,67 "${value.show().value} should have the same length as ${other.show().value}",68 "${value.show().value} should not have the same length as ${other.show().value}")69}70fun String?.shouldBeSingleLine() = this should haveLineCount(1)71fun String?.shouldNotBeSingleLine() = this shouldNot haveLineCount(1)72infix fun String?.shouldHaveLineCount(count: Int) = this should haveLineCount(count)73infix fun String?.shouldNotHaveLineCount(count: Int) = this shouldNot haveLineCount(count)74/**75 * Match on the number of newlines in a string.76 *77 * This will count both "\n" and "\r\n", and so is not dependant on the system line separator.78 */79fun haveLineCount(count: Int) = neverNullMatcher<String> { value ->80 // plus one because we always have one more line than the new line character81 val lines = if (value.isEmpty()) 0 else value.count { it == '\n' } + 182 MatcherResult(83 lines == count,84 { "${value.show().value} should have $count lines but had $lines" },85 { "${value.show().value} should not have $count lines" }86 )87}88fun String?.shouldBeBlank() = this should beBlank()89fun String?.shouldNotBeBlank() = this shouldNot beBlank()90fun containOnlyWhitespace() = beBlank()91fun beBlank() = neverNullMatcher<String> { value ->92 MatcherResult(93 value.isBlank(),94 { "${value.show().value} should contain only whitespace" },95 { "${value.show().value} should not contain only whitespace" }96 )97}98infix fun String?.shouldContainIgnoringCase(substr: String) = this should containIgnoringCase(99 substr)100infix fun String?.shouldNotContainIgnoringCase(substr: String) = this shouldNot containIgnoringCase(101 substr)102fun containIgnoringCase(substr: String) = neverNullMatcher<String> { value ->103 MatcherResult(104 value.toLowerCase().indexOf(substr.toLowerCase()) >= 0,105 { "${value.show().value} should contain the substring ${substr.show().value} (case insensitive)" },106 { "${value.show().value} should not contain the substring ${substr.show().value} (case insensitive)" }107 )108}109infix fun String?.shouldContain(regex: Regex) = this should contain(regex)110infix fun String?.shouldNotContain(regex: Regex) = this shouldNot contain(regex)111fun contain(regex: Regex) = neverNullMatcher<String> { value ->112 MatcherResult(113 value.contains(regex),114 { "${value.show().value} should contain regex $regex" },115 { "${value.show().value} should not contain regex $regex" })116}117fun String?.shouldContainInOrder(vararg substrings: String) = this should containInOrder(*substrings)118fun String?.shouldNotContainInOrder(vararg substrings: String) = this shouldNot containInOrder(*substrings)119fun containInOrder(vararg substrings: String) = neverNullMatcher<String> { value ->120 fun recTest(str:String, subs:List<String>):Boolean =121 subs.isEmpty() || str.indexOf(subs.first()).let{ it > -1 && recTest(str.substring(it + 1), subs.drop(1)) }122 MatcherResult(123 recTest(value, substrings.filter{ it.isNotEmpty() }),124 { "${value.show().value} should include substrings ${substrings.show().value} in order" },125 { "${value.show().value} should not include substrings ${substrings.show().value} in order" })126}127infix fun String?.shouldContain(substr: String) = this should contain(substr)128infix fun String?.shouldNotContain(substr: String) = this shouldNot contain(substr)129fun contain(substr: String) = include(substr)130infix fun String?.shouldInclude(substr: String) = this should include(substr)131infix fun String?.shouldNotInclude(substr: String) = this shouldNot include(substr)132fun include(substr: String) = neverNullMatcher<String> { value ->133 MatcherResult(134 value.contains(substr),135 "${value.show().value} should include substring ${substr.show().value}",136 "${value.show().value} should not include substring ${substr.show().value}")137}138infix fun String?.shouldHaveMaxLength(length: Int) = this should haveMaxLength(length)139infix fun String?.shouldNotHaveMaxLength(length: Int) = this shouldNot haveMaxLength(140 length)141fun haveMaxLength(length: Int) = neverNullMatcher<String> { value ->142 MatcherResult(143 value.length <= length,144 "${value.show().value} should have maximum length of $length",145 "${value.show().value} should have minimum length of ${length - 1}")146}147infix fun String?.shouldHaveMinLength(length: Int) = this should haveMinLength(length)148infix fun String?.shouldNotHaveMinLength(length: Int) = this shouldNot haveMinLength(length)149fun haveMinLength(length: Int) = neverNullMatcher<String> { value ->150 MatcherResult(151 value.length >= length,152 "${value.show().value} should have minimum length of $length",153 "${value.show().value} should have maximum length of ${length - 1}")154}155fun String?.shouldHaveLengthBetween(min: Int, max: Int) = this should haveLengthBetween(min, max)156fun String?.shouldNotHaveLengthBetween(min: Int, max: Int) = this shouldNot haveLengthBetween(min, max)157fun haveLengthBetween(min: Int, max: Int): Matcher<String?> {158 require(min <= max)159 return neverNullMatcher { value ->160 MatcherResult(161 value.length in min..max,162 "${value.show().value} should have length in $min..$max but was ${value.length}",163 "${value.show().value} should not have length between $min and $max")164 }165}166fun String?.shouldHaveLengthIn(range: IntRange) = this should haveLengthIn(range)167fun String?.shouldNotHaveLengthIn(range: IntRange) = this shouldNot haveLengthIn(range)168fun haveLengthIn(range: IntRange): Matcher<String?> {169 return neverNullMatcher { value ->170 MatcherResult(171 value.length in range,172 "${value.show().value} should have length in $range but was ${value.length}",173 "${value.show().value} should not have length between $range")174 }175}176infix fun String?.shouldHaveLength(length: Int) = this should haveLength(length)177infix fun String?.shouldNotHaveLength(length: Int) = this shouldNot haveLength(length)178infix fun String?.shouldMatch(regex: String) = this should match(regex)179infix fun String?.shouldMatch(regex: Regex) = this should match(regex)180infix fun String?.shouldNotMatch(regex: String) = this shouldNot match(regex)181infix fun String?.shouldEndWith(suffix: String) = this should endWith(suffix)182infix fun String?.shouldNotEndWith(suffix: String) = this shouldNot endWith(suffix)183infix fun String?.shouldStartWith(prefix: String) = this should startWith(prefix)184infix fun String?.shouldNotStartWith(prefix: String) = this shouldNot startWith(prefix)185/**186 * Asserts that [this] is equal to [other] (ignoring case)187 *188 * Verifies that this string is equal to [other], ignoring case.189 * Opposite of [shouldNotBeEqualIgnoringCase]190 *191 * ```192 * "foo" shouldBeEqualIgnoringCase "FoO" // Assertion passes193 *194 * "foo" shouldBeEqualIgnoringCase "BaR" // Assertion fails195 * ```196 *197 * @see [shouldNotBeEqualIgnoringCase]198 * @see [beEqualIgnoringCase]199 */200infix fun String?.shouldBeEqualIgnoringCase(other: String) = this should beEqualIgnoringCase( other)201/**202 * Asserts that [this] is NOT equal to [other] (ignoring case)203 *204 * Verifies that this string is NOT equal to [other], ignoring case.205 * Opposite of [shouldBeEqualIgnoringCase]206 *207 * ```208 * "foo" shouldNotBeEqualIgnoringCase "FoO" // Assertion fails209 * "foo" shouldNotBeEqualIgnoringCase "foo" // Assertion fails210 *211 * "foo" shouldNotBeEqualIgnoringCase "bar" // Assertion passes212 *213 * ```214 *215 * @see [shouldBeEqualIgnoringCase]216 * @see [beEqualIgnoringCase]217 */218infix fun String?.shouldNotBeEqualIgnoringCase(other: String) = this shouldNot beEqualIgnoringCase( other)219/**220 * Matcher that matches strings that are equal when case is not considered221 *222 * Verifies that a specific String is equal to another String when case is not considered.223 *224 * ```225 * "foo" should beEqualIgnoringCase("FoO") // Assertion passes226 *227 * "bar shouldNot beEqualIgnoringCase("BoB") // Assertion passes228 *229 * ```230 *231 */232fun beEqualIgnoringCase(other: String) = neverNullMatcher<String> { value ->233 MatcherResult(234 value.equals(other, ignoreCase = true),235 "${value.show().value} should be equal ignoring case ${other.show().value}",236 "${value.show().value} should not be equal ignoring case ${other.show().value}"237 )238}239/**240 * Assert that string should be truthy.241 *242 * Verifies that string is equal to one of the values: ["true", "yes", "y", "1"].243 * Assert is not case sensitive.244 *245 *246 * ```247 * "1".shouldBeTruthy() // Assertion passes248 * "YeS".shouldBeTruthy() // Assertion passes249 * "Y".shouldBeTruthy() // Assertion passes250 *251 * "no".shouldBeTruthy() // Assertion fails252 *253 * ```254 */255fun String?.shouldBeTruthy() = this should beTruthy()256/**257 * Assert that string should be falsy.258 *259 * Verifies that string is equal to one of the values: ["false", "no", "n", "0"].260 * Assert is not case sensitive.261 *262 *263 * ```264 * "0".shouldBeFalsy() // Assertion passes265 * "No".shouldBeFalsy() // Assertion passes266 * "n".shouldBeFalsy() // Assertion passes267 *268 * "yes".shouldBeFalsy() // Assertion fails269 *270 * ```271 */272fun String?.shouldBeFalsy() = this should beFalsy()273private val truthyValues = listOf("true", "yes", "y", "1")274private val falsyValues = listOf("false", "no", "n", "0")275/**276 * Matcher checks that string is truthy.277 *278 * Verifies that this string is equal to one of the values: ["true", "yes", "y", "1"].279 * Matcher is not case sensitive.280 *281 *282 * ```283 * "1" should beTruthy() // Assertion passes284 * "YeS" should beTruthy() // Assertion passes285 * "Y" should beTruthy() // Assertion passes286 *287 * "no" should beTruthy() // Assertion fails288 * "yes" shouldNot beTruthy() // Assertion fails289 *290 * ```291 */292fun beTruthy() = object : Matcher<String?> {293 override fun test(value: String?) = MatcherResult(294 truthyValues.any { it.equals(value, ignoreCase = true) },295 { """${value.show().value} should be equal (ignoring case) to one of: $truthyValues""" },296 { """${value.show().value} should not be equal (ignoring case) to one of: $truthyValues""" }297 )298}299/**300 * Matcher checks that string is falsy.301 *302 * Verifies that this string is equal to one of the values: ["false", "no", "n", "0"].303 * Matcher is not case sensitive.304 *305 *306 * ```307 * "0" should beFalsy() // Assertion passes308 * "No" should beFalsy() // Assertion passes309 * "n" should beFalsy() // Assertion passes310 *311 * "yes" should beFalsy() // Assertion fails312 * "no" shouldNot beFalsy() // Assertion fails313 *314 * ```315 */316fun beFalsy(): Matcher<String?> = object : Matcher<String?> {317 override fun test(value: String?): MatcherResult {318 return MatcherResult(319 falsyValues.any { it.equals(value, ignoreCase = true) },320 { """${value.show().value} should be equal (ignoring case) to one of: $falsyValues""" },321 { """${value.show().value} should not be equal (ignoring case) to one of: $falsyValues""" }322 )323 }324}325enum class UUIDVersion(326 val uuidRegex: Regex327) {328 ANY("[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}".toRegex(IGNORE_CASE)),329 V1("[0-9a-f]{8}-[0-9a-f]{4}-[1][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}".toRegex(IGNORE_CASE)),330 V2("[0-9a-f]{8}-[0-9a-f]{4}-[2][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}".toRegex(IGNORE_CASE)),331 V3("[0-9a-f]{8}-[0-9a-f]{4}-[3][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}".toRegex(IGNORE_CASE)),332 V4("[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}".toRegex(IGNORE_CASE)),333 V5("[0-9a-f]{8}-[0-9a-f]{4}-[5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}".toRegex(IGNORE_CASE));334}335/**336 * Asserts that this String is a valid UUID337 *338 * Opposite of [shouldNotBeUUID]339 *340 * Verifies that this string is a valid UUID as per RFC4122. Version depends on [version]. By default, all versions341 * (v1 through v5) are matched. A special attention is necessary for the NIL UUID (an UUID with all zeros),342 * which is considered a valid UUID. By default it's matched as valid.343 *344 * ```345 * "123e4567-e89b-12d3-a456-426655440000".shouldBeUUID(version = ANY) // Assertion passes346 * "123e4567-e89b-12d3-a456-426655440000".shouldBeUUID(version = V4) // Assertion Fails (is V1 UUID)347 * "123e4567e89b12d3a456426655440000".shouldBeUUID() // Assertion fails348 * "00000000-0000-0000-0000-000000000000".shouldBeUUID(considerNilValid = true) // Assertion passes349 *350 * ```351 *352 * @see [RFC4122] https://tools.ietf.org/html/rfc4122353 */354fun String.shouldBeUUID(355 version: UUIDVersion = ANY,356 considerNilValid: Boolean = true357) = this should beUUID(version, considerNilValid)358/**359 * Asserts that this String is NOT a valid UUID360 *361 * Opposite of [shouldBeUUID]362 *363 * Verifies that this string is a NOT valid UUID as per RFC4122. Version depends on [version]. By default, all versions364 * (v1 through v5) are matched. A special attention is necessary for the NIL UUID (an UUID with all zeros),365 * which is considered a valid UUID. By default it's matched as valid.366 *367 * ```368 * "123e4567-e89b-12d3-a456-426655440000".shouldNotBeUUID(version = ANY) // Assertion fails369 * "123e4567e89b12d3a456426655440000".shouldNotBeUUID() // Assertion passes370 * "00000000-0000-0000-0000-000000000000".shouldNotBeUUID(considerNilValid = true) // Assertion fails371 *372 * ```373 *374 * @see [RFC4122] https://tools.ietf.org/html/rfc4122375 */376fun String.shouldNotBeUUID(377 version: UUIDVersion = ANY,378 considerNilValid: Boolean = true379) = this shouldNot beUUID(version, considerNilValid)380/**381 * Matcher that verifies if a String is an UUID382 *383 *384 * Verifies that a string is a valid UUID as per RFC4122. Version depends on [version]. By default, all versions385 * (v1 through v5) are matched. A special attention is necessary for the NIL UUID (an UUID with all zeros),386 * which is considered a valid UUID. By default it's matched as valid.387 *388 *389 * @see [RFC4122] https://tools.ietf.org/html/rfc4122390 * @see shouldBeUUID391 * @see shouldNotBeUUID392 */393fun beUUID(394 version: UUIDVersion = ANY,395 considerNilValid: Boolean = true396) = object : Matcher<String> {397 override fun test(value: String) = MatcherResult(398 value.matches(version.uuidRegex) || (considerNilValid && value.isNilUUID()),399 "String $value is not an UUID ($version), but should be",400 "String $value is an UUID ($version), but shouldn't be"401 )402 private fun String.isNilUUID() = this == "00000000-0000-0000-0000-000000000000"403}404@OptIn(ExperimentalContracts::class)405fun String?.shouldBeInteger(radix: Int = 10): Int {406 contract {407 returns() implies (this@shouldBeInteger != null)408 }409 return when (this) {410 null -> throw failure("String is null, but it should be integer.")411 else -> when (val integer = this.toIntOrNull(radix)) {412 null -> throw failure("String '$this' is not integer, but it should be.")413 else -> integer414 }415 }416}...

Full Screen

Full Screen

OpenConsultingReservationTest.kt

Source:OpenConsultingReservationTest.kt Github

copy

Full Screen

1/*******************************************************************************2 * Copyright (C) 2021, Stefano Braggion, Alessia Cerami, Andrea Giordano, Nicola Lasagni.3 *4 * This file is part of Fausto Coppi Lab Automation, and is distributed under the terms of the5 * GNU General Public License, as described in the file LICENSE in the6 * Fausto Coppi Lab Automation distribution's top directory.7 *8 ******************************************************************************/910package it.unibo.lss.fcla.reservation.domain.entities.reservation1112import io.kotest.assertions.throwables.shouldNotThrowAny13import io.kotest.assertions.throwables.shouldThrow14import io.kotest.core.spec.style.FreeSpec15import io.kotest.matchers.shouldBe16import io.kotest.matchers.string.shouldBeUUID17import io.kotest.matchers.string.shouldNotBeEmpty18import it.unibo.lss.fcla.reservation.domain.entities.exceptions.FreelancerIdCannotBeEmpty19import it.unibo.lss.fcla.reservation.domain.entities.exceptions.OpenReservationMustNotHavePastDate20import java.util.Calendar21import java.util.UUID2223/**24 * @project fausto-coppi-lab-automation25 * @author Alessia Cerami and Andrea Giordano26 */2728class OpenConsultingReservationTest : FreeSpec({29 val calendar = Calendar.getInstance()30 val year = 202331 val invalidYear = 202032 val feb = Calendar.FEBRUARY33 val day = 2534 val freelancerId = UUID.randomUUID()35 calendar.set(year, feb, day)36 val validDateOfConsulting = calendar.time37 val openConsultingReservationId = UUID.randomUUID()38 val invalidFreelancer = UUID(0, 0)3940 var reservation = OpenConsultingReservation(41 validDateOfConsulting,42 freelancerId,43 openConsultingReservationId44 )4546 "An Open consulting reservation should" - {47 "have a freelancer that make a consulting and a valid date" - {48 calendar.set(invalidYear, feb, day)49 val invalidDateOfConsulting = calendar.time50 shouldNotThrowAny {51 reservation = OpenConsultingReservation(52 validDateOfConsulting,53 freelancerId,54 openConsultingReservationId55 )56 }5758 shouldThrow<FreelancerIdCannotBeEmpty> {59 OpenConsultingReservation(60 validDateOfConsulting,61 invalidFreelancer,62 openConsultingReservationId63 )64 }65 shouldThrow<OpenReservationMustNotHavePastDate> {66 OpenConsultingReservation(67 invalidDateOfConsulting,68 freelancerId,69 openConsultingReservationId70 )71 }72 }73 "not to be empty" - {74 reservation.id.toString().shouldBeUUID()75 reservation.id.toString().shouldNotBeEmpty()76 }77 "have correct UUID" - {78 reservation.id.toString().shouldBeUUID()79 reservation.id.toString().shouldNotBeEmpty()80 reservation.id.shouldBe(openConsultingReservationId)81 }82 "be named as requested" - {83 assert(84 reservation.toString() ==85 "Reservation consulting {$openConsultingReservationId} with freelancerId: " +86 "$freelancerId in date $validDateOfConsulting"87 )88 }8990 "A Member should" - {91 "be able to update correctly the date of a reservation" - {92 calendar.set(year, feb, 26)93 val newDateOfReservation = calendar.time94 val newReservation = reservation.updateDateOfConsulting(newDateOfReservation)95 println("test di correttezza valori")96 println("NewDate $newDateOfReservation")97 newReservation.freelancerId.value.shouldBe(freelancerId)98 newReservation.date.shouldBe(newDateOfReservation)99 newReservation.id.shouldBe(openConsultingReservationId)100 }101 "not to be able to update a reservation with an invalid date" - {102 calendar.set(invalidYear, feb, day)103 val invalidDateOfConsulting = calendar.time104 shouldThrow<OpenReservationMustNotHavePastDate> {105 reservation.updateDateOfConsulting(invalidDateOfConsulting)106 }107 }108 "be able to update the freelancer of a reservation" - {109 val newFreelancerId = UUID.randomUUID()110 val updatedFreelancer = reservation.updateFreelancerOfConsulting(newFreelancerId)111 updatedFreelancer.freelancerId.value.shouldBe(newFreelancerId)112 }113 "not to be able to update a reservation with an invalid freelancer" - {114 shouldThrow<FreelancerIdCannotBeEmpty> {115 reservation.updateFreelancerOfConsulting(invalidFreelancer)116 }117 }118 }119 }120}) ...

Full Screen

Full Screen

OpenWorkoutReservationTest.kt

Source:OpenWorkoutReservationTest.kt Github

copy

Full Screen

1/*******************************************************************************2 * Copyright (C) 2021, Stefano Braggion, Alessia Cerami, Andrea Giordano, Nicola Lasagni.3 *4 * This file is part of Fausto Coppi Lab Automation, and is distributed under the terms of the5 * GNU General Public License, as described in the file LICENSE in the6 * Fausto Coppi Lab Automation distribution's top directory.7 *8 ******************************************************************************/910package it.unibo.lss.fcla.reservation.domain.entities.reservation1112import io.kotest.assertions.throwables.shouldNotThrowAny13import io.kotest.assertions.throwables.shouldThrow14import io.kotest.core.spec.style.FreeSpec15import io.kotest.matchers.shouldBe16import io.kotest.matchers.string.shouldBeUUID17import io.kotest.matchers.string.shouldNotBeEmpty18import it.unibo.lss.fcla.reservation.domain.entities.exceptions.AimCannotBeEmpty19import it.unibo.lss.fcla.reservation.domain.entities.exceptions.OpenReservationMustNotHavePastDate20import java.util.Calendar21import java.util.UUID2223/**24 * @project fausto-coppi-lab-automation25 * @author Alessia Cerami and Andrea Giordano26 */2728class OpenWorkoutReservationTest : FreeSpec({29 val calendar = Calendar.getInstance()30 val year = 202331 val invalidYear = 202032 val feb = Calendar.FEBRUARY33 val day = 2534 val aim = "recovery"35 calendar.set(year, feb, day)36 val validDateOfConsulting = calendar.time37 val openWorkoutReservationId = UUID.randomUUID()3839 var reservation = OpenWorkoutReservation(40 aim,41 validDateOfConsulting,42 openWorkoutReservationId43 )4445 "An Open consulting reservation should" - {46 "have an aim and a valid date" - {47 calendar.set(invalidYear, feb, day)48 val invalidWorkoutDate = calendar.time4950 shouldNotThrowAny {51 val myReservation = OpenWorkoutReservation(52 aim,53 validDateOfConsulting,54 openWorkoutReservationId55 )56 println(myReservation)57 }58 shouldThrow<AimCannotBeEmpty> {59 OpenWorkoutReservation(60 "",61 validDateOfConsulting,62 openWorkoutReservationId63 )64 }65 shouldThrow<OpenReservationMustNotHavePastDate> {66 OpenWorkoutReservation(67 aim,68 invalidWorkoutDate,69 openWorkoutReservationId70 )71 }72 }73 "not to be empty" - {74 reservation.id.toString().shouldBeUUID()75 reservation.id.toString().shouldNotBeEmpty()76 }77 "have correct UUID" - {78 reservation.id.toString().shouldNotBeEmpty()79 reservation.id.shouldBe(openWorkoutReservationId)80 }81 "be named as requested" - {82 reservation.toString().shouldBe(83 "Reservation consulting {$openWorkoutReservationId} with aim: " +84 "$aim in date $validDateOfConsulting"85 )86 }8788 "A Member should" - {89 "be able to update correctly the date of a reservation" - {90 calendar.set(year, feb, 26)91 val newDateOfReservation = calendar.time92 val newReservation = reservation.updateWorkoutReservationDate(newDateOfReservation)93 newReservation.aim.value.shouldBe(aim)94 newReservation.date.shouldBe(newDateOfReservation)95 newReservation.id.shouldBe(openWorkoutReservationId)96 }97 "be able to update the aim of a reservation" - {98 val newAim = "Strengthening"99 val updatedFreelancer = reservation.updateWorkoutReservationAim(newAim)100 updatedFreelancer.aim.value.shouldBe(newAim)101 }102 "not to be able to update a reservation with an invalid aim" - {103 shouldThrow<AimCannotBeEmpty> {104 reservation.updateWorkoutReservationAim("")105 }106 }107 }108 }109}) ...

Full Screen

Full Screen

PropertySpec.kt

Source:PropertySpec.kt Github

copy

Full Screen

1package ru.iopump.qa.sample.property2import com.github.f4b6a3.uuid.UuidCreator3import io.kotest.core.spec.style.FreeSpec4import io.kotest.matchers.booleans.shouldBeTrue5import io.kotest.matchers.shouldBe6import io.kotest.matchers.string.UUIDVersion7import io.kotest.matchers.string.shouldBeUUID8import io.kotest.property.Arb9import io.kotest.property.Exhaustive10import io.kotest.property.arbitrary.int11import io.kotest.property.arbitrary.withEdgecases12import io.kotest.property.checkAll13import io.kotest.property.exhaustive.andNull14import io.kotest.property.exhaustive.enum15import io.kotest.property.forAll16import java.util.*17import kotlin.math.sqrt18class PropertySpec : FreeSpec() {19 init {20 "Basic theorem of arithmetic. Any number can be factorized to list of prime" {21 /*1*/Arb.int(2..Int.MAX_VALUE).withEdgecases(2, Int.MAX_VALUE).forAll(1000) { number ->22 val primeFactors = number.primeFactors23 println("#${attempts()} Source number '$number' = $primeFactors")24 /*2*/primeFactors.all(Int::isPrime) && primeFactors.reduce(Int::times) == number25 }26 /*3*/Arb.int(2..Int.MAX_VALUE).checkAll(1000) { number ->27 val primeFactors = number.primeFactors28 println("#${attempts()} Source number '$number' = $primeFactors")29 /*4*/primeFactors.onEach { it.isPrime.shouldBeTrue() }.reduce(Int::times) shouldBe number30 }31 }32 "UUIDVersion should be matched with regexp" {33 /*1*/Exhaustive.enum<UUIDVersion>().andNull().checkAll { uuidVersion ->34 /*2*/uuidVersion.generateUuid().toString()35 /*3*/.shouldBeUUID(uuidVersion ?: UUIDVersion.ANY)36 .also { println("${attempts()} $uuidVersion: $it") }37 }38 }39 }40}41val Int.isPrime get() = toBigInteger().isProbablePrime(1)42val Int.primeFactors: Collection<Int>43 get() {44 // Array that contains all the prime factors of given number.45 val arr: ArrayList<Int> = arrayListOf()46 var n = this47 if (n in (0..1)) throw IllegalArgumentException("Factorized number must be grater then 1")48 // At first check for divisibility by 2. add it in arr till it is divisible49 while (n % 2 == 0) {50 arr.add(2)51 n /= 252 }53 val squareRoot = sqrt(n.toDouble()).toInt()54 // Run loop from 3 to square root of n. Check for divisibility by i. Add i in arr till it is divisible by i.55 for (i in 3..squareRoot step 2) {56 while (n % i == 0) {57 arr.add(i)58 n /= i59 }60 }61 // If n is a prime number greater than 2.62 if (n > 2) {63 arr.add(n)64 }65 return arr66 }67/** Using [uuid-creator](https://github.com/f4b6a3/uuid-creator) */68fun UUIDVersion?.generateUuid(): UUID =69 when (this) {70 null -> UUID.randomUUID()71 UUIDVersion.ANY -> UUID.randomUUID()72 UUIDVersion.V1 -> UuidCreator.getTimeBased()73 UUIDVersion.V2 -> UuidCreator.getDceSecurity(1, 1)74 UUIDVersion.V3 -> UuidCreator.getNameBasedMd5("666")75 UUIDVersion.V4 -> UuidCreator.getRandomBased()76 UUIDVersion.V5 -> UuidCreator.getNameBasedSha1("666")77 }...

Full Screen

Full Screen

CloseConsultingReservationTest.kt

Source:CloseConsultingReservationTest.kt Github

copy

Full Screen

1/*******************************************************************************2 * Copyright (C) 2021, Stefano Braggion, Alessia Cerami, Andrea Giordano, Nicola Lasagni.3 *4 * This file is part of Fausto Coppi Lab Automation, and is distributed under the terms of the5 * GNU General Public License, as described in the file LICENSE in the6 * Fausto Coppi Lab Automation distribution's top directory.7 *8 ******************************************************************************/910package it.unibo.lss.fcla.reservation.domain.entities.reservation1112import io.kotest.assertions.throwables.shouldThrow13import io.kotest.core.spec.style.FreeSpec14import io.kotest.matchers.shouldBe15import io.kotest.matchers.string.shouldBeUUID16import io.kotest.matchers.string.shouldNotBeEmpty17import it.unibo.lss.fcla.reservation.domain.entities.exceptions.FreelancerIdCannotBeEmpty18import java.util.Calendar19import java.util.UUID2021/**22 * @project fausto-coppi-lab-automation23 * @author Alessia Cerami and Andrea Giordano24 */2526class CloseConsultingReservationTest : FreeSpec({27 val calendar = Calendar.getInstance()28 val year = 202329 val feb = 230 val day = 2531 calendar.set(year, feb, day)32 val validDateOfConsulting = calendar.time33 val freelancerId = UUID.randomUUID()34 val invalidFreelancer = UUID(0, 0)35 val closeConsultingId = UUID.randomUUID()3637 "A CloseConsultingReservation should" - {38 "not to be empty" - {39 val reservation = CloseConsultingReservation(validDateOfConsulting, freelancerId, closeConsultingId)40 reservation.id.toString().shouldBeUUID()41 reservation.id.toString().shouldNotBeEmpty()42 reservation.id.shouldBe(closeConsultingId)43 }44 "be named as requested" - {45 val reservation = CloseConsultingReservation(validDateOfConsulting, freelancerId, closeConsultingId)46 reservation.toString().shouldBe(47 "Reservation consulting {$closeConsultingId} with freelancerId: " +48 "$freelancerId in date $validDateOfConsulting"49 )50 reservation.freelancerId.value.toString().shouldBeUUID()51 reservation.freelancerId.value.shouldBe(freelancerId)52 reservation.id.hashCode().shouldBe(closeConsultingId.hashCode())53 }5455 "have a freelancer that made a consulting" - {56 shouldThrow<FreelancerIdCannotBeEmpty> {57 CloseConsultingReservation(58 validDateOfConsulting,59 invalidFreelancer,60 closeConsultingId61 )62 }63 }64 }65}) ...

Full Screen

Full Screen

CloseWorkoutReservationTest.kt

Source:CloseWorkoutReservationTest.kt Github

copy

Full Screen

1/*******************************************************************************2 * Copyright (C) 2021, Stefano Braggion, Alessia Cerami, Andrea Giordano, Nicola Lasagni.3 *4 * This file is part of Fausto Coppi Lab Automation, and is distributed under the terms of the5 * GNU General Public License, as described in the file LICENSE in the6 * Fausto Coppi Lab Automation distribution's top directory.7 *8 ******************************************************************************/910package it.unibo.lss.fcla.reservation.domain.entities.reservation1112import io.kotest.assertions.throwables.shouldThrow13import io.kotest.core.spec.style.FreeSpec14import io.kotest.matchers.shouldBe15import io.kotest.matchers.string.shouldBeUUID16import io.kotest.matchers.string.shouldNotBeEmpty17import it.unibo.lss.fcla.reservation.domain.entities.exceptions.AimCannotBeEmpty18import java.util.Calendar19import java.util.UUID2021/**22 * @project fausto-coppi-lab-automation23 * @author Alessia Cerami and Andrea Giordano24 */2526class CloseWorkoutReservationTest : FreeSpec({27 val calendar = Calendar.getInstance()28 val year = 202329 val feb = 230 val day = 2531 calendar.set(year, feb, day)32 val dateOfConsulting = calendar.time33 val aim = "recovery"34 val closeWorkoutId = UUID.randomUUID()3536 "A CloseWorkoutReservation should" - {37 "not to be empty" - {38 val reservation = CloseWorkoutReservation(aim, dateOfConsulting, closeWorkoutId)39 reservation.id.toString().shouldBeUUID()40 reservation.id.toString().shouldNotBeEmpty()41 reservation.id.shouldBe(closeWorkoutId)42 reservation.id.hashCode().shouldBe(closeWorkoutId.hashCode())43 }44 "be named as requested" - {45 val reservation = CloseWorkoutReservation(aim, dateOfConsulting, closeWorkoutId)46 reservation.toString().shouldBe(47 "Reservation workout {$closeWorkoutId} with aim: " +48 "$aim in date $dateOfConsulting"49 )50 }51 "have a aim of workout" - {52 shouldThrow<AimCannotBeEmpty> {53 CloseWorkoutReservation("", dateOfConsulting, closeWorkoutId)54 }55 }56 }57}) ...

Full Screen

Full Screen

uuid.kt

Source:uuid.kt Github

copy

Full Screen

1package com.sksamuel.kotest.matchers.string2import io.kotest.assertions.throwables.shouldThrow3import io.kotest.core.spec.style.FreeSpec4import io.kotest.matchers.string.shouldBeUUID5import io.kotest.matchers.string.shouldNotBeUUID6import io.kotest.property.Arb7import io.kotest.property.arbitrary.string8import io.kotest.property.arbitrary.uuid9import io.kotest.property.checkAll10class ShouldBeUUIDTest : FreeSpec({11 "Should be UUID" - {12 "Should pass for Java generated UUIDs" {13 Arb.uuid().checkAll(100) { uuid ->14 uuid.toString().shouldBeUUID()15 uuid.toString().uppercase().shouldBeUUID()16 uuid.toString().lowercase().shouldBeUUID()17 shouldThrow<AssertionError> { uuid.toString().shouldNotBeUUID() }18 }19 }20 "Should pass for nil UUID" {21 "00000000-0000-0000-0000-000000000000".shouldBeUUID()22 shouldThrow<AssertionError> { "00000000-0000-0000-0000-000000000000".shouldNotBeUUID() }23 }24 "Should fail for nil UUID if it should be considered invalid" {25 shouldThrow<AssertionError> { "00000000-0000-0000-0000-000000000000".shouldBeUUID(considerNilValid = false) }26 "00000000-0000-0000-0000-000000000000".shouldNotBeUUID(considerNilValid = false)27 }28 "Should fail for strings" {29 Arb.string(31, 41).checkAll(iterations = 100) { str ->30 shouldThrow<AssertionError> { str.shouldBeUUID() }31 str.shouldNotBeUUID()32 }33 }34 "Should fail for UUIDs without hyphens (not in accordance with specification)" {35 Arb.uuid().checkAll { uuid ->36 val nonHyphens = uuid.toString().replace("-", "")37 nonHyphens.shouldNotBeUUID()38 shouldThrow<AssertionError> { nonHyphens.shouldBeUUID() }39 }40 }41 }42})...

Full Screen

Full Screen

CreateTrialUserImplTest.kt

Source:CreateTrialUserImplTest.kt Github

copy

Full Screen

1package com.falcon.falcon.core.usecase.trial2import com.falcon.falcon.core.entity.User3import com.falcon.falcon.core.enumeration.UserType4import com.falcon.falcon.core.usecase.user.CreateUserUseCase5import io.kotest.matchers.date.shouldBeBetween6import io.kotest.matchers.shouldBe7import io.kotest.matchers.string.shouldBeUUID8import io.kotest.matchers.types.shouldBeTypeOf9import io.mockk.clearAllMocks10import io.mockk.every11import io.mockk.mockk12import org.junit.jupiter.api.BeforeEach13import org.junit.jupiter.api.Test14import org.junit.jupiter.api.TestInstance15import java.time.Instant16import java.time.temporal.ChronoUnit17@TestInstance(TestInstance.Lifecycle.PER_CLASS)18internal class CreateTrialUserImplTest {19 private val createUserUseCase: CreateUserUseCase = mockk()20 private val trialDuration = 1L21 private val underTest: CreateTrialUserImpl = CreateTrialUserImpl(createUserUseCase, trialDuration)22 @BeforeEach23 fun init() {24 clearAllMocks()25 }26 @Test27 fun `Should generate random user`() {28 // Given29 every { createUserUseCase.execute(any()) } returnsArgument 030 // When31 val result = underTest.execute()32 // Then33 result.shouldBeTypeOf<User>()34 result.username.shouldBeUUID()35 result.password.shouldBeUUID()36 result.type.shouldBe(UserType.TRIAL)37 result.expirationDate?.shouldBeBetween(38 Instant.now().plus(50, ChronoUnit.MINUTES),39 Instant.now().plus(70, ChronoUnit.MINUTES),40 )41 }42}...

Full Screen

Full Screen

String.shouldBeUUID

Using AI Code Generation

copy

Full Screen

1import io.kotest.assertions.throwables.shouldNotThrow2import io.kotest.matchers.string.shouldBeUUID3import org.junit.jupiter.api.Test4class StringTest {5 fun `should not throw exception when string is UUID`() {6 val result = shouldNotThrow {7 uuid.shouldBeUUID()8 }9 }10}11import io.kotest.assertions.throwables.shouldThrow12import io.kotest.matchers.string.shouldNotBeUUID13import org.junit.jupiter.api.Test14class StringTest {15 fun `should throw exception when string is not UUID`() {16 val result = shouldThrow<AssertionError> {17 notUuid.shouldNotBeUUID()18 }19 }20}21import io.kotest.assertions.throwables.shouldNotThrow22import io.kotest.matchers.string.shouldBeValidUrl23import org.junit.jupiter.api.Test24class StringTest {25 fun `should not throw exception when string is valid url`() {26 val result = shouldNotThrow {27 url.shouldBeValidUrl()28 }29 }30}31import io.kotest.assertions.throwables.shouldThrow32import io.kotest.matchers.string.shouldNotBeValidUrl33import org.junit.jupiter.api.Test34class StringTest {35 fun `should throw exception when string is not valid url`() {36 val result = shouldThrow<AssertionError> {

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful