Skip to content

Commit 5347433

Browse files
Enhance Sonyflake error handling by adding tests for invalid machine IDs, including cases for too large and negative values. (#73)
1 parent 7743425 commit 5347433

2 files changed

Lines changed: 22 additions & 0 deletions

File tree

v2/sonyflake.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,10 @@ func New(st Settings) (*Sonyflake, error) {
157157
return nil, err
158158
}
159159

160+
if sf.machine < 0 || sf.machine >= 1<<sf.bitsMachine {
161+
return nil, ErrInvalidMachineID
162+
}
163+
160164
if st.CheckMachineID != nil && !st.CheckMachineID(sf.machine) {
161165
return nil, ErrInvalidMachineID
162166
}

v2/sonyflake_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,24 @@ func TestNew(t *testing.T) {
6565
},
6666
err: errGetMachineID,
6767
},
68+
{
69+
name: "too large machine id",
70+
settings: Settings{
71+
MachineID: func() (int, error) {
72+
return 1 << defaultBitsMachine, nil
73+
},
74+
},
75+
err: ErrInvalidMachineID,
76+
},
77+
{
78+
name: "negative machine id",
79+
settings: Settings{
80+
MachineID: func() (int, error) {
81+
return -1, nil
82+
},
83+
},
84+
err: ErrInvalidMachineID,
85+
},
6886
{
6987
name: "invalid machine id",
7088
settings: Settings{

0 commit comments

Comments
 (0)