https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hiring-french
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
s

sam

11/02/2021, 3:24 PM
Right but in 5.0 you can. I'll double check that there's no changes required from a user perspective
d

dave08

11/03/2021, 1:09 PM
I think I'm missing something... is there some kind of documentation on best practices in making extensions/listeners?
s

sam

11/03/2021, 1:10 PM
Not yet. Once 5.0 is out I plan to overhaul the docs on this. If you have specific questions I can answer here.
d

dave08

11/03/2021, 1:11 PM
Say something like this:
class KtorExtension(val module: Application.() -> Unit) : TestListener {
    lateinit var appEngine: TestApplicationEngine

    lateinit var clientEngine: HttpClientEngine


    override suspend fun beforeTest(testCase: TestCase) {
        appEngine = TestApplicationEngine(createTestEnvironment())
            .also { it.application.module() }

        clientEngine = TestHttpClientEngine.create { app = appEngine }

        appEngine.start()
    }

    override suspend fun afterTest(testCase: TestCase, result: TestResult) {
        appEngine.stop(0L, 0L)
    }
}
is this the right way to do it?
Or should I be using an extension?
s

sam

11/03/2021, 1:11 PM
Yep that's fine, although I would do this:
class KtorExtension(val module: Application.() -> Unit) : BeforeTestListener, AfterTestListener {
    lateinit var appEngine: TestApplicationEngine

    lateinit var clientEngine: HttpClientEngine


    override suspend fun beforeTest(testCase: TestCase) {
        appEngine = TestApplicationEngine(createTestEnvironment())
            .also { it.application.module() }

        clientEngine = TestHttpClientEngine.create { app = appEngine }

        appEngine.start()
    }

    override suspend fun afterTest(testCase: TestCase, result: TestResult) {
        appEngine.stop(0L, 0L)
    }
}
d

dave08

11/03/2021, 1:12 PM
Why?
s

sam

11/03/2021, 1:12 PM
Because TestListener is just a combination of 10 interfaces that is around for legacy reasons. It won't be removed though.
d

dave08

11/03/2021, 1:13 PM
And so how are extensions different, and when would they apply?
s

sam

11/03/2021, 1:13 PM
An
extension
is anything you write that plugs into the kotest lifecycle - so before/after test/spec/project / etc. A
listener
is an older term we had that basically means "an extension that is read only". So notice in your example that you are notified of before/after test but you can't "change the engine". So that's a listener. An extension is just more powerful can do things like override test results, or skip tests entirely, etc.
d

dave08

11/03/2021, 1:14 PM
So why are you deprecating listener(...) if it has a different purpose?
s

sam

11/03/2021, 1:14 PM
because inside the code base listener extends extension. A listener is an extension, it's just a term for "simple extension" that really serves no purpose being it's own interface.
TestListener
won't be renamed as it's used by everyone, but what does this do:
interface Listener: Extension
It's irrelevant because internally, the code works on
interface Extension
Listener is just a marker interface serving no purpose other than to fuel discussions like this on "what is listener vs extension"
d

dave08

11/03/2021, 1:18 PM
Oh... that's a bit confusing on the user's side though... Since we're supposed to know that a listener is just another extension... after you explained it, it seems like both are useful... but you're right that having two ways to install the same thing isn't great either... I wonder if there's a way to make all this clearer.
s

sam

11/03/2021, 1:19 PM
This is meant to make things clearer. So instead of
class MyTest : FunSpec() {
  override fun extensions() = listOf(foo)
  override fun listeners() = listOf(bar)
}
Just do
class MyTest : FunSpec() {
  override fun extensions() = listOf(foo, bar)
}
everything is an extension, regardless of whether it's called an extension, a listener, or a filter, or a foo
I'll write up a page that goes over this in detail to hopefully make things clear and I'll circulate before we release 5.0
d

dave08

11/03/2021, 1:21 PM
Yeah, but it's not to evident that
BeforeTestListener
is an extension when the concept of
Extension
is something a bit more flexible. I guess the docs could be a big help do disambiguate things though...
s

sam

11/03/2021, 1:23 PM
Right, the nomenclature certainly isn't the best, for legacy reasons
but I think it's a clearer message to say "listeners are just extensions anyway" than "we have two parallel hierarchies of stuff"
👍🏼 1
d

dave08

11/03/2021, 1:24 PM
By the way, I was wondering what would be the most appropriate way to integrate Dagger2 into an extension to to dependency injection... also having a way to use the component's val's and functions without aliasing them
val dep1 get() = component.dep1()
would be nice...
I'd have to hook on to the test class creation somehow and maybe even make it a delegate of the component...
s

sam

11/03/2021, 1:27 PM
How does dagger integrate normally, outside of tests ?
is there a method you call like "setup my class" ?
d

dave08

11/03/2021, 1:31 PM
If I do:
class SomeSpec @Inject constructor(val dep1: Dep1) { ... }

// component interface
interface TestComponent {
   val someSpec: SomeSpec
}

// Will generate DaggerTestComponent, and then to build the graph:
val component = DaggerTestComponent.builder().build()

// And to retreive the injected spec:
component.someSpec
s

sam

11/03/2021, 1:32 PM
how does
someSpec
get inside the component ?
d

dave08

11/03/2021, 1:33 PM
Dagger2 generates
DaggerTestComponent
that derives from
TestComponent
with all the object initialization code
s

sam

11/03/2021, 1:33 PM
Through a compiler plugin ?
d

dave08

11/03/2021, 1:34 PM
Through kapt
s

sam

11/03/2021, 1:34 PM
You could write something like:
class DaggerExtension : PostInstantiationExtension {
  override suspend fun instantiated(spec: Spec): Spec {
    // get component somehow ? by casting ?
    return component.someSpec
  }
}
Or look at
ConstructorExtension
which allows you to control how the spec is created from the class
d

dave08

11/03/2021, 1:36 PM
Thanks! I'll take a look at those.
s

sam

11/03/2021, 1:40 PM
if you get stuck I can help
d

dave08

11/03/2021, 2:08 PM
Ok, a bit funny... I have say:
interface TestComponent {
  fun inject(spec: SomeSpec)
}

val component = DaggerTestComponent.builder().build()

class SomeSpec : DescribeSpec() {
  @Inject val dep1 : Dep1
}
I have to get the
PostInstantiationExtension
to run
component.inject(this@SomeSpec)
somehow... so that dep1 gets injected...
But how is the extension supposed to guess that TestComponent has an inject function that takes the SomeSpec type...
The start was:
class  DaggerExtension<C : Any, S : KotestDbSpec>(val component: C, val injector: (S) -> Unit) : PostInstantiationExtension {
    override fun process(spec: Spec): Spec = spec.also { component/*...?*/ }
}
s

sam

11/03/2021, 2:09 PM
Well, you could look for an annotation that tells it it's a dagger test, or you could do some reflection magic if something is possible there, or you could just say this extension should only be added to dagger specs and you cast and catch
d

dave08

11/03/2021, 2:11 PM
class  DaggerExtension<C : Any, S : KotestDbSpec>(val component: C, val injector: C.(S) -> Unit) : PostInstantiationExtension {
    override fun process(spec: Spec): Spec = spec.also { component.injector(spec as S) }
}
?
s

sam

11/03/2021, 2:12 PM
I don't know anything about dagger. How do you know something is dagger normally?
Does it generate a new class, or new functions, what does kapt add
d

dave08

11/03/2021, 2:13 PM
A DaggerTestComponent gets generated with something like:
@Override
  public void inject(GetCustomerSpec getCustomerSpec) {
    injectGetCustomerSpec(getCustomerSpec);
  }

  private GetCustomerSpec injectGetCustomerSpec(GetCustomerSpec instance) {
    GetCustomerSpec_MembersInjector.injectCustomerRepo(instance, customerTestRepoProvider.get());
    return instance;
  }
s

sam

11/03/2021, 2:14 PM
Is it called
DaggerTestComponent
and is there one per spec ?
or one giant one
d

dave08

11/03/2021, 2:15 PM
The generated class is Dagger{name of the component interface}
s

sam

11/03/2021, 2:16 PM
So then inside your extension, could you do
Class.forName(Dagger + kclass.name)
to get the class reference
Then you can use reflection to create the instance, call inject
that could easily be a ConstructorExtension
d

dave08

11/03/2021, 2:18 PM
And for each spec that needs injection, I would have to add an
fun inject(spec: SomeSpec)
, I don't need to create the spec, I just need to run
DaggerTestComponent.builder().build().inject(this)
before each test or spec.
I just need to find the appropriate inject function...
I suppose
Spec
doesn't contain it's type or something...
s

sam

11/03/2021, 2:20 PM
Spec::class is the spec's class
Right, so this is a start
class DaggerExtension : PostInstantiationExtension {
   override suspend fun instantiated(spec: Spec): Spec {
      val c = Class.forName("Dagger" + spec::class.name) // this would be DaggerMyTest
      val m = c.declaredMethods.find { it.name == "builder" ) // get builder() method
      val builder = m.invoke(null) as DaggerBuilder
      DaggerBuilder.build().inject(spec)
      return spec
   }
}
I didn't test any of that but it's probably in the right direction
d

dave08

11/03/2021, 2:33 PM
Class.forName("Dagger" + spec::class.name)
isn't the spec, it should be
Class.forName("Dagger" + componentInterface::class.name)
... say
TestComponent
would have
DaggerTestComponent
implementation generated that contains a function
inject(spec: SomeSpec)
which is the function that I need to run...
s

sam

11/03/2021, 2:33 PM
Well it's a start anyway
doing a prod release now, back later