How to use beEmpty method of io.kotest.matchers.optional.matchers class

Best Kotest code snippet using io.kotest.matchers.optional.matchers.beEmpty

FossIdTest.kt

Source:FossIdTest.kt Github

copy

Full Screen

...20import io.kotest.assertions.fail21import io.kotest.assertions.throwables.shouldThrow22import io.kotest.core.spec.style.WordSpec23import io.kotest.inspectors.forAtLeastOne24import io.kotest.matchers.collections.beEmpty25import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder26import io.kotest.matchers.collections.shouldHaveSize27import io.kotest.matchers.should28import io.kotest.matchers.shouldBe29import io.kotest.matchers.string.shouldContain30import io.mockk.coEvery31import io.mockk.coVerify32import io.mockk.every33import io.mockk.mockk34import io.mockk.mockkObject35import io.mockk.mockkStatic36import io.mockk.spyk37import io.mockk.unmockkObject38import java.time.Instant39import java.util.concurrent.atomic.AtomicInteger40import kotlinx.coroutines.TimeoutCancellationException41import kotlinx.coroutines.runBlocking42import kotlinx.coroutines.withTimeout43import org.ossreviewtoolkit.clients.fossid.EntityResponseBody44import org.ossreviewtoolkit.clients.fossid.FossIdRestService45import org.ossreviewtoolkit.clients.fossid.FossIdServiceWithVersion46import org.ossreviewtoolkit.clients.fossid.MapResponseBody47import org.ossreviewtoolkit.clients.fossid.PolymorphicList48import org.ossreviewtoolkit.clients.fossid.PolymorphicResponseBody49import org.ossreviewtoolkit.clients.fossid.checkDownloadStatus50import org.ossreviewtoolkit.clients.fossid.createIgnoreRule51import org.ossreviewtoolkit.clients.fossid.createProject52import org.ossreviewtoolkit.clients.fossid.createScan53import org.ossreviewtoolkit.clients.fossid.deleteScan54import org.ossreviewtoolkit.clients.fossid.downloadFromGit55import org.ossreviewtoolkit.clients.fossid.getProject56import org.ossreviewtoolkit.clients.fossid.listIdentifiedFiles57import org.ossreviewtoolkit.clients.fossid.listIgnoreRules58import org.ossreviewtoolkit.clients.fossid.listIgnoredFiles59import org.ossreviewtoolkit.clients.fossid.listMarkedAsIdentifiedFiles60import org.ossreviewtoolkit.clients.fossid.listPendingFiles61import org.ossreviewtoolkit.clients.fossid.listScansForProject62import org.ossreviewtoolkit.clients.fossid.model.Scan63import org.ossreviewtoolkit.clients.fossid.model.identification.common.LicenseMatchType64import org.ossreviewtoolkit.clients.fossid.model.identification.identifiedFiles.IdentifiedFile65import org.ossreviewtoolkit.clients.fossid.model.identification.ignored.IgnoredFile66import org.ossreviewtoolkit.clients.fossid.model.identification.markedAsIdentified.License67import org.ossreviewtoolkit.clients.fossid.model.identification.markedAsIdentified.LicenseFile68import org.ossreviewtoolkit.clients.fossid.model.identification.markedAsIdentified.MarkedAsIdentifiedFile69import org.ossreviewtoolkit.clients.fossid.model.rules.IgnoreRule70import org.ossreviewtoolkit.clients.fossid.model.rules.RuleScope71import org.ossreviewtoolkit.clients.fossid.model.rules.RuleType72import org.ossreviewtoolkit.clients.fossid.model.status.DownloadStatus73import org.ossreviewtoolkit.clients.fossid.model.status.ScanStatus74import org.ossreviewtoolkit.clients.fossid.model.status.UnversionedScanDescription75import org.ossreviewtoolkit.clients.fossid.runScan76import org.ossreviewtoolkit.model.CopyrightFinding77import org.ossreviewtoolkit.model.CuratedPackage78import org.ossreviewtoolkit.model.Identifier79import org.ossreviewtoolkit.model.LicenseFinding80import org.ossreviewtoolkit.model.OrtIssue81import org.ossreviewtoolkit.model.OrtResult82import org.ossreviewtoolkit.model.Package83import org.ossreviewtoolkit.model.ScanResult84import org.ossreviewtoolkit.model.ScanSummary85import org.ossreviewtoolkit.model.ScannerRun86import org.ossreviewtoolkit.model.Severity87import org.ossreviewtoolkit.model.TextLocation88import org.ossreviewtoolkit.model.VcsInfo89import org.ossreviewtoolkit.model.VcsType90import org.ossreviewtoolkit.model.config.DownloaderConfiguration91import org.ossreviewtoolkit.model.config.ScannerConfiguration92import org.ossreviewtoolkit.scanner.scanOrtResult93import org.ossreviewtoolkit.scanner.scanners.fossid.FossId.Companion.SCAN_CODE_KEY94import org.ossreviewtoolkit.scanner.scanners.fossid.FossId.Companion.convertGitUrlToProjectName95import org.ossreviewtoolkit.utils.test.shouldNotBeNull96class FossIdTest : WordSpec({97 beforeSpec {98 mockkStatic("org.ossreviewtoolkit.clients.fossid.ExtensionsKt")99 }100 beforeTest {101 // Here a static function of the companion object is mocked therefore `mockkobject` needs to be used.102 // See https://lifesaver.codes/answer/cannot-mockkstatic-for-kotlin-companion-object-static-method-136103 mockkObject(FossIdRestService)104 every { FossIdRestService.createService(any()) } returns createServiceMock()105 }106 afterTest {107 unmockkObject(FossIdRestService)108 }109 "version()" should {110 "return the version reported by FossIdServiceWithVersion" {111 val fossId = createFossId(createConfig())112 fossId.version shouldBe FOSSID_VERSION113 }114 }115 "convertGitUrlToProjectName()" should {116 "extract the repository name from the Git URL without the .git suffix" {117 convertGitUrlToProjectName("https://github.com/jshttp/mime-types.git") shouldBe "mime-types"118 convertGitUrlToProjectName("https://github.com/vdurmont/semver4j.git") shouldBe "semver4j"119 convertGitUrlToProjectName("https://dev.azure.com/org/project/_git/repo") shouldBe "repo"120 }121 }122 "scanPackages()" should {123 "create issues for packages not hosted in Git" {124 val projectCode = projectCode(PROJECT)125 val scanCode = scanCode(PROJECT, null)126 val config = createConfig(deltaScans = false)127 val vcsInfo = createVcsInfo(type = VcsType.UNKNOWN)128 val scan = createScan(vcsInfo.url, "${vcsInfo.revision}_other", scanCode)129 val pkgId = createIdentifier(index = 42)130 FossIdRestService.createService(config.serverUrl)131 .expectProjectRequest(projectCode)132 .expectListScans(projectCode, listOf(scan))133 .expectCheckScanStatus(scanCode, ScanStatus.FINISHED)134 val fossId = createFossId(config)135 val summary = fossId.scan(listOf(createPackage(pkgId, vcsInfo))).summary(pkgId)136 summary.issues shouldHaveSize 1137 with(summary.issues.first()) {138 message shouldContain pkgId.toCoordinates()139 message shouldContain "but only Git is supported"140 severity shouldBe Severity.WARNING141 }142 }143 "create a new scan for an existing project" {144 val projectCode = projectCode(PROJECT)145 val scanCode = scanCode(PROJECT, null)146 val config = createConfig(deltaScans = false)147 val vcsInfo = createVcsInfo()148 val scan = createScan(vcsInfo.url, "${vcsInfo.revision}_other", scanCode)149 val service = FossIdRestService.createService(config.serverUrl)150 .expectProjectRequest(projectCode)151 .expectListScans(projectCode, listOf(scan))152 .expectCheckScanStatus(scanCode, ScanStatus.FINISHED)153 .expectCreateScan(projectCode, scanCode, vcsInfo)154 .expectDownload(scanCode)155 .mockFiles(scanCode)156 val fossId = createFossId(config)157 fossId.scan(listOf(createPackage(createIdentifier(index = 1), vcsInfo)))158 coVerify {159 service.createScan(USER, API_KEY, projectCode, scanCode, vcsInfo.url, vcsInfo.revision)160 service.downloadFromGit(USER, API_KEY, scanCode)161 service.checkDownloadStatus(USER, API_KEY, scanCode)162 }163 coVerify(exactly = 0) {164 service.createProject(any())165 }166 }167 "throw an exception if the scan download failed" {168 val projectCode = projectCode(PROJECT)169 val scanCode = scanCode(PROJECT, null)170 val config = createConfig(deltaScans = false)171 val vcsInfo = createVcsInfo()172 val scan = createScan(vcsInfo.url, "${vcsInfo.revision}_other", scanCode)173 val service = FossIdRestService.createService(config.serverUrl)174 .expectProjectRequest(projectCode)175 .expectListScans(projectCode, listOf(scan))176 .expectCheckScanStatus(scanCode, ScanStatus.FINISHED)177 .expectCreateScan(projectCode, scanCode, vcsInfo)178 .expectDeleteScan(scanCode)179 coEvery { service.downloadFromGit(USER, API_KEY, scanCode) } returns180 EntityResponseBody(status = 1)181 coEvery { service.checkDownloadStatus(USER, API_KEY, scanCode) } returns182 EntityResponseBody(status = 1, data = DownloadStatus.FAILED)183 val fossId = createFossId(config)184 fossId.scan(listOf(createPackage(createIdentifier(index = 1), vcsInfo)))185 coVerify {186 service.createScan(USER, API_KEY, projectCode, scanCode, vcsInfo.url, vcsInfo.revision)187 service.downloadFromGit(USER, API_KEY, scanCode)188 service.checkDownloadStatus(USER, API_KEY, scanCode)189 service.downloadFromGit(USER, API_KEY, scanCode)190 // The fact that deleteScan has been called is a proof that an exception has been thrown.191 service.deleteScan(USER, API_KEY, scanCode)192 }193 }194 "return copyright and license findings from a new scan" {195 val projectCode = projectCode(PROJECT)196 val scanCode = scanCode(PROJECT, null)197 val config = createConfig(deltaScans = false)198 val vcsInfo = createVcsInfo()199 val scan = createScan(vcsInfo.url, "${vcsInfo.revision}_other", scanCode)200 val pkgId = createIdentifier(index = 42)201 FossIdRestService.createService(config.serverUrl)202 .expectProjectRequest(projectCode)203 .expectListScans(projectCode, listOf(scan))204 .expectCheckScanStatus(scanCode, ScanStatus.FINISHED)205 .expectCreateScan(projectCode, scanCode, vcsInfo)206 .expectDownload(scanCode)207 .mockFiles(scanCode, identifiedRange = 1..2, markedRange = 1..2)208 val fossId = createFossId(config)209 val summary = fossId.scan(listOf(createPackage(pkgId, vcsInfo))).summary(pkgId)210 val expectedCopyrightFindings = listOf(211 CopyrightFinding("copyrightMarked1", textLocation(1)),212 CopyrightFinding("copyrightMarked2", textLocation(2))213 )214 val expectedLicenseFindings = listOf(215 LicenseFinding("licenseMarkedIdentifier1", textLocation(1)),216 LicenseFinding("licenseMarkedIdentifier2", textLocation(2))217 )218 summary.copyrightFindings shouldContainExactlyInAnyOrder expectedCopyrightFindings219 summary.licenseFindings shouldContainExactlyInAnyOrder expectedLicenseFindings220 }221 "take ignored files into account" {222 val projectCode = projectCode(PROJECT)223 val scanCode = scanCode(PROJECT, null)224 val config = createConfig(deltaScans = false)225 val vcsInfo = createVcsInfo()226 val pkgId = createIdentifier(index = 42)227 FossIdRestService.createService(config.serverUrl)228 .expectProjectRequest(projectCode)229 .expectListScans(projectCode, emptyList())230 .expectCheckScanStatus(scanCode, ScanStatus.FINISHED)231 .expectCreateScan(projectCode, scanCode, vcsInfo)232 .expectDownload(scanCode)233 .mockFiles(scanCode, identifiedRange = 1..2, markedRange = 1..2, ignoredRange = 2..3)234 val fossId = createFossId(config)235 val summary = fossId.scan(listOf(createPackage(pkgId, vcsInfo))).summary(pkgId)236 val expectedCopyrightFindings = listOf(237 CopyrightFinding("copyrightMarked1", textLocation(1))238 )239 val expectedLicenseFindings = listOf(240 LicenseFinding("licenseMarkedIdentifier1", textLocation(1))241 )242 summary.copyrightFindings shouldContainExactlyInAnyOrder expectedCopyrightFindings243 summary.licenseFindings shouldContainExactlyInAnyOrder expectedLicenseFindings244 }245 "fallback to identified files if no marked identified files are available" {246 val projectCode = projectCode(PROJECT)247 val scanCode = scanCode(PROJECT, null)248 val config = createConfig(deltaScans = false)249 val vcsInfo = createVcsInfo()250 val scan = createScan(vcsInfo.url, "${vcsInfo.revision}_other", scanCode)251 val pkgId = createIdentifier(index = 42)252 FossIdRestService.createService(config.serverUrl)253 .expectProjectRequest(projectCode)254 .expectListScans(projectCode, listOf(scan))255 .expectCheckScanStatus(scanCode, ScanStatus.FINISHED)256 .expectCreateScan(projectCode, scanCode, vcsInfo)257 .expectDownload(scanCode)258 .mockFiles(scanCode, identifiedRange = 1..2)259 val fossId = createFossId(config)260 val summary = fossId.scan(listOf(createPackage(pkgId, vcsInfo))).summary(pkgId)261 val expectedCopyrightFindings = listOf(262 CopyrightFinding("copyright1", textLocation(1)),263 CopyrightFinding("copyright2", textLocation(2))264 )265 val expectedLicenseFindings = listOf(266 LicenseFinding("lic1", textLocation(1)),267 LicenseFinding("lic2", textLocation(2))268 )269 summary.copyrightFindings shouldContainExactlyInAnyOrder expectedCopyrightFindings270 summary.licenseFindings shouldContainExactlyInAnyOrder expectedLicenseFindings271 }272 "report pending files as issues" {273 val projectCode = projectCode(PROJECT)274 val scanCode = scanCode(PROJECT, null)275 val config = createConfig(deltaScans = false)276 val vcsInfo = createVcsInfo()277 val scan = createScan(vcsInfo.url, "${vcsInfo.revision}_other", scanCode)278 val pkgId = createIdentifier(index = 42)279 FossIdRestService.createService(config.serverUrl)280 .expectProjectRequest(projectCode)281 .expectListScans(projectCode, listOf(scan))282 .expectCheckScanStatus(scanCode, ScanStatus.FINISHED)283 .expectCreateScan(projectCode, scanCode, vcsInfo)284 .expectDownload(scanCode)285 .mockFiles(scanCode, pendingRange = 4..5)286 val fossId = createFossId(config)287 val summary = fossId.scan(listOf(createPackage(pkgId, vcsInfo))).summary(pkgId)288 val expectedIssues = listOf(createPendingFile(4), createPendingFile(5)).map {289 OrtIssue(Instant.EPOCH, "FossId", "Pending identification for '$it'.", Severity.HINT)290 }291 summary.issues.map { it.copy(timestamp = Instant.EPOCH) } shouldBe expectedIssues292 }293 "create a new project if none exists yet" {294 val projectCode = projectCode(PROJECT)295 val scanCode = scanCode(PROJECT, null)296 val config = createConfig(deltaScans = false)297 val vcsInfo = createVcsInfo()298 val scan = createScan(vcsInfo.url, "${vcsInfo.revision}_other", scanCode)299 val service = FossIdRestService.createService(config.serverUrl)300 .expectProjectRequest(projectCode, status = 0, error = "Project does not exist")301 .expectListScans(projectCode, listOf(scan))302 .expectCheckScanStatus(scanCode, ScanStatus.FINISHED)303 .expectCreateScan(projectCode, scanCode, vcsInfo)304 .expectDownload(scanCode)305 .mockFiles(scanCode)306 coEvery { service.createProject(USER, API_KEY, projectCode, projectCode) } returns307 MapResponseBody(status = 1, data = mapOf())308 val fossId = createFossId(config)309 fossId.scan(listOf(createPackage(createIdentifier(index = 1), vcsInfo)))310 coVerify {311 service.createProject(USER, API_KEY, projectCode, projectCode)312 }313 }314 "explicitly start a scan if necessary" {315 val projectCode = projectCode(PROJECT)316 val scanCode = scanCode(PROJECT, null)317 val config = createConfig(deltaScans = false)318 val vcsInfo = createVcsInfo()319 val service = FossIdRestService.createService(config.serverUrl)320 .expectProjectRequest(projectCode)321 .expectListScans(projectCode, emptyList())322 .expectCheckScanStatus(scanCode, ScanStatus.NOT_STARTED, ScanStatus.FINISHED)323 .expectCreateScan(projectCode, scanCode, vcsInfo)324 .expectDownload(scanCode)325 .mockFiles(scanCode)326 coEvery { service.runScan(USER, API_KEY, scanCode) } returns EntityResponseBody(status = 1)327 val fossId = createFossId(config)328 fossId.scan(listOf(createPackage(createIdentifier(index = 1), vcsInfo)))329 coVerify {330 service.runScan(USER, API_KEY, scanCode)331 }332 }333 "works if scan was queued in FossID older than 2021.2" {334 val projectCode = projectCode(PROJECT)335 val scanCode = scanCode(PROJECT, null)336 val config = createConfig(deltaScans = false)337 val vcsInfo = createVcsInfo()338 val service = FossIdRestService.createService(config.serverUrl)339 .expectProjectRequest(projectCode)340 .expectListScans(projectCode, emptyList())341 .expectCheckScanStatus(scanCode, ScanStatus.NOT_STARTED, ScanStatus.FINISHED)342 .expectCreateScan(projectCode, scanCode, vcsInfo)343 .expectDownload(scanCode)344 .mockFiles(scanCode)345 coEvery { service.version } returns "2021.1.1"346 coEvery { service.runScan(USER, API_KEY, scanCode) } returns EntityResponseBody(347 status = 0,348 error = "Scan was added to queue."349 )350 val fossId = createFossId(config)351 fossId.scan(listOf(createPackage(createIdentifier(index = 1), vcsInfo)))352 coVerify {353 service.runScan(USER, API_KEY, scanCode)354 }355 }356 "wait for a scan to complete" {357 val projectCode = projectCode(PROJECT)358 val scanCode = scanCode(PROJECT, null)359 val config = createConfig(deltaScans = false)360 val vcsInfo = createVcsInfo()361 val service = FossIdRestService.createService(config.serverUrl)362 .expectProjectRequest(projectCode)363 .expectListScans(projectCode, emptyList())364 .expectCheckScanStatus(scanCode, ScanStatus.NOT_STARTED, ScanStatus.SCANNING, ScanStatus.FINISHED)365 .expectCreateScan(projectCode, scanCode, vcsInfo)366 .expectDownload(scanCode)367 .expectDeleteScan(scanCode)368 .mockFiles(scanCode)369 coEvery { service.runScan(USER, API_KEY, scanCode) } returns EntityResponseBody(status = 1)370 val fossId = createFossId(config)371 shouldThrow<TimeoutCancellationException> {372 withTimeout(1000) {373 fossId.scanPackages(374 setOf(createPackage(createIdentifier(index = 1), vcsInfo)), emptyMap()375 )376 }377 }378 coVerify {379 service.checkScanStatus(USER, API_KEY, scanCode)380 }381 }382 "support triggering asynchronous scans" {383 val pkgId = createIdentifier(index = 1)384 val projectCode = projectCode(PROJECT)385 val scanCode = scanCode(PROJECT, null)386 val config = createConfig(deltaScans = false, waitForResult = false)387 val vcsInfo = createVcsInfo()388 val service = FossIdRestService.createService(config.serverUrl)389 .expectProjectRequest(projectCode)390 .expectListScans(projectCode, emptyList())391 .expectCheckScanStatus(scanCode, ScanStatus.NOT_STARTED, ScanStatus.SCANNING, ScanStatus.FINISHED)392 .expectCreateScan(projectCode, scanCode, vcsInfo)393 .expectDownload(scanCode)394 val fossId = createFossId(config)395 val scannerRun = fossId.scan(listOf(createPackage(pkgId, vcsInfo)))396 scannerRun.results.collectIssues()[pkgId] shouldNotBeNull {397 this shouldHaveSize 1398 val issue = first()399 issue.message shouldContain pkgId.toCoordinates()400 issue.message shouldContain "asynchronous mode"401 issue.severity shouldBe Severity.HINT402 }403 coVerify(exactly = 0) {404 service.checkScanStatus(USER, API_KEY, any())405 }406 }407 "apply filters for namespaces and authors" {408 val id1 = createIdentifier(1)409 val pkg1 = createPackage(id1, createVcsInfo())410 val ignoredAuthor = "hacker"411 val pkgAuthors = setOf("foo", "bar", ignoredAuthor)412 val id2 = createIdentifier(2).copy(namespace = "anotherNamespace")413 val pkg2 = createPackage(id2, createVcsInfo("anotherProject"), authors = pkgAuthors)414 val config = createConfig(packageNamespaceFilter = id1.namespace, packageAuthorsFilter = ignoredAuthor)415 val fossId = createFossId(config)416 val scannerRun = fossId.scan(listOf(pkg1, pkg2))417 scannerRun.results.collectIssues().keys should beEmpty()418 }419 "create a delta scan for an existing scan" {420 val projectCode = projectCode(PROJECT)421 val originCode = "originalScanCode"422 val scanCode = scanCode(PROJECT, FossId.DeltaTag.DELTA)423 val config = createConfig()424 val vcsInfo = createVcsInfo()425 val scan = createScan(vcsInfo.url, vcsInfo.revision, originCode)426 val service = FossIdRestService.createService(config.serverUrl)427 .expectProjectRequest(projectCode)428 .expectListScans(projectCode, listOf(scan))429 .expectCheckScanStatus(originCode, ScanStatus.FINISHED)430 .expectCheckScanStatus(scanCode, ScanStatus.NOT_STARTED, ScanStatus.FINISHED)431 .expectCreateScan(projectCode, scanCode, vcsInfo)...

Full Screen

Full Screen

NonTerminalTest.kt

Source:NonTerminalTest.kt Github

copy

Full Screen

...6import io.kotest.assertions.arrow.option.shouldBeSome7import io.kotest.assertions.assertSoftly8import io.kotest.assertions.throwables.shouldThrow9import io.kotest.inspectors.forAll10import io.kotest.matchers.collections.beEmpty11import io.kotest.matchers.maps.shouldBeEmpty12import io.kotest.matchers.should13import io.kotest.matchers.shouldBe14import io.kpeg.ParseError15import io.kpeg.ParserState16import io.kpeg.pe.NonTerminal.Predicate.PredicateType.And17import io.kpeg.pe.NonTerminal.Predicate.PredicateType.Not18import io.kpeg.testutils.NonTerminalTestUtils.PrChoiceCorrect19import io.kpeg.testutils.NonTerminalTestUtils.PrChoiceEmpty20import io.kpeg.testutils.NonTerminalTestUtils.PrChoiceIncorrect21import io.kpeg.testutils.NonTerminalTestUtils.RepeatedCorrect22import io.kpeg.testutils.NonTerminalTestUtils.RepeatedEmpty23import io.kpeg.testutils.NonTerminalTestUtils.RepeatedIncorrect24import io.kpeg.testutils.NonTerminalTestUtils.SequenceCorrect25import io.kpeg.testutils.NonTerminalTestUtils.SequenceEmpty26import io.kpeg.testutils.NonTerminalTestUtils.SequenceException27import io.kpeg.testutils.NonTerminalTestUtils.SequenceIncorrect28import io.kpeg.testutils.NonTerminalTestUtils.a29import io.kpeg.testutils.NonTerminalTestUtils.alpha30import io.kpeg.testutils.NonTerminalTestUtils.d31import io.kpeg.testutils.NonTerminalTestUtils.delta32import io.kpeg.testutils.NonTerminalTestUtils.prChoiceCorrectProvider33import io.kpeg.testutils.NonTerminalTestUtils.prChoiceEmptyProvider34import io.kpeg.testutils.NonTerminalTestUtils.prChoiceIncorrectProvider35import io.kpeg.testutils.NonTerminalTestUtils.repCorrectProvider36import io.kpeg.testutils.NonTerminalTestUtils.repEmptyProvider37import io.kpeg.testutils.NonTerminalTestUtils.repIncorrectProvider38import io.kpeg.testutils.NonTerminalTestUtils.seqCorrectProvider39import io.kpeg.testutils.NonTerminalTestUtils.seqEmptyProvider40import io.kpeg.testutils.NonTerminalTestUtils.seqExProvider41import io.kpeg.testutils.NonTerminalTestUtils.seqIncorrectProvider42import org.junit.jupiter.api.Nested43import org.junit.jupiter.api.Test44import org.junit.jupiter.params.ParameterizedTest45import org.junit.jupiter.params.provider.MethodSource46import io.kpeg.pe.NonTerminal.MapPe as M47import io.kpeg.pe.NonTerminal.Optional as Opt48import io.kpeg.pe.NonTerminal.Predicate as Pred49import io.kpeg.pe.NonTerminal.PrioritizedChoice as PrCh50import io.kpeg.pe.NonTerminal.Repeated as Rep51import io.kpeg.pe.NonTerminal.Sequence as Seq52import io.kpeg.pe.Terminal.Character as Ch53import io.kpeg.pe.Terminal.Literal as Lit54class NonTerminalTest {55 private lateinit var ps: ParserState56 @Nested57 inner class Optional {58 private val optPe = Opt(Now(Ch { it == a }))59 @Test60 fun `check logName`() {61 optPe.logName shouldBe "Optional(Character)"62 }63 @Test64 fun `parse 1 optional in correct string`() {65 ps = ParserState("$a")66 val actualOpt = optPe.parse(ps)67 actualOpt shouldBeSome Some(a)68 assertSoftly(ps) {69 i shouldBe 170 ignoreWS shouldBe false71 memNone.forAll { it.shouldBeEmpty() }72 memSome.forAll { it.shouldBeEmpty() }73 errs should beEmpty()74 }75 }76 @Test77 fun `parse 1 optional in incorrect string`() {78 ps = ParserState("$d")79 val actualOpt = optPe.parse(ps)80 actualOpt shouldBeSome None81 assertSoftly(ps) {82 i shouldBe 083 ignoreWS shouldBe false84 memNone.forAll { it.shouldBeEmpty() }85 memSome.forAll { it.shouldBeEmpty() }86 errs should beEmpty()87 }88 }89 @Test90 fun `parse 1 optional in empty string`() {91 ps = ParserState("")92 val actualOpt = optPe.parse(ps)93 actualOpt shouldBeSome None94 assertSoftly(ps) {95 i shouldBe 096 ignoreWS shouldBe false97 memNone.forAll { it.shouldBeEmpty() }98 memSome.forAll { it.shouldBeEmpty() }99 errs should beEmpty()100 }101 }102 }103 @Nested104 inner class Repeated {105 private fun correctProvider() = repCorrectProvider()106 private fun incorrectProvider() = repIncorrectProvider()107 private fun emptyProvider() = repEmptyProvider()108 @Test109 fun `check logName`() {110 val repPe = Rep(1u..3u, Now(Ch { it == a }))111 repPe.logName shouldBe "Repeated(Character) 1..3 times"112 }113 @Test114 fun `wrong init`() {115 val e = shouldThrow<IllegalArgumentException> {116 Rep(2u..1u, Now(Ch { it == a }))117 }118 e.message shouldBe "Range is empty"119 }120 @ParameterizedTest121 @MethodSource("correctProvider")122 internal fun `parse repeated in correct string`(data: RepeatedCorrect) {123 ps = ParserState(data.s)124 val actualRepeated = data.pe.parse(ps)125 actualRepeated shouldBe data.expected126 assertSoftly(ps) {127 i shouldBe data.i128 ignoreWS shouldBe false129 memNone.forAll { it.shouldBeEmpty() }130 memSome.forAll { it.shouldBeEmpty() }131 errs should beEmpty()132 }133 }134 @ParameterizedTest135 @MethodSource("incorrectProvider")136 internal fun `parse repeated in incorrect string`(data: RepeatedIncorrect) {137 ps = ParserState(data.s)138 val actualRepeated = data.pe.parse(ps)139 actualRepeated should beNone()140 assertSoftly(ps) {141 i shouldBe 0142 ignoreWS shouldBe false143 memNone.forAll { it.shouldBeEmpty() }144 memSome.forAll { it.shouldBeEmpty() }145 errs shouldBe data.errs146 }147 }148 @ParameterizedTest149 @MethodSource("emptyProvider")150 internal fun `parse repeated in empty string`(data: RepeatedEmpty) {151 ps = ParserState("")152 val actualRepeated = data.pe.parse(ps)153 actualRepeated shouldBe data.expected154 assertSoftly(ps) {155 i shouldBe 0156 ignoreWS shouldBe false157 memNone.forAll { it.shouldBeEmpty() }158 memSome.forAll { it.shouldBeEmpty() }159 errs shouldBe data.errs160 }161 }162 }163 @Nested164 inner class Predicate {165 @Nested166 inner class And {167 private val andPredPe = Pred(168 type = And,169 pe = Now(Lit(len = alpha.length) { it == alpha }),170 )171 @Test172 fun `check logName`() {173 andPredPe.logName shouldBe "And(Literal)"174 }175 @Test176 fun `parse 1 'and' predicate in correct string`() {177 ps = ParserState(alpha)178 val actualAndPred = andPredPe.parse(ps)179 actualAndPred shouldBeSome Unit180 assertSoftly(ps) {181 i shouldBe 0182 ignoreWS shouldBe false183 memNone.forAll { it.shouldBeEmpty() }184 memSome.forAll { it.shouldBeEmpty() }185 errs should beEmpty()186 }187 }188 @Test189 fun `parse 1 'and' predicate in incorrect string`() {190 ps = ParserState(delta)191 val actualAndPred = andPredPe.parse(ps)192 actualAndPred should beNone()193 assertSoftly(ps) {194 i shouldBe 0195 ignoreWS shouldBe false196 memNone.forAll { it.shouldBeEmpty() }197 memSome.forAll { it.shouldBeEmpty() }198 errs shouldBe listOf(199 ParseError(index = 0, message = "Wrong Literal"),200 ParseError(index = 0, message = "Wrong And(Literal)"),201 )202 }203 }204 @Test205 fun `parse 1 'and' predicate in empty string`() {206 ps = ParserState("")207 val actualAndPred = andPredPe.parse(ps)208 actualAndPred should beNone()209 assertSoftly(ps) {210 i shouldBe 0211 ignoreWS shouldBe false212 memNone.forAll { it.shouldBeEmpty() }213 memSome.forAll { it.shouldBeEmpty() }214 errs shouldBe listOf(215 ParseError(index = 0, message = "Can't parse Literal - text is too short"),216 ParseError(index = 0, message = "Wrong And(Literal)"),217 )218 }219 }220 }221 @Nested222 inner class Not {223 private val notPredPe = Pred(224 type = Not,225 pe = Now(Lit(len = alpha.length) { it == alpha }),226 )227 @Test228 fun `check logName`() {229 notPredPe.logName shouldBe "Not(Literal)"230 }231 @Test232 fun `parse 1 'not' predicate in correct string`() {233 ps = ParserState(delta)234 val actualNotPred = notPredPe.parse(ps)235 actualNotPred shouldBeSome Unit236 assertSoftly(ps) {237 i shouldBe 0238 ignoreWS shouldBe false239 memNone.forAll { it.shouldBeEmpty() }240 memSome.forAll { it.shouldBeEmpty() }241 errs should beEmpty()242 }243 }244 @Test245 fun `parse 1 'not' predicate in incorrect string`() {246 ps = ParserState(alpha)247 val actualNotPred = notPredPe.parse(ps)248 actualNotPred should beNone()249 assertSoftly(ps) {250 i shouldBe 0251 ignoreWS shouldBe false252 memNone.forAll { it.shouldBeEmpty() }253 memSome.forAll { it.shouldBeEmpty() }254 errs shouldBe listOf(ParseError(index = 0, message = "Wrong Not(Literal)"))255 }256 }257 @Test258 fun `parse 1 'not' predicate in empty string`() {259 ps = ParserState("")260 val actualNotPred = notPredPe.parse(ps)261 actualNotPred shouldBeSome Unit262 assertSoftly(ps) {263 i shouldBe 0264 ignoreWS shouldBe false265 memNone.forAll { it.shouldBeEmpty() }266 memSome.forAll { it.shouldBeEmpty() }267 errs should beEmpty()268 }269 }270 }271 }272 @Nested273 inner class Sequence {274 private fun correctProvider() = seqCorrectProvider()275 private fun incorrectProvider() = seqIncorrectProvider()276 private fun emptyProvider() = seqEmptyProvider()277 private fun exProvider() = seqExProvider()278 @Test279 fun `check logName`() {280 val seqPe = Seq<String> {281 val symChar = +Now(Ch { it == a })282 val symLiteral = +Now(Lit(len = alpha.length) { it == alpha })283 value { "${symChar.get}${symLiteral.get}" }284 }285 seqPe.logName shouldBe "Sequence(Character, Literal)"286 }287 @ParameterizedTest288 @MethodSource("correctProvider")289 internal fun `parse sequence in correct string`(data: SequenceCorrect) {290 ps = ParserState(data.s)291 val actualSequence = data.pe.parse(ps)292 actualSequence shouldBe data.expected293 assertSoftly(ps) {294 i shouldBe data.i295 ignoreWS shouldBe false296 memNone.forAll { it.shouldBeEmpty() }297 memSome.forAll { it.shouldBeEmpty() }298 errs should beEmpty()299 }300 }301 @ParameterizedTest302 @MethodSource("incorrectProvider")303 internal fun `parse sequence in incorrect string`(data: SequenceIncorrect) {304 ps = ParserState(data.s)305 val actualSequence = data.pe.parse(ps)306 actualSequence should beNone()307 assertSoftly(ps) {308 i shouldBe 0309 ignoreWS shouldBe false310 memNone.forAll { it.shouldBeEmpty() }311 memSome.forAll { it.shouldBeEmpty() }312 errs shouldBe data.errs313 }314 }315 @ParameterizedTest316 @MethodSource("emptyProvider")317 internal fun `parse sequence in empty string`(data: SequenceEmpty) {318 ps = ParserState("")319 val actualSequence = data.pe.parse(ps)320 actualSequence should beNone()321 assertSoftly(ps) {322 i shouldBe 0323 ignoreWS shouldBe false324 memNone.forAll { it.shouldBeEmpty() }325 memSome.forAll { it.shouldBeEmpty() }326 errs shouldBe data.errs327 }328 }329 @ParameterizedTest330 @MethodSource("exProvider")331 internal fun `create sequence wrongly`(data: SequenceException) {332 val e = shouldThrow<IllegalStateException> { data.peBlock() }333 e.message shouldBe "The sequence must contain 1 or more subexpressions"334 }335 }336 @Nested337 inner class PrioritizedChoice {338 private fun correctProvider() = prChoiceCorrectProvider()339 private fun incorrectProvider() = prChoiceIncorrectProvider()340 private fun emptyProvider() = prChoiceEmptyProvider()341 @Test342 fun `check logName`() {343 val prChoicePe = PrCh(344 Now(M(transform = { "$it" }, pe = Now(Ch { it == a }))),345 Now(Lit(len = alpha.length) { it == alpha }),346 )347 prChoicePe.logName shouldBe "PrioritizedChoice(Character / Literal)"348 }349 @ParameterizedTest350 @MethodSource("correctProvider")351 internal fun `parse prioritized choice in correct string`(data: PrChoiceCorrect) {352 ps = ParserState(data.s)353 val actualPrChoice = data.pe.parse(ps)354 actualPrChoice shouldBe data.expected355 assertSoftly(ps) {356 i shouldBe data.i357 ignoreWS shouldBe false358 memNone.forAll { it.shouldBeEmpty() }359 memSome.forAll { it.shouldBeEmpty() }360 errs should beEmpty()361 }362 }363 @ParameterizedTest364 @MethodSource("incorrectProvider")365 internal fun `parse prioritized choice in incorrect string`(data: PrChoiceIncorrect) {366 ps = ParserState(data.s)367 val actualPrChoice = data.pe.parse(ps)368 actualPrChoice should beNone()369 assertSoftly(ps) {370 i shouldBe 0371 ignoreWS shouldBe false372 memNone.forAll { it.shouldBeEmpty() }373 memSome.forAll { it.shouldBeEmpty() }374 errs shouldBe data.errs375 }376 }377 @ParameterizedTest378 @MethodSource("emptyProvider")379 internal fun `parse prioritized choice in empty string`(data: PrChoiceEmpty) {380 ps = ParserState("")381 val actualPrChoice = data.pe.parse(ps)382 actualPrChoice should beNone()383 assertSoftly(ps) {384 i shouldBe 0385 ignoreWS shouldBe false386 memNone.forAll { it.shouldBeEmpty() }387 memSome.forAll { it.shouldBeEmpty() }388 errs shouldBe data.errs389 }390 }391 }392 @Nested393 inner class MapPe {394 private val mapPe = M(transform = { it.toString() }, pe = Now(Ch { it == a }))395 @Test396 fun `check logName`() {397 mapPe.logName shouldBe "Character"398 }399 @Test400 fun `parse 1 map pe in correct string`() {401 ps = ParserState("$a")402 val actualMapPe = mapPe.parse(ps)403 actualMapPe shouldBeSome "$a"404 assertSoftly(ps) {405 i shouldBe 1406 ignoreWS shouldBe false407 memNone.forAll { it.shouldBeEmpty() }408 memSome.forAll { it.shouldBeEmpty() }409 errs should beEmpty()410 }411 }412 @Test413 fun `parse 1 map pe in incorrect string`() {414 ps = ParserState("$d")415 val actualMapPe = mapPe.parse(ps)416 actualMapPe should beNone()417 assertSoftly(ps) {418 i shouldBe 0419 ignoreWS shouldBe false420 memNone.forAll { it.shouldBeEmpty() }421 memSome.forAll { it.shouldBeEmpty() }422 errs shouldBe listOf(ParseError(index = 0, message = "Wrong Character"))423 }...

Full Screen

Full Screen

TcpRawHttpServerTests.kt

Source:TcpRawHttpServerTests.kt Github

copy

Full Screen

1package rawhttp.core.server2import io.kotest.assertions.fail3import io.kotest.core.spec.Spec4import io.kotest.core.spec.style.StringSpec5import io.kotest.matchers.optional.beEmpty6import io.kotest.matchers.optional.shouldBePresent7import io.kotest.matchers.shouldBe8import io.kotest.matchers.shouldHave9import rawhttp.core.RawHttp10import rawhttp.core.RawHttp.waitForPortToBeTaken11import rawhttp.core.RawHttpHeaders12import rawhttp.core.RawHttpRequest13import rawhttp.core.RawHttpResponse14import rawhttp.core.RequestLine15import rawhttp.core.body.EagerBodyReader16import rawhttp.core.body.StringBody17import rawhttp.core.client.TcpRawHttpClient18import rawhttp.core.validDateHeader19import java.lang.Thread.sleep20import java.net.InetAddress21import java.net.Socket22import java.net.SocketException23import java.nio.charset.StandardCharsets24import java.time.Duration25import java.util.Optional26class TcpRawHttpServerTests : StringSpec() {27 companion object {28 private val http = RawHttp()29 }30 private val server = TcpRawHttpServer(8093)31 private val httpClient = TcpRawHttpClient()32 private object TestRouter : Router {33 override fun route(req: RawHttpRequest): Optional<RawHttpResponse<*>> {34 return Optional.ofNullable(35 when (req.uri.path) {36 "/hello", "/" ->37 when (req.method) {38 "GET", "HEAD" ->39 http.parseResponse(40 "HTTP/1.1 200 OK\n" +41 "Content-Type: text/plain"42 ).withBody(StringBody("Hello RawHTTP!"))43 "DELETE" ->44 throw Exception("Cannot delete")45 "POST" ->46 http.parseResponse("HTTP/1.1 200 OK").withBody(StringBody("Thanks"))47 else ->48 http.parseResponse(49 "HTTP/1.1 405 Method Not Allowed\n" +50 "Content-Type: text/plain"51 ).withBody(StringBody("Sorry, can't handle this method"))52 }53 "/throw" -> throw Exception("Not doing it!")54 "/null" -> null55 else ->56 http.parseResponse(57 "HTTP/1.1 404 Not Found\n" +58 "Content-Type: text/plain"59 ).withBody(StringBody("Content was not found"))60 }61 )62 }63 override fun continueResponse(requestLine: RequestLine, headers: RawHttpHeaders):64 Optional<RawHttpResponse<Void>> {65 return Optional.of(66 HttpResponses.get100ContinueResponse()67 .withHeaders(68 RawHttpHeaders.newBuilder()69 .with("Accept-100", "True")70 .build()71 )72 )73 }74 }75 private fun startServer() {76 server.start(TestRouter)77 }78 private fun cleanup() {79 server.stop()80 httpClient.close()81 }82 override fun beforeSpec(spec: Spec) {83 startServer()84 waitForPortToBeTaken(8093, Duration.ofSeconds(2))85 }86 override fun afterSpec(spec: Spec) {87 cleanup()88 }89 init {90 "Server can handle successful http client request" {91 val request = http.parseRequest("GET http://localhost:8093/hello")92 val response = httpClient.send(request).eagerly()93 response.statusCode shouldBe 20094 response.body shouldBePresent {95 it.asRawString(Charsets.UTF_8) shouldBe "Hello RawHTTP!"96 }97 }98 "Server can handle multiple successful http client requests, including HEAD request" {99 val getRequest = http.parseRequest("GET http://localhost:8093/hello")100 val headRequest = http.parseRequest("HEAD http://localhost:8093/hello")101 val response = httpClient.send(getRequest).eagerly()102 response.statusCode shouldBe 200103 response.headers["Content-Length"] shouldBe listOf("14")104 response.body shouldBePresent {105 it.asRawString(Charsets.UTF_8) shouldBe "Hello RawHTTP!"106 }107 sleep(500)108 val response2 = httpClient.send(headRequest).eagerly()109 response2.statusCode shouldBe 200110 response2.headers["Content-Length"] shouldBe listOf("14")111 response2.body shouldBe beEmpty<EagerBodyReader>()112 val response3 = httpClient.send(getRequest).eagerly()113 response3.statusCode shouldBe 200114 response3.headers["Content-Length"] shouldBe listOf("14")115 response3.body shouldBePresent {116 it.asRawString(Charsets.UTF_8) shouldBe "Hello RawHTTP!"117 }118 }119 "Server can handle wrong method http client request" {120 val request = http.parseRequest("PUT http://localhost:8093")121 val response = httpClient.send(request).eagerly()122 response.statusCode shouldBe 405123 response.body shouldBePresent {124 it.asRawString(Charsets.UTF_8) shouldBe "Sorry, can't handle this method"125 }126 }127 "Server can handle wrong path http client request" {128 val request = http.parseRequest("GET http://localhost:8093/wrong/path")129 val response = httpClient.send(request).eagerly()130 response.statusCode shouldBe 404131 response.body shouldBePresent {132 it.asRawString(Charsets.UTF_8) shouldBe "Content was not found"133 }134 }135 "Server returns default error response when router throws an Exception" {136 val request = http.parseRequest("POST http://localhost:8093/throw")137 val response = httpClient.send(request).eagerly()138 response.statusCode shouldBe 500139 response.headers shouldHave validDateHeader()140 response.headers["Content-Type"] shouldBe listOf("text/plain")141 response.body shouldBePresent {142 it.asRawString(Charsets.UTF_8) shouldBe "A Server Error has occurred."143 }144 }145 "Server returns default error response when request handler throws an Exception" {146 val request = http.parseRequest("DELETE http://localhost:8093")147 val response = httpClient.send(request).eagerly()148 response.statusCode shouldBe 500149 response.headers shouldHave validDateHeader()150 response.headers["Content-Type"] shouldBe listOf("text/plain")151 response.body shouldBePresent {152 it.asRawString(Charsets.UTF_8) shouldBe "A Server Error has occurred."153 }154 }155 "Server returns default error response when request handler returns null" {156 val request = http.parseRequest("Get http://localhost:8093/null")157 val response = httpClient.send(request).eagerly()158 response.statusCode shouldBe 404159 response.headers shouldHave validDateHeader()160 response.headers["Content-Type"] shouldBe listOf("text/plain")161 response.body shouldBePresent {162 it.asRawString(Charsets.UTF_8) shouldBe "Resource was not found."163 }164 }165 "Server should persist connection on all HTTP/1.1 requests" {166 val socket = Socket("0.0.0.0", 8093)167 http.parseRequest("GET /hello HTTP/1.1\r\nHost: localhost").writeTo(socket.getOutputStream())168 val response = http.parseResponse(socket.getInputStream()).eagerly(true)169 response.statusCode shouldBe 200170 // the server should persist the connection171 socket.assertIsOpen()172 }173 "Server should close connection on HTTP/1.1 requests if 'Connection: close' header is sent" {174 val socket = Socket("0.0.0.0", 8093)175 http.parseRequest(176 "GET /hello HTTP/1.1\r\n" +177 "Host: localhost\r\n" +178 "Connection: close"179 ).writeTo(socket.getOutputStream())180 val response = http.parseResponse(socket.getInputStream()).eagerly(true)181 response.statusCode shouldBe 200182 // the server should have closed this Socket183 socket.assertIsClosed()184 }185 "Server should close connection on HTTP/1.0 requests" {186 val socket = Socket("0.0.0.0", 8093)187 http.parseRequest("GET /hello HTTP/1.0\r\nHost: localhost").writeTo(socket.getOutputStream())188 val response = http.parseResponse(socket.getInputStream()).eagerly(true)189 response.statusCode shouldBe 200190 // the server should have closed this Socket191 socket.assertIsClosed()192 }193 "Server should persist connection on HTTP/1.0 requests if 'Connection: keep-alive' header is sent" {194 val socket = Socket("0.0.0.0", 8093)195 http.parseRequest(196 "GET /hello HTTP/1.0\r\n" +197 "Host: localhost\r\n" +198 "Connection: keep-alive"199 ).writeTo(socket.getOutputStream())200 val response = http.parseResponse(socket.getInputStream()).eagerly(true)201 response.statusCode shouldBe 200202 // the server should persist the connection203 socket.assertIsOpen()204 }205 "Server honours http client request desire to use 100-Continue" {206 val request = http.parseRequest(207 "POST / HTTP/1.1\n" +208 "Host: localhost:8093\n" +209 "Expect: 100-continue\n" +210 "Content-Length: 10\n" +211 "\n" +212 "0123456789"213 ).eagerly()214 val socket = Socket(InetAddress.getLoopbackAddress(), 8093)215 socket.soTimeout = 500216 // don't send the body just yet217 val out = socket.getOutputStream()218 Thread {219 request.startLine.writeTo(out)220 request.headers.writeTo(out)221 }.start()222 val response100 = http.parseResponse(socket.getInputStream()).eagerly()223 response100.statusCode shouldBe 100224 response100.headers["Accept-100"] shouldBe listOf("True")225 response100.body shouldBe beEmpty<EagerBodyReader>()226 // Server accepted the body, send it227 request.body.map { it.writeTo(out) }228 // now the final response can be read229 val response = http.parseResponse(socket.getInputStream()).eagerly()230 response.statusCode shouldBe 200231 response.headers shouldHave validDateHeader()232 response.body shouldBePresent {233 it.asRawString(StandardCharsets.UTF_8) shouldBe "Thanks"234 }235 }236 }237 private fun Socket.assertIsOpen() {238 if (isClosed) {239 fail("Expected Socket to be open, but it has been closed")...

Full Screen

Full Screen

HttpHeadersTest.kt

Source:HttpHeadersTest.kt Github

copy

Full Screen

1package rawhttp.core2import io.kotest.assertions.throwables.shouldThrow3import io.kotest.matchers.collections.shouldHaveSize4import io.kotest.matchers.optional.beEmpty5import io.kotest.matchers.optional.shouldBePresent6import io.kotest.matchers.shouldBe7import org.junit.jupiter.api.Test8import rawhttp.core.errors.InvalidHttpHeader9import java.io.ByteArrayOutputStream10import java.nio.charset.StandardCharsets11class HttpHeadersTest {12 @Test13 fun headersAreMultiValueCaseInsensitive() {14 RawHttpHeaders.newBuilder()15 .with("hi", "aaa")16 .with("hi", "bbb")17 .with("ho", "ccc")18 .with("X-F", "ö")19 .build().run {20 get("hi") shouldBe listOf("aaa", "bbb")21 get("ho") shouldBe listOf("ccc")22 get("X-F") shouldBe listOf("ö")23 get("Hi") shouldBe get("hi")24 get("Hi") shouldBe get("HI")25 get("Ho") shouldBe get("ho")26 get("Ho") shouldBe get("hO")27 get("X-F") shouldBe get("x-f")28 getFirst("hi") shouldBePresent { it shouldBe "aaa" }29 getFirst("HI") shouldBePresent { it shouldBe "aaa" }30 getFirst("ho") shouldBePresent { it shouldBe "ccc" }31 getFirst("Ho") shouldBePresent { it shouldBe "ccc" }32 getFirst("X-F") shouldBePresent { it shouldBe "ö" }33 getFirst("HI") shouldBe getFirst("hi")34 getFirst("HO") shouldBe getFirst("ho")35 getFirst("x-f") shouldBe getFirst("X-f")36 get("blah") shouldHaveSize(0)37 getFirst("blah") shouldBe beEmpty<String>()38 contains("hi") shouldBe true39 contains("Hi") shouldBe true40 contains("hI") shouldBe true41 contains("HI") shouldBe true42 contains("Ho") shouldBe true43 contains("x-f") shouldBe true44 contains("X-F") shouldBe true45 contains("Blah") shouldBe false46 headerNames shouldBe listOf("hi", "hi", "ho", "X-F")47 uniqueHeaderNames shouldBe setOf("HI", "HO", "X-F")48 }49 }50 @Test51 fun headersCanContainMultipleEntriesAndMultipleValuesWithinEachEntry() {...

Full Screen

Full Screen

RangeTest.kt

Source:RangeTest.kt Github

copy

Full Screen

...7import com.github.ajalt.clikt.testing.parse8import io.kotest.assertions.throwables.shouldThrow9import io.kotest.data.blocking.forAll10import io.kotest.data.row11import io.kotest.matchers.collections.beEmpty12import io.kotest.matchers.should13import io.kotest.matchers.shouldBe14import kotlin.js.JsName15import kotlin.test.Test16class RangeTest {17 @Test18 @JsName("restrictTo_option_min")19 fun `restrictTo option min`() {20 class C : TestCommand() {21 val x by option("-x", "--xx").int().restrictTo(min = 1)22 }23 C().apply {24 parse("")25 x shouldBe null26 }27 C().apply {28 parse("-x1")29 x shouldBe 130 }31 C().apply {32 parse("-x3")33 x shouldBe 334 }35 shouldThrow<BadParameterValue> { C().parse("--xx=0") }36 .message shouldBe "Invalid value for \"--xx\": 0 is smaller than the minimum valid value of 1."37 }38 @Test39 @JsName("restrictTo_option_min_clamp")40 fun `restrictTo option min clamp`() = forAll(41 row("", null),42 row("--xx=1", 1),43 row("--xx -123", 1),44 row("-x0", 1)) { argv, expected ->45 class C : TestCommand() {46 val x by option("-x", "--xx").int().restrictTo(min = 1, clamp = true)47 override fun run_() {48 x shouldBe expected49 }50 }51 C().parse(argv)52 }53 @Test54 @JsName("restrictTo_option_max")55 fun `restrictTo option max`() {56 class C : TestCommand() {57 val x by option("-x", "--xx").int().restrictTo(max = 1)58 }59 C().apply {60 parse("")61 x shouldBe null62 }63 C().apply {64 parse("-x1")65 x shouldBe 166 }67 C().apply {68 parse("-x0")69 x shouldBe 070 }71 shouldThrow<BadParameterValue> { C().parse("--xx=2") }72 .message shouldBe "Invalid value for \"--xx\": 2 is larger than the maximum valid value of 1."73 }74 @Test75 @JsName("restrictTo_option_max_clamp")76 fun `restrictTo option max clamp`() = forAll(77 row("", null),78 row("--xx=1", 1),79 row("--xx 123", 1),80 row("-x2", 1)) { argv, expected ->81 class C : TestCommand() {82 val x by option("-x", "--xx").int().restrictTo(max = 1, clamp = true)83 override fun run_() {84 x shouldBe expected85 }86 }87 C().parse(argv)88 }89 @Test90 @JsName("restrictTo_option_range")91 fun `restrictTo option range`() {92 class C : TestCommand() {93 val x by option("-x", "--xx").int().restrictTo(1..2)94 }95 C().apply {96 parse("")97 x shouldBe null98 }99 C().apply {100 parse("-x1")101 x shouldBe 1102 }103 C().apply {104 parse("-x2")105 x shouldBe 2106 }107 shouldThrow<BadParameterValue> { C().parse("--xx=3") }108 .message shouldBe "Invalid value for \"--xx\": 3 is not in the valid range of 1 to 2."109 shouldThrow<BadParameterValue> { C().parse("-x0") }110 .message shouldBe "Invalid value for \"-x\": 0 is not in the valid range of 1 to 2."111 }112 @Test113 @JsName("restrictTo_option_default")114 fun `restrictTo option default`() {115 class C : TestCommand() {116 val x by option("-x", "--xx").int().restrictTo(1..2).default(2)117 val y by option("-y", "--yy").int().restrictTo(min = 3, max = 4).default(3)118 }119 C().apply {120 parse("")121 x shouldBe 2122 y shouldBe 3123 }124 C().apply {125 parse("-x1")126 x shouldBe 1127 y shouldBe 3128 }129 C().apply {130 parse("-y4")131 x shouldBe 2132 y shouldBe 4133 }134 shouldThrow<BadParameterValue> { C().parse("--xx=3") }135 .message shouldBe "Invalid value for \"--xx\": 3 is not in the valid range of 1 to 2."136 shouldThrow<BadParameterValue> { C().parse("-y10") }137 .message shouldBe "Invalid value for \"-y\": 10 is not in the valid range of 3 to 4."138 }139 @Test140 @JsName("restrictTo_option_multiple")141 fun `restrictTo option multiple`() {142 class C : TestCommand() {143 val x by option("-x", "--xx").int().restrictTo(1..2).multiple()144 val y by option("-y", "--yy").int().restrictTo(min = 3, max = 4).pair()145 }146 C().apply {147 parse("")148 x should beEmpty()149 y shouldBe null150 }151 C().apply {152 parse("-x1 -x2")153 x shouldBe listOf(1, 2)154 y shouldBe null155 }156 C().apply {157 parse("-y 3 4")158 x should beEmpty()159 y shouldBe (3 to 4)160 }161 shouldThrow<BadParameterValue> { C().parse("--xx=3") }162 .message shouldBe "Invalid value for \"--xx\": 3 is not in the valid range of 1 to 2."163 shouldThrow<BadParameterValue> { C().parse("-y10 1") }164 .message shouldBe "Invalid value for \"-y\": 10 is not in the valid range of 3 to 4."165 }166 @Test167 @JsName("restrictTo_option_char")168 fun `restrictTo option char`() {169 class C : TestCommand() {170 val x by option("-x", "--xx").convert { it[0] }.restrictTo('b'..'d')171 }172 C().apply {...

Full Screen

Full Screen

ArgumentsTest.kt

Source:ArgumentsTest.kt Github

copy

Full Screen

...257 arr.shouldHaveElementAt(1, File("./test").path)258 }259 }260 // <editor-fold desc="Helper extensions">261 private fun beEmpty() = object : Matcher<Arguments> {262 override fun test(value: Arguments) = MatcherResult(263 value.toArray().isEmpty(),264 "Arguments $value should be empty",265 "String $value should not be empty"266 )267 }268 private fun Arguments.shouldBeEmpty() = this should beEmpty()269 private fun Arguments.shouldNotBeEmpty() = this shouldNot beEmpty()270 // </editor-fold>271}...

Full Screen

Full Screen

OptionalMatchersTest.kt

Source:OptionalMatchersTest.kt Github

copy

Full Screen

1package com.sksamuel.kotest.matchers.optional2import io.kotest.assertions.throwables.shouldThrow3import io.kotest.core.spec.style.ShouldSpec4import io.kotest.matchers.optional.beEmpty5import io.kotest.matchers.optional.bePresent6import io.kotest.matchers.optional.shouldBeEmpty7import io.kotest.matchers.optional.shouldBePresent8import io.kotest.matchers.optional.shouldNotBeEmpty9import io.kotest.matchers.optional.shouldNotBePresent10import io.kotest.matchers.should11import io.kotest.matchers.shouldBe12import io.kotest.matchers.shouldNot13import io.kotest.matchers.throwable.shouldHaveMessage14import java.util.Optional15class OptionalMatchersTest : ShouldSpec({16 context("Empty optional") {17 val optional = Optional.empty<Any>()18 should("Be empty") {19 optional.shouldBeEmpty()20 optional should beEmpty()21 }22 should("Not be present") {23 optional.shouldNotBePresent()24 optional shouldNot bePresent()25 }26 should("Fail to be notEmpty") {27 shouldThrow<AssertionError> { optional.shouldNotBeEmpty() }28 shouldThrow<AssertionError> { optional shouldNot beEmpty() }29 }30 should("Fail to be present") {31 shouldThrow<AssertionError> { optional.shouldBePresent() }32 shouldThrow<AssertionError> { optional should bePresent() }33 }34 }35 context("Present optional") {36 val optional = Optional.of("A")37 should("Be present") {38 optional.shouldBePresent()39 optional should bePresent()40 }41 42 should("Return the present value for usage in more assertions") {...

Full Screen

Full Screen

matchers.kt

Source:matchers.kt Github

copy

Full Screen

...12 *13 * Optional.of("A").shouldBeEmpty() // Assertion fails14 * ```15 */16fun <T> Optional<T>.shouldBeEmpty() = this should beEmpty()17/**18 * Asserts that a [Optional] is not empty19 *20 * ```21 * Optional.of("A").shouldNotBeEmpty() // Assertion passes22 *23 * Optional.empty().shouldNotBeEmpty() // Assertion fails24 * ```25 */26fun <T> Optional<T>.shouldNotBeEmpty() = this shouldNot beEmpty()27/**28 * Matcher to verify whether an [Optional] is empty or not29 */30fun <T> beEmpty() = object : Matcher<Optional<T>> {31 override fun test(value: Optional<T>) = MatcherResult(32 !value.isPresent,33 { "Expected optional to be empty, but instead was ${value.get()}" },34 { "Expected optional to not be empty, but was" }35 )36}37/**38 * Verifies if this [Optional] is present then execute [block] with it's value39 *40 * ```41 * val optional = Optional.of("A")42 *43 * optional shouldBePresent {44 * it shouldBe "A"...

Full Screen

Full Screen

beEmpty

Using AI Code Generation

copy

Full Screen

1val emptyOptional : Optional < String > = Optional . empty () emptyOptional . shouldBeEmpty ()2val presentOptional : Optional < String > = Optional . of ( "test" ) presentOptional . shouldBePresent ()3val presentOptional : Optional < String > = Optional . of ( "test" ) presentOptional . shouldBePresentAnd { it . shouldHaveLength ( 4 ) }4val presentOptional : Optional < String > = Optional . of ( "test" ) presentOptional . shouldBePresentOr { it . shouldHaveLength ( 5 ) }5val presentOptional : Optional < String > = Optional . of ( "test" ) presentOptional . shouldBePresentOrElse ( { it . shouldHaveLength ( 4 ) } , { it . shouldHaveLength ( 5 ) } )6val presentOptional : Optional < String > = Optional . of ( "test" ) presentOptional . shouldHaveValue ( "test" )7val presentOptional : Optional < String > = Optional . of ( "test" ) presentOptional . shouldHaveValueSatisfying { it . shouldHaveLength ( 4 ) }8val presentOptional : Optional < String > = Optional . of ( "test" ) presentOptional . shouldHaveValueOr { it . shouldHaveLength ( 5 ) }9val presentOptional : Optional < String > = Optional . of ( "test" ) presentOptional . shouldHaveValueOrElse ( { it . shouldHaveLength ( 4 ) } , { it . shouldHaveLength ( 5 ) } )

Full Screen

Full Screen

beEmpty

Using AI Code Generation

copy

Full Screen

1import io.kotest.matchers.optional.shouldBeEmpty2val optional: Optional<Int> = Optional.empty()3optional.shouldBeEmpty()4import io.kotest.matchers.optional.shouldBePresent5val optional: Optional<Int> = Optional.of(2)6optional.shouldBePresent()7import io.kotest.matchers.optional.shouldBePresentWithValue8val optional: Optional<Int> = Optional.of(2)9optional.shouldBePresentWithValue(2)10import io.kotest.matchers.optional.shouldBePresentWithValue11val optional: Optional<Int> = Optional.of(2)12import io.kotest.matchers.optional.shouldBePresentWithValue13val optional: Optional<Int> = Optional.of(2)14import io.kotest.matchers.optional.shouldBePresentWithValue15val optional: Optional<Int> = Optional.of(2)16import io.kotest.matchers.optional.shouldBePresentWithValue17val optional: Optional<Int> = Optional.of(2)18import io.kotest.matchers.optional.shouldBePresentWithValue19val optional: Optional<Int> = Optional.of(2)20import io.kotest.matchers.optional.shouldBePresentWithValue21val optional: Optional<Int> = Optional.of(2)22import io.kotest.matchers.optional

Full Screen

Full Screen

beEmpty

Using AI Code Generation

copy

Full Screen

1val opt : Optional < String > = Optional . empty () opt . shouldNotBeEmpty ()2val opt : Optional < String > = Optional . of ( "hello" ) opt . shouldBeEmpty ()3val opt : Optional < String > = Optional . empty () opt . shouldBeEmpty ()4val opt : Optional < String > = Optional . of ( "hello" ) opt . shouldNotBePresent ()5val opt : Optional < String > = Optional . empty () opt . shouldBePresent ()6val opt : Optional < String > = Optional . of ( "hello" ) opt . shouldBePresent ()7val opt : Optional < String > = Optional . empty () opt . shouldNotBePresent ()8val opt : Optional < String > = Optional . of ( "hello" ) opt . shouldNotBePresent ()9val opt : Optional < String > = Optional . empty () opt . shouldBePresent ()10val opt : Optional < String > = Optional . of ( "hello" ) opt . shouldBePresent ()11val opt : Optional < String > = Optional . empty () opt . shouldNotBePresent ()12val opt : Optional < String > = Optional . of ( "hello" ) opt . shouldNotBePresent ()13val opt : Optional < String > = Optional . empty () opt . shouldBePresent ()

Full Screen

Full Screen

beEmpty

Using AI Code Generation

copy

Full Screen

1val optionalString: Optional<String> = Optional.of(“Kotest”)2optionalString.shouldBeEmpty()3val optionalString: Optional<String> = Optional.of(“Kotest”)4optionalString.shouldBePresent()5val optionalString: Optional<String> = Optional.of(“Kotest”)6optionalString.shouldBePresent()7val optionalString: Optional<String> = Optional.of(“Kotest”)8optionalString.shouldBePresent()9val optionalString: Optional<String> = Optional.of(“Kotest”)10optionalString.shouldBePresent()11val optionalString: Optional<String> = Optional.of(“Kotest”)12optionalString.shouldBePresent()13val optionalString: Optional<String> = Optional.of(“Kotest”)14optionalString.shouldBePresent()15val optionalString: Optional<String> = Optional.of(“Kotest”)16optionalString.shouldBePresent()17val optionalString: Optional<String> = Optional.of(“Kotest”)18optionalString.shouldBePresent()19val optionalString: Optional<String> = Optional.of(“Kotest”)20optionalString.shouldBePresent()21val optionalString: Optional<String> = Optional.of(“Kotest”)22optionalString.shouldBePresent()23val optionalString: Optional<String> = Optional.of(“Kotest”)24optionalString.shouldBePresent()

Full Screen

Full Screen

beEmpty

Using AI Code Generation

copy

Full Screen

1val optVal: Optional<String> = Optional.empty()2optVal.shouldBeEmpty()3val optVal: Optional<String> = Optional.empty()4optVal.shouldBeEmpty()5val optVal: Optional<String> = Optional.empty()6optVal.shouldBeEmpty()7val optVal: Optional<String> = Optional.empty()8optVal.shouldBeEmpty()9val optVal: Optional<String> = Optional.empty()10optVal.shouldBeEmpty()11val optVal: Optional<String> = Optional.empty()12optVal.shouldBeEmpty()13val optVal: Optional<String> = Optional.empty()14optVal.shouldBeEmpty()15val optVal: Optional<String> = Optional.empty()16optVal.shouldBeEmpty()17val optVal: Optional<String> = Optional.empty()18optVal.shouldBeEmpty()19val optVal: Optional<String> = Optional.empty()20optVal.shouldBeEmpty()21val optVal: Optional<String> = Optional.empty()22optVal.shouldBeEmpty()23val optVal: Optional<String> = Optional.empty()24optVal.shouldBeEmpty()25val optVal: Optional<String> = Optional.empty()26optVal.shouldBeEmpty()27val optVal: Optional<String> = Optional.empty()28optVal.shouldBeEmpty()

Full Screen

Full Screen

beEmpty

Using AI Code Generation

copy

Full Screen

1BeEmptyMatcher().test(Optional.empty())2BePresentMatcher().test(Optional.of("Hello"))3BePresentMatcher().test(Optional.ofNullable("Hello"))4BePresentMatcher().test(Optional.empty())5BePresentMatcher().test(Optional.ofNullable(null))6BePresentMatcher().test(Optional.of("Hello"))7BePresentMatcher().test(Optional.ofNullable("Hello"))8BePresentMatcher().test(Optional.empty())9BePresentMatcher().test(Optional.ofNullable(null))10BePresentMatcher().test(Optional.of("Hello"))11BePresentMatcher().test(Optional.ofNullable("Hello"))12BePresentMatcher().test(Optional.empty())13BePresentMatcher().test(Optional.ofNullable(null))14BePresentMatcher().test(Optional.of("Hello"))15BePresentMatcher().test(Optional.ofNullable("Hello"))16BePresentMatcher().test(Optional.empty())17BePresentMatcher().test(Optional.ofNullable(null))18BePresentMatcher().test(Optional.of("Hello"))

Full Screen

Full Screen

beEmpty

Using AI Code Generation

copy

Full Screen

1@DisplayName("Test to check optional empty")2fun `Test to check optional empty`(){3val optional = Optional.empty<String>()4optional.shouldBeEmpty()5}6@DisplayName("Test to check optional present")7fun `Test to check optional present`(){8val optional = Optional.of("Hello")9optional.shouldBePresent()10}11@DisplayName("Test to check optional present and")12fun `Test to check optional present and`(){13val optional = Optional.of("Hello")14optional.shouldBePresentAnd("Hello")15}16@DisplayName("Test to check optional present and")17fun `Test to check optional present and`(){18val optional = Optional.of("Hello")19optional.shouldBePresentAnd("Hello")20}21@DisplayName("Test to check optional present and")22fun `Test to check optional present and`(){23val optional = Optional.of("Hello")24optional.shouldBePresentAnd("Hello")25}26@DisplayName("Test to check optional present and")27fun `Test to check optional present and`(){28val optional = Optional.of("Hello")29optional.shouldBePresentAnd("Hello")30}31@DisplayName("Test to check optional present and")32fun `Test to check optional present and`(){33val optional = Optional.of("Hello")34optional.shouldBePresentAnd("Hello")35}36@DisplayName("Test to check optional present and")37fun `Test to check optional present and`(){38val optional = Optional.of("Hello")39optional.shouldBePresentAnd("Hello")40}41@DisplayName("Test to check optional present and")42fun `Test to check optional present and`(){43val optional = Optional.of("Hello")44optional.shouldBePresentAnd("Hello")

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