ConfigurationFileTest.groovy 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * Copyright The OpenTelemetry Authors
  3. * SPDX-License-Identifier: Apache-2.0
  4. */
  5. package io.opentelemetry.javaagent.tooling.config
  6. import org.junit.Rule
  7. import org.junit.contrib.java.lang.system.EnvironmentVariables
  8. import spock.lang.Shared
  9. import spock.lang.Specification
  10. import spock.lang.TempDir
  11. import spock.util.environment.RestoreSystemProperties
  12. @RestoreSystemProperties
  13. class ConfigurationFileTest extends Specification {
  14. @Rule
  15. public final EnvironmentVariables environmentVariables = new EnvironmentVariables()
  16. @TempDir
  17. @Shared
  18. public File tmpDir
  19. def "should use env property"() {
  20. given:
  21. def path = createFile("config", "property1=val-env")
  22. environmentVariables.set(ConfigInitializer.CONFIGURATION_FILE_ENV_VAR, path)
  23. when:
  24. def properties = ConfigInitializer.loadConfigurationFile()
  25. then:
  26. properties.get("property1") == "val-env"
  27. }
  28. def "should use system property"() {
  29. given:
  30. def path = createFile("config", "property1=val-sys")
  31. System.setProperty(ConfigInitializer.CONFIGURATION_FILE_PROPERTY, path)
  32. when:
  33. def properties = ConfigInitializer.loadConfigurationFile()
  34. then:
  35. properties.get("property1") == "val-sys"
  36. }
  37. def "system property should take precedence over env property"() {
  38. given:
  39. def pathEnv = createFile("configEnv", "property1=val-env")
  40. def pathSys = createFile("configSys", "property1=val-sys")
  41. environmentVariables.set(ConfigInitializer.CONFIGURATION_FILE_ENV_VAR, pathEnv)
  42. System.setProperty(ConfigInitializer.CONFIGURATION_FILE_PROPERTY, pathSys)
  43. when:
  44. def properties = ConfigInitializer.loadConfigurationFile()
  45. then:
  46. properties.get("property1") == "val-sys"
  47. }
  48. def "should return empty properties if file does not exist"() {
  49. given:
  50. environmentVariables.set(ConfigInitializer.CONFIGURATION_FILE_ENV_VAR, "somePath")
  51. when:
  52. def properties = ConfigInitializer.loadConfigurationFile()
  53. then:
  54. !properties.propertyNames().hasMoreElements()
  55. }
  56. def "should return empty properties if property is not set"() {
  57. when:
  58. def properties = ConfigInitializer.loadConfigurationFile()
  59. then:
  60. !properties.propertyNames().hasMoreElements()
  61. }
  62. def createFile(String name, String contents) {
  63. def file = new File(tmpDir, name)
  64. file.write(contents)
  65. return file.getAbsolutePath()
  66. }
  67. }