github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/core/ip/mock_resolver.go (about) 1 /* 2 * Copyright (C) 2017 The "MysteriumNetwork/node" Authors. 3 * 4 * This program is free software: you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License as published by 6 * the Free Software Foundation, either version 3 of the License, or 7 * (at your option) any later version. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program. If not, see <http://www.gnu.org/licenses/>. 16 */ 17 18 package ip 19 20 import ( 21 "net" 22 ) 23 24 // NewResolverMock returns mockResolver which resolves statically entered IP. 25 // If multiple addresses are provided then return will depend on call order. 26 func NewResolverMock(ip string) Resolver { 27 return &mockResolver{ 28 publicIP: ip, 29 outboundIP: net.ParseIP(ip), 30 error: nil, 31 } 32 } 33 34 // NewResolverMockMultiple returns mockResolver which resolves statically entered IP. 35 // If multiple addresses are provided then return will depend on call order. 36 func NewResolverMockMultiple(outboundIP string, publicIPs ...string) Resolver { 37 return &mockResolver{ 38 publicIPs: publicIPs, 39 outboundIP: net.ParseIP(outboundIP), 40 error: nil, 41 } 42 } 43 44 // NewResolverMockFailing returns mockResolver with entered error 45 func NewResolverMockFailing(err error) Resolver { 46 return &mockResolver{ 47 error: err, 48 } 49 } 50 51 type mockResolver struct { 52 publicIP string 53 publicIPs []string 54 outboundIP net.IP 55 error error 56 } 57 58 func (client *mockResolver) MockPublicIPs(ips ...string) { 59 client.publicIPs = ips 60 } 61 62 func (client *mockResolver) GetPublicIP() (string, error) { 63 if client.publicIPs != nil { 64 return client.getNextIP(), client.error 65 } 66 return client.publicIP, client.error 67 } 68 69 func (client *mockResolver) GetProxyIP(_ int) (string, error) { 70 if client.publicIPs != nil { 71 return client.getNextIP(), client.error 72 } 73 return client.publicIP, client.error 74 } 75 76 func (client *mockResolver) GetOutboundIP() (string, error) { 77 return client.outboundIP.String(), client.error 78 } 79 80 func (client *mockResolver) getNextIP() string { 81 // Return first address if only one provided. 82 if len(client.publicIPs) == 1 { 83 return client.publicIPs[0] 84 } 85 // Return first address and dequeue from address list. This allows to 86 // mock to return different value for each call. 87 if len(client.publicIPs) > 0 { 88 ip := client.publicIPs[0] 89 client.publicIPs = client.publicIPs[1:] 90 return ip 91 } 92 return "" 93 }