github.com/demonoid81/moby@v0.0.0-20200517203328-62dd8e17c460/container/env_test.go (about)

     1  package container // import "github.com/demonoid81/moby/container"
     2  
     3  import (
     4  	"crypto/rand"
     5  	"testing"
     6  
     7  	"gotest.tools/v3/assert"
     8  )
     9  
    10  func TestReplaceAndAppendEnvVars(t *testing.T) {
    11  	var (
    12  		d = []string{"HOME=/", "FOO=foo_default"}
    13  		// remove FOO from env
    14  		// remove BAR from env (nop)
    15  		o = []string{"HOME=/root", "TERM=xterm", "FOO", "BAR"}
    16  	)
    17  
    18  	env := ReplaceOrAppendEnvValues(d, o)
    19  	t.Logf("default=%v, override=%v, result=%v", d, o, env)
    20  	if len(env) != 2 {
    21  		t.Fatalf("expected len of 2 got %d", len(env))
    22  	}
    23  	if env[0] != "HOME=/root" {
    24  		t.Fatalf("expected HOME=/root got '%s'", env[0])
    25  	}
    26  	if env[1] != "TERM=xterm" {
    27  		t.Fatalf("expected TERM=xterm got '%s'", env[1])
    28  	}
    29  }
    30  
    31  func BenchmarkReplaceOrAppendEnvValues(b *testing.B) {
    32  	b.Run("0", func(b *testing.B) {
    33  		benchmarkReplaceOrAppendEnvValues(b, 0)
    34  	})
    35  	b.Run("100", func(b *testing.B) {
    36  		benchmarkReplaceOrAppendEnvValues(b, 100)
    37  	})
    38  	b.Run("1000", func(b *testing.B) {
    39  		benchmarkReplaceOrAppendEnvValues(b, 1000)
    40  	})
    41  	b.Run("10000", func(b *testing.B) {
    42  		benchmarkReplaceOrAppendEnvValues(b, 10000)
    43  	})
    44  }
    45  
    46  func benchmarkReplaceOrAppendEnvValues(b *testing.B, extraEnv int) {
    47  	b.StopTimer()
    48  	// remove FOO from env
    49  	// remove BAR from env (nop)
    50  	o := []string{"HOME=/root", "TERM=xterm", "FOO", "BAR"}
    51  
    52  	if extraEnv > 0 {
    53  		buf := make([]byte, 5)
    54  		for i := 0; i < extraEnv; i++ {
    55  			n, err := rand.Read(buf)
    56  			assert.NilError(b, err)
    57  			key := string(buf[:n])
    58  
    59  			n, err = rand.Read(buf)
    60  			assert.NilError(b, err)
    61  			val := string(buf[:n])
    62  
    63  			o = append(o, key+"="+val)
    64  		}
    65  	}
    66  	d := make([]string, 0, len(o)+2)
    67  	d = append(d, []string{"HOME=/", "FOO=foo_default"}...)
    68  
    69  	b.StartTimer()
    70  	for i := 0; i < b.N; i++ {
    71  		_ = ReplaceOrAppendEnvValues(d, o)
    72  	}
    73  }