| 1 | package libp2p |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "strconv" |
| 6 | "testing" |
| 7 | |
| 8 | "github.com/libp2p/go-libp2p" |
| 9 | ma "github.com/multiformats/go-multiaddr" |
| 10 | |
| 11 | "github.com/stretchr/testify/require" |
| 12 | ) |
| 13 | |
| 14 | func TestPrioritize(t *testing.T) { |
| 15 | // The option is encoded into the port number of a TCP multiaddr. |
| 16 | // By extracting the port numbers obtained from the applied option, we can make sure that |
| 17 | // prioritization sorted the options correctly. |
| 18 | newOption := func(num int) libp2p.Option { |
| 19 | return func(cfg *libp2p.Config) error { |
| 20 | cfg.ListenAddrs = append(cfg.ListenAddrs, ma.StringCast(fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", num))) |
| 21 | return nil |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | extractNums := func(cfg *libp2p.Config) []int { |
| 26 | addrs := cfg.ListenAddrs |
| 27 | nums := make([]int, 0, len(addrs)) |
| 28 | for _, addr := range addrs { |
| 29 | _, comp := ma.SplitLast(addr) |
| 30 | num, err := strconv.Atoi(comp.Value()) |
| 31 | require.NoError(t, err) |
| 32 | nums = append(nums, num) |
| 33 | } |
| 34 | return nums |
| 35 | } |
| 36 | |
| 37 | t.Run("using default priorities", func(t *testing.T) { |
| 38 | opts := []priorityOption{ |
| 39 | {defaultPriority: 200, opt: newOption(200)}, |
| 40 | {defaultPriority: 1, opt: newOption(1)}, |
| 41 | {defaultPriority: 300, opt: newOption(300)}, |
| 42 | } |
| 43 | var cfg libp2p.Config |
| 44 | require.NoError(t, prioritizeOptions(opts)(&cfg)) |
| 45 | require.Equal(t, extractNums(&cfg), []int{1, 200, 300}) |
| 46 | }) |
| 47 | |
| 48 | t.Run("using custom priorities", func(t *testing.T) { |
| 49 | opts := []priorityOption{ |
| 50 | {defaultPriority: 200, priority: 1, opt: newOption(1)}, |
| 51 | {defaultPriority: 1, priority: 300, opt: newOption(300)}, |
| 52 | {defaultPriority: 300, priority: 20, opt: newOption(20)}, |
| 53 | } |
| 54 | var cfg libp2p.Config |
| 55 | require.NoError(t, prioritizeOptions(opts)(&cfg)) |
| 56 | require.Equal(t, extractNums(&cfg), []int{1, 20, 300}) |
| 57 | }) |
| 58 | } |