Skip to content
This repository has been archived by the owner on Jan 12, 2024. It is now read-only.

Commit

Permalink
Fix flaky PrometheusModuleSpec
Browse files Browse the repository at this point in the history
Use private methods testers to check if modules are registered
  • Loading branch information
stijndehaes committed Apr 20, 2019
1 parent b4d5ca0 commit a44f9b0
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 10 deletions.
2 changes: 1 addition & 1 deletion project/build.properties
@@ -1 +1 @@
sbt.version=1.1.2
sbt.version=1.2.3
@@ -1,28 +1,27 @@
package com.github.stijndehaes.playprometheusfilters

import io.prometheus.client.CollectorRegistry
import org.scalatest.{BeforeAndAfter, MustMatchers, WordSpec}
import org.slf4j.LoggerFactory
import io.prometheus.client.{Collector, CollectorRegistry}
import org.scalatest.{BeforeAndAfter, MustMatchers, PrivateMethodTester, WordSpec}
import org.scalatestplus.play.guice.GuiceOneAppPerTest
import play.api.inject.guice.GuiceApplicationBuilder

class PrometheusModuleSpec extends WordSpec with MustMatchers with BeforeAndAfter {
class PrometheusModuleSpec extends WordSpec with MustMatchers with BeforeAndAfter with PrivateMethodTester with GuiceOneAppPerTest {

before {
// clearing registry before each test
CollectorRegistry.defaultRegistry.clear()
}

private val logger = LoggerFactory.getLogger(classOf[PrometheusModuleSpec])

"PrometheusModule" should {
"register default exporters when enabled" in {
// default enabled
val app = new GuiceApplicationBuilder()
.configure(PrometheusModule.defaultExportsKey -> true)
.build()

val collector = app.injector.instanceOf[CollectorRegistry]
logger.info(s"More elements: ${collector.metricFamilySamples.hasMoreElements}")
collector.metricFamilySamples.hasMoreElements mustBe true
val collectors = PrivateMethod[java.util.HashSet[Collector]]('collectors)
(collector invokePrivate collectors()).size must be > 0
}

"not register default exporters when disabled" in {
Expand All @@ -32,8 +31,25 @@ class PrometheusModuleSpec extends WordSpec with MustMatchers with BeforeAndAfte
.build()

val collector = app.injector.instanceOf[CollectorRegistry]
collector.metricFamilySamples.hasMoreElements mustBe false
val collectors = PrivateMethod[java.util.HashSet[Collector]]('collectors)
(collector invokePrivate collectors()).size must be (0)
}
}

/**
* Utility to expose exporter names for test on [[CollectorRegistry]].
*/
implicit class CollectorRegistryExtention(val registry: CollectorRegistry) {
/**
* @return Registered exporter names.
*/
def getExporterNames: Seq[String] = {
val exportNames = collection.mutable.Buffer.empty[String]
val mfs = registry.metricFamilySamples()
while(mfs.hasMoreElements) {
exportNames += mfs.nextElement().name
}
exportNames
}
}
}

0 comments on commit a44f9b0

Please sign in to comment.