github.com/cs3org/reva/v2@v2.27.7/pkg/utils/cfg/cfg_test.go (about)

     1  // Copyright 2018-2023 CERN
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  //
    15  // In applying this license, CERN does not waive the privileges and immunities
    16  // granted to it by virtue of its status as an Intergovernmental Organization
    17  // or submit itself to any jurisdiction.
    18  
    19  package cfg_test
    20  
    21  import (
    22  	"testing"
    23  
    24  	"github.com/cs3org/reva/v2/pkg/utils/cfg"
    25  	"github.com/stretchr/testify/assert"
    26  )
    27  
    28  type NoDefaults struct {
    29  	A string `mapstructure:"a"`
    30  	B int    `mapstructure:"b"`
    31  	C bool   `mapstructure:"c"`
    32  }
    33  
    34  type WithDefaults struct {
    35  	A string `mapstructure:"a"`
    36  	B int    `mapstructure:"b" validate:"required"`
    37  }
    38  
    39  func (c *WithDefaults) ApplyDefaults() {
    40  	if c.A == "" {
    41  		c.A = "default"
    42  	}
    43  }
    44  
    45  func TestDecode(t *testing.T) {
    46  	t1 := map[string]any{
    47  		"b": 10,
    48  		"c": true,
    49  	}
    50  	var noDefaults NoDefaults
    51  	if err := cfg.Decode(t1, &noDefaults); err != nil {
    52  		t.Fatal("not expected error", err)
    53  	}
    54  	assert.Equal(t, NoDefaults{
    55  		A: "",
    56  		B: 10,
    57  		C: true,
    58  	}, noDefaults)
    59  
    60  	t2 := map[string]any{
    61  		"b": 100,
    62  	}
    63  	var defaults WithDefaults
    64  	if err := cfg.Decode(t2, &defaults); err != nil {
    65  		t.Fatal("not expected error", err)
    66  	}
    67  	assert.Equal(t, WithDefaults{
    68  		A: "default",
    69  		B: 100,
    70  	}, defaults)
    71  
    72  	t3 := map[string]any{
    73  		"a": "string",
    74  	}
    75  	var required WithDefaults
    76  	if err := cfg.Decode(t3, &required); err == nil {
    77  		t.Fatal("expected error, but none returned")
    78  	}
    79  }