github.com/prebid/prebid-server/v2@v2.18.0/main_test.go (about)

     1  package main
     2  
     3  import (
     4  	"os"
     5  	"testing"
     6  
     7  	"github.com/prebid/prebid-server/v2/config"
     8  	"github.com/stretchr/testify/assert"
     9  
    10  	"github.com/spf13/viper"
    11  )
    12  
    13  func compareStrings(t *testing.T, message string, expect string, actual string) {
    14  	if expect != actual {
    15  		t.Errorf(message, expect, actual)
    16  	}
    17  }
    18  
    19  // forceEnv sets an environment variable to a certain value, and return a deferable function to reset it to the original value.
    20  func forceEnv(t *testing.T, key string, val string) func() {
    21  	orig, set := os.LookupEnv(key)
    22  	err := os.Setenv(key, val)
    23  	if err != nil {
    24  		t.Fatalf("Error setting environment %s", key)
    25  	}
    26  	if set {
    27  		return func() {
    28  			if os.Setenv(key, orig) != nil {
    29  				t.Fatalf("Error unsetting environment %s", key)
    30  			}
    31  		}
    32  	}
    33  	return func() {
    34  		if os.Unsetenv(key) != nil {
    35  			t.Fatalf("Error unsetting environment %s", key)
    36  		}
    37  	}
    38  }
    39  
    40  // Test the viper setup
    41  func TestViperInit(t *testing.T) {
    42  	v := viper.New()
    43  	config.SetupViper(v, "", nil)
    44  	compareStrings(t, "Viper error: external_url expected to be %s, found %s", "http://localhost:8000", v.Get("external_url").(string))
    45  	compareStrings(t, "Viper error: accounts.filesystem.directorypath expected to be %s, found %s", "./stored_requests/data/by_id", v.Get("accounts.filesystem.directorypath").(string))
    46  }
    47  
    48  func TestViperEnv(t *testing.T) {
    49  	v := viper.New()
    50  	config.SetupViper(v, "", nil)
    51  	port := forceEnv(t, "PBS_PORT", "7777")
    52  	defer port()
    53  
    54  	endpt := forceEnv(t, "PBS_EXPERIMENT_ADSCERT_INPROCESS_ORIGIN", "not_an_endpoint")
    55  	defer endpt()
    56  
    57  	ttl := forceEnv(t, "PBS_HOST_COOKIE_TTL_DAYS", "60")
    58  	defer ttl()
    59  
    60  	ipv4Networks := forceEnv(t, "PBS_REQUEST_VALIDATION_IPV4_PRIVATE_NETWORKS", "1.1.1.1/24 2.2.2.2/24")
    61  	defer ipv4Networks()
    62  
    63  	assert.Equal(t, 7777, v.Get("port"), "Basic Config")
    64  	assert.Equal(t, "not_an_endpoint", v.Get("experiment.adscert.inprocess.origin"), "Nested Config")
    65  	assert.Equal(t, 60, v.Get("host_cookie.ttl_days"), "Config With Underscores")
    66  	assert.ElementsMatch(t, []string{"1.1.1.1/24", "2.2.2.2/24"}, v.Get("request_validation.ipv4_private_networks"), "Arrays")
    67  }