Best Kotest code snippet using io.kotest.core.spec.style.scopes.FunSpecContainerScope.context
KotlinPoetAggregateCoderTest.kt
Source:KotlinPoetAggregateCoderTest.kt
...178 179 fun plane(tailNo: String = testTailNo, apply: (Events.() -> Unit)? = null) =180 Arranger<PlaneCommands, Plane, Events, PlaneEvent>(PlaneTestAggregate(Plane(tailNo)))(apply)181 182 fun gear(test: suspend FunSpecContainerScope.() -> Unit) = context("gear", test)183 184 fun pilot(test: suspend FunSpecContainerScope.() -> Unit) = context("pilot", test)185 }186 """187 }188 test("codeEvent") {189 coder.codeEvent() shouldCodeInPlaneApp """190 import app.dokt.app.RootEvent191 192 sealed interface PlaneEvent : RootEvent193 """194 }195 test("codeSerializer") {196 coder.codeSerializer() shouldCodeInPlaneApp """197 import com.airline.plane.Plane198 import kotlinx.serialization.KSerializer199 200 private val serializer: KSerializer<Plane> = Plane.serializer()201 """202 }203 test("codeService") {204 coder.codeService() shouldCodeInPlaneApp """205 import app.dokt.app.ApplicationService206 import app.dokt.app.To207 import com.airline.plane.Plane208 import com.airline.plane.PlaneEvent209 210 object PlaneService : ApplicationService<Plane, String, PlaneEvent>(Plane::class) {211 suspend fun gear(to: To<String>) = tx(to) { gear() }212 213 suspend fun pilot(214 to: To<String>,215 horizontal: Byte,216 vertical: Byte217 ) = tx(to) { pilot(horizontal, vertical) }218 }219 """220 }221 test("codeSpec") {222 coder.codeSpec() shouldCodeInPlane """223 import app.dokt.test.Actor224 import app.dokt.test.Arranger225 import com.airline.plane.app.PlaneCommands226 import com.airline.plane.app.PlaneTestAggregate227 import io.kotest.core.spec.style.FunSpec228 import io.kotest.core.spec.style.scopes.FunSpecContainerScope229 230 abstract class PlaneSpec(231 body: PlaneSpec.() -> Unit,232 private val testTailNo: String = "testTailNo"233 ) : FunSpec() {234 init {235 body()}236 237 val plane: Actor<PlaneCommands, Plane, PlaneEvent> =238 Actor(PlaneTestAggregate(Plane(testTailNo)))239 240 fun plane(tailNo: String = testTailNo, apply: (Events.() -> Unit)? = null) =241 Arranger<PlaneCommands, Plane, Events, PlaneEvent>(PlaneTestAggregate(Plane(tailNo)))(apply)242 243 fun gear(test: suspend FunSpecContainerScope.() -> Unit) = context("gear", test)244 245 fun pilot(test: suspend FunSpecContainerScope.() -> Unit) = context("pilot", test)246 }247 """248 }249 test("codeTestAggregate") {250 coder.codeTestAggregate() shouldCodeInPlaneApp """251 import app.dokt.test.TestAggregate252 import com.airline.plane.Events253 import com.airline.plane.Plane254 import com.airline.plane.PlaneEvent255 256 class PlaneTestAggregate(257 root: Plane258 ) : TestAggregate<Plane, Events, PlaneEvent>(root, serializer), PlaneCommands, Events {259 override fun gear() = command.gear()...
RepositoryTest.kt
Source:RepositoryTest.kt
...47 fromBudget to listOf(FROM_ACCOUNT, FROM_TRANSFER_SOURCE_ACCOUNT),48 toBudget to listOf(TO_ACCOUNT)49 )50 }51 context("with filled SyncData") {52 setUpLocalDatabase {53 syncDataQueries.replaceOnly(54 SyncData(55 firstServerKnowledge = 0,56 firstBudgetId = FROM_BUDGET_ID,57 firstAccountId = FROM_ACCOUNT_ID,58 firstAccountPayeeId = FROM_ACCOUNT_PAYEE_ID,59 secondServerKnowledge = 0,60 secondBudgetId = TO_BUDGET_ID,61 secondAccountId = TO_ACCOUNT_ID,62 secondAccountPayeeId = TO_ACCOUNT_PAYEE_ID63 )64 )65 }66 fetchTransactionsPullsDataProperly(67 setUpServerDatabase,68 setUpLocalDatabase,69 localDatabase,70 repository71 )72 }73 context("with no SyncData") {74 fetchTransactionsPullsDataProperly(75 setUpServerDatabase,76 setUpLocalDatabase,77 localDatabase,78 repository79 )80 }81})82private suspend fun FunSpecContainerScope.fetchTransactionsPullsDataProperly(83 setUpServerDatabase: Setup<FakeYnabServerDatabase>,84 setUpLocalDatabase: Setup<Database>,85 localDatabase: Database,86 repository: Repository87) = context("fetchNewTransactions pulls data properly") {88 context("with empty server") {89 test("fetchNewTransactions does nothing") {90 repository.fetchNewTransactions()91 repository.getTransactionsByAccount(FROM_ACCOUNT_ID).shouldBeEmpty()92 }93 }94 context("with one unremarkable transaction on the server") {95 setUpServerDatabase {96 addOrUpdateTransactionsForAccount(97 FROM_TRANSFER_SOURCE_ACCOUNT_ID,98 listOf(unremarkableTransactionInTransferSource().toApiTransaction())99 )100 }101 test("fetchNewTransactions finds a new transaction") {102 repository.fetchNewTransactions()103 repository.getTransactionsByAccount(FROM_TRANSFER_SOURCE_ACCOUNT_ID).shouldContainExactly(104 unremarkableTransactionInTransferSource(CREATED)105 )106 localDatabase.shouldHaveAllTransactionsProcessedExcept(107 setOf(unremarkableTransactionInTransferSource().id)108 )109 }110 context("when that transaction is an update") {111 setUpLocalDatabase {112 storedTransactionQueries.replaceSingle(113 unremarkableTransactionInTransferSource(UP_TO_DATE).toStoredTransaction()114 )115 }116 test("fetchNewTransactions recognizes an updated transaction") {117 repository.fetchNewTransactions()118 repository.getTransactionsByAccount(FROM_TRANSFER_SOURCE_ACCOUNT_ID)119 .shouldHaveSingleElement(120 unremarkableTransactionInTransferSource(UP_TO_DATE)121 )122 localDatabase.shouldHaveAllTransactionsProcessed()123 }124 }125 }126 context("with manually added complement transactions") {127 setUpServerDatabase {128 addOrUpdateTransactionsForAccount(129 FROM_ACCOUNT_ID,130 listOf(manuallyAddedTransaction().toApiTransaction())131 )132 addOrUpdateTransactionsForAccount(133 TO_ACCOUNT_ID,134 listOf(manuallyAddedTransactionComplement().toApiTransaction())135 )136 }137 test("fetchNewTransactions finds new transactions") {138 repository.fetchNewTransactions()139 repository.getTransactionsByAccount(FROM_ACCOUNT_ID) shouldHaveSingleElement140 manuallyAddedTransaction(CREATED)141 repository.getTransactionsByAccount(TO_ACCOUNT_ID) shouldHaveSingleElement142 manuallyAddedTransactionComplement(CREATED)143 }144 context("when those transactions are updates") {145 val replacedTransaction = manuallyAddedTransaction(UP_TO_DATE).copy(amount = 100_000)146 val replacedTransactionComplement =147 manuallyAddedTransactionComplement(UP_TO_DATE).copy(amount = 100_000)148 setUpLocalDatabase {149 addTransactions(150 replacedTransaction,151 replacedTransactionComplement152 )153 }154 test("fetchNewTransactions recognizes updated transactions") {155 repository.fetchNewTransactions()156 repository.getTransactionsByAccount(FROM_ACCOUNT_ID)157 .shouldHaveSingleElement(manuallyAddedTransaction(UPDATED))158 repository.getReplacedTransactionById(manuallyAddedTransaction().id) shouldBe159 replacedTransaction160 repository.getTransactionsByAccount(TO_ACCOUNT_ID)161 .shouldHaveSingleElement(manuallyAddedTransactionComplement(UPDATED))162 repository.getReplacedTransactionById(manuallyAddedTransactionComplement().id) shouldBe163 replacedTransactionComplement164 }165 }166 context("when those transactions are updates to identical transactions") {167 setUpLocalDatabase {168 addTransactions(169 manuallyAddedTransaction(UP_TO_DATE),170 manuallyAddedTransactionComplement(UP_TO_DATE)171 )172 }173 test("fetchNewTransactions ignores the updated transactions") {174 repository.fetchNewTransactions()175 repository.getTransactionsByAccount(FROM_ACCOUNT_ID)176 .shouldHaveSingleElement(manuallyAddedTransaction(UP_TO_DATE))177 repository.getTransactionsByAccount(TO_ACCOUNT_ID)178 .shouldHaveSingleElement(manuallyAddedTransactionComplement(UP_TO_DATE))179 localDatabase.shouldHaveNoReplacedTransactions()180 }181 }182 context("when those transactions are updates to unprocessed transactions") {183 setUpLocalDatabase {184 addTransactions(185 manuallyAddedTransaction(UPDATED),186 manuallyAddedTransactionComplement(CREATED)187 )188 addReplacedTransactions(manuallyAddedTransaction())189 }190 test("fetchNewTransactions recognizes updated transactions") {191 repository.fetchNewTransactions()192 repository.getTransactionsByAccount(FROM_ACCOUNT_ID)193 .shouldHaveSingleElement(manuallyAddedTransaction(UPDATED))194 repository.getReplacedTransactionById(manuallyAddedTransaction().id) shouldBe195 manuallyAddedTransaction(UP_TO_DATE)196 repository.getTransactionsByAccount(TO_ACCOUNT_ID)...
UserApiTest.kt
Source:UserApiTest.kt
...20import mu.KotlinLogging21import java.util.*22import kotlin.test.assertEquals23import kotlin.test.assertNotNull24val userApiTest: suspend TestApplicationEngine.(FunSpecContainerScope) -> Unit = { context ->25 val logger = KotlinLogging.logger {}26 lateinit var userId: UUID27 lateinit var runAsToken: UserRunAsToken28 val userAdmin1Form = CreateUserForm(29 "user-admin_1@test.com", "123456",30 true, ClubUserRole.Admin, "user-admin_1",31 Gender.Male, 2000, "user-admin_1@test.com", "0987654321", Lang.zh_TW32 )33 context.test("create admin user") {34 with(clubHandleSecuredRequest(35 HttpMethod.Post, "/users", ClubAuth.RootSource36 ) {37 setBody(userAdmin1Form.toJsonString())38 }) {39 assertEquals(HttpStatusCode.OK, response.status())40 val userIdStr = response.dataJsonObject()["id"]?.jsonPrimitive?.content41 assertNotNull(userIdStr)42 userId = UUID.fromString(userIdStr)43 runAsToken = UserRunAsToken(ClubUserType.User.value, userId)44 }45 with(clubHandleSecuredRequest(46 HttpMethod.Get, "/users", ClubAuth.Android, runAsToken47 ) {48 }) {49 assertEquals(HttpStatusCode.OK, response.status())50 assertEquals(1, response.dataJsonArray().size)51 val userDTO = response.dataList<UserDTO>().first()52 assertEquals(userAdmin1Form.account, userDTO.account)53 }54 }55 context.test("create user with duplicated account") {56 with(clubHandleSecuredRequest(57 HttpMethod.Post, "/users", ClubAuth.RootSource58 ) {59 setBody(userAdmin1Form.toJsonString())60 }) {61 assertEquals(HttpStatusCode.UnprocessableEntity, response.status())62 assertEquals(InfraResponseCode.ENTITY_ALREADY_EXISTS, response.code())63 }64 }65 context.test("update user data") {66 with(clubHandleSecuredRequest(67 HttpMethod.Put, "/users/$userId", ClubAuth.Android, runAsToken68 ) {69 setBody(UpdateUserForm(userId, enabled = false).toJsonString())70 }) {71 assertEquals(HttpStatusCode.OK, response.status())72 }73 with(clubHandleSecuredRequest(74 HttpMethod.Get, "/users?q_filter=[enabled = false]", ClubAuth.Android, runAsToken75 ) {76 }) {77 assertEquals(HttpStatusCode.OK, response.status())78 assertEquals(1, response.dataJsonArray().size)79 val userDTO = response.dataList<UserDTO>().first()80 assertEquals(userAdmin1Form.account, userDTO.account)81 assertEquals(false, userDTO.enabled)82 }83 }84 context.test("update my password with incorrect old password") {85 with(clubHandleSecuredRequest(86 HttpMethod.Put, "/users/myPassword", ClubAuth.Android, runAsToken87 ) {88 setBody(UpdateUserPasswordForm("incorrectOldPassword", "newPassword").toJsonString())89 }) {90 assertEquals(HttpStatusCode.Unauthorized, response.status())91 assertEquals(InfraResponseCode.AUTH_BAD_PASSWORD, response.code())92 }93 }94 context.test("update my password with correct old password") {95 with(clubHandleSecuredRequest(96 HttpMethod.Put, "/users/myPassword", ClubAuth.Android, runAsToken97 ) {98 setBody(UpdateUserPasswordForm(userAdmin1Form.password, "newPassword").toJsonString())99 }) {100 assertEquals(HttpStatusCode.OK, response.status())101 }102 }103}...
NotificationTest.kt
Source:NotificationTest.kt
...33import org.jetbrains.exposed.sql.select34import java.util.*35import kotlin.test.assertEquals36import kotlin.test.assertNotNull37val notificationApiTest: suspend TestApplicationEngine.(FunSpecContainerScope) -> Unit = { context ->38 val logger = KotlinLogging.logger {}39 lateinit var userId: UUID40 lateinit var runAsToken: UserRunAsToken41 val notificationUser1Form = CreateUserForm(42 "notification-user_1@test.com", "123456",43 true, ClubUserRole.Admin, "notification-user_1",44 Gender.Male, 2000, "notification-user_1@test.com", "0987654321", Lang.zh_TW45 )46 context.test("send multi-notifications") {47 with(clubHandleSecuredRequest(48 HttpMethod.Post, "/users", ClubAuth.RootSource49 ) {50 setBody(notificationUser1Form.toJsonString())51 }) {52 assertEquals(HttpStatusCode.OK, response.status())53 val userIdStr = response.dataJsonObject()["id"]?.jsonPrimitive?.content54 assertNotNull(userIdStr)55 userId = UUID.fromString(userIdStr)56 runAsToken = UserRunAsToken(ClubUserType.User.value, userId)57 }58 val sendNotificationForm = SendNotificationForm(59 userFilters = mapOf(ClubUserType.User.value to "[account = ${notificationUser1Form.account}]"),60 content = NotificationContent(...
KtorTestUtils.kt
Source:KtorTestUtils.kt
...43suspend fun <R> FunSpecContainerScope.withTestApplicationInKotestContext(44 moduleFunction: Application.() -> Unit,45 test: suspend TestApplicationEngine.(FunSpecContainerScope) -> R46): R {47 val context = this48 return withTestApplicationInKotestContext(createTestEnvironment()) {49 moduleFunction(application)50 test(context)51 }52}53suspend fun <R> FunSpecContainerScope.withTestApplicationInKotestContext(54 environment: ApplicationEngineEnvironment = createTestEnvironment(),55 configure: TestApplicationEngine.Configuration.() -> Unit = {},56 test: suspend TestApplicationEngine.(FunSpecContainerScope) -> R57): R {58 val context = this59 val engine = TestApplicationEngine(environment, configure)60 engine.start()61 try {62 return engine.test(context)63 } finally {64 engine.stop(0L, 0L)65 }66}...
FunSpecContainerScope.kt
Source:FunSpecContainerScope.kt
...8typealias FunSpecContextScope = FunSpecContainerScope9@Deprecated("This interface has been renamed to FunSpecContainerScope. Deprecated since 5.0")10typealias FunSpecContainerContext = FunSpecContainerScope11/**12 * A context that allows tests to be registered using the syntax:13 *14 * context("some context")15 * test("some test")16 * test("some test").config(...)17 *18 */19@KotestTestScope20class FunSpecContainerScope(21 private val testScope: TestScope,22) : AbstractContainerScope(testScope) {23 /**24 * Adds a 'context' container test as a child of the current test case.25 */26 suspend fun context(name: String, test: suspend FunSpecContainerScope.() -> Unit) {27 registerContainer(TestName(name), false, null) { FunSpecContainerScope(this).test() }28 }29 /**30 * Adds a container test to this context expecting config.31 */32 @ExperimentalKotest33 fun context(name: String): ContainerWithConfigBuilder<FunSpecContainerScope> {34 return ContainerWithConfigBuilder(35 name = TestName(name),36 context = this,37 xdisabled = false,38 contextFn = { FunSpecContainerScope(it) }39 )40 }41 /**42 * Adds a disabled container test to this context.43 */44 suspend fun xcontext(name: String, test: suspend FunSpecContainerScope.() -> Unit) {45 registerContainer(TestName(name), true, null) { FunSpecContainerScope(this).test() }46 }47 /**48 * Adds a disabled container to this context, expecting config.49 */50 @ExperimentalKotest51 fun xcontext(name: String): ContainerWithConfigBuilder<FunSpecContainerScope> {52 return ContainerWithConfigBuilder(53 TestName(name),54 this,55 true56 ) { FunSpecContainerScope(it) }57 }58 /**59 * Adds a test case to this context, expecting config.60 */61 suspend fun test(name: String): TestWithConfigBuilder {62 TestDslState.startTest(testScope.testCase.descriptor.append(name))63 return TestWithConfigBuilder(64 name = TestName(name),65 context = this,66 xdisabled = false,67 )68 }69 /**70 * Adds a disabled test case to this context, expecting config.71 */72 suspend fun xtest(name: String): TestWithConfigBuilder {73 TestDslState.startTest(testScope.testCase.descriptor.append(name))74 return TestWithConfigBuilder(75 name = TestName(name),76 context = this,77 xdisabled = true,78 )79 }80 /**81 * Adds a test case to this context.82 */83 suspend fun test(name: String, test: suspend TestScope.() -> Unit) {84 registerTest(TestName(name), false, null, test)85 }86 /**87 * Adds a disabled test case to this context.88 */89 suspend fun xtest(name: String, test: suspend TestScope.() -> Unit) {90 registerTest(TestName(name), true, null, test)91 }92}...
FunSpecRootScope.kt
Source:FunSpecRootScope.kt
...9 * Extends [RootScope] with dsl-methods for the 'fun spec' style.10 */11interface FunSpecRootScope : RootScope {12 /**13 * Adds a container [RootTest] that uses a [FunSpecContainerScope] as the test context.14 */15 fun context(name: String, test: suspend FunSpecContainerScope.() -> Unit) {16 addContainer(TestName("context ", name, false), false, null) { FunSpecContainerScope(this).test() }17 }18 /**19 * Adds a disabled container [RootTest] that uses a [FunSpecContainerScope] as the test context.20 */21 fun xcontext(name: String, test: suspend FunSpecContainerScope.() -> Unit) =22 addContainer(TestName("context ", name, false), true, null) { FunSpecContainerScope(this).test() }23 @ExperimentalKotest24 fun context(name: String): RootContainerWithConfigBuilder<FunSpecContainerScope> =25 RootContainerWithConfigBuilder(TestName("context ", name, false), false, this) { FunSpecContainerScope(it) }26 @ExperimentalKotest27 fun xcontext(name: String): RootContainerWithConfigBuilder<FunSpecContainerScope> =28 RootContainerWithConfigBuilder(TestName("context ", name, false), true, this) { FunSpecContainerScope(it) }29 /**30 * Adds a [RootTest], with the given name and config taken from the config builder.31 */32 fun test(name: String): RootTestWithConfigBuilder =33 RootTestWithConfigBuilder(this, TestName(name), xdisabled = false)34 /**35 * Adds a [RootTest], with the given name and default config.36 */37 fun test(name: String, test: suspend TestScope.() -> Unit) = addTest(TestName(name), false, null, test)38 /**39 * Adds a disabled [RootTest], with the given name and default config.40 */41 fun xtest(name: String, test: suspend TestScope.() -> Unit) = addTest(TestName(name), true, null, test)42 /**...
AccountSpec.kt
Source:AccountSpec.kt
...8 val account get() =9 Arranger<AccountCommands, Account, Events, AccountEvent>(AccountTestAggregate(Account(testNumber)))()10 fun account(number: Iban = testNumber, apply: (Events.() -> Unit)? = null) =11 Arranger<AccountCommands, Account, Events, AccountEvent>(AccountTestAggregate(Account(number)))(apply)12 fun deposit(test: suspend FunSpecContainerScope.() -> Unit) = context("deposit", test)13 fun freeze(test: suspend FunSpecContainerScope.() -> Unit) = context("freeze", test)14 fun withdraw(test: suspend FunSpecContainerScope.() -> Unit) = context("withdraw", test)15}...
context
Using AI Code Generation
1context(“test context”){2test(“test case 1”){3}4test(“test case 2”){5}6}7}8}9}10FunSpecContainerScope class also provides other methods like given(), xgiven(), xcontext(), xit(), xspecify(), xtest(), xwhen(), specify(), when() and it() to create test contexts and
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!