Update javaxval/src/test/java/org/baeldung/javaxval/messageinterpolator/ParameterMessageInterpolaterIntegrationTest.java

update to use the givenX_whenY_thenZ naming convention for tests

Co-Authored-By: KevinGilmore <kpg102@gmail.com>
This commit is contained in:
Yavuz Tas
2019-10-29 10:02:27 +01:00
committed by GitHub
parent db85c8f275
commit e28fd3e7c9
20479 changed files with 1642089 additions and 0 deletions
+14
View File
@@ -0,0 +1,14 @@
/bin/
#ignore gradle
.gradle/
#ignore build and generated files
build/
node/
out/
#ignore installed node modules and package lock file
node_modules/
package-lock.json
+17
View File
@@ -0,0 +1,17 @@
## Kotlin Libraries
This module contains articles about Kotlin Libraries.
### Relevant articles:
- [Kotlin with Mockito](https://www.baeldung.com/kotlin-mockito)
- [HTTP Requests with Kotlin and khttp](https://www.baeldung.com/kotlin-khttp)
- [Kotlin Dependency Injection with Kodein](https://www.baeldung.com/kotlin-kodein-dependency-injection)
- [Writing Specifications with Kotlin and Spek](https://www.baeldung.com/kotlin-spek)
- [Processing JSON with Kotlin and Klaxson](https://www.baeldung.com/kotlin-json-klaxson)
- [Guide to the Kotlin Exposed Framework](https://www.baeldung.com/kotlin-exposed-persistence)
- [Working with Dates in Kotlin](https://www.baeldung.com/kotlin-dates)
- [Introduction to Arrow in Kotlin](https://www.baeldung.com/kotlin-arrow)
- [Kotlin with Ktor](https://www.baeldung.com/kotlin-ktor)
- [REST API With Kotlin and Kovert](https://www.baeldung.com/kotlin-kovert)
- More articles: [[next -->]](/kotlin-libraries-2)
+62
View File
@@ -0,0 +1,62 @@
group 'com.baeldung.ktor'
version '1.0-SNAPSHOT'
buildscript {
ext.kotlin_version = '1.2.41'
ext.ktor_version = '0.9.2'
ext.khttp_version = '0.1.0'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'java'
apply plugin: 'kotlin'
apply plugin: 'application'
mainClassName = 'APIServer.kt'
sourceCompatibility = 1.8
compileKotlin { kotlinOptions.jvmTarget = "1.8" }
compileTestKotlin { kotlinOptions.jvmTarget = "1.8" }
kotlin { experimental { coroutines "enable" } }
repositories {
mavenCentral()
jcenter()
maven { url "https://dl.bintray.com/kotlin/ktor" }
}
sourceSets {
main{
kotlin{
srcDirs 'com/baeldung/ktor'
}
}
}
dependencies {
compile "io.ktor:ktor-server-netty:$ktor_version"
compile "ch.qos.logback:logback-classic:1.2.1"
compile "io.ktor:ktor-gson:$ktor_version"
compile "khttp:khttp:$khttp_version"
testCompile group: 'junit', name: 'junit', version: '4.12'
testCompile group: 'org.jetbrains.spek', name: 'spek-api', version: '1.1.5'
testCompile group: 'org.jetbrains.spek', name: 'spek-subject-extension', version: '1.1.5'
testCompile group: 'org.jetbrains.spek', name: 'spek-junit-platform-engine', version: '1.1.5'
implementation 'com.beust:klaxon:3.0.1'
}
task runServer(type: JavaExec) {
main = 'APIServer'
classpath = sourceSets.main.runtimeClasspath
}
Binary file not shown.
@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
+84
View File
@@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+177
View File
@@ -0,0 +1,177 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>kotlin-libraries</artifactId>
<name>kotlin-libraries</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-kotlin</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../parent-kotlin</relativePath>
</parent>
<repositories>
<repository>
<id>exposed</id>
<name>exposed</name>
<url>https://dl.bintray.com/kotlin/exposed</url>
</repository>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>kotlinx</id>
<name>bintray</name>
<url>https://dl.bintray.com/kotlin/kotlinx</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.jetbrains.spek</groupId>
<artifactId>spek-api</artifactId>
<version>1.1.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.spek</groupId>
<artifactId>spek-subject-extension</artifactId>
<version>1.1.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.spek</groupId>
<artifactId>spek-junit-platform-engine</artifactId>
<version>1.1.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>khttp</groupId>
<artifactId>khttp</artifactId>
<version>${khttp.version}</version>
</dependency>
<dependency>
<groupId>com.nhaarman</groupId>
<artifactId>mockito-kotlin</artifactId>
<version>${mockito-kotlin.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.salomonbrys.kodein</groupId>
<artifactId>kodein</artifactId>
<version>${kodein.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.beust</groupId>
<artifactId>klaxon</artifactId>
<version>${klaxon.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.exposed</groupId>
<artifactId>exposed</artifactId>
<version>${exposed.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.arrow-kt/arrow-core -->
<dependency>
<groupId>io.arrow-kt</groupId>
<artifactId>arrow-core</artifactId>
<version>${arrow-core.version}</version>
</dependency>
<dependency>
<groupId>uy.kohesive.kovert</groupId>
<artifactId>kovert-vertx</artifactId>
<version>[1.5.0,1.6.0)</version>
<exclusions>
<exclusion>
<groupId>nl.komponents.kovenant</groupId>
<artifactId>kovenant</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>nl.komponents.kovenant</groupId>
<artifactId>kovenant</artifactId>
<version>${kovenant.version}</version>
<type>pom</type>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>${byte-buddy.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy-agent</artifactId>
<version>${byte-buddy.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.objenesis</groupId>
<artifactId>objenesis</artifactId>
<version>${objenesis.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.reactivex.rxjava2</groupId>
<artifactId>rxkotlin</artifactId>
<version>${rxkotlin.version}</version>
</dependency>
</dependencies>
<properties>
<junit.version>4.12</junit.version>
<mockito-kotlin.version>1.5.0</mockito-kotlin.version>
<kodein.version>4.1.0</kodein.version>
<klaxon.version>3.0.4</klaxon.version>
<khttp.version>0.1.0</khttp.version>
<commons-math3.version>3.6.1</commons-math3.version>
<junit.platform.version>1.1.1</junit.platform.version>
<junit.vintage.version>5.2.0</junit.vintage.version>
<assertj.version>3.10.0</assertj.version>
<exposed.version>0.10.4</exposed.version>
<kovenant.version>3.3.0</kovenant.version>
<byte-buddy.version>1.8.13</byte-buddy.version>
<objenesis.version>2.6</objenesis.version>
<rxkotlin.version>2.3.0</rxkotlin.version>
<arrow-core.version>0.7.3</arrow-core.version>
</properties>
</project>
+11
View File
@@ -0,0 +1,11 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT"/>
</root>
</configuration>
+2
View File
@@ -0,0 +1,2 @@
rootProject.name = 'KtorWithKotlin'
@@ -0,0 +1,9 @@
package com.baeldung.klaxon
import com.beust.klaxon.Json
class CustomProduct(
@Json(name = "productName")
val name: String,
@Json(ignored = true)
val id: Int)
@@ -0,0 +1,3 @@
package com.baeldung.klaxon
class Product(val name: String)
@@ -0,0 +1,3 @@
package com.baeldung.klaxon
data class ProductData(val name: String, val capacityInGb: Int)
@@ -0,0 +1,54 @@
package com.baeldung.kotlin.arrow
import arrow.core.Either
import arrow.core.filterOrElse
import kotlin.math.sqrt
class FunctionalErrorHandlingWithEither {
sealed class ComputeProblem {
object OddNumber : ComputeProblem()
object NotANumber : ComputeProblem()
}
fun parseInput(s : String) : Either<ComputeProblem, Int> = Either.cond(s.toIntOrNull() != null, {-> s.toInt()}, {->ComputeProblem.NotANumber} )
fun isEven(x : Int) : Boolean = x % 2 == 0
fun biggestDivisor(x: Int) : Int = biggestDivisor(x, 2)
fun biggestDivisor(x : Int, y : Int) : Int {
if(x == y){
return 1;
}
if(x % y == 0){
return x / y;
}
return biggestDivisor(x, y+1)
}
fun isSquareNumber(x : Int) : Boolean {
val sqrt: Double = sqrt(x.toDouble())
return sqrt % 1.0 == 0.0
}
fun computeWithEither(input : String) : Either<ComputeProblem, Boolean> {
return parseInput(input)
.filterOrElse(::isEven) {->ComputeProblem.OddNumber}
.map (::biggestDivisor)
.map (::isSquareNumber)
}
fun computeWithEitherClient(input : String) {
val computeWithEither = computeWithEither(input)
when(computeWithEither){
is Either.Right -> "The greatest divisor is square number: ${computeWithEither.b}"
is Either.Left -> when(computeWithEither.a){
is ComputeProblem.NotANumber -> "Wrong input! Not a number!"
is ComputeProblem.OddNumber -> "It is an odd number!"
}
}
}
}
@@ -0,0 +1,46 @@
package com.baeldung.kotlin.arrow
import arrow.core.None
import arrow.core.Option
import arrow.core.Some
import kotlin.math.sqrt
class FunctionalErrorHandlingWithOption {
fun parseInput(s : String) : Option<Int> = Option.fromNullable(s.toIntOrNull())
fun isEven(x : Int) : Boolean = x % 2 == 0
fun biggestDivisor(x: Int) : Int = biggestDivisor(x, 2)
fun biggestDivisor(x : Int, y : Int) : Int {
if(x == y){
return 1;
}
if(x % y == 0){
return x / y;
}
return biggestDivisor(x, y+1)
}
fun isSquareNumber(x : Int) : Boolean {
val sqrt: Double = sqrt(x.toDouble())
return sqrt % 1.0 == 0.0
}
fun computeWithOption(input : String) : Option<Boolean> {
return parseInput(input)
.filter(::isEven)
.map(::biggestDivisor)
.map(::isSquareNumber)
}
fun computeWithOptionClient(input : String) : String{
val computeOption = computeWithOption(input)
return when(computeOption){
is None -> "Not an even number!"
is Some -> "The greatest divisor is square number: ${computeOption.t}"
}
}
}
@@ -0,0 +1,3 @@
package com.baeldung.kotlin.kodein
class Controller(private val service : Service)
@@ -0,0 +1,3 @@
package com.baeldung.kotlin.kodein
interface Dao
@@ -0,0 +1,3 @@
package com.baeldung.kotlin.kodein
class JdbcDao : Dao
@@ -0,0 +1,3 @@
package com.baeldung.kotlin.kodein
class MongoDao : Dao
@@ -0,0 +1,3 @@
package com.baeldung.kotlin.kodein
class Service(private val dao: Dao, private val tag: String)
@@ -0,0 +1,6 @@
package com.baeldung.kotlin
interface BookService {
fun inStock(bookId: Int): Boolean
fun lend(bookId: Int, memberId: Int)
}
@@ -0,0 +1,11 @@
package com.baeldung.kotlin
class LendBookManager(val bookService:BookService) {
fun checkout(bookId: Int, memberId: Int) {
if(bookService.inStock(bookId)) {
bookService.lend(bookId, memberId)
} else {
throw IllegalStateException("Book is not available")
}
}
}
@@ -0,0 +1,73 @@
package com.baeldung.kovert
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import nl.komponents.kovenant.functional.bind
import org.kodein.di.Kodein
import org.kodein.di.conf.global
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import uy.klutter.config.typesafe.ClassResourceConfig
import uy.klutter.config.typesafe.ReferenceConfig
import uy.klutter.config.typesafe.kodein.importConfig
import uy.klutter.config.typesafe.loadConfig
import uy.klutter.vertx.kodein.KodeinVertx
import uy.kohesive.kovert.core.HttpVerb
import uy.kohesive.kovert.core.Location
import uy.kohesive.kovert.core.Verb
import uy.kohesive.kovert.core.VerbAlias
import uy.kohesive.kovert.vertx.bindController
import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx
import uy.kohesive.kovert.vertx.boot.KovertVerticle
import uy.kohesive.kovert.vertx.boot.KovertVerticleModule
import uy.kohesive.kovert.vertx.boot.KovertVertx
class AnnotatedServer {
companion object {
private val LOG: Logger = LoggerFactory.getLogger(AnnotatedServer::class.java)
@JvmStatic
fun main(args: Array<String>) {
AnnotatedServer().start()
}
}
@VerbAlias("show", HttpVerb.GET)
class AnnotatedController {
fun RoutingContext.showStringById(id: String) = id
@Verb(HttpVerb.GET)
@Location("/ping/:id")
fun RoutingContext.ping(id: String) = id
}
fun start() {
Kodein.global.addImport(Kodein.Module {
importConfig(loadConfig(ClassResourceConfig("/kovert.conf", AnnotatedServer::class.java), ReferenceConfig())) {
import("kovert.vertx", KodeinKovertVertx.configModule)
import("kovert.server", KovertVerticleModule.configModule)
}
// includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j
import(KodeinVertx.moduleWithLoggingToSlf4j)
// Kovert boot
import(KodeinKovertVertx.module)
import(KovertVerticleModule.module)
})
val initControllers = fun Router.() {
bindController(AnnotatedController(), "api")
}
// startup asynchronously...
KovertVertx.start() bind { vertx ->
KovertVerticle.deploy(vertx, routerInit = initControllers)
} success { deploymentId ->
LOG.warn("Deployment complete.")
} fail { error ->
LOG.error("Deployment failed!", error)
}
}
}
@@ -0,0 +1,75 @@
package com.baeldung.kovert
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import nl.komponents.kovenant.functional.bind
import org.kodein.di.Kodein
import org.kodein.di.conf.global
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import uy.klutter.config.typesafe.ClassResourceConfig
import uy.klutter.config.typesafe.ReferenceConfig
import uy.klutter.config.typesafe.kodein.importConfig
import uy.klutter.config.typesafe.loadConfig
import uy.klutter.vertx.kodein.KodeinVertx
import uy.kohesive.kovert.core.HttpErrorCode
import uy.kohesive.kovert.core.HttpErrorCodeWithBody
import uy.kohesive.kovert.core.HttpErrorForbidden
import uy.kohesive.kovert.vertx.bindController
import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx
import uy.kohesive.kovert.vertx.boot.KovertVerticle
import uy.kohesive.kovert.vertx.boot.KovertVerticleModule
import uy.kohesive.kovert.vertx.boot.KovertVertx
class ErrorServer {
companion object {
private val LOG: Logger = LoggerFactory.getLogger(ErrorServer::class.java)
@JvmStatic
fun main(args: Array<String>) {
ErrorServer().start()
}
}
class ErrorController {
fun RoutingContext.getForbidden() {
throw HttpErrorForbidden()
}
fun RoutingContext.getError() {
throw HttpErrorCode("Something went wrong", 590)
}
fun RoutingContext.getErrorbody() {
throw HttpErrorCodeWithBody("Something went wrong", 591, "Body here")
}
}
fun start() {
Kodein.global.addImport(Kodein.Module {
importConfig(loadConfig(ClassResourceConfig("/kovert.conf", ErrorServer::class.java), ReferenceConfig())) {
import("kovert.vertx", KodeinKovertVertx.configModule)
import("kovert.server", KovertVerticleModule.configModule)
}
// includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j
import(KodeinVertx.moduleWithLoggingToSlf4j)
// Kovert boot
import(KodeinKovertVertx.module)
import(KovertVerticleModule.module)
})
val initControllers = fun Router.() {
bindController(ErrorController(), "api")
}
// startup asynchronously...
KovertVertx.start() bind { vertx ->
KovertVerticle.deploy(vertx, routerInit = initControllers)
} success { deploymentId ->
LOG.warn("Deployment complete.")
} fail { error ->
LOG.error("Deployment failed!", error)
}
}
}
@@ -0,0 +1,76 @@
package com.baeldung.kovert
import com.fasterxml.jackson.annotation.JsonProperty
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import nl.komponents.kovenant.functional.bind
import org.kodein.di.Kodein
import org.kodein.di.conf.global
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import uy.klutter.config.typesafe.ClassResourceConfig
import uy.klutter.config.typesafe.ReferenceConfig
import uy.klutter.config.typesafe.kodein.importConfig
import uy.klutter.config.typesafe.loadConfig
import uy.klutter.vertx.kodein.KodeinVertx
import uy.kohesive.kovert.vertx.bindController
import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx
import uy.kohesive.kovert.vertx.boot.KovertVerticle
import uy.kohesive.kovert.vertx.boot.KovertVerticleModule
import uy.kohesive.kovert.vertx.boot.KovertVertx
class JsonServer {
companion object {
private val LOG: Logger = LoggerFactory.getLogger(JsonServer::class.java)
@JvmStatic
fun main(args: Array<String>) {
JsonServer().start()
}
}
data class Person(
@JsonProperty("_id")
val id: String,
val name: String,
val job: String
)
class JsonController {
fun RoutingContext.getPersonById(id: String) = Person(
id = id,
name = "Tony Stark",
job = "Iron Man"
)
fun RoutingContext.putPersonById(id: String, person: Person) = person
}
fun start() {
Kodein.global.addImport(Kodein.Module {
importConfig(loadConfig(ClassResourceConfig("/kovert.conf", JsonServer::class.java), ReferenceConfig())) {
import("kovert.vertx", KodeinKovertVertx.configModule)
import("kovert.server", KovertVerticleModule.configModule)
}
// includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j
import(KodeinVertx.moduleWithLoggingToSlf4j)
// Kovert boot
import(KodeinKovertVertx.module)
import(KovertVerticleModule.module)
})
val initControllers = fun Router.() {
bindController(JsonController(), "api")
}
// startup asynchronously...
KovertVertx.start() bind { vertx ->
KovertVerticle.deploy(vertx, routerInit = initControllers)
} success { deploymentId ->
LOG.warn("Deployment complete.")
} fail { error ->
LOG.error("Deployment failed!", error)
}
}
}
@@ -0,0 +1,57 @@
package com.baeldung.kovert
import io.vertx.ext.web.Router
import nl.komponents.kovenant.functional.bind
import org.kodein.di.Kodein
import org.kodein.di.conf.global
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import uy.klutter.config.typesafe.ClassResourceConfig
import uy.klutter.config.typesafe.ReferenceConfig
import uy.klutter.config.typesafe.kodein.importConfig
import uy.klutter.config.typesafe.loadConfig
import uy.klutter.vertx.kodein.KodeinVertx
import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx
import uy.kohesive.kovert.vertx.boot.KovertVerticle
import uy.kohesive.kovert.vertx.boot.KovertVerticleModule
import uy.kohesive.kovert.vertx.boot.KovertVertx
class NoopServer {
companion object {
private val LOG: Logger = LoggerFactory.getLogger(NoopServer::class.java)
@JvmStatic
fun main(args: Array<String>) {
NoopServer().start()
}
}
fun start() {
Kodein.global.addImport(Kodein.Module {
importConfig(loadConfig(ClassResourceConfig("/kovert.conf", NoopServer::class.java), ReferenceConfig())) {
import("kovert.vertx", KodeinKovertVertx.configModule)
import("kovert.server", KovertVerticleModule.configModule)
}
// includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j
import(KodeinVertx.moduleWithLoggingToSlf4j)
// Kovert boot
import(KodeinKovertVertx.module)
import(KovertVerticleModule.module)
})
val initControllers = fun Router.() {
}
// startup asynchronously...
KovertVertx.start() bind { vertx ->
KovertVerticle.deploy(vertx, routerInit = initControllers)
} success { deploymentId ->
LOG.warn("Deployment complete.")
} fail { error ->
LOG.error("Deployment failed!", error)
}
}
}
@@ -0,0 +1,68 @@
package com.baeldung.kovert
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import nl.komponents.kovenant.functional.bind
import org.kodein.di.Kodein
import org.kodein.di.conf.global
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import uy.klutter.config.typesafe.ClassResourceConfig
import uy.klutter.config.typesafe.ReferenceConfig
import uy.klutter.config.typesafe.kodein.importConfig
import uy.klutter.config.typesafe.loadConfig
import uy.klutter.vertx.kodein.KodeinVertx
import uy.kohesive.kovert.vertx.bindController
import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx
import uy.kohesive.kovert.vertx.boot.KovertVerticle
import uy.kohesive.kovert.vertx.boot.KovertVerticleModule
import uy.kohesive.kovert.vertx.boot.KovertVertx
class SecuredServer {
companion object {
private val LOG: Logger = LoggerFactory.getLogger(SecuredServer::class.java)
@JvmStatic
fun main(args: Array<String>) {
SecuredServer().start()
}
}
class SecuredContext(private val routingContext: RoutingContext) {
val authenticated = routingContext.request().getHeader("Authorization") == "Secure"
}
class SecuredController {
fun SecuredContext.getSecured() = this.authenticated
}
fun start() {
Kodein.global.addImport(Kodein.Module {
importConfig(loadConfig(ClassResourceConfig("/kovert.conf", SecuredServer::class.java), ReferenceConfig())) {
import("kovert.vertx", KodeinKovertVertx.configModule)
import("kovert.server", KovertVerticleModule.configModule)
}
// includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j
import(KodeinVertx.moduleWithLoggingToSlf4j)
// Kovert boot
import(KodeinKovertVertx.module)
import(KovertVerticleModule.module)
})
val initControllers = fun Router.() {
bindController(SecuredController(), "api")
}
// startup asynchronously...
KovertVertx.start() bind { vertx ->
KovertVerticle.deploy(vertx, routerInit = initControllers)
} success { deploymentId ->
LOG.warn("Deployment complete.")
} fail { error ->
LOG.error("Deployment failed!", error)
}
}
}
@@ -0,0 +1,65 @@
package com.baeldung.kovert
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import nl.komponents.kovenant.functional.bind
import org.kodein.di.Kodein
import org.kodein.di.conf.global
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import uy.klutter.config.typesafe.ClassResourceConfig
import uy.klutter.config.typesafe.ReferenceConfig
import uy.klutter.config.typesafe.kodein.importConfig
import uy.klutter.config.typesafe.loadConfig
import uy.klutter.vertx.kodein.KodeinVertx
import uy.kohesive.kovert.vertx.bindController
import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx
import uy.kohesive.kovert.vertx.boot.KovertVerticle
import uy.kohesive.kovert.vertx.boot.KovertVerticleModule
import uy.kohesive.kovert.vertx.boot.KovertVertx
class SimpleServer {
companion object {
private val LOG: Logger = LoggerFactory.getLogger(SimpleServer::class.java)
@JvmStatic
fun main(args: Array<String>) {
SimpleServer().start()
}
}
class SimpleController {
fun RoutingContext.getStringById(id: String) = id
fun RoutingContext.get_truncatedString_by_id(id: String, length: Int = 1) = id.subSequence(0, length)
}
fun start() {
Kodein.global.addImport(Kodein.Module {
importConfig(loadConfig(ClassResourceConfig("/kovert.conf", SimpleServer::class.java), ReferenceConfig())) {
import("kovert.vertx", KodeinKovertVertx.configModule)
import("kovert.server", KovertVerticleModule.configModule)
}
// includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j
import(KodeinVertx.moduleWithLoggingToSlf4j)
// Kovert boot
import(KodeinKovertVertx.module)
import(KovertVerticleModule.module)
})
val initControllers = fun Router.() {
bindController(SimpleController(), "api")
}
// startup asynchronously...
KovertVertx.start() bind { vertx ->
KovertVerticle.deploy(vertx, routerInit = initControllers)
} success { deploymentId ->
LOG.warn("Deployment complete.")
} fail { error ->
LOG.error("Deployment failed!", error)
}
}
}
@@ -0,0 +1,73 @@
@file:JvmName("APIServer")
import io.ktor.application.call
import io.ktor.application.install
import io.ktor.features.CallLogging
import io.ktor.features.ContentNegotiation
import io.ktor.features.DefaultHeaders
import io.ktor.gson.gson
import io.ktor.request.path
import io.ktor.request.receive
import io.ktor.response.respond
import io.ktor.routing.*
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import org.slf4j.event.Level
data class Author(val name: String, val website: String)
data class ToDo(var id: Int, val name: String, val description: String, val completed: Boolean)
fun main(args: Array<String>) {
val toDoList = ArrayList<ToDo>();
val jsonResponse = """{
"id": 1,
"task": "Pay waterbill",
"description": "Pay water bill today",
}"""
embeddedServer(Netty, 8080) {
install(DefaultHeaders) {
header("X-Developer", "Baeldung")
}
install(CallLogging) {
level = Level.DEBUG
filter { call -> call.request.path().startsWith("/todo") }
filter { call -> call.request.path().startsWith("/author") }
}
install(ContentNegotiation) {
gson {
setPrettyPrinting()
}
}
routing() {
route("/todo") {
post {
var toDo = call.receive<ToDo>();
toDo.id = toDoList.size;
toDoList.add(toDo);
call.respond("Added")
}
delete("/{id}") {
call.respond(toDoList.removeAt(call.parameters["id"]!!.toInt()));
}
get("/{id}") {
call.respond(toDoList[call.parameters["id"]!!.toInt()]);
}
get {
call.respond(toDoList);
}
}
get("/author"){
call.respond(Author("Baeldung","baeldung.com"));
}
}
}.start(wait = true)
}
@@ -0,0 +1,15 @@
{
kovert: {
vertx: {
clustered: false
}
server: {
listeners: [
{
host: "0.0.0.0"
port: "8000"
}
]
}
}
}
@@ -0,0 +1,163 @@
package com.baeldung.klaxon
import com.beust.klaxon.JsonArray
import com.beust.klaxon.JsonObject
import com.beust.klaxon.JsonReader
import com.beust.klaxon.Klaxon
import com.beust.klaxon.Parser
import com.beust.klaxon.PathMatcher
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.SoftAssertions.assertSoftly
import org.junit.Assert
import org.junit.jupiter.api.Test
import java.io.StringReader
import java.util.regex.Pattern
class KlaxonUnitTest {
@Test
fun giveProduct_whenSerialize_thenGetJsonString() {
val product = Product("HDD")
val result = Klaxon().toJsonString(product)
assertThat(result).isEqualTo("""{"name" : "HDD"}""")
}
@Test
fun giveJsonString_whenDeserialize_thenGetProduct() {
val result = Klaxon().parse<Product>("""
{
"name" : "RAM"
}
""")
assertThat(result?.name).isEqualTo("RAM")
}
@Test
fun giveCustomProduct_whenSerialize_thenGetJsonString() {
val product = CustomProduct("HDD", 1)
val result = Klaxon().toJsonString(product)
assertThat(result).isEqualTo("""{"productName" : "HDD"}""")
}
@Test
fun giveJsonArray_whenStreaming_thenGetProductArray() {
val jsonArray = """
[
{ "name" : "HDD", "capacityInGb" : 512 },
{ "name" : "RAM", "capacityInGb" : 16 }
]"""
val expectedArray = arrayListOf(ProductData("HDD", 512),
ProductData("RAM", 16))
val klaxon = Klaxon()
val productArray = arrayListOf<ProductData>()
JsonReader(StringReader(jsonArray)).use { reader ->
reader.beginArray {
while (reader.hasNext()) {
val product = klaxon.parse<ProductData>(reader)
productArray.add(product!!)
}
}
}
assertThat(productArray).hasSize(2).isEqualTo(expectedArray)
}
@Test
fun giveJsonString_whenParser_thenGetJsonObject() {
val jsonString = StringBuilder("""
{
"name" : "HDD",
"capacityInGb" : 512,
"sizeInInch" : 2.5
}
""")
val parser = Parser()
val json = parser.parse(jsonString) as JsonObject
assertThat(json).hasSize(3).containsEntry("name", "HDD").containsEntry("capacityInGb", 512).containsEntry("sizeInInch", 2.5)
}
@Suppress("UNCHECKED_CAST")
@Test
fun giveJsonStringArray_whenParser_thenGetJsonArray() {
val jsonString = StringBuilder("""
[
{ "name" : "SDD" },
{ "madeIn" : "Taiwan" },
{ "warrantyInYears" : 5 }
]""")
val parser = Parser()
val json = parser.parse(jsonString) as JsonArray<JsonObject>
assertSoftly({ softly ->
softly.assertThat(json).hasSize(3)
softly.assertThat(json[0]["name"]).isEqualTo("SDD")
softly.assertThat(json[1]["madeIn"]).isEqualTo("Taiwan")
softly.assertThat(json[2]["warrantyInYears"]).isEqualTo(5)
})
}
@Test
fun givenJsonString_whenStreaming_thenProcess() {
val jsonString = """
{
"name" : "HDD",
"madeIn" : "Taiwan",
"warrantyInYears" : 5
"hasStock" : true
"capacitiesInTb" : [ 1, 2 ],
"features" : { "cacheInMb" : 64, "speedInRpm" : 7200 }
}"""
JsonReader(StringReader(jsonString)).use { reader ->
reader.beginObject {
while (reader.hasNext()) {
val readName = reader.nextName()
when (readName) {
"name" -> assertThat(reader.nextString()).isEqualTo("HDD")
"madeIn" -> assertThat(reader.nextString()).isEqualTo("Taiwan")
"warrantyInYears" -> assertThat(reader.nextInt()).isEqualTo(5)
"hasStock" -> assertThat(reader.nextBoolean()).isEqualTo(true)
"capacitiesInTb" -> assertThat(reader.nextArray()).contains(1, 2)
"features" -> assertThat(reader.nextObject()).containsEntry("cacheInMb", 64).containsEntry("speedInRpm", 7200)
else -> Assert.fail("Unexpected name: $readName")
}
}
}
}
}
@Test
fun givenDiskInventory_whenRegexMatches_thenGetTypes() {
val jsonString = """
{
"inventory" : {
"disks" : [
{
"type" : "HDD",
"sizeInGb" : 1000
},
{
"type" : "SDD",
"sizeInGb" : 512
}
]
}
}"""
val pathMatcher = object : PathMatcher {
override fun pathMatches(path: String) = Pattern.matches(".*inventory.*disks.*type.*", path)
override fun onMatch(path: String, value: Any) {
when (path) {
"$.inventory.disks[0].type" -> assertThat(value).isEqualTo("HDD")
"$.inventory.disks[1].type" -> assertThat(value).isEqualTo("SDD")
}
}
}
Klaxon().pathMatcher(pathMatcher).parseJsonObject(StringReader(jsonString))
}
}
@@ -0,0 +1,143 @@
package com.baeldung.kotlin.arrow
import arrow.core.*
import org.junit.Assert
import org.junit.Test
class FunctionalDataTypes {
@Test
fun whenIdCreated_thanValueIsPresent(){
val id = Id("foo")
val justId = Id.just("foo");
Assert.assertEquals("foo", id.extract())
Assert.assertEquals(justId, id)
}
fun length(s : String) : Int = s.length
fun isBigEnough(i : Int) : Boolean = i > 10
@Test
fun whenIdCreated_thanMapIsAssociative(){
val foo = Id("foo")
val map1 = foo.map(::length)
.map(::isBigEnough)
val map2 = foo.map { s -> isBigEnough(length(s)) }
Assert.assertEquals(map1, map2)
}
fun lengthId(s : String) : Id<Int> = Id.just(length(s))
fun isBigEnoughId(i : Int) : Id<Boolean> = Id.just(isBigEnough(i))
@Test
fun whenIdCreated_thanFlatMapIsAssociative(){
val bar = Id("bar")
val flatMap = bar.flatMap(::lengthId)
.flatMap(::isBigEnoughId)
val flatMap1 = bar.flatMap { s -> lengthId(s).flatMap(::isBigEnoughId) }
Assert.assertEquals(flatMap, flatMap1)
}
@Test
fun whenOptionCreated_thanValueIsPresent(){
val factory = Option.just(42)
val constructor = Option(42)
val emptyOptional = Option.empty<Integer>()
val fromNullable = Option.fromNullable(null)
Assert.assertEquals(42, factory.getOrElse { -1 })
Assert.assertEquals(factory, constructor)
Assert.assertEquals(emptyOptional, fromNullable)
}
@Test
fun whenOptionCreated_thanConstructorDifferFromFactory(){
val constructor : Option<String?> = Option(null)
val fromNullable : Option<String?> = Option.fromNullable(null)
try{
constructor.map { s -> s!!.length }
Assert.fail()
} catch (e : KotlinNullPointerException){
fromNullable.map { s->s!!.length }
}
Assert.assertNotEquals(constructor, fromNullable)
}
fun wrapper(x : Integer?) : Option<Int> = if (x == null) Option.just(-1) else Option.just(x.toInt())
@Test
fun whenOptionFromNullableCreated_thanItBreaksLeftIdentity(){
val optionFromNull = Option.fromNullable(null)
Assert.assertNotEquals(optionFromNull.flatMap(::wrapper), wrapper(null))
}
@Test
fun whenEitherCreated_thanOneValueIsPresent(){
val rightOnly : Either<String,Int> = Either.right(42)
val leftOnly : Either<String,Int> = Either.left("foo")
Assert.assertTrue(rightOnly.isRight())
Assert.assertTrue(leftOnly.isLeft())
Assert.assertEquals(42, rightOnly.getOrElse { -1 })
Assert.assertEquals(-1, leftOnly.getOrElse { -1 })
Assert.assertEquals(0, rightOnly.map { it % 2 }.getOrElse { -1 })
Assert.assertEquals(-1, leftOnly.map { it % 2 }.getOrElse { -1 })
Assert.assertTrue(rightOnly.flatMap { Either.Right(it % 2) }.isRight())
Assert.assertTrue(leftOnly.flatMap { Either.Right(it % 2) }.isLeft())
}
@Test
fun whenEvalNowUsed_thenMapEvaluatedLazily(){
val now = Eval.now(1)
Assert.assertEquals(1, now.value())
var counter : Int = 0
val map = now.map { x -> counter++; x+1 }
Assert.assertEquals(0, counter)
val value = map.value()
Assert.assertEquals(2, value)
Assert.assertEquals(1, counter)
}
@Test
fun whenEvalLaterUsed_theResultIsMemoized(){
var counter : Int = 0
val later = Eval.later { counter++; counter }
Assert.assertEquals(0, counter)
val firstValue = later.value()
Assert.assertEquals(1, firstValue)
Assert.assertEquals(1, counter)
val secondValue = later.value()
Assert.assertEquals(1, secondValue)
Assert.assertEquals(1, counter)
}
@Test
fun whenEvalAlwaysUsed_theResultIsNotMemoized(){
var counter : Int = 0
val later = Eval.always { counter++; counter }
Assert.assertEquals(0, counter)
val firstValue = later.value()
Assert.assertEquals(1, firstValue)
Assert.assertEquals(1, counter)
val secondValue = later.value()
Assert.assertEquals(2, secondValue)
Assert.assertEquals(2, counter)
}
}
@@ -0,0 +1,68 @@
package com.baeldung.kotlin.arrow
import arrow.core.Either
import com.baeldung.kotlin.arrow.FunctionalErrorHandlingWithEither.ComputeProblem.NotANumber
import com.baeldung.kotlin.arrow.FunctionalErrorHandlingWithEither.ComputeProblem.OddNumber
import org.junit.Assert
import org.junit.Test
class FunctionalErrorHandlingWithEitherTest {
val operator = FunctionalErrorHandlingWithEither()
@Test
fun givenInvalidInput_whenComputeInvoked_NotANumberIsPresent(){
val computeWithEither = operator.computeWithEither("bar")
Assert.assertTrue(computeWithEither.isLeft())
when(computeWithEither){
is Either.Left -> when(computeWithEither.a){
NotANumber -> "Ok."
else -> Assert.fail()
}
else -> Assert.fail()
}
}
@Test
fun givenOddNumberInput_whenComputeInvoked_OddNumberIsPresent(){
val computeWithEither = operator.computeWithEither("121")
Assert.assertTrue(computeWithEither.isLeft())
when(computeWithEither){
is Either.Left -> when(computeWithEither.a){
OddNumber -> "Ok."
else -> Assert.fail()
}
else -> Assert.fail()
}
}
@Test
fun givenEvenNumberWithoutSquare_whenComputeInvoked_OddNumberIsPresent(){
val computeWithEither = operator.computeWithEither("100")
Assert.assertTrue(computeWithEither.isRight())
when(computeWithEither){
is Either.Right -> when(computeWithEither.b){
false -> "Ok."
else -> Assert.fail()
}
else -> Assert.fail()
}
}
@Test
fun givenEvenNumberWithSquare_whenComputeInvoked_OddNumberIsPresent(){
val computeWithEither = operator.computeWithEither("98")
Assert.assertTrue(computeWithEither.isRight())
when(computeWithEither){
is Either.Right -> when(computeWithEither.b){
true -> "Ok."
else -> Assert.fail()
}
else -> Assert.fail()
}
}
}
@@ -0,0 +1,34 @@
package com.baeldung.kotlin.arrow
import org.junit.Assert
import org.junit.Test
class FunctionalErrorHandlingWithOptionTest {
val operator = FunctionalErrorHandlingWithOption()
@Test
fun givenInvalidInput_thenErrorMessageIsPresent(){
val useComputeOption = operator.computeWithOptionClient("foo")
Assert.assertEquals("Not an even number!", useComputeOption)
}
@Test
fun givenOddNumberInput_thenErrorMessageIsPresent(){
val useComputeOption = operator.computeWithOptionClient("539")
Assert.assertEquals("Not an even number!",useComputeOption)
}
@Test
fun givenEvenNumberInputWithNonSquareNum_thenFalseMessageIsPresent(){
val useComputeOption = operator.computeWithOptionClient("100")
Assert.assertEquals("The greatest divisor is square number: false",useComputeOption)
}
@Test
fun givenEvenNumberInputWithSquareNum_thenTrueMessageIsPresent(){
val useComputeOption = operator.computeWithOptionClient("242")
Assert.assertEquals("The greatest divisor is square number: true",useComputeOption)
}
}
@@ -0,0 +1,34 @@
package com.baeldung.kotlin.dates
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.time.LocalDate
import java.time.format.DateTimeFormatter
class CreateDateUnitTest {
@Test
fun givenString_whenDefaultFormat_thenCreated() {
var date = LocalDate.parse("2018-12-31")
assertThat(date).isEqualTo("2018-12-31")
}
@Test
fun givenString_whenCustomFormat_thenCreated() {
var formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy")
var date = LocalDate.parse("31-12-2018", formatter)
assertThat(date).isEqualTo("2018-12-31")
}
@Test
fun givenYMD_whenUsingOf_thenCreated() {
var date = LocalDate.of(2018, 12, 31)
assertThat(date).isEqualTo("2018-12-31")
}
}
@@ -0,0 +1,29 @@
package com.baeldung.kotlin.dates
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.Month
class ExtractDateUnitTest {
@Test
fun givenDate_thenExtractedYMD() {
var date = LocalDate.parse("2018-12-31")
assertThat(date.year).isEqualTo(2018)
assertThat(date.month).isEqualTo(Month.DECEMBER)
assertThat(date.dayOfMonth).isEqualTo(31)
}
@Test
fun givenDate_thenExtractedEraDowDoy() {
var date = LocalDate.parse("2018-12-31")
assertThat(date.era.toString()).isEqualTo("CE")
assertThat(date.dayOfWeek).isEqualTo(DayOfWeek.MONDAY)
assertThat(date.dayOfYear).isEqualTo(365)
}
}
@@ -0,0 +1,29 @@
package com.baeldung.kotlin.dates
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.time.LocalDate
import java.time.format.DateTimeFormatter
class FormatDateUnitTest {
@Test
fun givenDate_whenDefaultFormat_thenFormattedString() {
var date = LocalDate.parse("2018-12-31")
assertThat(date.toString()).isEqualTo("2018-12-31")
}
@Test
fun givenDate_whenCustomFormat_thenFormattedString() {
var date = LocalDate.parse("2018-12-31")
var formatter = DateTimeFormatter.ofPattern("dd-MMMM-yyyy")
var formattedDate = date.format(formatter)
assertThat(formattedDate).isEqualTo("31-December-2018")
}
}
@@ -0,0 +1,48 @@
package com.baeldung.kotlin.dates
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.time.LocalDate
import java.time.Period
class PeriodDateUnitTest {
@Test
fun givenYMD_thenCreatePeriod() {
var period = Period.of(1, 2, 3)
assertThat(period.toString()).isEqualTo("P1Y2M3D")
}
@Test
fun givenPeriod_whenAdd_thenModifiedDate() {
var period = Period.of(1, 2, 3)
var date = LocalDate.of(2018, 6, 25)
var modifiedDate = date.plus(period)
assertThat(modifiedDate).isEqualTo("2019-08-28")
}
@Test
fun givenPeriod_whenSubtracted_thenModifiedDate() {
var period = Period.of(1, 2, 3)
var date = LocalDate.of(2018, 6, 25)
var modifiedDate = date.minus(period)
assertThat(modifiedDate).isEqualTo("2017-04-22")
}
@Test
fun givenTwoDate_whenUsingBetween_thenDiffOfDates() {
var date1 = LocalDate.parse("2018-06-25")
var date2 = LocalDate.parse("2018-12-25")
var period = Period.between(date1, date2)
assertThat(period.toString()).isEqualTo("P6M")
}
}
@@ -0,0 +1,333 @@
package com.baeldung.kotlin.exposed
import org.jetbrains.exposed.dao.*
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.TransactionManager
import org.jetbrains.exposed.sql.transactions.transaction
import org.junit.Test
import java.sql.DriverManager
import kotlin.test.*
class ExposedTest {
@Test
fun whenH2Database_thenConnectionSuccessful() {
val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
transaction {
assertEquals(1.4.toBigDecimal(), database.version)
assertEquals("h2", database.vendor)
}
}
@Test
fun whenH2DatabaseWithCredentials_thenConnectionSuccessful() {
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver", user = "myself", password = "secret")
}
@Test
fun whenH2DatabaseWithManualConnection_thenConnectionSuccessful() {
var connected = false
Database.connect({ connected = true; DriverManager.getConnection("jdbc:h2:mem:test;MODE=MySQL") })
assertEquals(false, connected)
transaction {
addLogger(StdOutSqlLogger)
assertEquals(false, connected)
SchemaUtils.create(Cities)
assertEquals(true, connected)
}
}
@Test
fun whenManualCommit_thenOk() {
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
transaction {
assertTrue(this is Transaction)
commit()
commit()
commit()
}
}
@Test
fun whenInsert_thenGeneratedKeys() {
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
transaction {
SchemaUtils.create(StarWarsFilms)
val id = StarWarsFilms.insertAndGetId {
it[name] = "The Last Jedi"
it[sequelId] = 8
it[director] = "Rian Johnson"
}
assertEquals(1, id.value)
val insert = StarWarsFilms.insert {
it[name] = "The Force Awakens"
it[sequelId] = 7
it[director] = "J.J. Abrams"
}
assertEquals(2, insert[StarWarsFilms.id]?.value)
val selectAll = StarWarsFilms.selectAll()
selectAll.forEach {
assertTrue { it[StarWarsFilms.sequelId] >= 7 }
}
StarWarsFilms.slice(StarWarsFilms.name, StarWarsFilms.director).selectAll()
.forEach {
assertTrue { it[StarWarsFilms.name].startsWith("The") }
}
val select = StarWarsFilms.select { (StarWarsFilms.director like "J.J.%") and (StarWarsFilms.sequelId eq 7) }
assertEquals(1, select.count())
StarWarsFilms.update ({ StarWarsFilms.sequelId eq 8 }) {
it[name] = "Episode VIII The Last Jedi"
with(SqlExpressionBuilder) {
it.update(StarWarsFilms.sequelId, StarWarsFilms.sequelId + 1)
}
}
}
}
@Test
fun whenForeignKey_thenAutoJoin() {
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
transaction {
addLogger(StdOutSqlLogger)
SchemaUtils.create(StarWarsFilms, Players)
StarWarsFilms.insert {
it[name] = "The Last Jedi"
it[sequelId] = 8
it[director] = "Rian Johnson"
}
StarWarsFilms.insert {
it[name] = "The Force Awakens"
it[sequelId] = 7
it[director] = "J.J. Abrams"
}
Players.insert {
it[name] = "Mark Hamill"
it[sequelId] = 7
}
Players.insert {
it[name] = "Mark Hamill"
it[sequelId] = 8
}
val simpleInnerJoin = (StarWarsFilms innerJoin Players).selectAll()
assertEquals(2, simpleInnerJoin.count())
simpleInnerJoin.forEach {
assertNotNull(it[StarWarsFilms.name])
assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId])
assertEquals("Mark Hamill", it[Players.name])
}
val innerJoinWithCondition = (StarWarsFilms innerJoin Players)
.select { StarWarsFilms.sequelId eq Players.sequelId }
assertEquals(2, innerJoinWithCondition.count())
innerJoinWithCondition.forEach {
assertNotNull(it[StarWarsFilms.name])
assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId])
assertEquals("Mark Hamill", it[Players.name])
}
val complexInnerJoin = Join(StarWarsFilms, Players, joinType = JoinType.INNER, onColumn = StarWarsFilms.sequelId, otherColumn = Players.sequelId, additionalConstraint = {
StarWarsFilms.sequelId eq 8
}).selectAll()
assertEquals(1, complexInnerJoin.count())
complexInnerJoin.forEach {
assertNotNull(it[StarWarsFilms.name])
assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId])
assertEquals("Mark Hamill", it[Players.name])
}
}
}
@Test
fun whenJoinWithAlias_thenFun() {
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
transaction {
addLogger(StdOutSqlLogger)
SchemaUtils.create(StarWarsFilms, Players)
StarWarsFilms.insert {
it[name] = "The Last Jedi"
it[sequelId] = 8
it[director] = "Rian Johnson"
}
StarWarsFilms.insert {
it[name] = "The Force Awakens"
it[sequelId] = 7
it[director] = "J.J. Abrams"
}
val sequel = StarWarsFilms.alias("sequel")
Join(StarWarsFilms, sequel,
additionalConstraint = { sequel[StarWarsFilms.sequelId] eq StarWarsFilms.sequelId + 1 })
.selectAll().forEach {
assertEquals(it[sequel[StarWarsFilms.sequelId]], it[StarWarsFilms.sequelId] + 1)
}
}
}
@Test
fun whenEntity_thenDAO() {
val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
val connection = database.connector.invoke() //Keep a connection open so the DB is not destroyed after the first transaction
val inserted = transaction {
addLogger(StdOutSqlLogger)
SchemaUtils.create(StarWarsFilms, Players)
val theLastJedi = StarWarsFilm.new {
name = "The Last Jedi"
sequelId = 8
director = "Rian Johnson"
}
assertFalse(TransactionManager.current().entityCache.inserts.isEmpty())
assertEquals(1, theLastJedi.id.value) //Reading this causes a flush
assertTrue(TransactionManager.current().entityCache.inserts.isEmpty())
theLastJedi
}
transaction {
val theLastJedi = StarWarsFilm.findById(1)
assertNotNull(theLastJedi)
assertEquals(inserted.id, theLastJedi?.id)
}
connection.close()
}
@Test
fun whenManyToOne_thenNavigation() {
val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
val connection = database.connector.invoke()
transaction {
addLogger(StdOutSqlLogger)
SchemaUtils.create(StarWarsFilms, Players, Users, UserRatings)
val theLastJedi = StarWarsFilm.new {
name = "The Last Jedi"
sequelId = 8
director = "Rian Johnson"
}
val someUser = User.new {
name = "Some User"
}
val rating = UserRating.new {
value = 9
user = someUser
film = theLastJedi
}
assertEquals(theLastJedi, rating.film)
assertEquals(someUser, rating.user)
assertEquals(rating, theLastJedi.ratings.first())
}
transaction {
val theLastJedi = StarWarsFilm.find { StarWarsFilms.sequelId eq 8 }.first()
val ratings = UserRating.find { UserRatings.film eq theLastJedi.id }
assertEquals(1, ratings.count())
val rating = ratings.first()
assertEquals("Some User", rating.user.name)
assertEquals(rating, theLastJedi.ratings.first())
UserRating.new {
value = 8
user = rating.user
film = theLastJedi
}
assertEquals(2, theLastJedi.ratings.count())
}
connection.close()
}
@Test
fun whenManyToMany_thenAssociation() {
val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
val connection = database.connector.invoke()
val film = transaction {
SchemaUtils.create(StarWarsFilms)
StarWarsFilm.new {
name = "The Last Jedi"
sequelId = 8
director = "Rian Johnson"
}
}
val actor = transaction {
SchemaUtils.create(Actors)
Actor.new {
firstname = "Daisy"
lastname = "Ridley"
}
}
transaction {
SchemaUtils.create(StarWarsFilmActors)
film.actors = SizedCollection(listOf(actor))
}
connection.close()
}
}
object Cities: IntIdTable() {
val name = varchar("name", 50)
}
object StarWarsFilms_Simple : Table() {
val id = integer("id").autoIncrement().primaryKey()
val sequelId = integer("sequel_id").uniqueIndex()
val name = varchar("name", 50)
val director = varchar("director", 50)
}
object StarWarsFilms : IntIdTable() {
val sequelId = integer("sequel_id").uniqueIndex()
val name = varchar("name", 50)
val director = varchar("director", 50)
}
object Players : Table() {
//val sequelId = integer("sequel_id").uniqueIndex().references(StarWarsFilms.sequelId)
val sequelId = reference("sequel_id", StarWarsFilms.sequelId).uniqueIndex()
//val filmId = reference("film_id", StarWarsFilms).nullable()
val name = varchar("name", 50)
}
class StarWarsFilm(id: EntityID<Int>) : Entity<Int>(id) {
companion object : EntityClass<Int, StarWarsFilm>(StarWarsFilms)
var sequelId by StarWarsFilms.sequelId
var name by StarWarsFilms.name
var director by StarWarsFilms.director
var actors by Actor via StarWarsFilmActors
val ratings by UserRating referrersOn UserRatings.film
}
object Users: IntIdTable() {
val name = varchar("name", 50)
}
object UserRatings: IntIdTable() {
val value = long("value")
val film = reference("film", StarWarsFilms)
val user = reference("user", Users)
}
class User(id: EntityID<Int>): IntEntity(id) {
companion object : IntEntityClass<User>(Users)
var name by Users.name
}
class UserRating(id: EntityID<Int>): IntEntity(id) {
companion object : IntEntityClass<UserRating>(UserRatings)
var value by UserRatings.value
var film by StarWarsFilm referencedOn UserRatings.film
var user by User referencedOn UserRatings.user
}
object Actors: IntIdTable() {
val firstname = varchar("firstname", 50)
val lastname = varchar("lastname", 50)
}
class Actor(id: EntityID<Int>): IntEntity(id) {
companion object : IntEntityClass<Actor>(Actors)
var firstname by Actors.firstname
var lastname by Actors.lastname
}
object StarWarsFilmActors : Table() {
val starWarsFilm = reference("starWarsFilm", StarWarsFilms).primaryKey(0)
val actor = reference("actor", Actors).primaryKey(1)
}
@@ -0,0 +1,17 @@
package com.baeldung.kotlin.junit5
class Calculator {
fun add(a: Int, b: Int) = a + b
fun divide(a: Int, b: Int) = if (b == 0) {
throw DivideByZeroException(a)
} else {
a / b
}
fun square(a: Int) = a * a
fun squareRoot(a: Int) = Math.sqrt(a.toDouble())
fun log(base: Int, value: Int) = Math.log(value.toDouble()) / Math.log(base.toDouble())
}
@@ -0,0 +1,3 @@
package com.baeldung.kotlin.junit5
class DivideByZeroException(val numerator: Int) : Exception()
@@ -0,0 +1,153 @@
package com.baeldung.kotlin.khttp
import khttp.structures.files.FileLike
import org.json.JSONObject
import org.junit.Test
import java.beans.ExceptionListener
import java.beans.XMLEncoder
import java.io.*
import java.lang.Exception
import java.net.ConnectException
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlin.test.fail
class KhttpLiveTest {
@Test
fun whenHttpGetRequestIsMade_thenArgsAreReturned() {
val response = khttp.get(
url = "http://httpbin.org/get",
params = mapOf("p1" to "1", "p2" to "2"))
val args = response.jsonObject.getJSONObject("args")
assertEquals("1", args["p1"])
assertEquals("2", args["p2"])
}
@Test
fun whenAlternateHttpGetRequestIsMade_thenArgsAreReturned() {
val response = khttp.request(
method = "GET",
url = "http://httpbin.org/get",
params = mapOf("p1" to "1", "p2" to "2"))
val args = response.jsonObject.getJSONObject("args")
assertEquals("1", args["p1"])
assertEquals("2", args["p2"])
}
@Test
fun whenHeadersAreSet_thenHeadersAreSent() {
val response = khttp.get(
url = "http://httpbin.org/get",
headers = mapOf("header1" to "1", "header2" to "2"))
val headers = response.jsonObject.getJSONObject("headers")
assertEquals("1", headers["Header1"])
assertEquals("2", headers["Header2"])
}
@Test
fun whenHttpPostRequestIsMadeWithJson_thenBodyIsReturned() {
val response = khttp.post(
url = "http://httpbin.org/post",
params = mapOf("p1" to "1", "p2" to "2"),
json = mapOf("pr1" to "1", "pr2" to "2"))
val args = response.jsonObject.getJSONObject("args")
assertEquals("1", args["p1"])
assertEquals("2", args["p2"])
val json = response.jsonObject.getJSONObject("json")
assertEquals("1", json["pr1"])
assertEquals("2", json["pr2"])
}
@Test
fun whenHttpPostRequestIsMadeWithMapData_thenBodyIsReturned() {
val response = khttp.post(
url = "http://httpbin.org/post",
params = mapOf("p1" to "1", "p2" to "2"),
data = mapOf("pr1" to "1", "pr2" to "2"))
val args = response.jsonObject.getJSONObject("args")
assertEquals("1", args["p1"])
assertEquals("2", args["p2"])
val form = response.jsonObject.getJSONObject("form")
assertEquals("1", form["pr1"])
assertEquals("2", form["pr2"])
}
@Test
fun whenHttpPostRequestIsMadeWithFiles_thenBodyIsReturned() {
val response = khttp.post(
url = "http://httpbin.org/post",
params = mapOf("p1" to "1", "p2" to "2"),
files = listOf(
FileLike("file1", "content1"),
FileLike("file2", javaClass.getResource("KhttpTest.class").openStream().readBytes())))
val args = response.jsonObject.getJSONObject("args")
assertEquals("1", args["p1"])
assertEquals("2", args["p2"])
val files = response.jsonObject.getJSONObject("files")
assertEquals("content1", files["file1"])
}
@Test
fun whenHttpPostRequestIsMadeWithInputStream_thenBodyIsReturned() {
val response = khttp.post(
url = "http://httpbin.org/post",
params = mapOf("p1" to "1", "p2" to "2"),
data = ByteArrayInputStream("content!".toByteArray()))
val args = response.jsonObject.getJSONObject("args")
assertEquals("1", args["p1"])
assertEquals("2", args["p2"])
assertEquals("content!", response.jsonObject["data"])
}
@Test
fun whenHttpPostStreamingRequestIsMade_thenBodyIsReturnedInChunks() {
val response = khttp.post(
url = "http://httpbin.org/post",
stream = true,
json = mapOf("pr1" to "1", "pr2" to "2"))
val baos = ByteArrayOutputStream()
response.contentIterator(chunkSize = 10).forEach { arr : ByteArray -> baos.write(arr) }
val json = JSONObject(String(baos.toByteArray())).getJSONObject("json")
assertEquals("1", json["pr1"])
assertEquals("2", json["pr2"])
}
@Test
fun whenHttpRequestFails_thenExceptionIsThrown() {
try {
khttp.get(url = "http://localhost/nothing/to/see/here")
fail("Should have thrown an exception")
} catch (e : ConnectException) {
//Ok
}
}
@Test
fun whenHttpNotFound_thenExceptionIsThrown() {
val response = khttp.get(url = "http://httpbin.org/nothing/to/see/here")
assertEquals(404, response.statusCode)
}
}
@@ -0,0 +1,191 @@
package com.baeldung.kotlin.kodein
import com.github.salomonbrys.kodein.*
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class KodeinUnitTest {
class InMemoryDao : Dao
@Test
fun whenSingletonBinding_thenSingleInstanceIsCreated() {
var created = false
val kodein = Kodein {
bind<Dao>() with singleton {
created = true
MongoDao()
}
}
assertThat(created).isFalse()
val dao1: Dao = kodein.instance()
assertThat(created).isTrue()
val dao2: Dao = kodein.instance()
assertThat(dao1).isSameAs(dao2)
}
@Test
fun whenFactoryBinding_thenNewInstanceIsCreated() {
val kodein = Kodein {
bind<Dao>() with singleton { MongoDao() }
bind<Service>() with factory { tag: String -> Service(instance(), tag) }
}
val service1: Service = kodein.with("myTag").instance()
val service2: Service = kodein.with("myTag").instance()
assertThat(service1).isNotSameAs(service2)
}
@Test
fun whenProviderBinding_thenNewInstanceIsCreated() {
val kodein = Kodein {
bind<Dao>() with provider { MongoDao() }
}
val dao1: Dao = kodein.instance()
val dao2: Dao = kodein.instance()
assertThat(dao1).isNotSameAs(dao2)
}
@Test
fun whenTaggedBinding_thenMultipleInstancesOfSameTypeCanBeRegistered() {
val kodein = Kodein {
bind<Dao>("dao1") with singleton { MongoDao() }
bind<Dao>("dao2") with singleton { MongoDao() }
}
val dao1: Dao = kodein.instance("dao1")
val dao2: Dao = kodein.instance("dao2")
assertThat(dao1).isNotSameAs(dao2)
}
@Test
fun whenEagerSingletonBinding_thenCreationIsEager() {
var created = false
val kodein = Kodein {
bind<Dao>() with eagerSingleton {
created = true
MongoDao()
}
}
assertThat(created).isTrue()
val dao1: Dao = kodein.instance()
val dao2: Dao = kodein.instance()
assertThat(dao1).isSameAs(dao2)
}
@Test
fun whenMultitonBinding_thenInstancesAreReused() {
val kodein = Kodein {
bind<Dao>() with singleton { MongoDao() }
bind<Service>() with multiton { tag: String -> Service(instance(), tag) }
}
val service1: Service = kodein.with("myTag").instance()
val service2: Service = kodein.with("myTag").instance()
assertThat(service1).isSameAs(service2)
}
@Test
fun whenInstanceBinding_thenItIsReused() {
val dao = MongoDao()
val kodein = Kodein {
bind<Dao>() with instance(dao)
}
val fromContainer: Dao = kodein.instance()
assertThat(dao).isSameAs(fromContainer)
}
@Test
fun whenConstantBinding_thenItIsAvailable() {
val kodein = Kodein {
constant("magic") with 42
}
val fromContainer: Int = kodein.instance("magic")
assertThat(fromContainer).isEqualTo(42)
}
@Test
fun whenUsingModules_thenTransitiveDependenciesAreSuccessfullyResolved() {
val jdbcModule = Kodein.Module {
bind<Dao>() with singleton { JdbcDao() }
}
val kodein = Kodein {
import(jdbcModule)
bind<Controller>() with singleton { Controller(instance()) }
bind<Service>() with singleton { Service(instance(), "myService") }
}
val dao: Dao = kodein.instance()
assertThat(dao).isInstanceOf(JdbcDao::class.java)
}
@Test
fun whenComposition_thenBeansAreReUsed() {
val persistenceContainer = Kodein {
bind<Dao>() with singleton { MongoDao() }
}
val serviceContainer = Kodein {
extend(persistenceContainer)
bind<Service>() with singleton { Service(instance(), "myService") }
}
val fromPersistence: Dao = persistenceContainer.instance()
val fromService: Dao = serviceContainer.instance()
assertThat(fromPersistence).isSameAs(fromService)
}
@Test
fun whenOverriding_thenRightBeanIsUsed() {
val commonModule = Kodein.Module {
bind<Dao>() with singleton { MongoDao() }
bind<Service>() with singleton { Service(instance(), "myService") }
}
val testContainer = Kodein {
import(commonModule)
bind<Dao>(overrides = true) with singleton { InMemoryDao() }
}
val dao: Dao = testContainer.instance()
assertThat(dao).isInstanceOf(InMemoryDao::class.java)
}
@Test
fun whenMultiBinding_thenWorks() {
val kodein = Kodein {
bind() from setBinding<Dao>()
bind<Dao>().inSet() with singleton { MongoDao() }
bind<Dao>().inSet() with singleton { JdbcDao() }
}
val daos: Set<Dao> = kodein.instance()
assertThat(daos.map { it.javaClass as Class<*> }).containsOnly(MongoDao::class.java, JdbcDao::class.java)
}
@Test
fun whenInjector_thenWorks() {
class Controller2 {
private val injector = KodeinInjector()
val service: Service by injector.instance()
fun injectDependencies(kodein: Kodein) = injector.inject(kodein)
}
val kodein = Kodein {
bind<Dao>() with singleton { MongoDao() }
bind<Service>() with singleton { Service(instance(), "myService") }
}
val controller = Controller2()
controller.injectDependencies(kodein)
assertThat(controller.service).isNotNull
}
}
@@ -0,0 +1,30 @@
package com.baeldung.kotlin;
import org.junit.Test
import org.mockito.Mockito
class LibraryManagementTest {
@Test(expected = IllegalStateException::class)
fun whenBookIsNotAvailable_thenAnExceptionIsThrown() {
val mockBookService = Mockito.mock(BookService::class.java)
Mockito.`when`(mockBookService.inStock(100)).thenReturn(false)
val manager = LendBookManager(mockBookService)
manager.checkout(100, 1)
}
@Test
fun whenBookIsAvailable_thenLendMethodIsCalled() {
val mockBookService = Mockito.mock(BookService::class.java)
Mockito.`when`(mockBookService.inStock(100)).thenReturn(true)
val manager = LendBookManager(mockBookService)
manager.checkout(100, 1)
Mockito.verify(mockBookService).lend(100, 1)
}
}
@@ -0,0 +1,32 @@
package com.baeldung.kotlin;
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import org.junit.Test
class LibraryManagementTestMockitoKotlin {
@Test(expected = IllegalStateException::class)
fun whenBookIsNotAvailable_thenAnExceptionIsThrown() {
val mockBookService = mock<BookService>()
whenever(mockBookService.inStock(100)).thenReturn(false)
val manager = LendBookManager(mockBookService)
manager.checkout(100, 1)
}
@Test
fun whenBookIsAvailable_thenLendMethodIsCalled() {
val mockBookService : BookService = mock()
whenever(mockBookService.inStock(100)).thenReturn(true)
val manager = LendBookManager(mockBookService)
manager.checkout(100, 1)
verify(mockBookService).lend(100, 1)
}
}
@@ -0,0 +1,157 @@
package com.baeldung.kotlin.rxkotlin
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.functions.BiFunction
import io.reactivex.rxkotlin.*
import io.reactivex.subjects.PublishSubject
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
class RxKotlinTest {
@Test
fun whenBooleanArrayToObserver_thenBooleanObserver() {
val observable = listOf(true, false, false).toObservable()
observable.test().assertValues(true, false, false)
}
@Test
fun whenBooleanArrayToFlowable_thenBooleanFlowable() {
val flowable = listOf(true, false, false).toFlowable()
flowable.buffer(2).test().assertValues(listOf(true, false), listOf(false))
}
@Test
fun whenIntArrayToObserver_thenIntObserver() {
val observable = listOf(1, 1, 2, 3).toObservable()
observable.test().assertValues(1, 1, 2, 3)
}
@Test
fun whenIntArrayToFlowable_thenIntFlowable() {
val flowable = listOf(1, 1, 2, 3).toFlowable()
flowable.buffer(2).test().assertValues(listOf(1, 1), listOf(2, 3))
}
@Test
fun whenObservablePairToMap_thenSingleNoDuplicates() {
val list = listOf(Pair("a", 1), Pair("b", 2), Pair("c", 3), Pair("a", 4))
val observable = list.toObservable()
val map = observable.toMap()
assertEquals(mapOf(Pair("a", 4), Pair("b", 2), Pair("c", 3)), map.blockingGet())
}
@Test
fun whenObservablePairToMap_thenSingleWithDuplicates() {
val list = listOf(Pair("a", 1), Pair("b", 2), Pair("c", 3), Pair("a", 4))
val observable = list.toObservable()
val map = observable.toMultimap()
assertEquals(
mapOf(Pair("a", listOf(1, 4)), Pair("b", listOf(2)), Pair("c", listOf(3))),
map.blockingGet())
}
@Test
fun whenMergeAll_thenStream() {
val subject = PublishSubject.create<Observable<String>>()
val observable = subject.mergeAll()
val testObserver = observable.test()
subject.onNext(Observable.just("first", "second"))
testObserver.assertValues("first", "second")
subject.onNext(Observable.just("third", "fourth"))
subject.onNext(Observable.just("fifth"))
testObserver.assertValues("first", "second", "third", "fourth", "fifth")
}
@Test
fun whenConcatAll_thenStream() {
val subject = PublishSubject.create<Observable<String>>()
val observable = subject.concatAll()
val testObserver = observable.test()
subject.onNext(Observable.just("first", "second"))
testObserver.assertValues("first", "second")
subject.onNext(Observable.just("third", "fourth"))
subject.onNext(Observable.just("fifth"))
testObserver.assertValues("first", "second", "third", "fourth", "fifth")
}
@Test
fun whenSwitchLatest_thenStream() {
val subject = PublishSubject.create<Observable<String>>()
val observable = subject.switchLatest()
val testObserver = observable.test()
subject.onNext(Observable.just("first", "second"))
testObserver.assertValues("first", "second")
subject.onNext(Observable.just("third", "fourth"))
subject.onNext(Observable.just("fifth"))
testObserver.assertValues("first", "second", "third", "fourth", "fifth")
}
@Test
fun whenMergeAllMaybes_thenObservable() {
val subject = PublishSubject.create<Maybe<Int>>()
val observable = subject.mergeAllMaybes()
val testObserver = observable.test()
subject.onNext(Maybe.just(1))
subject.onNext(Maybe.just(2))
subject.onNext(Maybe.empty())
testObserver.assertValues(1, 2)
subject.onNext(Maybe.error(Exception("")))
subject.onNext(Maybe.just(3))
testObserver.assertValues(1, 2).assertError(Exception::class.java)
}
@Test
fun whenMerge_thenStream() {
val observables = mutableListOf(Observable.just("first", "second"))
val observable = observables.merge()
observables.add(Observable.just("third", "fourth"))
observables.add(Observable.error(Exception("e")))
observables.add(Observable.just("fifth"))
observable.test().assertValues("first", "second", "third", "fourth").assertError(Exception::class.java)
}
@Test
fun whenMergeDelayError_thenStream() {
val observables = mutableListOf<Observable<String>>(Observable.error(Exception("e1")))
val observable = observables.mergeDelayError()
observables.add(Observable.just("1", "2"))
observables.add(Observable.error(Exception("e2")))
observables.add(Observable.just("3"))
observable.test().assertValues("1", "2", "3").assertError(Exception::class.java)
}
@Test
fun whenCast_thenUniformType() {
val observable = Observable.just<Number>(1, 1, 2, 3)
observable.cast<Int>().test().assertValues(1, 1, 2, 3)
}
@Test
fun whenOfType_thenFilter() {
val observable = Observable.just(1, "and", 2, "and")
observable.ofType<Int>().test().assertValues(1, 2)
}
@Test
fun whenFunction_thenCompletable() {
var value = 0
val completable = { value = 3 }.toCompletable()
assertFalse(completable.test().isCancelled)
assertEquals(3, value)
}
@Test
fun whenHelper_thenMoreIdiomaticKotlin() {
val zipWith = Observable.just(1).zipWith(Observable.just(2)) { a, b -> a + b }
zipWith.subscribeBy(onNext = { println(it) })
val zip = Observables.zip(Observable.just(1), Observable.just(2)) { a, b -> a + b }
zip.subscribeBy(onNext = { println(it) })
val zipOrig = Observable.zip(Observable.just(1), Observable.just(2), BiFunction<Int, Int, Int> { a, b -> a + b })
zipOrig.subscribeBy(onNext = { println(it) })
}
}
@@ -0,0 +1,19 @@
package com.baeldung.kotlin.spek
import com.baeldung.kotlin.junit5.Calculator
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.subject.SubjectSpek
import org.junit.jupiter.api.Assertions.assertEquals
class CalculatorSubjectTest5 : SubjectSpek<Calculator>({
subject { Calculator() }
describe("A calculator") {
describe("Addition") {
val result = subject.add(3, 5)
it("Produces the correct answer") {
assertEquals(8, result)
}
}
}
})
@@ -0,0 +1,32 @@
package com.baeldung.kotlin.spek
import com.baeldung.kotlin.junit5.Calculator
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.junit.jupiter.api.Assertions.assertEquals
class CalculatorTest5 : Spek({
given("A calculator") {
val calculator = Calculator()
on("Adding 3 and 5") {
val result = calculator.add(3, 5)
it("Produces 8") {
assertEquals(8, result)
}
}
}
describe("A calculator") {
val calculator = Calculator()
describe("Addition") {
val result = calculator.add(3, 5)
it("Produces the correct answer") {
assertEquals(8, result)
}
}
}
})
@@ -0,0 +1,21 @@
package com.baeldung.kotlin.spek
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.junit.jupiter.api.Assertions
class DataDrivenTest5 : Spek({
describe("A data driven test") {
mapOf(
"hello" to "HELLO",
"world" to "WORLD"
).forEach { input, expected ->
describe("Capitalising $input") {
it("Correctly returns $expected") {
Assertions.assertEquals(expected, input.toUpperCase())
}
}
}
}
})
@@ -0,0 +1,62 @@
package com.baeldung.kotlin.spek
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
class GroupTest5 : Spek({
describe("Outer group") {
beforeEachTest {
System.out.println("BeforeEachTest 0")
}
beforeGroup {
System.out.println("BeforeGroup 0")
}
afterEachTest {
System.out.println("AfterEachTest 0")
}
afterGroup {
System.out.println("AfterGroup 0")
}
describe("Inner group 1") {
beforeEachTest {
System.out.println("BeforeEachTest 1")
}
beforeGroup {
System.out.println("BeforeGroup 1")
}
afterEachTest {
System.out.println("AfterEachTest 1")
}
afterGroup {
System.out.println("AfterGroup 1")
}
it("Test 1") {
System.out.println("Test 1")
}
it("Test 2") {
System.out.println("Test 2")
}
}
describe("Inner group 2") {
beforeEachTest {
System.out.println("BeforeEachTest 2")
}
beforeGroup {
System.out.println("BeforeGroup 2")
}
afterEachTest {
System.out.println("AfterEachTest 2")
}
afterGroup {
System.out.println("AfterGroup 2")
}
it("Test 3") {
System.out.println("Test 3")
}
it("Test 4") {
System.out.println("Test 4")
}
}
}
})