package snowflake import ( "flag" "os" "reflect" "testing" "time" "go.uber.org/goleak" ) func TestMain(m *testing.M) { leak := flag.Bool("leak", false, "use leak detector") flag.Parse() if *leak { goleak.VerifyTestMain(m) return } os.Exit(m.Run()) } func TestSnowflake(t *testing.T) { st, err := GetNowDate() if err != nil { t.Error(err) } t.Parallel() type args struct { machineNodeID int64 startTime time.Time } tests := []struct { name string args args want *Snowflake wantDeepEqualErr bool wantNewNodeErr bool }{ { name: "success", args: args{ machineNodeID: 10, startTime: st, }, want: &Snowflake{ machineNodeID: 10, startTime: st, }, wantDeepEqualErr: false, wantNewNodeErr: false, }, { name: "failed machine node ID negative number", args: args{ machineNodeID: -1, startTime: time.Time{}, }, want: &Snowflake{ machineNodeID: -1, startTime: time.Time{}, }, wantDeepEqualErr: false, wantNewNodeErr: true, }, { name: "failed snowflake struct field by machine node ID", args: args{ machineNodeID: 10, startTime: st, }, want: &Snowflake{ machineNodeID: 2, startTime: st, }, wantDeepEqualErr: true, wantNewNodeErr: false, }, { name: "failed snowflake struct field by startTime", args: args{ machineNodeID: 2, startTime: st, }, want: &Snowflake{ machineNodeID: 2, startTime: time.Time{}, }, wantDeepEqualErr: true, wantNewNodeErr: false, }, } for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() got := New( WithMachineNodeID(tt.args.machineNodeID), WithStartTime(tt.args.startTime), ) if !reflect.DeepEqual(got, tt.want) != tt.wantDeepEqualErr { t.Errorf("Snowflake.New() = %v, want %v", got, tt.want) } node, err := got.NewNode() if (err != nil) != tt.wantNewNodeErr { t.Errorf("NewNode() = %v, want %v", err != nil, tt.wantNewNodeErr) } if err == nil { id := node.Generate().Int64() if id <= 0 { t.Errorf("node.Generate().Int64() = %v, want %s", id, "id > 0") } } }) } } func BenchmarkSnowflake(b *testing.B) { st, err := GetNowDate() if err != nil { b.Error(err) } snowflake := New( WithMachineNodeID(1), WithStartTime(st), ) node, err := snowflake.NewNode() if err != nil { b.Error(err) } for i := 0; i < b.N; i++ { node.Generate().Int64() } }