github.com/RedHatInsights/insights-results-aggregator@v1.4.1/conf/configuration_test.go (about)

     1  /*
     2  Copyright © 2020, 2021, 2022, 2023 Red Hat, Inc.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package conf_test
    18  
    19  import (
    20  	"fmt"
    21  	"os"
    22  	"strings"
    23  	"testing"
    24  	"time"
    25  
    26  	"github.com/RedHatInsights/insights-operator-utils/logger"
    27  	"github.com/RedHatInsights/insights-operator-utils/tests/helpers"
    28  	mapset "github.com/deckarep/golang-set"
    29  	clowder "github.com/redhatinsights/app-common-go/pkg/api/v1"
    30  	"github.com/rs/zerolog"
    31  	"github.com/stretchr/testify/assert"
    32  
    33  	"github.com/RedHatInsights/insights-results-aggregator/conf"
    34  	"github.com/RedHatInsights/insights-results-aggregator/server"
    35  	"github.com/RedHatInsights/insights-results-aggregator/storage"
    36  	"github.com/RedHatInsights/insights-results-aggregator/types"
    37  )
    38  
    39  func init() {
    40  	zerolog.SetGlobalLevel(zerolog.WarnLevel)
    41  }
    42  
    43  func mustLoadConfiguration(path string) {
    44  	err := conf.LoadConfiguration(path)
    45  	if err != nil {
    46  		panic(err)
    47  	}
    48  }
    49  
    50  func removeFile(t *testing.T, filename string) {
    51  	err := os.Remove(filename)
    52  	helpers.FailOnError(t, err)
    53  }
    54  
    55  func setEnvVariables(t *testing.T) {
    56  	os.Clearenv()
    57  
    58  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__BROKER__ADDRESSES", "localhost:9093")
    59  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__BROKER__TOPIC", "platform.results.ccx")
    60  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__BROKER__GROUP", "aggregator")
    61  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__BROKER__ENABLED", "true")
    62  
    63  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__SERVER__ADDRESS", ":8080")
    64  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__SERVER__API_PREFIX", "/api/v1/")
    65  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__SERVER__API_SPEC_FILE", "openapi.json")
    66  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__SERVER__DEBUG", "true")
    67  
    68  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__PROCESSING__ORG_ALLOWLIST", "org_allowlist.csv")
    69  
    70  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__OCP_RECOMMENDATIONS_STORAGE__DB_DRIVER", "postgres")
    71  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__OCP_RECOMMENDATIONS_STORAGE__PG_USERNAME", "user")
    72  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__OCP_RECOMMENDATIONS_STORAGE__PG_PASSWORD", "password")
    73  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__OCP_RECOMMENDATIONS_STORAGE__PG_HOST", "localhost")
    74  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__OCP_RECOMMENDATIONS_STORAGE__PG_PORT", "5432")
    75  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__OCP_RECOMMENDATIONS_STORAGE__PG_DB_NAME", "aggregator")
    76  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__OCP_RECOMMENDATIONS_STORAGE__PG_PARAMS", "params")
    77  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__OCP_RECOMMENDATIONS_STORAGE__LOG_SQL_QUERIES", "true")
    78  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__OCP_RECOMMENDATIONS_STORAGE__TYPE", "sql")
    79  
    80  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__DVO_RECOMMENDATIONS_STORAGE__DB_DRIVER", "postgres")
    81  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__DVO_RECOMMENDATIONS_STORAGE__PG_USERNAME", "user")
    82  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__DVO_RECOMMENDATIONS_STORAGE__PG_PASSWORD", "password")
    83  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__DVO_RECOMMENDATIONS_STORAGE__PG_HOST", "localhost")
    84  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__DVO_RECOMMENDATIONS_STORAGE__PG_PORT", "5432")
    85  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__DVO_RECOMMENDATIONS_STORAGE__PG_DB_NAME", "aggregator")
    86  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__DVO_RECOMMENDATIONS_STORAGE__PG_PARAMS", "params")
    87  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__DVO_RECOMMENDATIONS_STORAGE__LOG_SQL_QUERIES", "true")
    88  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__DVO_RECOMMENDATIONS_STORAGE__TYPE", "sql")
    89  
    90  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__REDIS__ENDPOINT", "default-redis-endpoint")
    91  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__REDIS__DATABASE", "42")
    92  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__REDIS__TIMEOUT_SECONDS", "0")
    93  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__REDIS__PASSWORD", "top secret")
    94  
    95  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__SENTRY__DSN", "test.example.com")
    96  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__SENTRY__ENVIRONMENT", "test")
    97  }
    98  
    99  func mustSetEnv(t *testing.T, key, val string) {
   100  	err := os.Setenv(key, val)
   101  	helpers.FailOnError(t, err)
   102  }
   103  
   104  func GetTmpConfigFile(configData string) (string, error) {
   105  	tmpFile, err := os.CreateTemp("/tmp", "tmp_config_*.toml")
   106  	if err != nil {
   107  		return "", err
   108  	}
   109  
   110  	if _, err := tmpFile.WriteString(configData); err != nil {
   111  		return "", err
   112  	}
   113  
   114  	if err := tmpFile.Close(); err != nil {
   115  		return "", err
   116  	}
   117  
   118  	return tmpFile.Name(), nil
   119  }
   120  
   121  // TestLoadConfiguration loads a configuration file for testing
   122  func TestLoadConfiguration(_ *testing.T) {
   123  	os.Clearenv()
   124  
   125  	mustLoadConfiguration("tests/config1")
   126  }
   127  
   128  // TestLoadConfigurationEnvVariable tests loading the config. file for testing from an environment variable
   129  func TestLoadConfigurationEnvVariable(t *testing.T) {
   130  	os.Clearenv()
   131  
   132  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR_CONFIG_FILE", "../tests/config1")
   133  
   134  	mustLoadConfiguration("foobar")
   135  }
   136  
   137  // TestLoadingConfigurationFailure tests loading a non-existent configuration file
   138  func TestLoadingConfigurationFailure(t *testing.T) {
   139  	os.Clearenv()
   140  
   141  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR_CONFIG_FILE", "non existing file")
   142  
   143  	err := conf.LoadConfiguration("")
   144  	assert.Contains(t, err.Error(), `fatal error config file: Config File "non existing file" Not Found in`)
   145  }
   146  
   147  // TestLoadBrokerConfiguration tests loading the broker configuration sub-tree
   148  func TestLoadBrokerConfiguration(t *testing.T) {
   149  	helpers.FailOnError(t, os.Chdir(".."))
   150  	TestLoadConfiguration(t)
   151  	expectedTimeout, _ := time.ParseDuration("30s")
   152  
   153  	brokerCfg := conf.GetBrokerConfiguration()
   154  
   155  	assert.Equal(t, "localhost:29092", brokerCfg.Addresses)
   156  	assert.Equal(t, "platform.results.ccx", brokerCfg.Topic)
   157  	assert.Equal(t, "aggregator", brokerCfg.Group)
   158  	assert.Equal(t, expectedTimeout, brokerCfg.Timeout)
   159  }
   160  
   161  // TestLoadServerConfiguration tests loading the server configuration sub-tree
   162  func TestLoadServerConfiguration(t *testing.T) {
   163  	TestLoadConfiguration(t)
   164  
   165  	serverCfg := conf.GetServerConfiguration()
   166  
   167  	assert.Equal(t, ":8080", serverCfg.Address)
   168  	assert.Equal(t, "/api/v1/", serverCfg.APIPrefix)
   169  }
   170  
   171  // TestLoadStorageBackendConfigurationChangedFromEnvVar tests loading the
   172  // storage backend configuration subtree
   173  func TestLoadStorageBackendConfigurationChangedFromEnvVar(t *testing.T) {
   174  	os.Clearenv()
   175  
   176  	const configPath = "../tests/config1"
   177  
   178  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__STORAGE_BACKEND__USE", "dvo_recommendations")
   179  
   180  	mustLoadConfiguration(configPath)
   181  
   182  	storageCfg := conf.GetStorageBackendConfiguration()
   183  	assert.Equal(t, "dvo_recommendations", storageCfg.Use)
   184  }
   185  
   186  // TestLoadStorageBackendConfigurationChangedFromEnvVar tests loading the
   187  // storage backend configuration subtree doesn't change from empty
   188  func TestLoadStorageBackendConfigurationNotChangedWhenEmpty(t *testing.T) {
   189  	os.Clearenv()
   190  
   191  	const configPath = "../tests/config1"
   192  
   193  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__STORAGE_BACKEND__USE", "")
   194  	mustLoadConfiguration(configPath)
   195  
   196  	storageCfg := conf.GetStorageBackendConfiguration()
   197  	assert.Equal(t, "", storageCfg.Use)
   198  }
   199  
   200  // TestLoadOCPRecommendationsStorageConfiguration tests loading the OCP
   201  // recommendations storage configuration subtree
   202  func TestLoadOCPRecommendationsStorageConfiguration(t *testing.T) {
   203  	TestLoadConfiguration(t)
   204  
   205  	storageCfg := conf.GetOCPRecommendationsStorageConfiguration()
   206  
   207  	assert.Equal(t, "postgres", storageCfg.Driver)
   208  	assert.Equal(t, "sql", storageCfg.Type)
   209  }
   210  
   211  // TestLoadDVORecommendationsStorageConfiguration tests loading the DVO
   212  // recommendations storage configuration subtree
   213  func TestLoadDVORecommendationsStorageConfiguration(t *testing.T) {
   214  	TestLoadConfiguration(t)
   215  
   216  	storageCfg := conf.GetDVORecommendationsStorageConfiguration()
   217  
   218  	assert.Equal(t, "postgres", storageCfg.Driver)
   219  	assert.Equal(t, "user", storageCfg.PGUsername)
   220  	assert.Equal(t, "password", storageCfg.PGPassword)
   221  	assert.Equal(t, "sql", storageCfg.Type)
   222  }
   223  
   224  // TestLoadRedisConfiguration tests loading the Redis configuration subtree
   225  func TestLoadRedisConfiguration(t *testing.T) {
   226  	TestLoadConfiguration(t)
   227  
   228  	redisCfg := conf.GetRedisConfiguration()
   229  
   230  	assert.Equal(t, "localhost:6379", redisCfg.RedisEndpoint)
   231  	assert.Equal(t, 0, redisCfg.RedisDatabase)
   232  	assert.Equal(t, 30, redisCfg.RedisTimeoutSeconds)
   233  	assert.Equal(t, "", redisCfg.RedisPassword)
   234  }
   235  
   236  // TestLoadConfigurationOverrideFromEnv1 tests overriding configuration by env variables
   237  func TestLoadConfigurationOverrideFromEnv1(t *testing.T) {
   238  	os.Clearenv()
   239  
   240  	const configPath = "../tests/config1"
   241  
   242  	mustLoadConfiguration(configPath)
   243  
   244  	storageCfg := conf.GetOCPRecommendationsStorageConfiguration()
   245  	assert.Equal(t, storage.Configuration{
   246  		Driver:     "postgres",
   247  		PGUsername: "user",
   248  		PGPassword: "password",
   249  		PGHost:     "localhost",
   250  		PGPort:     5432,
   251  		PGDBName:   "aggregator",
   252  		PGParams:   "",
   253  		Type:       "sql",
   254  	}, storageCfg)
   255  
   256  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__OCP_RECOMMENDATIONS_STORAGE__PG_PASSWORD", "some very secret password")
   257  
   258  	mustLoadConfiguration(configPath)
   259  
   260  	storageCfg = conf.GetOCPRecommendationsStorageConfiguration()
   261  	assert.Equal(t, storage.Configuration{
   262  		Driver:     "postgres",
   263  		PGUsername: "user",
   264  		PGPassword: "some very secret password",
   265  		PGHost:     "localhost",
   266  		PGPort:     5432,
   267  		PGDBName:   "aggregator",
   268  		PGParams:   "",
   269  		Type:       "sql",
   270  	}, storageCfg)
   271  }
   272  
   273  // TestLoadConfigurationOverrideFromEnv2 tests overriding configuration by env variables
   274  func TestLoadConfigurationOverrideFromEnv2(t *testing.T) {
   275  	os.Clearenv()
   276  
   277  	const configPath = "../tests/config1"
   278  
   279  	mustLoadConfiguration(configPath)
   280  
   281  	storageCfg := conf.GetDVORecommendationsStorageConfiguration()
   282  	assert.Equal(t, storage.Configuration{
   283  		Driver:     "postgres",
   284  		PGUsername: "user",
   285  		PGPassword: "password",
   286  		PGHost:     "localhost",
   287  		PGPort:     5432,
   288  		PGDBName:   "aggregator",
   289  		PGParams:   "",
   290  		Type:       "sql",
   291  	}, storageCfg)
   292  
   293  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__DVO_RECOMMENDATIONS_STORAGE__PG_PASSWORD", "some very secret password")
   294  
   295  	mustLoadConfiguration(configPath)
   296  
   297  	storageCfg = conf.GetDVORecommendationsStorageConfiguration()
   298  	assert.Equal(t, storage.Configuration{
   299  		Driver:     "postgres",
   300  		PGUsername: "user",
   301  		PGPassword: "some very secret password",
   302  		PGHost:     "localhost",
   303  		PGPort:     5432,
   304  		PGDBName:   "aggregator",
   305  		PGParams:   "",
   306  		Type:       "sql",
   307  	}, storageCfg)
   308  }
   309  
   310  // TestLoadOrganizationAllowlist tests if the allow-list CSV file gets loaded properly
   311  func TestLoadOrganizationAllowlist(t *testing.T) {
   312  	expectedAllowlist := mapset.NewSetWith(
   313  		types.OrgID(1),
   314  		types.OrgID(2),
   315  		types.OrgID(3),
   316  		types.OrgID(11789772),
   317  		types.OrgID(656485),
   318  	)
   319  
   320  	orgAllowlist := conf.GetOrganizationAllowlist()
   321  	if equal := orgAllowlist.Equal(expectedAllowlist); !equal {
   322  		t.Errorf(
   323  			"Org allowlist did not load properly. Order of elements does not matter. Expected %v. Got %v",
   324  			expectedAllowlist, orgAllowlist,
   325  		)
   326  	}
   327  }
   328  
   329  // TestLoadAllowlistFromCSVExtraParam tests incorrect CSV format
   330  func TestLoadAllowlistFromCSVExtraParam(t *testing.T) {
   331  	extraParamCSV := `OrgID
   332  1,2
   333  3
   334  `
   335  	r := strings.NewReader(extraParamCSV)
   336  	_, err := conf.LoadAllowlistFromCSV(r)
   337  	assert.EqualError(t, err, "error reading CSV file: record on line 2: wrong number of fields")
   338  }
   339  
   340  // TestLoadAllowlistFromCSVNonInt tests non-integer ID in CSV
   341  func TestLoadAllowlistFromCSVNonInt(t *testing.T) {
   342  	nonIntIDCSV := `OrgID
   343  str
   344  3
   345  `
   346  	r := strings.NewReader(nonIntIDCSV)
   347  	_, err := conf.LoadAllowlistFromCSV(r)
   348  	assert.EqualError(t, err, "organization ID on line 2 in allowlist CSV is not numerical. Found value: str")
   349  }
   350  
   351  func TestLoadConfigurationFromFile(t *testing.T) {
   352  	config := `[broker]
   353  		Addresses = "localhost:29092"
   354  		topic = "platform.results.ccx"
   355  		group = "aggregator"
   356  		enabled = true
   357  		enable_org_allowlist = true
   358  
   359  		[processing]
   360  		org_allowlist_file = "org_allowlist.csv"
   361  
   362  		[server]
   363  		Addresses = ":8080"
   364  		api_prefix = "/api/v1/"
   365  		api_spec_file = "openapi.json"
   366  		debug = true
   367  
   368  		[ocp_recommendations_storage]
   369  		db_driver = "postgres"
   370  		pg_username = "user"
   371  		pg_password = "password"
   372  		pg_host = "localhost"
   373  		pg_port = 5432
   374  		pg_db_name = "aggregator"
   375  		pg_params = "params"
   376  		log_sql_queries = true
   377  		type = "sql"
   378  
   379  		[redis]
   380  		database = 0
   381  		endpoint = "localhost:6379"
   382  		password = ""
   383  		timeout_seconds = 30
   384  
   385  		[sentry]
   386  		dsn = "test.example2.com"
   387  		environment = "test2"
   388  	`
   389  
   390  	tmpFilename, err := GetTmpConfigFile(config)
   391  	helpers.FailOnError(t, err)
   392  
   393  	defer removeFile(t, tmpFilename)
   394  
   395  	os.Clearenv()
   396  	mustSetEnv(t, conf.ConfigFileEnvVariableName, tmpFilename)
   397  	mustLoadConfiguration("../tests/config1")
   398  
   399  	brokerCfg := conf.GetBrokerConfiguration()
   400  
   401  	assert.Equal(t, "localhost:29092", brokerCfg.Addresses)
   402  	assert.Equal(t, "platform.results.ccx", brokerCfg.Topic)
   403  	assert.Equal(t, "aggregator", brokerCfg.Group)
   404  	assert.Equal(t, true, brokerCfg.Enabled)
   405  
   406  	assert.Equal(t, server.Configuration{
   407  		Address:                      ":8080",
   408  		APIPrefix:                    "/api/v1/",
   409  		APISpecFile:                  "openapi.json",
   410  		AuthType:                     "xrh",
   411  		Auth:                         false,
   412  		Debug:                        true,
   413  		MaximumFeedbackMessageLength: 255,
   414  		OrgOverviewLimitHours:        2,
   415  	}, conf.GetServerConfiguration())
   416  
   417  	orgAllowlist := conf.GetOrganizationAllowlist()
   418  
   419  	assert.True(
   420  		t,
   421  		orgAllowlist.Equal(mapset.NewSetWith(
   422  			types.OrgID(1),
   423  			types.OrgID(2),
   424  			types.OrgID(3),
   425  			types.OrgID(11789772),
   426  			types.OrgID(656485),
   427  		)),
   428  		"organization_white_list is wrong",
   429  	)
   430  
   431  	assert.Equal(t, storage.Configuration{
   432  		Driver:        "postgres",
   433  		LogSQLQueries: true,
   434  		PGUsername:    "user",
   435  		PGPassword:    "password",
   436  		PGHost:        "localhost",
   437  		PGPort:        5432,
   438  		PGDBName:      "aggregator",
   439  		PGParams:      "params",
   440  		Type:          "sql",
   441  	}, conf.GetOCPRecommendationsStorageConfiguration())
   442  
   443  	assert.Equal(t, storage.RedisConfiguration{
   444  		RedisEndpoint:       "localhost:6379",
   445  		RedisDatabase:       0,
   446  		RedisTimeoutSeconds: 30,
   447  		RedisPassword:       "",
   448  	}, conf.GetRedisConfiguration())
   449  
   450  	assert.Equal(t, logger.SentryLoggingConfiguration{
   451  		SentryDSN:         "test.example2.com",
   452  		SentryEnvironment: "test2",
   453  	}, conf.GetSentryLoggingConfiguration())
   454  }
   455  
   456  func TestLoadConfigurationFromEnv(t *testing.T) {
   457  	setEnvVariables(t)
   458  
   459  	mustLoadConfiguration("/non_existing_path")
   460  
   461  	brokerCfg := conf.GetBrokerConfiguration()
   462  
   463  	assert.Equal(t, "localhost:9093", brokerCfg.Addresses)
   464  	assert.Equal(t, "platform.results.ccx", brokerCfg.Topic)
   465  	assert.Equal(t, "aggregator", brokerCfg.Group)
   466  	assert.Equal(t, true, brokerCfg.Enabled)
   467  
   468  	assert.Equal(t, server.Configuration{
   469  		Address:                      ":8080",
   470  		APIPrefix:                    "/api/v1/",
   471  		APISpecFile:                  "openapi.json",
   472  		AuthType:                     "xrh",
   473  		Auth:                         false,
   474  		Debug:                        true,
   475  		MaximumFeedbackMessageLength: 255,
   476  		OrgOverviewLimitHours:        2,
   477  	}, conf.GetServerConfiguration())
   478  
   479  	orgAllowlist := conf.GetOrganizationAllowlist()
   480  
   481  	assert.True(
   482  		t,
   483  		orgAllowlist.Equal(mapset.NewSetWith(
   484  			types.OrgID(1),
   485  			types.OrgID(2),
   486  			types.OrgID(3),
   487  			types.OrgID(11789772),
   488  			types.OrgID(656485),
   489  		)),
   490  		"organization_white_list is wrong",
   491  	)
   492  
   493  	assert.Equal(t, storage.Configuration{
   494  		Driver:        "postgres",
   495  		LogSQLQueries: true,
   496  		PGUsername:    "user",
   497  		PGPassword:    "password",
   498  		PGHost:        "localhost",
   499  		PGPort:        5432,
   500  		PGDBName:      "aggregator",
   501  		PGParams:      "params",
   502  		Type:          "sql",
   503  	}, conf.GetOCPRecommendationsStorageConfiguration())
   504  
   505  	assert.Equal(t, storage.RedisConfiguration{
   506  		RedisEndpoint:       "default-redis-endpoint",
   507  		RedisDatabase:       42,
   508  		RedisTimeoutSeconds: 0,
   509  		RedisPassword:       "top secret",
   510  	}, conf.GetRedisConfiguration())
   511  
   512  	assert.Equal(t, logger.SentryLoggingConfiguration{
   513  		SentryDSN:         "test.example.com",
   514  		SentryEnvironment: "test",
   515  	}, conf.GetSentryLoggingConfiguration())
   516  }
   517  
   518  func TestGetLoggingConfigurationDefault(t *testing.T) {
   519  	setEnvVariables(t)
   520  
   521  	mustLoadConfiguration("/non_existing_path")
   522  
   523  	assert.Equal(t, logger.LoggingConfiguration{
   524  		Debug:                      false,
   525  		LogLevel:                   "",
   526  		LoggingToCloudWatchEnabled: false,
   527  	},
   528  		conf.GetLoggingConfiguration())
   529  }
   530  
   531  func TestGetLoggingConfigurationFromEnv(t *testing.T) {
   532  	setEnvVariables(t)
   533  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__LOGGING__DEBUG", "true")
   534  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__LOGGING__LOG_LEVEL", "info")
   535  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR__LOGGING__LOGGING_TO_CLOUD_WATCH_ENABLED", "true")
   536  
   537  	mustLoadConfiguration("/non_existing_path")
   538  
   539  	assert.Equal(t, logger.LoggingConfiguration{
   540  		Debug:                      true,
   541  		LogLevel:                   "info",
   542  		LoggingToCloudWatchEnabled: true,
   543  	},
   544  		conf.GetLoggingConfiguration())
   545  }
   546  
   547  func TestGetCloudWatchConfigurationDefault(t *testing.T) {
   548  	mustLoadConfiguration("/non_existing_path")
   549  
   550  	assert.Equal(t, logger.CloudWatchConfiguration{
   551  		AWSAccessID:             "",
   552  		AWSSecretKey:            "",
   553  		AWSSessionToken:         "",
   554  		AWSRegion:               "",
   555  		LogGroup:                "",
   556  		StreamName:              "",
   557  		CreateStreamIfNotExists: false,
   558  		Debug:                   false,
   559  	}, conf.GetCloudWatchConfiguration())
   560  }
   561  
   562  func TestGetMetricsConfiguration(t *testing.T) {
   563  	helpers.FailOnError(t, os.Chdir(".."))
   564  	TestLoadConfiguration(t)
   565  
   566  	metricsCfg := conf.GetMetricsConfiguration()
   567  	assert.Equal(t, "aggregator", metricsCfg.Namespace)
   568  }
   569  
   570  // TestLoadConfigurationFromEnvVariableClowderEnabled tests loading the config
   571  // file for testing from an environment variable. Clowder config is enabled in
   572  // this case.
   573  func TestLoadConfigurationFromEnvVariableClowderEnabled(t *testing.T) {
   574  	var testDB = "test_db"
   575  	os.Clearenv()
   576  
   577  	// explicit database and broker config
   578  	clowder.LoadedConfig = &clowder.AppConfig{
   579  		Database: &clowder.DatabaseConfig{
   580  			Name: testDB,
   581  		},
   582  	}
   583  
   584  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR_CONFIG_FILE", "../tests/config1")
   585  	mustSetEnv(t, "ACG_CONFIG", "tests/clowder_config.json")
   586  
   587  	err := conf.LoadConfiguration("config")
   588  	assert.NoError(t, err, "Failed loading configuration file")
   589  
   590  	// Set the org allow list to avoid loading a non-existing file
   591  	conf.Config.Broker.OrgAllowlistEnabled = false
   592  
   593  	// retrieve broker config
   594  	brokerCfg := conf.GetBrokerConfiguration()
   595  	storageCfg := conf.GetOCPRecommendationsStorageConfiguration()
   596  
   597  	// check
   598  	assert.Equal(t, "localhost:29092", brokerCfg.Addresses, "Broker doesn't match")
   599  	assert.Equal(t, "platform.results.ccx", brokerCfg.Topic, "Topic doesn't match")
   600  	assert.Equal(t, testDB, storageCfg.PGDBName)
   601  }
   602  
   603  // TestClowderConfigForKafka tests loading the config file for testing from an
   604  // environment variable. Clowder config is enabled in this case, checking the Kafka
   605  // configuration.
   606  func TestClowderConfigForKafka(t *testing.T) {
   607  	os.Clearenv()
   608  
   609  	var hostname = "kafka"
   610  	var port = 9092
   611  	var topicName = "platform.results.ccx"
   612  	var newTopicName = "new-topic-name"
   613  
   614  	// explicit database and broker config
   615  	clowder.LoadedConfig = &clowder.AppConfig{
   616  		Kafka: &clowder.KafkaConfig{
   617  			Brokers: []clowder.BrokerConfig{
   618  				{
   619  					Hostname: hostname,
   620  					Port:     &port,
   621  				},
   622  			},
   623  		},
   624  	}
   625  
   626  	clowder.KafkaTopics = make(map[string]clowder.TopicConfig)
   627  	clowder.KafkaTopics[topicName] = clowder.TopicConfig{
   628  		Name:          newTopicName,
   629  		RequestedName: topicName,
   630  	}
   631  
   632  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR_CONFIG_FILE", "../tests/config1")
   633  	mustSetEnv(t, "ACG_CONFIG", "tests/clowder_config.json")
   634  
   635  	err := conf.LoadConfiguration("config")
   636  	assert.NoError(t, err, "Failed loading configuration file")
   637  
   638  	conf.Config.Broker.OrgAllowlistEnabled = false
   639  
   640  	brokerCfg := conf.GetBrokerConfiguration()
   641  	assert.Equal(t, fmt.Sprintf("%s:%d", hostname, port), brokerCfg.Addresses)
   642  	assert.Equal(t, newTopicName, conf.Config.Broker.Topic)
   643  }
   644  
   645  // TestClowderConfigForStorage tests loading the config file for testing from an
   646  // environment variable. Clowder config is enabled in this case, checking the database
   647  // configuration.
   648  func TestClowderConfigForStorage(t *testing.T) {
   649  	os.Clearenv()
   650  
   651  	var name = "db"
   652  	var hostname = "hostname"
   653  	var port = 8888
   654  	var username = "username"
   655  	var password = "password"
   656  
   657  	// explicit database and broker config
   658  	clowder.LoadedConfig = &clowder.AppConfig{
   659  		Database: &clowder.DatabaseConfig{
   660  			Name:     name,
   661  			Hostname: hostname,
   662  			Port:     port,
   663  			Username: username,
   664  			Password: password,
   665  		},
   666  	}
   667  
   668  	mustSetEnv(t, "INSIGHTS_RESULTS_AGGREGATOR_CONFIG_FILE", "../tests/config1")
   669  	mustSetEnv(t, "ACG_CONFIG", "tests/clowder_config.json")
   670  
   671  	err := conf.LoadConfiguration("config")
   672  	assert.NoError(t, err, "Failed loading configuration file")
   673  
   674  	ocpStorageConf := conf.GetOCPRecommendationsStorageConfiguration()
   675  	assert.Equal(t, name, ocpStorageConf.PGDBName)
   676  	assert.Equal(t, hostname, ocpStorageConf.PGHost)
   677  	assert.Equal(t, port, ocpStorageConf.PGPort)
   678  	assert.Equal(t, username, ocpStorageConf.PGUsername)
   679  	assert.Equal(t, password, ocpStorageConf.PGPassword)
   680  	// rest of config outside of clowder must be loaded correctly
   681  	assert.Equal(t, "postgres", ocpStorageConf.Driver)
   682  	assert.Equal(t, "sql", ocpStorageConf.Type)
   683  
   684  	// same config loaded for DVO storage in envs using clowder (stage/prod)
   685  	dvoStorageConf := conf.GetDVORecommendationsStorageConfiguration()
   686  	assert.Equal(t, name, dvoStorageConf.PGDBName)
   687  	assert.Equal(t, hostname, dvoStorageConf.PGHost)
   688  	assert.Equal(t, port, dvoStorageConf.PGPort)
   689  	assert.Equal(t, username, dvoStorageConf.PGUsername)
   690  	assert.Equal(t, password, dvoStorageConf.PGPassword)
   691  	// rest of config outside of clowder must be loaded correctly
   692  	assert.Equal(t, "postgres", dvoStorageConf.Driver)
   693  	assert.Equal(t, "sql", dvoStorageConf.Type)
   694  }