Dragonfly2
140 строк · 2.6 Кб
1/*
2* Copyright 2022 The Dragonfly Authors
3*
4* Licensed under the Apache License, Version 2.0 (the "License");
5* you may not use this file except in compliance with the License.
6* You may obtain a copy of the License at
7*
8* http://www.apache.org/licenses/LICENSE-2.0
9*
10* Unless required by applicable law or agreed to in writing, software
11* distributed under the License is distributed on an "AS IS" BASIS,
12* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13* See the License for the specific language governing permissions and
14* limitations under the License.
15*/
16
17package peer18
19import (20"sync"21"testing"22
23testifyassert "github.com/stretchr/testify/assert"24)
25
26func TestBroker(t *testing.T) {27var testCases = []struct {28name string29total int3230pubSeq []int3231desire []*PieceInfo32}{33{34name: "order publish",35total: 3,36pubSeq: []int32{0, 1, 2},37desire: []*PieceInfo{38{39Num: 0,40OrderedNum: 0,41Finished: false,42},43{44Num: 1,45OrderedNum: 1,46Finished: false,47},48{49Num: 2,50OrderedNum: 2,51Finished: true,52},53},54},55{56name: "partial order publish",57total: 3,58pubSeq: []int32{0, 2, 1},59desire: []*PieceInfo{60{61Num: 0,62OrderedNum: 0,63Finished: false,64},65{66Num: 2,67OrderedNum: 0,68Finished: false,69},70{71Num: 1,72OrderedNum: 2,73Finished: true,74},75},76},77{78name: "inverted order publish",79total: 3,80pubSeq: []int32{2, 1, 0},81desire: []*PieceInfo{82{83Num: 2,84OrderedNum: -1,85Finished: false,86},87{88Num: 1,89OrderedNum: -1,90Finished: false,91},92{93Num: 0,94OrderedNum: 2,95Finished: true,96},97},98},99}100for _, tc := range testCases {101t.Run(tc.name, func(t *testing.T) {102assert := testifyassert.New(t)103broker := newPieceBroker()104go broker.Start()105ch := broker.Subscribe()106done := make(chan struct{})107var received []*PieceInfo108
109wg := sync.WaitGroup{}110wg.Add(len(tc.pubSeq))111go func() {112for {113select {114case <-done:115return116case info := <-ch:117received = append(received, info)118wg.Done()119}120}121}()122var sent int32123for _, n := range tc.pubSeq {124sent++125var finished bool126if sent == tc.total {127finished = true128}129broker.Publish(&PieceInfo{130Num: n,131Finished: finished,132})133}134wg.Wait()135broker.Stop()136close(done)137assert.Equal(tc.desire, received)138})139}140}
141