...

Source file src/edge-infra.dev/pkg/edge/iam/util/util_test.go

Documentation: edge-infra.dev/pkg/edge/iam/util

     1  package util
     2  
     3  import (
     4  	"os"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/stretchr/testify/require"
     9  	"gotest.tools/v3/assert"
    10  
    11  	"edge-infra.dev/pkg/edge/iam/config"
    12  )
    13  
    14  func TestRolesSerialize(t *testing.T) {
    15  	roles := []string{"SELLING_EXECUTE", "TDM_VIEW"}
    16  
    17  	serializedRoles, _ := Serialize(roles)
    18  	deserializedRoles, _ := Deserialize(serializedRoles)
    19  
    20  	require.Contains(t, deserializedRoles, roles[0])
    21  	require.Contains(t, deserializedRoles, roles[1])
    22  }
    23  
    24  func TestDeviceLoginAvailable(t *testing.T) {
    25  	os.Setenv("IAM_MODE", "debug")
    26  	assert.Equal(t, IsDeviceLoginAvailable(), true)
    27  	config.ToggleDisruptWAN()
    28  	assert.Equal(t, IsDeviceLoginAvailable(), false)
    29  }
    30  
    31  // mock time.Now() for testing.
    32  func mockNow() time.Time {
    33  	return time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)
    34  }
    35  func TestCalculateAge(t *testing.T) {
    36  	tests := []struct {
    37  		dob      string
    38  		expected int
    39  		hasError bool
    40  		tz       string
    41  	}{
    42  		{"1990-01-29", 32, false, "UTC"},          // takes UTC into consideration as the reference is, so it must be 32 as birthday is on Jan 29th.
    43  		{"1990-01-01", 32, false, "US/Eastern"},   // takes US/East into consideration, so the age would be still be 32 as US wouldn't enter 1-1-2023 yet.
    44  		{"1990-01-01", 33, false, "Asia/Kolkata"}, // takes Asia/Kolkta into consideration, so the age would be 33 as India should have entered 1-1-2023 by then.
    45  		{"1990-01-01", 33, false, "UTC"},          // takes UTC into consideration, so the age would be 33 as India should have entered 1-1-2023 by then.
    46  		{"2023-01-01", 0, false, "UTC"},           // Birthday today
    47  		{"2025-12-31", 0, true, "UTC"},            // Future date
    48  		{"invalid-date", 0, true, "UTC"},          // Invalid date format
    49  	}
    50  
    51  	for _, test := range tests {
    52  		age, err := CalculateAge(test.dob, mockNow, test.tz)
    53  		if (err != nil) != test.hasError {
    54  			t.Errorf("calculateAge(%q) error = %v, wantErr %v", test.dob, err, test.hasError)
    55  			continue
    56  		}
    57  		if age != test.expected {
    58  			t.Errorf("calculateAge(%q) = %d, want %d", test.dob, age, test.expected)
    59  		}
    60  	}
    61  }
    62  

View as plain text