summaryrefslogtreecommitdiffstats
path: root/container-di/src/test/scala/com/yahoo/container/di/ContainerTest.scala
blob: 6cccd5c06a4c65acb2c1efd779a03329ba79d935 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.di

import com.yahoo.container.di.componentgraph.core.ComponentGraphTest.{SimpleComponent, SimpleComponent2}
import com.yahoo.container.di.componentgraph.Provider
import com.yahoo.container.di.componentgraph.core.{ComponentGraph, Node}
import org.junit.{After, Before, Test}
import org.junit.Assert._
import org.hamcrest.CoreMatchers._
import com.yahoo.config.test.TestConfig
import com.yahoo.component.AbstractComponent
import ContainerTest._

import scala.collection.JavaConversions
import com.yahoo.config.di.IntConfig

import scala.concurrent.{Await, Future, future}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.Try
import com.yahoo.container.di.config.RestApiContext
import com.yahoo.container.bundle.MockBundle

import scala.language.postfixOps

/**
 * @author tonytv
 * @author gjoranv
 */
class ContainerTest {
  var dirConfigSource: DirConfigSource = _

  @Before def setup()  {
    dirConfigSource = new DirConfigSource("ContainerTest-")
  }

  @After def cleanup() {
    dirConfigSource.cleanup()
  }

  @Test
  def components_can_be_created_from_config() {
    writeBootstrapConfigs()
    dirConfigSource.writeConfig("test", """stringVal "myString" """)

    val container = newContainer(dirConfigSource)

    val component = createComponentTakingConfig(container.runOnce())
    assertThat(component.config.stringVal(), is("myString"))

    container.shutdownConfigurer()
  }

  @Test
  def components_are_reconfigured_after_config_update_without_bootstrap_configs() {
    writeBootstrapConfigs()
    dirConfigSource.writeConfig("test", """stringVal "original" """)

    val container = newContainer(dirConfigSource)

    val componentGraph = container.runOnce()
    val component = createComponentTakingConfig(componentGraph)

    assertThat(component.config.stringVal(), is("original"))

    // Reconfigure
    dirConfigSource.writeConfig("test", """stringVal "reconfigured" """)
    container.reloadConfig(2)

    val newComponentGraph = container.runOnce(componentGraph)
    val component2 = createComponentTakingConfig(newComponentGraph)
    assertThat(component2.config.stringVal(), is("reconfigured"))

    container.shutdownConfigurer()
  }

  @Test
  def graph_is_updated_after_bootstrap_update() {
    dirConfigSource.writeConfig("test", """stringVal "original" """)
    writeBootstrapConfigs("id1")

    val container = newContainer(dirConfigSource)

    val graph = container.runOnce()
    val component = createComponentTakingConfig(graph)
    assertThat(component.getId.toString, is("id1"))

    writeBootstrapConfigsWithMultipleComponents(Array(
      ("id1", classOf[ComponentTakingConfig]),
      ("id2", classOf[ComponentTakingConfig])))

    container.reloadConfig(2)
    val newGraph = container.runOnce(graph)

    assertThat(ComponentGraph.getNode(newGraph, "id1"), notNullValue(classOf[Node]))
    assertThat(ComponentGraph.getNode(newGraph, "id2"), notNullValue(classOf[Node]))

    container.shutdownConfigurer()
  }

  //@Test TODO
  def deconstructor_is_given_guice_components() {
  }

  @Test
  def osgi_component_is_deconstructed_when_not_reused() {
    writeBootstrapConfigs("id1", classOf[DestructableComponent])

    val container = newContainer(dirConfigSource)

    val oldGraph = container.runOnce()
    val componentToDestruct = oldGraph.getInstance(classOf[DestructableComponent])

    writeBootstrapConfigs("id2", classOf[DestructableComponent])
    container.reloadConfig(2)
    container.runOnce(oldGraph)
    assertTrue(componentToDestruct.deconstructed)
  }

  @Test
  def previous_graph_is_retained_when_new_graph_throws_exception_for_missing_config() {
    val simpleComponentEntry = ComponentEntry("simpleComponent", classOf[SimpleComponent])

    writeBootstrapConfigs(Array(simpleComponentEntry))
    val container = newContainer(dirConfigSource)
    var currentGraph = container.runOnce()

    val simpleComponent = currentGraph.getInstance(classOf[SimpleComponent])

    writeBootstrapConfigs("thrower", classOf[ComponentThrowingExceptionForMissingConfig])
    dirConfigSource.writeConfig("test", """stringVal "myString" """)
    container.reloadConfig(2)
    try {
      currentGraph = container.runOnce(currentGraph)
      fail("Expected exception")
    } catch {
      case e: Exception => e.printStackTrace()
    }
    assertEquals(1, currentGraph.generation)

    val componentTakingConfigEntry = ComponentEntry("componentTakingConfig", classOf[ComponentTakingConfig])
    writeBootstrapConfigs(Array(simpleComponentEntry, componentTakingConfigEntry))
    container.reloadConfig(3)
    currentGraph = container.runOnce(currentGraph)

    assertEquals(3, currentGraph.generation)
    assertSame(simpleComponent, currentGraph.getInstance(classOf[SimpleComponent]))
    assertNotNull(currentGraph.getInstance(classOf[ComponentTakingConfig]))
  }

  @Test
  def runOnce_hangs_waiting_for_valid_config_after_invalid_config() {
    dirConfigSource.writeConfig("test", """stringVal "original" """)
    writeBootstrapConfigs("myId", classOf[ComponentTakingConfig])

    val container = newContainer(dirConfigSource)
    var currentGraph = container.runOnce()

    writeBootstrapConfigs("thrower", classOf[ComponentThrowingExceptionForMissingConfig])
    container.reloadConfig(2)

    try {
      currentGraph = container.runOnce(currentGraph)
      fail("expected exception")
    } catch {
      case e: Exception =>
    }

    val newGraph = Future {
      currentGraph = container.runOnce(currentGraph)
      currentGraph
    }

    Try {
      Await.ready(newGraph, 1 second)
    } foreach { x => fail("Expected waiting for new config.") }


    writeBootstrapConfigs("myId2", classOf[ComponentTakingConfig])
    container.reloadConfig(3)

    assertNotNull(Await.result(newGraph, 5 minutes))
  }


  @Test
  def bundle_info_is_set_on_rest_api_context() {
    val clazz = classOf[RestApiContext]

    writeBootstrapConfigs("restApiContext", clazz)
    dirConfigSource.writeConfig("jersey-bundles", """bundles[0].spec "mock-entry-to-enforce-a-MockBundle" """)
    dirConfigSource.writeConfig("jersey-injection", """inject[0]" """)

    val container = newContainer(dirConfigSource)
    val componentGraph = container.runOnce()

    val restApiContext = componentGraph.getInstance(clazz)
    assertNotNull(restApiContext)

    assertThat(restApiContext.getBundles.size, is(1))
    assertThat(restApiContext.getBundles.get(0).symbolicName, is(MockBundle.SymbolicName))
    assertThat(restApiContext.getBundles.get(0).version, is(MockBundle.BundleVersion))

    container.shutdownConfigurer()
   }

  @Test
  def restApiContext_has_all_components_injected() {
    new JerseyInjectionTest {
      assertFalse(restApiContext.getInjectableComponents.isEmpty)
      assertThat(restApiContext.getInjectableComponents.size(), is(2))

      container.shutdownConfigurer()
    }
  }

  // TODO: reuse injectedComponent as a named component when we support that
  trait JerseyInjectionTest {
    val restApiClass = classOf[RestApiContext]
    val injectedClass = classOf[SimpleComponent]
    val injectedComponentId = "injectedComponent"
    val anotherComponentClass = classOf[SimpleComponent2]
    val anotherComponentId = "anotherComponent"

    val componentsConfig: String =
      ComponentEntry(injectedComponentId, injectedClass).asConfig(0) + "\n" +
        ComponentEntry(anotherComponentId, anotherComponentClass).asConfig(1) + "\n" +
        ComponentEntry("restApiContext", restApiClass).asConfig(2) + "\n" +
        s"components[2].inject[0].id $injectedComponentId\n" +
        s"components[2].inject[1].id $anotherComponentId\n"

    val injectionConfig = s"""inject[1]
                             |inject[0].instance $injectedComponentId
                             |inject[0].forClass "${injectedClass.getName}"
                            """.stripMargin

    dirConfigSource.writeConfig("components", componentsConfig)
    dirConfigSource.writeConfig("bundles", "")
    dirConfigSource.writeConfig("jersey-bundles", """bundles[0].spec "mock-entry-to-enforce-a-MockBundle" """)
    dirConfigSource.writeConfig("jersey-injection", injectionConfig)

    val container = newContainer(dirConfigSource)
    val componentGraph = container.runOnce()

    val restApiContext = componentGraph.getInstance(restApiClass)
  }

  case class ComponentEntry(componentId: String,  classId: Class[_]) {
    def asConfig(position: Int): String = {
      <config>
      |components[{position}].id "{componentId}"
      |components[{position}].classId "{classId.getName}"
      |components[{position}].configId "{dirConfigSource.configId}"
      </config>.text.stripMargin.trim
    }
  }

  def writeBootstrapConfigs(componentEntries: Array[ComponentEntry]) {
    dirConfigSource.writeConfig("bundles", "")
    dirConfigSource.writeConfig("components", """
      components[%s]
      %s
    """.format(componentEntries.length,
      componentEntries.zipWithIndex.map{ case (entry, index) => entry.asConfig(index) }.mkString("\n")))
  }

  def writeBootstrapConfigs(componentId: String = classOf[ComponentTakingConfig].getName,
                            classId: Class[_] = classOf[ComponentTakingConfig]) {

    writeBootstrapConfigs(Array(ComponentEntry(componentId, classId)))
  }

  def writeBootstrapConfigsWithMultipleComponents(idAndClass: Array[(String, Class[_])]) {
    writeBootstrapConfigs(idAndClass.map{case(id, classId) => ComponentEntry(id, classId)})
  }


  @Test
  def providers_are_destructed() {
    writeBootstrapConfigs("id1", classOf[DestructableProvider])

    val deconstructor = new ComponentDeconstructor {
      def deconstruct(component: AnyRef) {
        component match  {
          case c : AbstractComponent => c.deconstruct()
          case p : Provider[_] => p.deconstruct()
        }
      }
    }

    val container = newContainer(dirConfigSource, deconstructor)

    val oldGraph = container.runOnce()
    val destructableEntity = oldGraph.getInstance(classOf[DestructableEntity])

    writeBootstrapConfigs("id2", classOf[DestructableProvider])
    container.reloadConfig(2)
    container.runOnce(oldGraph)

    assertTrue(destructableEntity.deconstructed)
  }
}


object ContainerTest {
  class DestructableEntity {
    var deconstructed = false
  }

  class DestructableProvider extends Provider[DestructableEntity] {
    val instance = new DestructableEntity

    def get() = instance

    def deconstruct() {
      require(! instance.deconstructed)
      instance.deconstructed = true
    }
  }

  class ComponentTakingConfig(val config: TestConfig) extends AbstractComponent {
    require(config != null)
  }

  class ComponentThrowingExceptionForMissingConfig(intConfig: IntConfig) extends AbstractComponent {
    fail("This component should never be created. Only used for tests where 'int' config is missing.")
  }

  class DestructableComponent extends AbstractComponent {
    var deconstructed = false
    override def deconstruct() {
      deconstructed = true
    }
  }

  class TestDeconstructor extends ComponentDeconstructor {
    def deconstruct(component: AnyRef) {
      component match {
        case vespaComponent: DestructableComponent => vespaComponent.deconstruct()
        case _ =>
      }
    }
  }

  private def newContainer(dirConfigSource: DirConfigSource,
                           deconstructor: ComponentDeconstructor = new TestDeconstructor()):
  Container = {
    new Container(new CloudSubscriberFactory(dirConfigSource.configSource), dirConfigSource.configId, deconstructor)
  }

  def createComponentTakingConfig(componentGraph: ComponentGraph): ComponentTakingConfig = {
    componentGraph.getInstance(classOf[ComponentTakingConfig])
  }

  def convertMap[K, V](map: java.util.Map[K, V]): Map[K, V] = JavaConversions.mapAsScalaMap(map).toMap
}