|
| 1 | +package sonyflake |
| 2 | + |
| 3 | +import ( |
| 4 | + "net" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/sony/sonyflake/v2/mock" |
| 8 | +) |
| 9 | + |
| 10 | +// TestDefaultMachineIDWithCustomBits tests that when using default machine ID |
| 11 | +// with custom BitsMachineID, the machine ID is properly masked to fit within |
| 12 | +// the specified bit length. |
| 13 | +func TestDefaultMachineIDWithCustomBits(t *testing.T) { |
| 14 | + testCases := []struct { |
| 15 | + name string |
| 16 | + bitsMachineID int |
| 17 | + mockIP net.IP |
| 18 | + expectError bool |
| 19 | + }{ |
| 20 | + { |
| 21 | + name: "10 bits machine ID with IP that fits", |
| 22 | + bitsMachineID: 10, |
| 23 | + mockIP: net.IP{192, 168, 0, 1}, // lower 16 bits = 1, fits in 10 bits |
| 24 | + expectError: false, |
| 25 | + }, |
| 26 | + { |
| 27 | + name: "10 bits machine ID with IP that exceeds without masking", |
| 28 | + bitsMachineID: 10, |
| 29 | + mockIP: net.IP{192, 168, 255, 255}, // lower 16 bits = 65535, needs masking to fit in 10 bits |
| 30 | + expectError: false, |
| 31 | + }, |
| 32 | + { |
| 33 | + name: "8 bits machine ID", |
| 34 | + bitsMachineID: 8, |
| 35 | + mockIP: net.IP{192, 168, 100, 200}, // lower 16 bits = 25800 |
| 36 | + expectError: false, |
| 37 | + }, |
| 38 | + { |
| 39 | + name: "default 16 bits", |
| 40 | + bitsMachineID: 0, // will use default 16 |
| 41 | + mockIP: net.IP{192, 168, 255, 255}, |
| 42 | + expectError: false, |
| 43 | + }, |
| 44 | + } |
| 45 | + |
| 46 | + for _, tc := range testCases { |
| 47 | + t.Run(tc.name, func(t *testing.T) { |
| 48 | + // Create a mock that returns our test IP |
| 49 | + mockInterfaceAddrs := mock.NewInterfaceAddrsWithIP(tc.mockIP) |
| 50 | + |
| 51 | + settings := Settings{ |
| 52 | + BitsMachineID: tc.bitsMachineID, |
| 53 | + } |
| 54 | + |
| 55 | + // Temporarily replace the default interface addrs function |
| 56 | + oldDefaultInterfaceAddrs := defaultInterfaceAddrs |
| 57 | + defaultInterfaceAddrs = mockInterfaceAddrs |
| 58 | + defer func() { defaultInterfaceAddrs = oldDefaultInterfaceAddrs }() |
| 59 | + |
| 60 | + sf, err := New(settings) |
| 61 | + |
| 62 | + if tc.expectError { |
| 63 | + if err == nil { |
| 64 | + t.Errorf("expected error but got none") |
| 65 | + } |
| 66 | + } else { |
| 67 | + if err != nil { |
| 68 | + t.Errorf("unexpected error: %v", err) |
| 69 | + } |
| 70 | + if sf == nil { |
| 71 | + t.Error("sonyflake instance should not be nil") |
| 72 | + } |
| 73 | + |
| 74 | + // Verify the machine ID fits within the specified bits |
| 75 | + expectedBits := tc.bitsMachineID |
| 76 | + if expectedBits == 0 { |
| 77 | + expectedBits = defaultBitsMachine |
| 78 | + } |
| 79 | + maxMachineID := 1 << expectedBits |
| 80 | + if sf.machine >= maxMachineID { |
| 81 | + t.Errorf("machine ID %d exceeds max for %d bits (%d)", sf.machine, expectedBits, maxMachineID) |
| 82 | + } |
| 83 | + } |
| 84 | + }) |
| 85 | + } |
| 86 | +} |
0 commit comments