github.com/GuanceCloud/cliutils@v1.1.21/diskcache/envs_test.go (about)

     1  // Unless explicitly stated otherwise all files in this repository are licensed
     2  // under the MIT License.
     3  // This product includes software developed at Guance Cloud (https://www.guance.com/).
     4  // Copyright 2021-present Guance, Inc.
     5  
     6  package diskcache
     7  
     8  import (
     9  	"os"
    10  	"testing"
    11  
    12  	"github.com/stretchr/testify/assert"
    13  )
    14  
    15  func TestSyncEnv(t *testing.T) {
    16  	cases := []struct {
    17  		name   string
    18  		envs   map[string]string
    19  		expect *DiskCache
    20  	}{
    21  		{
    22  			name: "env-diskcache-max-data-size",
    23  			envs: map[string]string{
    24  				"ENV_DISKCACHE_MAX_DATA_SIZE": "123",
    25  			},
    26  			expect: func() *DiskCache {
    27  				c := defaultInstance()
    28  				c.maxDataSize = int32(123)
    29  				return c
    30  			}(),
    31  		},
    32  
    33  		{
    34  			name: "env-bad-capacity",
    35  			envs: map[string]string{
    36  				"ENV_DISKCACHE_MAX_DATA_SIZE": "123",
    37  				"ENV_DISKCACHE_BATCH_SIZE":    "234",
    38  				"ENV_DISKCACHE_CAPACITY":      "1.2",
    39  			},
    40  			expect: func() *DiskCache {
    41  				c := defaultInstance()
    42  				c.maxDataSize = int32(123)
    43  				c.batchSize = int64(234)
    44  				c.capacity = 0
    45  				return c
    46  			}(),
    47  		},
    48  
    49  		{
    50  			name: "env-all",
    51  			envs: map[string]string{
    52  				"ENV_DISKCACHE_MAX_DATA_SIZE":        "123",
    53  				"ENV_DISKCACHE_BATCH_SIZE":           "234",
    54  				"ENV_DISKCACHE_CAPACITY":             "1234567890",
    55  				"ENV_DISKCACHE_NO_SYNC":              "foo-bar",
    56  				"ENV_DISKCACHE_NO_POS":               "on",
    57  				"ENV_DISKCACHE_NO_LOCK":              "on",
    58  				"ENV_DISKCACHE_NO_FALLBACK_ON_ERROR": "on",
    59  			},
    60  			expect: func() *DiskCache {
    61  				c := defaultInstance()
    62  				c.maxDataSize = int32(123)
    63  				c.batchSize = int64(234)
    64  				c.capacity = int64(1234567890)
    65  				c.noSync = true
    66  				c.noPos = true
    67  				c.noLock = true
    68  				c.noFallbackOnError = true
    69  				return c
    70  			}(),
    71  		},
    72  	}
    73  	os.Clearenv()
    74  
    75  	for _, tc := range cases {
    76  		t.Run(tc.name, func(t *testing.T) {
    77  			for k, v := range tc.envs {
    78  				if err := os.Setenv(k, v); err != nil {
    79  					t.Error(err)
    80  				}
    81  			}
    82  
    83  			c := defaultInstance()
    84  			c.syncEnv()
    85  			assert.Equal(t, tc.expect.String(), c.String())
    86  
    87  			t.Cleanup(func() {
    88  				for k := range tc.envs {
    89  					if err := os.Unsetenv(k); err != nil {
    90  						t.Error(err)
    91  					}
    92  				}
    93  			})
    94  		})
    95  	}
    96  }