From 33f52064b4ffb3beb4f407ff93d5d1aa09d53134 Mon Sep 17 00:00:00 2001 From: rekby Date: Tue, 12 Nov 2019 17:31:05 +0300 Subject: [PATCH 01/10] style --- .golangci.yml | 4 +- internal/cache/value_lru_test.go | 2 - internal/contexthelper/contexthelper_test.go | 1 - internal/dns/parallel_test.go | 2 - internal/dns/resolver_test.go | 1 - internal/tlslistener/tlslistenershandler.go | 55 ++++++++------------ 6 files changed, 24 insertions(+), 41 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 1bc926c9..ad56062e 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,5 +1,5 @@ service: - golangci-lint-version: 1.16.0 + golangci-lint-version: 1.20.0 run: deadline: 5m issues-exit-code: 1 @@ -26,7 +26,7 @@ issues: - funlen - linters: - stylecheck - source: "package (cert_manager|domain_checker)" + source: "package (acme_client_manager|cert_manager|domain_checker)" linters: enable-all: true diff --git a/internal/cache/value_lru_test.go b/internal/cache/value_lru_test.go index c3883948..767bd3c9 100644 --- a/internal/cache/value_lru_test.go +++ b/internal/cache/value_lru_test.go @@ -103,7 +103,6 @@ func TestValueLRULimitAtPut(t *testing.T) { res, err = c.Get(ctx, "6") td.CmpDeeply(res, 6) td.CmpNoError(err) - } func TestValueLRULimitClean(t *testing.T) { @@ -260,5 +259,4 @@ func TestLimitValueRenumberItems(t *testing.T) { td.CmpDeeply(c.m["4"].lastUsedTime, uint64(4)) td.CmpDeeply(c.m["5"].lastUsedTime, uint64(5)) td.CmpDeeply(c.m["6"].lastUsedTime, uint64(6)) - } diff --git a/internal/contexthelper/contexthelper_test.go b/internal/contexthelper/contexthelper_test.go index f53c383c..beb28057 100644 --- a/internal/contexthelper/contexthelper_test.go +++ b/internal/contexthelper/contexthelper_test.go @@ -137,5 +137,4 @@ func TestCombinedContext_Done(t *testing.T) { wait() td.True(done) - } diff --git a/internal/dns/parallel_test.go b/internal/dns/parallel_test.go index 6b53c8e1..3626b0c1 100644 --- a/internal/dns/parallel_test.go +++ b/internal/dns/parallel_test.go @@ -73,7 +73,6 @@ func TestParallel(t *testing.T) { ips, err = p.LookupIPAddr(ctx, "6") td.Any(err, []interface{}{error61, error62}) td.Nil(ips) - } func TestParallelReadl(t *testing.T) { @@ -91,5 +90,4 @@ func TestParallelReadl(t *testing.T) { net.IPAddr{IP: net.IPv4(1, 1, 1, 1).To16()}, ), ) - } diff --git a/internal/dns/resolver_test.go b/internal/dns/resolver_test.go index d810202d..13b71949 100644 --- a/internal/dns/resolver_test.go +++ b/internal/dns/resolver_test.go @@ -401,5 +401,4 @@ func TestResolverReal(t *testing.T) { net.IPAddr{IP: net.ParseIP("127.0.0.1").To16()}, ), ) - } diff --git a/internal/tlslistener/tlslistenershandler.go b/internal/tlslistener/tlslistenershandler.go index 03c60637..90becb5a 100644 --- a/internal/tlslistener/tlslistenershandler.go +++ b/internal/tlslistener/tlslistenershandler.go @@ -73,43 +73,13 @@ func (p *ListenersHandler) Start(ctx context.Context) error { logger := zc.L(ctx) logger.Info("StartAutoRenew handleListeners") + for _, listenerForTLS := range p.ListenersForHandleTLS { - go func(l net.Listener) { - for { - conn, err := l.Accept() - if err != nil { - if ctx.Err() != nil { - err = nil - } - log.InfoError(logger, err, "Close listener", zap.String("local_addr", l.Addr().String())) - err = l.Close() - log.DebugError(logger, err, "Listener closed", zap.String("local_addr", l.Addr().String())) - listenerClosed <- struct{}{} - return - } - go p.handleTCPTLSConnection(ctx, conn) - } - }(listenerForTLS) + go handleConnections(ctx, listenerForTLS, p.handleTCPTLSConnection, listenerClosed) } for _, listener := range p.Listeners { - go func(l net.Listener) { - for { - conn, err := l.Accept() - if err != nil { - if ctx.Err() != nil { - err = nil - } - log.InfoError(logger, err, "Close listener", zap.String("local_addr", l.Addr().String())) - err = l.Close() - log.DebugError(logger, err, "Listener closed", zap.String("local_addr", l.Addr().String())) - listenerClosed <- struct{}{} - return - } - go p.handleTCPConnection(ctx, conn) - } - }(listener) - + go handleConnections(ctx, listener, p.handleTCPConnection, listenerClosed) } go func() { @@ -130,6 +100,25 @@ func (p *ListenersHandler) Start(ctx context.Context) error { return nil } +func handleConnections(ctx context.Context, l net.Listener, handleFunc func(ctx context.Context, conn net.Conn), listenerClosed chan<- struct{}) { + logger := zc.L(ctx) + + for { + conn, err := l.Accept() + if err != nil { + if ctx.Err() != nil { + err = nil + } + log.InfoError(logger, err, "Close listener", zap.String("local_addr", l.Addr().String())) + err = l.Close() + log.DebugError(logger, err, "Listener closed", zap.String("local_addr", l.Addr().String())) + listenerClosed <- struct{}{} + return + } + go handleFunc(ctx, conn) + } +} + func (p *ListenersHandler) init() { p.connListenProxy.connections = make(chan net.Conn) var nextProtos = p.NextProtos From 173349f8be38f42f436cb86c87c390946103e2d1 Mon Sep 17 00:00:00 2001 From: rekby Date: Tue, 12 Nov 2019 17:43:13 +0300 Subject: [PATCH 02/10] style --- internal/cert_manager/manager.go | 34 ++++++++++++++------------------ 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/internal/cert_manager/manager.go b/internal/cert_manager/manager.go index 9241ba6d..af2808c7 100644 --- a/internal/cert_manager/manager.go +++ b/internal/cert_manager/manager.go @@ -115,18 +115,7 @@ func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (resultCert *tls.Ce logger = logger.With(logDomain(needDomain)) logger.Info("Get certificate", zap.String("original_domain", hello.ServerName)) if isTLSALPN01Hello(hello) { - logger.Debug("It is tls-alpn-01 token request.") - - certInterface, err := m.certForDomainAuthorize.Get(ctx, needDomain.String()) - logger.Debug("Got authcert from cache", zap.Error(err)) - - cert, _ := certInterface.(*tls.Certificate) - - if cert == nil { - logger.Warn("Doesn't have token for request domain") - return nil, errHaveNoCert - } - return cert, nil + return m.handleTLSALPN(logger, ctx, needDomain) } certName := certNameFromDomain(needDomain) @@ -193,7 +182,6 @@ func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (resultCert *tls.Ce return nil, errHaveNoCert } - // TODO: check domain certIssueContext, cancelFunc := context.WithTimeout(ctx, m.CertificateIssueTimeout) defer cancelFunc() @@ -211,6 +199,18 @@ func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (resultCert *tls.Ce } +func (m *Manager) handleTLSALPN(logger *zap.Logger, ctx context.Context, needDomain DomainName) (*tls.Certificate, error) { + logger.Debug("It is tls-alpn-01 token request.") + certInterface, err := m.certForDomainAuthorize.Get(ctx, needDomain.String()) + logger.Debug("Got authcert from cache", zap.Error(err)) + cert, _ := certInterface.(*tls.Certificate) + if cert == nil { + logger.Warn("Doesn't have token for request domain") + return nil, errHaveNoCert + } + return cert, nil +} + func filterDomains(ctx context.Context, checker DomainChecker, originalDomains []DomainName, needDomain DomainName) ([]DomainName, error) { logger := zc.L(ctx) logger.Debug("filter domains from certificate list", logDomains(originalDomains)) @@ -615,10 +615,6 @@ func (m *Manager) deleteCertToken(ctx context.Context, key DomainName) { func storeCertificate(ctx context.Context, cache cache.Bytes, certName certNameType, cert *tls.Certificate) error { logger := zc.L(ctx) - if cache == nil { - logger.Debug("Can't save certificate to nil cache") - return nil - } locked, _ := isCertLocked(ctx, cache, certName) if locked { @@ -662,15 +658,15 @@ func storeCertificate(ctx context.Context, cache cache.Bytes, certName certNameT keyKeyName := string(certName) + "." + string(keyType) + ".key" err := cache.Put(ctx, certKeyName, certBuf.Bytes()) + zc.InfoError(logger, err, "Store certificate file", zap.String("cert_key", certKeyName)) if err != nil { - logger.Error("Can't store certificate file", zap.Error(err)) return err } err = cache.Put(ctx, keyKeyName, privateKeyBuf.Bytes()) + zc.InfoError(logger, err, "Store key file", zap.String("key_key", keyKeyName)) if err != nil { _ = cache.Delete(ctx, certKeyName) - logger.Error("Can't store certificate key file", zap.Error(err)) return err } return nil From 7fc8e9564465cd1e8e9e10a648b93ef0102b96e0 Mon Sep 17 00:00:00 2001 From: rekby Date: Tue, 19 Nov 2019 08:27:24 +0300 Subject: [PATCH 03/10] style --- cmd/log.go | 1 - internal/cert_manager/manager.go | 3 +++ internal/proxy/config.go | 1 - internal/proxy/directors_test.go | 2 -- internal/tlslistener/config.go | 6 +++--- 5 files changed, 6 insertions(+), 7 deletions(-) diff --git a/cmd/log.go b/cmd/log.go index 4c26ee3b..c439d40a 100644 --- a/cmd/log.go +++ b/cmd/log.go @@ -41,7 +41,6 @@ func initLogger(config logConfig) *zap.Logger { writeSyncer := (*logWriteSyncer)(lr) writers = append(writers, writeSyncer) } - if config.EnableLogToStdErr { writer, _, err := zap.Open("stderr") if err != nil { diff --git a/internal/cert_manager/manager.go b/internal/cert_manager/manager.go index af2808c7..23e0ea11 100644 --- a/internal/cert_manager/manager.go +++ b/internal/cert_manager/manager.go @@ -147,6 +147,9 @@ func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (resultCert *tls.Ce locked, err := isCertLocked(ctx, m.Cache, certName) log.DebugDPanic(logger, err, "Check if certificate locked", zap.Bool("locked", locked)) + if err != nil { + return nil, errHaveNoCert + } cert, err = loadCertificateFromCache(ctx, m.Cache, certName, keyRSA) logLevel := zapcore.DebugLevel diff --git a/internal/proxy/config.go b/internal/proxy/config.go index cc4219cd..c5f0b1aa 100644 --- a/internal/proxy/config.go +++ b/internal/proxy/config.go @@ -77,7 +77,6 @@ func (c *Config) getDefaultTargetDirector(ctx context.Context) (Director, error) } logger.Info("Create host ip director", zap.Int("port", defaultTarget.Port)) return NewDirectorHost(defaultTarget.String()), nil - } //can return nil,nil diff --git a/internal/proxy/directors_test.go b/internal/proxy/directors_test.go index 6886c147..5b11227d 100644 --- a/internal/proxy/directors_test.go +++ b/internal/proxy/directors_test.go @@ -70,7 +70,6 @@ func TestDirectorDestMap(t *testing.T) { ctx, http.LocalAddrContextKey, &net.TCPAddr{IP: net.ParseIP("1.2.3.2"), Port: 443})) d.Director(req) td.CmpDeeply(req.URL.Host, "2.2.2.2:80") - } func TestDirectorHost(t *testing.T) { @@ -80,7 +79,6 @@ func TestDirectorHost(t *testing.T) { req := &http.Request{} d.Director(req) td.CmpDeeply(req.URL.Host, "haha:81") - } func TestDirectorSameIP(t *testing.T) { diff --git a/internal/tlslistener/config.go b/internal/tlslistener/config.go index 23809aa9..fcbe9c7c 100644 --- a/internal/tlslistener/config.go +++ b/internal/tlslistener/config.go @@ -16,9 +16,8 @@ type Config struct { func (c *Config) Apply(ctx context.Context, l *ListenersHandler) error { logger := zc.L(ctx) + var tlsListeners = make([]net.Listener, 0, len(c.TLSAddresses)) - var tcpListeners = make([]net.Listener, 0, len(c.TCPAddresses)) - for _, addr := range c.TLSAddresses { listener, err := net.Listen("tcp", addr) log.DebugError(logger, err, "Start listen tls binding", zap.String("address", addr)) @@ -27,7 +26,8 @@ func (c *Config) Apply(ctx context.Context, l *ListenersHandler) error { } tlsListeners = append(tlsListeners, listener) } - + + var tcpListeners = make([]net.Listener, 0, len(c.TCPAddresses)) for _, addr := range c.TCPAddresses { listener, err := net.Listen("tcp", addr) log.DebugError(logger, err, "Start listen tcp binding", zap.String("address", addr)) From 3e34a17120bef4690c7cf33658a6c1dffc749f82 Mon Sep 17 00:00:00 2001 From: rekby Date: Tue, 19 Nov 2019 08:36:29 +0300 Subject: [PATCH 04/10] Fix loglevel on cache miss cert. Close #95 --- internal/cert_manager/cert-state.go | 7 ++++--- internal/cert_manager/manager.go | 19 ++++++++++++++----- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/internal/cert_manager/cert-state.go b/internal/cert_manager/cert-state.go index 4c7354e3..b89d8850 100644 --- a/internal/cert_manager/cert-state.go +++ b/internal/cert_manager/cert-state.go @@ -4,12 +4,13 @@ package cert_manager import ( "context" "crypto/tls" - "errors" "sync" - "github.com/rekby/lets-proxy2/internal/log" zc "github.com/rekby/zapcontext" + "github.com/rekby/lets-proxy2/internal/cache" + "github.com/rekby/lets-proxy2/internal/log" + "go.uber.org/zap" ) @@ -95,7 +96,7 @@ func (s *certState) Cert() (cert *tls.Certificate, lastError error) { cert = s.cert if cert == nil && s.lastError == nil { - lastError = errors.New("have no cert in state") + lastError = cache.ErrCacheMiss } else { lastError = s.lastError } diff --git a/internal/cert_manager/manager.go b/internal/cert_manager/manager.go index 23e0ea11..437e44f0 100644 --- a/internal/cert_manager/manager.go +++ b/internal/cert_manager/manager.go @@ -142,7 +142,11 @@ func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (resultCert *tls.Ce } } if err != nil { - logger.Debug("Can't get certificate from local state", zap.Error(err)) + logLevel := zapcore.ErrorLevel + if err == cache.ErrCacheMiss { + logLevel = zapcore.DebugLevel + } + log.LevelParam(logger, logLevel, "Can't get certificate from local state", zap.Error(err)) } locked, err := isCertLocked(ctx, m.Cache, certName) @@ -152,9 +156,9 @@ func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (resultCert *tls.Ce } cert, err = loadCertificateFromCache(ctx, m.Cache, certName, keyRSA) - logLevel := zapcore.DebugLevel - if err != nil && err != cache.ErrCacheMiss { - logLevel = zapcore.ErrorLevel + logLevel := zapcore.ErrorLevel + if err == nil || err == cache.ErrCacheMiss { + logLevel = zapcore.DebugLevel } log.LevelParam(logger, logLevel, "Load certificate from cache", zap.Error(err)) @@ -716,7 +720,12 @@ func loadCertificateFromCache(ctx context.Context, c cache.Bytes, certName certN certKeyName := string(certName) + "." + string(keyType) + ".cer" certBytes, err := c.Get(ctx, certKeyName) - log.DebugError(logger, err, "Get certificate from cache") + logLevel := zapcore.ErrorLevel + if err == nil || err == cache.ErrCacheMiss { + logLevel = zapcore.DebugLevel + } + log.LevelParam(logger, logLevel, "Get certificate from cache", zap.Error(err)) + if err != nil { return nil, err } From 1292f75a5401462a5551ad8ec9a5ef6e19292770 Mon Sep 17 00:00:00 2001 From: rekby Date: Tue, 19 Nov 2019 09:52:36 +0300 Subject: [PATCH 05/10] style disable wsl linter --- .golangci.yml | 3 +++ cmd/config.go | 1 + cmd/config_test.go | 1 + cmd/log.go | 5 ++-- .../acme_client_manager/client_manager.go | 9 ++++++- internal/cache/disk.go | 1 + internal/cache/value_lru.go | 2 ++ internal/cache/value_lru_test.go | 2 ++ internal/cert_manager/cert-state_test.go | 8 +++--- internal/cert_manager/manager.go | 27 +++++++++++++------ .../manager_semi_integration_test.go | 2 ++ internal/contexthelper/contexthelper_test.go | 2 ++ internal/dns/parallel.go | 4 +-- internal/dns/resolver.go | 10 ++++--- internal/dns/resolver_test.go | 2 ++ internal/domain_checker/chains_test.go | 3 --- internal/domain_checker/config.go | 4 +-- internal/domain_checker/ip_list.go | 5 +++- internal/domain_checker/ip_list_test.go | 4 +-- internal/log/log.go | 3 +++ internal/proxy/config.go | 9 +++++++ internal/proxy/directors.go | 5 ++++ internal/proxy/http-proxy_test.go | 1 + internal/th/helper.go | 1 + internal/tlslistener/config.go | 9 ++++--- internal/tlslistener/config_test.go | 2 +- internal/tlslistener/tlslistenershandler.go | 1 + .../tlslistener/tlslistenershandler_test.go | 1 - 28 files changed, 94 insertions(+), 33 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index ad56062e..d3718807 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -13,6 +13,8 @@ linters-settings: locale: US gocyclo: min-complexity: 20 + wsl: + allow-trailing-comment: true issues: exclude-rules: @@ -32,4 +34,5 @@ linters: enable-all: true disable: - gochecknoglobals + - wsl diff --git a/cmd/config.go b/cmd/config.go index 3d0b92ce..33d12eb6 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -135,6 +135,7 @@ func mergeConfigByFilepath(ctx context.Context, c *configType, filename string) log.DebugFatal(logger, err, "Restore workdir to", zap.String("dir", dir)) }() } + mergeConfigBytes(ctx, c, content, filename) } diff --git a/cmd/config_test.go b/cmd/config_test.go index 56a015dd..797a275c 100644 --- a/cmd/config_test.go +++ b/cmd/config_test.go @@ -55,6 +55,7 @@ StorageDir = "storage2" `), 0600) var config configType + mergeConfigBytes(ctx, &config, defaultConfig(ctx), "") mergeConfigByFilepath(ctx, &config, filepath.Join(tmpDir, "config.toml")) td.CmpDeeply(config.General.IssueTimeout, 1) diff --git a/cmd/log.go b/cmd/log.go index c439d40a..0f64d265 100644 --- a/cmd/log.go +++ b/cmd/log.go @@ -41,11 +41,13 @@ func initLogger(config logConfig) *zap.Logger { writeSyncer := (*logWriteSyncer)(lr) writers = append(writers, writeSyncer) } + if config.EnableLogToStdErr { writer, _, err := zap.Open("stderr") if err != nil { panic("Can't open stderr to log") } + writers = append(writers, writer) } @@ -76,7 +78,7 @@ func initLogger(config logConfig) *zap.Logger { func parseLogLevel(logLevelS string) (zapcore.Level, error) { logLevelS = strings.TrimSpace(logLevelS) logLevelS = strings.ToLower(logLevelS) - switch logLevelS { + switch logLevelS { //nolint:wsl case "debug": return zapcore.DebugLevel, nil case "info": @@ -90,7 +92,6 @@ func parseLogLevel(logLevelS string) (zapcore.Level, error) { default: return zapcore.InfoLevel, errors.New("undefined log level") } - } func getLogOptions(config logConfig) (res []zap.Option) { diff --git a/internal/acme_client_manager/client_manager.go b/internal/acme_client_manager/client_manager.go index 2cb1df5a..2b613d9c 100644 --- a/internal/acme_client_manager/client_manager.go +++ b/internal/acme_client_manager/client_manager.go @@ -70,15 +70,18 @@ func (m *AcmeManager) GetClient(ctx context.Context) (*acme.Client, error) { } client := &acme.Client{DirectoryURL: m.DirectoryURL} + key, account, err := createAccount(ctx, client, m.AgreeFunction) if err != nil { return nil, err } + m.account = account m.client = client state := acmeManagerState{PrivateKey: key, AcmeAccount: account} stateBytes, err := json.Marshal(state) log.InfoPanicCtx(ctx, err, "Marshal account state to json") + if m.cache != nil { err = m.cache.Put(ctx, certName(m.DirectoryURL), stateBytes) if err != nil { @@ -96,6 +99,7 @@ func (m *AcmeManager) GetClient(ctx context.Context) (*acme.Client, error) { func (m *AcmeManager) accountRenew() { ticker := time.NewTicker(m.RenewAccountInterval) ctxDone := m.ctx.Done() + for { select { case <-ctxDone: @@ -128,20 +132,23 @@ func (m *AcmeManager) loadFromCache(ctx context.Context) (err error) { var state acmeManagerState err = json.Unmarshal(content, &state) - if err != nil { + if err != nil { // nolint:wsl return err } if state.PrivateKey == nil { return errors.New("empty private key") } + if state.AcmeAccount == nil { return errors.New("empty account info") } m.client = &acme.Client{DirectoryURL: m.DirectoryURL, Key: state.PrivateKey} m.account = state.AcmeAccount + go m.accountRenew() + return nil } diff --git a/internal/cache/disk.go b/internal/cache/disk.go index 85ee741a..224b2bd0 100644 --- a/internal/cache/disk.go +++ b/internal/cache/disk.go @@ -27,6 +27,7 @@ func (c *DiskCache) Get(ctx context.Context, key string) ([]byte, error) { defer c.mu.RUnlock() filePath := c.filepath(key) + res, err := ioutil.ReadFile(filePath) if os.IsNotExist(err) { err = ErrCacheMiss diff --git a/internal/cache/value_lru.go b/internal/cache/value_lru.go index 1e073a17..294f3930 100644 --- a/internal/cache/value_lru.go +++ b/internal/cache/value_lru.go @@ -98,10 +98,12 @@ func (c *MemoryValueLRU) time() uint64 { func (c *MemoryValueLRU) renumberTime() { c.mu.Lock() + items := c.getSortedItems() for i, item := range items { item.lastUsedTime = uint64(i) + 1 } + c.mu.Unlock() } diff --git a/internal/cache/value_lru_test.go b/internal/cache/value_lru_test.go index 767bd3c9..b8ff4b4b 100644 --- a/internal/cache/value_lru_test.go +++ b/internal/cache/value_lru_test.go @@ -12,6 +12,7 @@ import ( func TestValueLRUAsCache(t *testing.T) { td := testdeep.NewT(t) + ctx, flush := th.TestContext() defer flush() @@ -41,6 +42,7 @@ func TestValueLRUAsCache(t *testing.T) { func TestValueLRULimitAtPut(t *testing.T) { td := testdeep.NewT(t) + ctx, flush := th.TestContext() defer flush() diff --git a/internal/cert_manager/cert-state_test.go b/internal/cert_manager/cert-state_test.go index 1b6ed1ab..0efc21ba 100644 --- a/internal/cert_manager/cert-state_test.go +++ b/internal/cert_manager/cert-state_test.go @@ -39,7 +39,6 @@ func TestCertState(t *testing.T) { rCert, rErr = s.Cert() testdeep.CmpNil(t, rCert) testdeep.CmpDeeply(t, rErr, err1) - } func TestCertStateManyIssuers(t *testing.T) { @@ -66,6 +65,7 @@ func TestCertStateManyIssuers(t *testing.T) { lockFunc := func() []lockTimeStruct { res := make([]lockTimeStruct, 0, cnt) i := 0 + for { if i%checkEvery == 0 { if timeoutCtx.Err() != nil { @@ -79,14 +79,16 @@ func TestCertStateManyIssuers(t *testing.T) { time.Sleep(pause) item.end = time.Now() s.FinishIssue(ctxNoLog, nil, err1) + res = append(res, item) + i = 0 // for check exit } } } var wg sync.WaitGroup - wg.Add(cnt) + wg.Add(cnt) //nolint:wsl lockTimesChan := make(chan []lockTimeStruct, cnt) @@ -100,6 +102,7 @@ func TestCertStateManyIssuers(t *testing.T) { close(lockTimesChan) var lockTimesSlice []lockTimeStruct + for i := 0; i < cnt; i++ { items := <-lockTimesChan lockTimesSlice = append(lockTimesSlice, items...) @@ -213,7 +216,6 @@ func TestCertState_FinishIssuePanic(t *testing.T) { testdeep.CmpPanic(t, func() { s.FinishIssue(th.NoLog(ctx), cert1, err1) }, testdeep.NotEmpty()) - } func TestCertState_CertSet(t *testing.T) { diff --git a/internal/cert_manager/manager.go b/internal/cert_manager/manager.go index 437e44f0..dfb416a1 100644 --- a/internal/cert_manager/manager.go +++ b/internal/cert_manager/manager.go @@ -94,6 +94,7 @@ func New(client AcmeClient, c cache.Bytes) *Manager { } // GetCertificate implements the tls.Config.GetCertificate hook. +// nolint:funlen func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (resultCert *tls.Certificate, err error) { var ctx context.Context if getContext, ok := hello.Conn.(GetContext); ok { @@ -124,6 +125,7 @@ func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (resultCert *tls.Ce ctx = zc.WithLogger(ctx, zc.L(ctx).With(logCertName(certName))) now := time.Now() + defer func() { if isNeedRenew(resultCert, now) { go m.renewCertInBackground(ctx, certName) @@ -178,22 +180,26 @@ func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (resultCert *tls.Ce return nil, errHaveNoCert } + return m.issueNewCert(ctx, needDomain, certName) +} + +func (m *Manager) issueNewCert(ctx context.Context, needDomain DomainName, certName certNameType) (*tls.Certificate, error) { + logger := zc.L(ctx) + allowed, err := m.DomainChecker.IsDomainAllowed(ctx, needDomain.ASCII()) log.DebugError(logger, err, "Check if domain allowed for certificate", zap.Bool("allowed", allowed)) if err != nil { return nil, errHaveNoCert } - if !allowed { logger.Info("Deny certificate issue by filter") return nil, errHaveNoCert } - certIssueContext, cancelFunc := context.WithTimeout(ctx, m.CertificateIssueTimeout) defer cancelFunc() - domains := domainNamesFromCertificateName(certName) domains, err = filterDomains(ctx, m.DomainChecker, domains, needDomain) + log.DebugError(logger, err, "Filter domains", logDomains(domains)) res, err := m.createCertificateForDomains(certIssueContext, certName, domains) if err == nil { @@ -203,7 +209,6 @@ func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (resultCert *tls.Ce } logger.Warn("Can't issue certificate", zap.Error(err)) return nil, errHaveNoCert - } func (m *Manager) handleTLSALPN(logger *zap.Logger, ctx context.Context, needDomain DomainName) (*tls.Certificate, error) { @@ -223,9 +228,10 @@ func filterDomains(ctx context.Context, checker DomainChecker, originalDomains [ logger.Debug("filter domains from certificate list", logDomains(originalDomains)) var allowedDomains = make(chan DomainName, len(originalDomains)) var hasNeedDomain bool - var wg sync.WaitGroup + wg.Add(len(originalDomains)) + for _, domain := range originalDomains { domain := domain // pin var @@ -319,10 +325,10 @@ func (m *Manager) supportedChallenges() []string { return allowedChallenges } +// createOrderForDomains similar to func (m *Manager) verifyRFC(ctx context.Context, client *acme.Client, domain string) (*acme.Order, error) +// from acme/autocert +//nolint:funlen func (m *Manager) createOrderForDomains(ctx context.Context, domains ...DomainName) (*acme.Order, error) { - // similar to func (m *Manager) verifyRFC(ctx context.Context, client *acme.Client, domain string) (*acme.Order, error) - // from acme/autocert - client := m.Client logger := zc.L(ctx) challengeTypes := m.supportedChallenges() @@ -547,6 +553,7 @@ func (m *Manager) certKeyGetOrCreate(ctx context.Context, certName certNameType, func (m *Manager) fulfill(ctx context.Context, challenge *acme.Challenge, domain DomainName) (func(context.Context), error) { logger := zc.L(ctx) + switch challenge.Type { case tlsAlpn01: cert, err := m.Client.TLSALPN01ChallengeCert(challenge.Token, domain.String()) @@ -631,6 +638,7 @@ func storeCertificate(ctx context.Context, cache cache.Bytes, certName certNameT var keyType = getKeyType(cert) var certBuf bytes.Buffer + for _, block := range cert.Certificate { pemBlock := pem.Block{Type: "CERTIFICATE", Bytes: block} err := pem.Encode(&certBuf, &pemBlock) @@ -779,6 +787,7 @@ func parsePrivateKey(keyPEMBlock []byte) (crypto.Signer, error) { var keyDERBlock *pem.Block var skippedBlockTypes []string + for { keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock) if keyDERBlock == nil { @@ -788,6 +797,7 @@ func parsePrivateKey(keyPEMBlock []byte) (crypto.Signer, error) { if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") { break } + skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type) } @@ -830,6 +840,7 @@ func isNeedRenew(cert *tls.Certificate, now time.Time) bool { func isCertLocked(ctx context.Context, storage cache.Bytes, certName certNameType) (bool, error) { lockName := certName.String() + ".lock" + _, err := storage.Get(ctx, lockName) switch err { case cache.ErrCacheMiss: diff --git a/internal/cert_manager/manager_semi_integration_test.go b/internal/cert_manager/manager_semi_integration_test.go index 47303315..2a4ceb26 100644 --- a/internal/cert_manager/manager_semi_integration_test.go +++ b/internal/cert_manager/manager_semi_integration_test.go @@ -53,6 +53,7 @@ func TestManager_GetCertificateHttp01(t *testing.T) { if err != nil { t.Fatal(err) } + defer lisneter.Close() go func() { @@ -217,6 +218,7 @@ func TestManager_GetCertificateTls(t *testing.T) { if err != nil { t.Fatal(err) } + defer lisneter.Close() go func() { diff --git a/internal/contexthelper/contexthelper_test.go b/internal/contexthelper/contexthelper_test.go index beb28057..23e78e7e 100644 --- a/internal/contexthelper/contexthelper_test.go +++ b/internal/contexthelper/contexthelper_test.go @@ -104,6 +104,7 @@ func TestCombinedContext_Value(t *testing.T) { td := testdeep.NewT(t) var ctx = CombineContext() + td.CmpDeeply(ctx.Value(one), nil) ctx1 := context.WithValue(context.Background(), one, 2) @@ -130,6 +131,7 @@ func TestCombinedContext_Done(t *testing.T) { done = false ctx = CombineContext(ctx1) + go func() { <-ctx.Done() done = true diff --git a/internal/dns/parallel.go b/internal/dns/parallel.go index 6a53972d..a0651946 100644 --- a/internal/dns/parallel.go +++ b/internal/dns/parallel.go @@ -37,8 +37,8 @@ func (p Parallel) LookupIPAddr(ctx context.Context, host string) ([]net.IPAddr, var errs = make([]error, len(p)) var wg sync.WaitGroup - wg.Add(len(p)) - for i := range p { + wg.Add(len(p)) // nolint:wsl + for i := range p { // nolint:wsl go func(i int) { ips[i], errs[i] = p[i].LookupIPAddr(ctx, host) wg.Done() diff --git a/internal/dns/resolver.go b/internal/dns/resolver.go index e7e44162..a8b1530d 100644 --- a/internal/dns/resolver.go +++ b/internal/dns/resolver.go @@ -58,14 +58,14 @@ func (r *Resolver) LookupIPAddr(ctx context.Context, host string) ([]net.IPAddr, var errA, errAAAA error wg.Add(1) - go func() { + go func() { //nolint:wsl defer wg.Done() errA = errPanic ipAddrA, errA = r.lookup(ctx, host, mdns.TypeA) }() wg.Add(1) - go func() { + go func() { //nolint:wsl defer wg.Done() errAAAA = errPanic ipAddrAAAA, errAAAA = r.lookup(ctx, host, mdns.TypeAAAA) @@ -80,6 +80,7 @@ func (r *Resolver) LookupIPAddr(ctx context.Context, host string) ([]net.IPAddr, if errA != nil { resultErr = errA } + log.DebugErrorCtx(ctx, resultErr, "Host lookup", zap.NamedError("errA", errA), zap.NamedError("errAAAA", errAAAA), zap.Any("ipAddrA", ipAddrA), zap.Any("ipAddrAAAA", ipAddrAAAA)) @@ -102,6 +103,7 @@ func (r *Resolver) lookup(ctx context.Context, host string, recordType uint16) ( return res, err } +//nolint:funlen func lookupWithClient(ctx context.Context, host string, server string, recordType uint16, recursion int, client mDNSClient) (ipResults []net.IPAddr, err error) { logger := zc.L(ctx) @@ -114,6 +116,7 @@ func lookupWithClient(ctx context.Context, host string, server string, recordTyp logger.Debug("Context canceled") return nil, ctx.Err() } + defer func() { log.DebugError(logger, err, "Resolved ips", zap.Any("ipResults", ipResults), zap.Uint16("record_type", recordType)) @@ -136,7 +139,7 @@ func lookupWithClient(ctx context.Context, host string, server string, recordTyp exchangeCompleted := make(chan struct{}) var dnsAnswer *mdns.Msg - go func() { + go func() { // nolint:wsl dnsAnswer, _, err = client.Exchange(&msg, server) close(exchangeCompleted) }() @@ -154,6 +157,7 @@ func lookupWithClient(ctx context.Context, host string, server string, recordTyp var resIPs []net.IPAddr for _, r := range dnsAnswer.Answer { rType := r.Header().Rrtype + switch { case rType == mdns.TypeA && rType == recordType: resIPs = append(resIPs, net.IPAddr{IP: r.(*mdns.A).A}) diff --git a/internal/dns/resolver_test.go b/internal/dns/resolver_test.go index 13b71949..06c32ad1 100644 --- a/internal/dns/resolver_test.go +++ b/internal/dns/resolver_test.go @@ -203,8 +203,10 @@ func TestLookupWithClient(t *testing.T) { }, }, 0, nil }) + timeoutCtx, timeoutCancelCtx := context.WithTimeout(ctx, time.Millisecond*10) defer timeoutCancelCtx() + ips, err = lookupWithClient(timeoutCtx, "asd.com", "1.2.3.4:53", mdns.TypeA, 1, client) td.CmpError(err) td.Nil(ips) diff --git a/internal/domain_checker/chains_test.go b/internal/domain_checker/chains_test.go index ae9b19be..2c03415d 100644 --- a/internal/domain_checker/chains_test.go +++ b/internal/domain_checker/chains_test.go @@ -66,7 +66,6 @@ func TestAny(t *testing.T) { res, err = any.IsDomainAllowed(ctx, "edc") td.False(res) td.CmpError(err) - } func TestAll(t *testing.T) { @@ -117,7 +116,6 @@ func TestAll(t *testing.T) { res, err = any.IsDomainAllowed(ctx, "edc") td.False(res) td.CmpNoError(err) - } func TestNot(t *testing.T) { @@ -152,5 +150,4 @@ func TestNot(t *testing.T) { res, err = not.IsDomainAllowed(ctx, "kkk") td.False(res) td.CmpError(err) - } diff --git a/internal/domain_checker/config.go b/internal/domain_checker/config.go index a0f2973c..3b57654b 100644 --- a/internal/domain_checker/config.go +++ b/internal/domain_checker/config.go @@ -69,11 +69,11 @@ func (c *Config) CreateDomainChecker(ctx context.Context) (DomainChecker, error) if err != nil { return nil, err } - whiteIpList := NewIPList(ctx, func(ctx context.Context) ([]net.IP, error) { + whiteIPList := NewIPList(ctx, func(ctx context.Context) ([]net.IP, error) { return ips, nil }) // ipList.StartAutoRenew() - doesn't need renew, because list static - ipCheckers = append(ipCheckers, whiteIpList) + ipCheckers = append(ipCheckers, whiteIPList) } // If no ip checks - allow domain without ip check diff --git a/internal/domain_checker/ip_list.go b/internal/domain_checker/ip_list.go index f19ffa97..a5302637 100644 --- a/internal/domain_checker/ip_list.go +++ b/internal/domain_checker/ip_list.go @@ -173,6 +173,7 @@ func getBindedIPAddress(ctx context.Context, interfacesAddr InterfacesAddrFunc) log.DebugDPanic(logger, err, "Get system addresses", zap.Any("addresses", binded)) var parsed = make([]net.IP, 0, len(binded)) + for _, addr := range binded { ip, _, err := net.ParseCIDR(addr.String()) log.DebugDPanic(logger, err, "Parse ip from interface", zap.Any("ip", ip), @@ -189,7 +190,7 @@ func getBindedIPAddress(ctx context.Context, interfacesAddr InterfacesAddrFunc) func filterPublicOnlyIPs(ips []net.IP) []net.IP { var public = make([]net.IP, 0, len(ips)) - for _, ip := range ips { + for _, ip := range ips { // nolint:wsl if isPublicIP(ip) { public = append(public, ip) } @@ -258,6 +259,8 @@ func truncatedCopyIPs(ips []net.IP) []net.IP { } var res = make([]net.IP, len(ips)) + copy(res, ips) + return res } diff --git a/internal/domain_checker/ip_list_test.go b/internal/domain_checker/ip_list_test.go index 23b1cd35..dbceeeba 100644 --- a/internal/domain_checker/ip_list_test.go +++ b/internal/domain_checker/ip_list_test.go @@ -127,7 +127,6 @@ func TestIPList_Update(t *testing.T) { td.CmpNotPanic(func() { l.updateIPs() }) - } func TestIPList_UpdateByTimer(t *testing.T) { @@ -187,7 +186,7 @@ func TestIPList_UpdateByTimer(t *testing.T) { func TestSetDefaultResolver(t *testing.T) { oldResolver := defaultResolver - defer func() { + defer func() { // nolint:wsl defaultResolver = oldResolver }() @@ -261,7 +260,6 @@ func TestSelfPublicIP_IsDomainAllowed(t *testing.T) { res, err = s.IsDomainAllowed(ctx2, "asd8") td.False(res) td.CmpError(err) - } func TestSelfPublicIP_IsDomainAllowed_CanceledMainContext(t *testing.T) { diff --git a/internal/log/log.go b/internal/log/log.go index 5bed3b2b..9f9d5968 100644 --- a/internal/log/log.go +++ b/internal/log/log.go @@ -19,6 +19,7 @@ func (c *certLogger) String() string { if cert == nil { return "x509 nil" } + return fmt.Sprintf("Common name: %q, Domains: %q, Expire: %q, SerialNumber: %q", cert.Subject.CommonName, cert.DNSNames, cert.NotAfter, cert.Subject.SerialNumber) } @@ -69,6 +70,7 @@ func DebugDPanicCtx(ctx context.Context, err error, mess string, fields ...zap.F func debugDpanic(logger *zap.Logger, err error, mess string, fields ...zap.Field) { logger = logger.WithOptions(zap.AddCallerSkip(2)) + if err == nil { logger.Debug(mess, fields...) } else { @@ -86,6 +88,7 @@ func DebugFatalCtx(ctx context.Context, err error, mess string, fields ...zap.Fi func debugFatal(logger *zap.Logger, err error, mess string, fields ...zap.Field) { logger = logger.WithOptions(zap.AddCallerSkip(2)) + if err == nil { logger.Debug(mess, fields...) } else { diff --git a/internal/proxy/config.go b/internal/proxy/config.go index c5f0b1aa..3a3c8559 100644 --- a/internal/proxy/config.go +++ b/internal/proxy/config.go @@ -27,6 +27,7 @@ type Config struct { func (c *Config) Apply(ctx context.Context, p *HTTPProxy) error { var resErr error + var chain []Director appendDirector := func(f func(ctx context.Context) (Director, error)) { if resErr != nil { @@ -34,6 +35,7 @@ func (c *Config) Apply(ctx context.Context, p *HTTPProxy) error { } director, err := f(ctx) resErr = err + chain = append(chain, director) } @@ -62,6 +64,7 @@ func (c *Config) getDefaultTargetDirector(ctx context.Context) (Director, error) } defaultTarget, err := net.ResolveTCPAddr("tcp", c.DefaultTarget) logger.Debug("Parse default target as tcp address", zap.Stringer("default_target", defaultTarget), zap.Error(err)) + if err != nil { defaultTargetIP, err := net.ResolveIPAddr("ip", c.DefaultTarget) logger.Debug("Parse default target as ip address", zap.Stringer("default_target", defaultTarget), zap.Error(err)) @@ -71,10 +74,12 @@ func (c *Config) getDefaultTargetDirector(ctx context.Context) (Director, error) } defaultTarget = &net.TCPAddr{IP: defaultTargetIP.IP, Port: defaultHTTPPort} } + if len(defaultTarget.IP) == 0 { logger.Info("Create same ip director", zap.Int("port", defaultTarget.Port)) return NewDirectorSameIP(defaultTarget.Port), nil } + logger.Info("Create host ip director", zap.Int("port", defaultTarget.Port)) return NewDirectorHost(defaultTarget.String()), nil } @@ -88,6 +93,7 @@ func (c *Config) getHeadersDirector(ctx context.Context) (Director, error) { } m := make(map[string]string) + for _, line := range c.Headers { line = strings.TrimSpace(line) lineParts := strings.SplitN(line, ":", 2) @@ -97,6 +103,7 @@ func (c *Config) getHeadersDirector(ctx context.Context) (Director, error) { } m[lineParts[0]] = lineParts[1] } + logger.Info("Create headers director", zap.Any("headers", m)) return NewDirectorSetHeaders(m), nil } @@ -107,6 +114,7 @@ func (c *Config) getMapDirector(ctx context.Context) (Director, error) { if len(c.TargetMap) == 0 { return nil, nil } + m := make(map[string]string) for _, line := range c.TargetMap { from, to, err := parseTCPMapPair(line) @@ -117,6 +125,7 @@ func (c *Config) getMapDirector(ctx context.Context) (Director, error) { } m[from] = to } + logger.Info("Add target-map director", zap.Any("map", m)) return NewDirectorDestMap(m), nil } diff --git a/internal/proxy/directors.go b/internal/proxy/directors.go index 808c99dd..c717785f 100644 --- a/internal/proxy/directors.go +++ b/internal/proxy/directors.go @@ -39,6 +39,7 @@ func (c DirectorChain) Director(request *http.Request) { // skip nil directors func NewDirectorChain(directors ...Director) DirectorChain { cnt := 0 + for _, item := range directors { if item != nil { cnt++ @@ -46,11 +47,13 @@ func NewDirectorChain(directors ...Director) DirectorChain { } ownDirectors := make(DirectorChain, 0, cnt) + for _, item := range directors { if item != nil { ownDirectors = append(ownDirectors, item) } } + return ownDirectors } @@ -135,6 +138,7 @@ func (h DirectorSetHeaders) Director(request *http.Request) { for name, headerVal := range h { var value string + switch headerVal { case ConnectionID: value = request.Context().Value(contextlabel.ConnectionID).(string) @@ -161,6 +165,7 @@ func (h DirectorSetHeaders) Director(request *http.Request) { if request.Header == nil { request.Header = make(http.Header) } + request.Header.Set(name, value) } } diff --git a/internal/proxy/http-proxy_test.go b/internal/proxy/http-proxy_test.go index 7520e12f..027cf312 100644 --- a/internal/proxy/http-proxy_test.go +++ b/internal/proxy/http-proxy_test.go @@ -28,6 +28,7 @@ func TestHttpProxy_HandleHttpValidationDefault(t *testing.T) { td.FailureIsFatal() listener, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)}) td.CmpNoError(err) + defer func() { _ = listener.Close() }() proxy := NewHTTPProxy(ctx, listener) diff --git a/internal/th/helper.go b/internal/th/helper.go index 646ea7ef..7b04b2ed 100644 --- a/internal/th/helper.go +++ b/internal/th/helper.go @@ -13,6 +13,7 @@ func TestContext() (ctx context.Context, flush func()) { flush = func() { cancel() } + return ctx, flush } diff --git a/internal/tlslistener/config.go b/internal/tlslistener/config.go index fcbe9c7c..54798f4d 100644 --- a/internal/tlslistener/config.go +++ b/internal/tlslistener/config.go @@ -16,24 +16,27 @@ type Config struct { func (c *Config) Apply(ctx context.Context, l *ListenersHandler) error { logger := zc.L(ctx) - + var tlsListeners = make([]net.Listener, 0, len(c.TLSAddresses)) - for _, addr := range c.TLSAddresses { + for _, addr := range c.TLSAddresses { //nolint:wsl listener, err := net.Listen("tcp", addr) log.DebugError(logger, err, "Start listen tls binding", zap.String("address", addr)) if err != nil { return err } + tlsListeners = append(tlsListeners, listener) } - + var tcpListeners = make([]net.Listener, 0, len(c.TCPAddresses)) + for _, addr := range c.TCPAddresses { listener, err := net.Listen("tcp", addr) log.DebugError(logger, err, "Start listen tcp binding", zap.String("address", addr)) if err != nil { return err } + tcpListeners = append(tcpListeners, listener) } l.ListenersForHandleTLS = tlsListeners diff --git a/internal/tlslistener/config_test.go b/internal/tlslistener/config_test.go index 1d72b783..9fbe773b 100644 --- a/internal/tlslistener/config_test.go +++ b/internal/tlslistener/config_test.go @@ -63,12 +63,12 @@ func TestConfig_Apply(t *testing.T) { tlsListenerAddresses := []string{l.ListenersForHandleTLS[0].Addr().String(), l.ListenersForHandleTLS[1].Addr().String(), l.ListenersForHandleTLS[2].Addr().String()} td.CmpDeeply(tlsListenerAddresses, []string{addr + ":" + ports[2], addr + ":" + ports[3], addr + ":" + ports[4]}) - } func getFreePorts(ip string, cnt int) []string { var res = make([]string, cnt) var listeners = make([]net.Listener, cnt) + for i := 0; i < cnt; i++ { listener, err := net.Listen("tcp", ip+":0") if err != nil { diff --git a/internal/tlslistener/tlslistenershandler.go b/internal/tlslistener/tlslistenershandler.go index 90becb5a..b2fd4e4f 100644 --- a/internal/tlslistener/tlslistenershandler.go +++ b/internal/tlslistener/tlslistenershandler.go @@ -109,6 +109,7 @@ func handleConnections(ctx context.Context, l net.Listener, handleFunc func(ctx if ctx.Err() != nil { err = nil } + log.InfoError(logger, err, "Close listener", zap.String("local_addr", l.Addr().String())) err = l.Close() log.DebugError(logger, err, "Listener closed", zap.String("local_addr", l.Addr().String())) diff --git a/internal/tlslistener/tlslistenershandler_test.go b/internal/tlslistener/tlslistenershandler_test.go index bf8e693f..fffa784c 100644 --- a/internal/tlslistener/tlslistenershandler_test.go +++ b/internal/tlslistener/tlslistenershandler_test.go @@ -21,7 +21,6 @@ import ( ) func TestProxyListenerType(t *testing.T) { - listener := listenerType{connections: make(chan net.Conn)} // test proxy From 4ce4b83b99cf7358a65abab7b431b0b45aa41ed5 Mon Sep 17 00:00:00 2001 From: rekby Date: Sun, 24 Nov 2019 12:23:21 +0300 Subject: [PATCH 06/10] add secret handler for profiler --- cmd/config.go | 2 + internal/profiler/handler_mock_test.go | 254 +++++++++++++++++++++++ internal/profiler/profiler.go | 18 ++ internal/profiler/secret_handler.go | 19 ++ internal/profiler/secret_handler_test.go | 63 ++++++ 5 files changed, 356 insertions(+) create mode 100644 internal/profiler/handler_mock_test.go create mode 100644 internal/profiler/profiler.go create mode 100644 internal/profiler/secret_handler.go create mode 100644 internal/profiler/secret_handler_test.go diff --git a/cmd/config.go b/cmd/config.go index 33d12eb6..a1f5e329 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -11,6 +11,7 @@ import ( "github.com/gobuffalo/packr" + "github.com/rekby/lets-proxy2/internal/profiler" "github.com/rekby/lets-proxy2/internal/tlslistener" "github.com/rekby/lets-proxy2/internal/proxy" @@ -31,6 +32,7 @@ type ConfigGeneral struct { StoreJSONMetadata bool IncludeConfigs []string MaxConfigFilesRead int + Profiler profiler.Config } //go:generate packr diff --git a/internal/profiler/handler_mock_test.go b/internal/profiler/handler_mock_test.go new file mode 100644 index 00000000..26ef80df --- /dev/null +++ b/internal/profiler/handler_mock_test.go @@ -0,0 +1,254 @@ +package profiler + +// Code generated by http://github.com/gojuno/minimock (3.0.6). DO NOT EDIT. + +import ( + mm_http "net/http" + "sync" + mm_atomic "sync/atomic" + mm_time "time" + + "github.com/gojuno/minimock/v3" +) + +// HandlerMock implements http.Handler +type HandlerMock struct { + t minimock.Tester + + funcServeHTTP func(r1 mm_http.ResponseWriter, rp1 *mm_http.Request) + inspectFuncServeHTTP func(r1 mm_http.ResponseWriter, rp1 *mm_http.Request) + afterServeHTTPCounter uint64 + beforeServeHTTPCounter uint64 + ServeHTTPMock mHandlerMockServeHTTP +} + +// NewHandlerMock returns a mock for http.Handler +func NewHandlerMock(t minimock.Tester) *HandlerMock { + m := &HandlerMock{t: t} + if controller, ok := t.(minimock.MockController); ok { + controller.RegisterMocker(m) + } + + m.ServeHTTPMock = mHandlerMockServeHTTP{mock: m} + m.ServeHTTPMock.callArgs = []*HandlerMockServeHTTPParams{} + + return m +} + +type mHandlerMockServeHTTP struct { + mock *HandlerMock + defaultExpectation *HandlerMockServeHTTPExpectation + expectations []*HandlerMockServeHTTPExpectation + + callArgs []*HandlerMockServeHTTPParams + mutex sync.RWMutex +} + +// HandlerMockServeHTTPExpectation specifies expectation struct of the Handler.ServeHTTP +type HandlerMockServeHTTPExpectation struct { + mock *HandlerMock + params *HandlerMockServeHTTPParams + + Counter uint64 +} + +// HandlerMockServeHTTPParams contains parameters of the Handler.ServeHTTP +type HandlerMockServeHTTPParams struct { + r1 mm_http.ResponseWriter + rp1 *mm_http.Request +} + +// Expect sets up expected params for Handler.ServeHTTP +func (mmServeHTTP *mHandlerMockServeHTTP) Expect(r1 mm_http.ResponseWriter, rp1 *mm_http.Request) *mHandlerMockServeHTTP { + if mmServeHTTP.mock.funcServeHTTP != nil { + mmServeHTTP.mock.t.Fatalf("HandlerMock.ServeHTTP mock is already set by Set") + } + + if mmServeHTTP.defaultExpectation == nil { + mmServeHTTP.defaultExpectation = &HandlerMockServeHTTPExpectation{} + } + + mmServeHTTP.defaultExpectation.params = &HandlerMockServeHTTPParams{r1, rp1} + for _, e := range mmServeHTTP.expectations { + if minimock.Equal(e.params, mmServeHTTP.defaultExpectation.params) { + mmServeHTTP.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmServeHTTP.defaultExpectation.params) + } + } + + return mmServeHTTP +} + +// Inspect accepts an inspector function that has same arguments as the Handler.ServeHTTP +func (mmServeHTTP *mHandlerMockServeHTTP) Inspect(f func(r1 mm_http.ResponseWriter, rp1 *mm_http.Request)) *mHandlerMockServeHTTP { + if mmServeHTTP.mock.inspectFuncServeHTTP != nil { + mmServeHTTP.mock.t.Fatalf("Inspect function is already set for HandlerMock.ServeHTTP") + } + + mmServeHTTP.mock.inspectFuncServeHTTP = f + + return mmServeHTTP +} + +// Return sets up results that will be returned by Handler.ServeHTTP +func (mmServeHTTP *mHandlerMockServeHTTP) Return() *HandlerMock { + if mmServeHTTP.mock.funcServeHTTP != nil { + mmServeHTTP.mock.t.Fatalf("HandlerMock.ServeHTTP mock is already set by Set") + } + + if mmServeHTTP.defaultExpectation == nil { + mmServeHTTP.defaultExpectation = &HandlerMockServeHTTPExpectation{mock: mmServeHTTP.mock} + } + + return mmServeHTTP.mock +} + +//Set uses given function f to mock the Handler.ServeHTTP method +func (mmServeHTTP *mHandlerMockServeHTTP) Set(f func(r1 mm_http.ResponseWriter, rp1 *mm_http.Request)) *HandlerMock { + if mmServeHTTP.defaultExpectation != nil { + mmServeHTTP.mock.t.Fatalf("Default expectation is already set for the Handler.ServeHTTP method") + } + + if len(mmServeHTTP.expectations) > 0 { + mmServeHTTP.mock.t.Fatalf("Some expectations are already set for the Handler.ServeHTTP method") + } + + mmServeHTTP.mock.funcServeHTTP = f + return mmServeHTTP.mock +} + +// ServeHTTP implements http.Handler +func (mmServeHTTP *HandlerMock) ServeHTTP(r1 mm_http.ResponseWriter, rp1 *mm_http.Request) { + mm_atomic.AddUint64(&mmServeHTTP.beforeServeHTTPCounter, 1) + defer mm_atomic.AddUint64(&mmServeHTTP.afterServeHTTPCounter, 1) + + if mmServeHTTP.inspectFuncServeHTTP != nil { + mmServeHTTP.inspectFuncServeHTTP(r1, rp1) + } + + mm_params := &HandlerMockServeHTTPParams{r1, rp1} + + // Record call args + mmServeHTTP.ServeHTTPMock.mutex.Lock() + mmServeHTTP.ServeHTTPMock.callArgs = append(mmServeHTTP.ServeHTTPMock.callArgs, mm_params) + mmServeHTTP.ServeHTTPMock.mutex.Unlock() + + for _, e := range mmServeHTTP.ServeHTTPMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) + return + } + } + + if mmServeHTTP.ServeHTTPMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmServeHTTP.ServeHTTPMock.defaultExpectation.Counter, 1) + mm_want := mmServeHTTP.ServeHTTPMock.defaultExpectation.params + mm_got := HandlerMockServeHTTPParams{r1, rp1} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmServeHTTP.t.Errorf("HandlerMock.ServeHTTP got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) + } + + return + + } + if mmServeHTTP.funcServeHTTP != nil { + mmServeHTTP.funcServeHTTP(r1, rp1) + return + } + mmServeHTTP.t.Fatalf("Unexpected call to HandlerMock.ServeHTTP. %v %v", r1, rp1) + +} + +// ServeHTTPAfterCounter returns a count of finished HandlerMock.ServeHTTP invocations +func (mmServeHTTP *HandlerMock) ServeHTTPAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmServeHTTP.afterServeHTTPCounter) +} + +// ServeHTTPBeforeCounter returns a count of HandlerMock.ServeHTTP invocations +func (mmServeHTTP *HandlerMock) ServeHTTPBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmServeHTTP.beforeServeHTTPCounter) +} + +// Calls returns a list of arguments used in each call to HandlerMock.ServeHTTP. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmServeHTTP *mHandlerMockServeHTTP) Calls() []*HandlerMockServeHTTPParams { + mmServeHTTP.mutex.RLock() + + argCopy := make([]*HandlerMockServeHTTPParams, len(mmServeHTTP.callArgs)) + copy(argCopy, mmServeHTTP.callArgs) + + mmServeHTTP.mutex.RUnlock() + + return argCopy +} + +// MinimockServeHTTPDone returns true if the count of the ServeHTTP invocations corresponds +// the number of defined expectations +func (m *HandlerMock) MinimockServeHTTPDone() bool { + for _, e := range m.ServeHTTPMock.expectations { + if mm_atomic.LoadUint64(&e.Counter) < 1 { + return false + } + } + + // if default expectation was set then invocations count should be greater than zero + if m.ServeHTTPMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterServeHTTPCounter) < 1 { + return false + } + // if func was set then invocations count should be greater than zero + if m.funcServeHTTP != nil && mm_atomic.LoadUint64(&m.afterServeHTTPCounter) < 1 { + return false + } + return true +} + +// MinimockServeHTTPInspect logs each unmet expectation +func (m *HandlerMock) MinimockServeHTTPInspect() { + for _, e := range m.ServeHTTPMock.expectations { + if mm_atomic.LoadUint64(&e.Counter) < 1 { + m.t.Errorf("Expected call to HandlerMock.ServeHTTP with params: %#v", *e.params) + } + } + + // if default expectation was set then invocations count should be greater than zero + if m.ServeHTTPMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterServeHTTPCounter) < 1 { + if m.ServeHTTPMock.defaultExpectation.params == nil { + m.t.Error("Expected call to HandlerMock.ServeHTTP") + } else { + m.t.Errorf("Expected call to HandlerMock.ServeHTTP with params: %#v", *m.ServeHTTPMock.defaultExpectation.params) + } + } + // if func was set then invocations count should be greater than zero + if m.funcServeHTTP != nil && mm_atomic.LoadUint64(&m.afterServeHTTPCounter) < 1 { + m.t.Error("Expected call to HandlerMock.ServeHTTP") + } +} + +// MinimockFinish checks that all mocked methods have been called the expected number of times +func (m *HandlerMock) MinimockFinish() { + if !m.minimockDone() { + m.MinimockServeHTTPInspect() + m.t.FailNow() + } +} + +// MinimockWait waits for all mocked methods to be called the expected number of times +func (m *HandlerMock) MinimockWait(timeout mm_time.Duration) { + timeoutCh := mm_time.After(timeout) + for { + if m.minimockDone() { + return + } + select { + case <-timeoutCh: + m.MinimockFinish() + return + case <-mm_time.After(10 * mm_time.Millisecond): + } + } +} + +func (m *HandlerMock) minimockDone() bool { + done := true + return done && + m.MinimockServeHTTPDone() +} diff --git a/internal/profiler/profiler.go b/internal/profiler/profiler.go new file mode 100644 index 00000000..e006c546 --- /dev/null +++ b/internal/profiler/profiler.go @@ -0,0 +1,18 @@ +package profiler + +import ( + _ "net/http/pprof" +) + +type Config struct { + Enable bool + BindAddress string + Password string +} + +type Profiler struct { +} + +func New(config Config) *Profiler { + return &Profiler{} +} diff --git a/internal/profiler/secret_handler.go b/internal/profiler/secret_handler.go new file mode 100644 index 00000000..d349f6e2 --- /dev/null +++ b/internal/profiler/secret_handler.go @@ -0,0 +1,19 @@ +package profiler + +import "net/http" + +type secretHandler struct { + argName string + secret string + next http.Handler +} + +func (s secretHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) { + querySecret := req.URL.Query().Get(s.argName) + if s.secret == querySecret { + s.next.ServeHTTP(resp, req) + return + } + + http.Error(resp, "Forbidden", http.StatusForbidden) +} diff --git a/internal/profiler/secret_handler_test.go b/internal/profiler/secret_handler_test.go new file mode 100644 index 00000000..65a32274 --- /dev/null +++ b/internal/profiler/secret_handler_test.go @@ -0,0 +1,63 @@ +package profiler + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/gojuno/minimock/v3" + "github.com/maxatome/go-testdeep" +) + +//go:generate minimock -g -i net/http.Handler -o ./handler_mock_test.go + +func TestSecretHandler_ServeHTTP(t *testing.T) { + td := testdeep.NewT(t) + mt := minimock.NewController(td) + defer mt.Finish() + + nextHandler := NewHandlerMock(mt) + nextCalled := false + nextHandler.ServeHTTPMock.Set(func(resp http.ResponseWriter, req *http.Request) { + resp.WriteHeader(http.StatusOK) + _, _ = resp.Write([]byte("OK")) + nextCalled = true + }) + defer nextHandler.MinimockFinish() + + const argName = "pass" + const secret = "asd" + + secretHandler := secretHandler{ + next: nextHandler, + argName: argName, + secret: secret, + } + + nextCalled = false + respWriter := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "http://test?pass=asd", nil) + secretHandler.ServeHTTP(respWriter, req) + respWriter.Flush() + resp := respWriter.Result() + td.Cmp(resp.StatusCode, http.StatusOK) + td.True(nextCalled) + + nextCalled = false + respWriter = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "http://test", nil) + secretHandler.ServeHTTP(respWriter, req) + respWriter.Flush() + resp = respWriter.Result() + td.Cmp(resp.StatusCode, http.StatusForbidden) + td.False(nextCalled) + nextCalled = false + + respWriter = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "http://test?pass=asdf", nil) + secretHandler.ServeHTTP(respWriter, req) + respWriter.Flush() + resp = respWriter.Result() + td.Cmp(resp.StatusCode, http.StatusForbidden) + td.False(nextCalled) +} From 519bb5e3e2a5ee75c4359d17763f0e7c068fffae Mon Sep 17 00:00:00 2001 From: rekby Date: Sun, 24 Nov 2019 14:40:52 +0300 Subject: [PATCH 07/10] refactor profiler - for allow by ip networks Close #20 --- internal/profiler/profiler.go | 47 +++++++++++++++++++++--- internal/profiler/profiler_test.go | 37 +++++++++++++++++++ internal/profiler/secret_handler.go | 30 +++++++++++---- internal/profiler/secret_handler_test.go | 25 ++++++++----- 4 files changed, 117 insertions(+), 22 deletions(-) create mode 100644 internal/profiler/profiler_test.go diff --git a/internal/profiler/profiler.go b/internal/profiler/profiler.go index e006c546..a1c0791f 100644 --- a/internal/profiler/profiler.go +++ b/internal/profiler/profiler.go @@ -1,18 +1,53 @@ package profiler import ( - _ "net/http/pprof" + "net" + "net/http" + "net/http/pprof" + + "go.uber.org/zap" + + "github.com/rekby/lets-proxy2/internal/log" ) type Config struct { - Enable bool - BindAddress string - Password string + Enable bool + AllowedNetworks []string + BindAddress string } type Profiler struct { + secretHandler secretHandler +} + +func New(logger *zap.Logger, config Config) *Profiler { + mux := http.NewServeMux() + + mux.HandleFunc("/debug/pprof/", pprof.Index) + mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline) + mux.HandleFunc("/debug/pprof/profile", pprof.Profile) + mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol) + mux.HandleFunc("/debug/pprof/trace", pprof.Trace) + + var allowedNetworks []net.IPNet + for _, network := range config.AllowedNetworks { + _, parsedNet, err := net.ParseCIDR(network) + log.InfoError(logger, err, "Parse allowed CIDR", zap.Stringer("network", parsedNet)) + if err == nil { + allowedNetworks = append(allowedNetworks, *parsedNet) + } + } + + handler := secretHandler{ + logger: logger, + next: mux, + AllowedNetworks: allowedNetworks, + } + return &Profiler{ + secretHandler: handler, + } } -func New(config Config) *Profiler { - return &Profiler{} +func (p Profiler) ServeHTTP(resp http.ResponseWriter, req *http.Request) { + p.secretHandler.ServeHTTP(resp, req) } diff --git a/internal/profiler/profiler_test.go b/internal/profiler/profiler_test.go new file mode 100644 index 00000000..3ad8356c --- /dev/null +++ b/internal/profiler/profiler_test.go @@ -0,0 +1,37 @@ +package profiler + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/maxatome/go-testdeep" + "go.uber.org/zap" +) + +func TestNew(t *testing.T) { + const argName = "pass" + const pass = "qwe" + td := testdeep.NewT(t) + profiler := New(zap.NewNop(), Config{AllowedNetworks: []string{"127.0.0.1/32", "::1/128"}}) + td.Len(profiler.secretHandler.AllowedNetworks, 2) + td.NotNil(profiler.secretHandler.next) + td.NotNil(profiler.secretHandler.logger) +} + +func TestProfiler_ServeHTTP(t *testing.T) { + const argName = "pass" + const pass = "qwe" + td := testdeep.NewT(t) + profiler := New(zap.NewNop(), Config{AllowedNetworks: []string{"127.0.0.1/32", "::1/128"}}) + + respWriter := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "http://test/debug/pprof/", nil) + req.RemoteAddr = "127.0.0.1:1234" + profiler.ServeHTTP(respWriter, req) + respWriter.Flush() + resp := respWriter.Result() + td.Cmp(resp.StatusCode, http.StatusOK) + td.True(strings.Contains(resp.Header.Get("content-type"), "text/html")) +} diff --git a/internal/profiler/secret_handler.go b/internal/profiler/secret_handler.go index d349f6e2..504c0954 100644 --- a/internal/profiler/secret_handler.go +++ b/internal/profiler/secret_handler.go @@ -1,19 +1,35 @@ package profiler -import "net/http" +import ( + "net" + "net/http" + + "go.uber.org/zap" +) type secretHandler struct { - argName string - secret string - next http.Handler + AllowedNetworks []net.IPNet + logger *zap.Logger + next http.Handler } func (s secretHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) { - querySecret := req.URL.Query().Get(s.argName) - if s.secret == querySecret { - s.next.ServeHTTP(resp, req) + remoteIP, err := net.ResolveTCPAddr("tcp", req.RemoteAddr) + if err != nil { + s.logger.Error("Parse remote address", zap.String("remote_addr", req.RemoteAddr), zap.Error(err)) + http.Error(resp, "Internal error", http.StatusInternalServerError) return } + localLogger := s.logger.With(zap.Stringer("path", req.URL), zap.String("remote_addr", req.RemoteAddr)) + for _, subnet := range s.AllowedNetworks { + if subnet.Contains(remoteIP.IP) { + localLogger.Info("Profiler access") + s.next.ServeHTTP(resp, req) + return + } + } + + localLogger.Error("Profiler deny") http.Error(resp, "Forbidden", http.StatusForbidden) } diff --git a/internal/profiler/secret_handler_test.go b/internal/profiler/secret_handler_test.go index 65a32274..f098a41a 100644 --- a/internal/profiler/secret_handler_test.go +++ b/internal/profiler/secret_handler_test.go @@ -1,12 +1,14 @@ package profiler import ( + "net" "net/http" "net/http/httptest" "testing" "github.com/gojuno/minimock/v3" "github.com/maxatome/go-testdeep" + "go.uber.org/zap" ) //go:generate minimock -g -i net/http.Handler -o ./handler_mock_test.go @@ -16,6 +18,9 @@ func TestSecretHandler_ServeHTTP(t *testing.T) { mt := minimock.NewController(td) defer mt.Finish() + _, n, _ := net.ParseCIDR("1.2.3.4/32") + var localNetworks = []net.IPNet{*n} + nextHandler := NewHandlerMock(mt) nextCalled := false nextHandler.ServeHTTPMock.Set(func(resp http.ResponseWriter, req *http.Request) { @@ -25,18 +30,16 @@ func TestSecretHandler_ServeHTTP(t *testing.T) { }) defer nextHandler.MinimockFinish() - const argName = "pass" - const secret = "asd" - secretHandler := secretHandler{ - next: nextHandler, - argName: argName, - secret: secret, + next: nextHandler, + AllowedNetworks: localNetworks, + logger: zap.NewNop(), } nextCalled = false respWriter := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "http://test?pass=asd", nil) + req := httptest.NewRequest(http.MethodGet, "http://test", nil) + req.RemoteAddr = "1.2.3.4:1234" secretHandler.ServeHTTP(respWriter, req) respWriter.Flush() resp := respWriter.Result() @@ -46,6 +49,7 @@ func TestSecretHandler_ServeHTTP(t *testing.T) { nextCalled = false respWriter = httptest.NewRecorder() req = httptest.NewRequest(http.MethodGet, "http://test", nil) + req.RemoteAddr = "2.3.4.5:1234" secretHandler.ServeHTTP(respWriter, req) respWriter.Flush() resp = respWriter.Result() @@ -53,11 +57,14 @@ func TestSecretHandler_ServeHTTP(t *testing.T) { td.False(nextCalled) nextCalled = false + nextCalled = false respWriter = httptest.NewRecorder() - req = httptest.NewRequest(http.MethodGet, "http://test?pass=asdf", nil) + req = httptest.NewRequest(http.MethodGet, "http://test", nil) + req.RemoteAddr = "asdf" secretHandler.ServeHTTP(respWriter, req) respWriter.Flush() resp = respWriter.Result() - td.Cmp(resp.StatusCode, http.StatusForbidden) + td.Cmp(resp.StatusCode, http.StatusInternalServerError) td.False(nextCalled) + nextCalled = false } From b2e84a80d836e68f6e2fdb4d581cd06bef39d324 Mon Sep 17 00:00:00 2001 From: rekby Date: Sun, 24 Nov 2019 14:44:07 +0300 Subject: [PATCH 08/10] update generated code --- cmd/a_main-packr.go | 2 +- cmd/config.go | 2 +- cmd/main.go | 31 + cmd/static/default-config.toml | 10 + .../cache_bytes_mock_test.go | 504 ++++-- .../cert_manager/acme_client_mock_test.go | 1486 +++++++++++------ .../cert_manager/cache_bytes_mock_test.go | 504 ++++-- internal/cert_manager/conn_mock_test.go | 1141 ++++++++----- .../cert_manager/domain_checker_mock_test.go | 178 +- internal/cert_manager/value_mock_test.go | 504 ++++-- internal/dns/m_dns_client_mock_test.go | 179 +- internal/dns/resolver_interface_mock_test.go | 179 +- .../domain_checker_mock_test.go | 178 +- internal/domain_checker/resolver_mock_test.go | 179 +- internal/proxy/director_mock_test.go | 158 +- internal/proxy/http_proxy_test_mock_test.go | 342 ++-- .../proxy/http_round_tripper_mock_test.go | 187 ++- internal/tlslistener/net_conn_mock_test.go | 1141 ++++++++----- 18 files changed, 4350 insertions(+), 2555 deletions(-) diff --git a/cmd/a_main-packr.go b/cmd/a_main-packr.go index 8c0a5760..b4541952 100644 --- a/cmd/a_main-packr.go +++ b/cmd/a_main-packr.go @@ -7,5 +7,5 @@ import "github.com/gobuffalo/packr" // You can use the "packr clean" command to clean up this, // and any other packr generated files. func init() { - packr.PackJSONBytes("static", "default-config.toml", "\"IyMgQVRURU5USU9OCiMgaXQgaXMgZXhhbXBsZSBmaWxlIG9ubHkuIEl0IGJ1aWx0aW4gaW4gYmluYXJ5IGFuZCBkb24ndCByZWFkIGZyb20gZmlsZSBzeXN0ZW0uCiMgY2hhbmdlcyBpbiBjb25maWdfZGVmYXVsdC50b21sIGhhdmUgbm8gcmVhbCBlZmZlY3QuCgpbR2VuZXJhbF0KCiMgU2Vjb25kcyBmb3IgaXNzdWUgZXZlcnkgY2VydGlmaWNhdGUuIENhbmNlbCBpc3N1ZSBhbmQgcmV0dXJuIGVycm9yIGlmIHRpbWVvdXQuCklzc3VlVGltZW91dCA9IDMwMAoKIyBQYXRoIHRvIGRpciwgd2hpY2ggd2lsbCBzdG9yZSBzdGF0ZSBhbmQgY2VydGlmaWNhdGVzClN0b3JhZ2VEaXIgPSAic3RvcmFnZSIKCiMgU3RvcmUgLmpzb24gaW5mbyB3aXRoIGNlcnRpZmljYXRlIG1ldGFkYXRhIG5lYXIgY2VydGlmaWNhdGUuClN0b3JlSlNPTk1ldGFkYXRhID0gdHJ1ZQoKIyBEaXJlY3RvcnkgdXJsIG9mIGFjbWUgc2VydmVyLgojVGVzdCBzZXJ2ZXI6IGh0dHBzOi8vYWNtZS1zdGFnaW5nLXYwMi5hcGkubGV0c2VuY3J5cHQub3JnL2RpcmVjdG9yeQpBY21lU2VydmVyID0gImh0dHBzOi8vYWNtZS12MDIuYXBpLmxldHNlbmNyeXB0Lm9yZy9kaXJlY3RvcnkiCgojIEluY2x1ZGUgb3RoZXIgY29uZmlnIGZpbGVzCiMgSXQgc3VwcG9ydCBnbG9iIHN5bnRheAojIElmIGl0IGhhcyBwYXRoIHdpdGhvdXQgdGVtcGxhdGUgLSB0aGUgZmlsZSBtdXN0IGV4aXN0LgojIEZvciBhbGxvdyBvcHRpb25hbCBpbmNsdWRlIGZpbGUgLSBpdCBjYW4gY29udGFpbiBzb21lIGdsb2Igc3ltYm9sCiMgSW5jbHVkZWQgY29uZmlncyBtZXJnZSB3aXRoIGN1cnJlbnQgcmVhZGVkIHN0YXRlLgojIGV4YW1wbGU9WyAiY29uZmlnLnRvbVtsXSIgXQpJbmNsdWRlQ29uZmlncyA9IFtdCgojIEZvciBwcmV2ZW50IGluZmluaXRlIGxvb3AgYW5kIGNvbnN1bWUgYWxsIG1lbW9yeSBpZiBjeWNsZSBpbiBpbmNsdWRlcwpNYXhDb25maWdGaWxlc1JlYWQgPSAxMDAwMAoKW0xvZ10KRW5hYmxlTG9nVG9GaWxlID0gdHJ1ZQpFbmFibGVMb2dUb1N0ZEVyciA9IHRydWUKCiMgdmVyYm9zZSBsZXZlbCBvZiBsb2csIG9uZSBvZjogZGVidWcsIGluZm8sIHdhcm5pbmcsIGVycm9yLCBmYXRhbApMb2dMZXZlbCA9ICJpbmZvIgoKIyBFbmFibGUgc2VsZiBsb2cgcm90YXRpbmcKRW5hYmxlUm90YXRlID0gdHJ1ZQoKIyBFbmFibGUgZGV2ZWxvcGVyIG1vZGU6IG1vcmUgc3RhY2t0cmFjZXMgYW5kIHBhbmljIChzdG9wIHByb2dyYW0pIG9uIHNvbWUgaW50ZXJuYWwgZXJyb3JzLgpEZXZlbG9wZXJNb2RlID0gZmFsc2UKCiMgUGF0aCB0byBsb2cgZmlsZQpGaWxlID0gImxldHMtcHJveHkubG9nIgoKIyBSb3RhdGUgbG9nIGlmIGN1cnJlbnQgZmlsZSBzaXplIG1vcmUgdGhhbiBYIE1CClJvdGF0ZUJ5U2l6ZU1CID0gMTAwCgojIENvbXByZXNzIG9sZCBsb2cgd2l0aCBnemlwIGFmdGVyIHJvdGF0ZQpDb21wcmVzc1JvdGF0ZWQgPSBmYWxzZQoKIyBEZWxldGUgb2xkIGJhY2t1cHMgYWZ0ZXIgWCBkYXlzLiAwIGZvciBkaXNhYmxlLgpNYXhEYXlzID0gMTAKCiMgRGVsZXRlIG9sZCBiYWNrdXBzIGlmIG9sZCBmaWxlIG51bWJlciBtb3JlIHRoZW4gWC4gMCBmb3IgZGlzYWJsZS4KTWF4Q291bnQgPSAxMAoKW1Byb3h5XQoKIyBEZWZhdWx0IHJ1bGUgb2Ygc2VsZWN0IGRlc3RpbmF0aW9uIGFkZHJlc3MuCiNJdCBjYW4gYmU6IElQICh3aXRoIGRlZmF1bHQgcG9ydCA4MCksIDpQb3J0IChkZWZhdWx0IC0gc2FtZSBJUCBhcyByZWNlaXZlIGNvbm5lY3Rpb24pLCBJUHY0OlBvcnQgb3IgW0lQdjZdOlBvcnQKRGVmYXVsdFRhcmdldCA9ICI6ODAiCgojIEFmdGVyIEtlZXBBbGl2ZVRpbWVvdXRTZWNvbmRzIG9mIGluYWN0aXZlIGluY29taW5nIGNvbm5lY3Rpb24gd2lsbCBjbG9zZS4KS2VlcEFsaXZlVGltZW91dFNlY29uZHMgPSA5MDAKCiMgQXJyYXkgb2YgJy0nIHNlcGFyYXRlZCBwYWlycyBvciBJUDpQb3J0LiBGb3IgZXhhbXBsZToKIyBbCiMgICAiMS4yLjMuNDo0NDMtMi4yLjIuMjoxMjM0IiwKIyAgICIzLjMuMy4zOjMzMy1bOjoxXTo5NCIKIyAiXQojIE1lYW46IGNvbm5lY3Rpb25zLCBhY2NlcHRlZCBvbiAxLjIuMy40OjQ0MyBzZW5kIHRvIHNlcnZlciAyLjIuMi4yOjEyMzQKIyBhbmQgY29ubmVjdGlvbnMgYWNjZXB0ZWQgb24gMy4zLjMuMzozMzMgc2VuZCB0byBpcHY2IDo6MSBwb3J0IDk0ClRhcmdldE1hcCA9IFtdCgojIEFycmF5IG9mIGNvbG9uIHNlcGFyYXRlZCBIZWFkZXJOYW1lOkhlYWRlclZhbHVlIGZvciBhZGQgdG8gcmVxdWVzdCBmb3IgYmFja2VuZC4ge3tWYWx1ZX19IGlzIHNwZWNpYWwgZm9ybXMsIHdoaWNoIGNhbgojIGludGVybmFsbHkgcGFyc2luZy4gTm93IGl0IHN1cHBvcnQgb25seSBzcGVjaWFsIHZhbHVlczoKIyB7e0NPTk5FQ1RJT05fSUR9fSAtIElkIG9mIGFjY2VwdGVkIGNvbm5lY3Rpb24sIGdlbmVyYXRlZCBieSBsZXRzLXByb3h5CiMge3tIVFRQX1BST1RPfX0gLSBzZXQgdG8gaHR0cC9odHRwcyBkZXBlbmRlbmNlIGluY29taW5nIGNvbm5lY3Rpb25zIGhhbmRsZWQKIyB7e1NPVVJDRV9JUH19IC0gUmVtb3RlIElQIG9mIGluY29taW5nIGNvbm5lY3Rpb24KIyB7U09VUkNFX1BPUlR9fSAtIFJlbW90ZSBwb3J0IG9mIGluY29taW5nIGNvbm5lY3Rpb24KIyB7e1NPVVJDRV9JUH19Ont7U09VUkNFX1BPUlR9fSAtIFJlbW90ZSBJUDpQb3J0IG9mIGluY29taW5nIGNvbm5lY3Rpb24uCiMgTm93IGl0IGFjY2VwdGVkIG9ubHkgdGhpcyBzcGVjaWFsIHZhbHVlcywgd2hpY2ggbXVzdCBiZSBleGF4bHR5IGVxdWFsIHRvIGV4YW1wbGVzLiBBbGwgb3RoZXIgdmFsdWVzIHNlbmQgYXMgaXMuCiMgQnV0IGl0IGNhbiBjaGFuZ2UgYW5kIGV4dGVuZCBpbiBmdXR1cmUuIERvZXNuJ3QgdXNlIHt7Li4ufX0gYXMgb3duIHZhbHVlcy4KIyBFeGFtcGxlOgojIFsiSVA6e3tTT1VSQ0VfSVB9fSIsICJQcm94eTpsZXRzLXByb3h5IiwgIlByb3RvY29sOnt7SFRUUF9QUk9UT319IiBdCkhlYWRlcnMgPSBbXQoKW0NoZWNrRG9tYWluc10KCiMgQWxsb3cgZG9tYWluIGlmIGl0IHJlc29sdmVyIGZvciBvbmUgb2YgcHVibGljIElQcyBvZiB0aGlzIHNlcnZlci4KSVBTZWxmID0gdHJ1ZQoKIyBBbGxvdyBkb21haW4gaWYgaXQgcmVzb2x2ZXIgZm9yIG9uZSBvZiB0aGUgaXBzLgpJUFdoaXRlTGlzdCA9ICIiCgojIFJlZ2V4cCBpbiBnb2xhbmcgc3ludGF4IG9mIGJsYWNrbGlzdGVkIGRvbWFpbiBmb3IgaXNzdWUgY2VydGlmaWNhdGUuCiNUaGlzIGxpc3Qgb3ZlcnJpZGVkIGJ5IHdoaXRlbGlzdC4KQmxhY2tMaXN0ID0gIiIKCiMgUmVnZXhwIGluIGdvbGFuZyBzeW50YXggb2Ygd2hpdGVsaXN0IGRvbWFpbnMgZm9yIGlzc3VlIGNlcnRpZmljYXRlLgojV2hpdGVsaXN0IG5lZWQgZm9yIGFsbG93IHBhcnQgb2YgZG9tYWlucywgd2hpY2ggZXhjbHVkZWQgYnkgYmxhY2tsaXN0LgojCldoaXRlTGlzdCA9ICIiCgojIENvbW1hIHNlcGFyYXRlZCBkbnMgc2VydmVyLCB1c2VkIGZvciByZXNvbHZlIGlwOnBvcnQgYWRkcmVzcyBvZiBkb21haW5zIHdoaWxlIGNoZWNrIGl0LgojIGlmIGVtcHR5IC0gdXNlIHN5c3RlbSBkbnMgcmVzb2x2ZXIgKHVzdWFsbHkgaW5jbHVkZSBob3N0cyBmaWxlLCBjYWNoZSwgZXRjKQojIGlmIHNldCAtIHVzZSBkaXJlY3QgZG5zIHF1ZXJpZXMgZm9yIHNlcnZlcnMsIHdpdGhvdXQgc2VsZiBjYWNoZS4KIyBpZiBzZXQgbW9yZSwgdGhhbiBvbmUgZG5zIHNlcnZlciAtIHNlbmQgcXVlcmllcyBpbiBwYXJhbGxlbCB0byBhbGwgc2VydmVycy4KIyBlcnJvciByZXN1bHRzIGZyb20gcGFydCBvZiBzZXJ2ZXJzIC0gaWdub3JlLiBOZWVkIG1pbmltdW0gb25lIGFuc3dlci4KIyBpZiBkaWZmZXJlbnQgZG5zIHNlcnZlcnMgcmV0dXJuIGRpZmZlcmVudCBpcCBhZGRyZXNzZXMgLSBhbGwgb2YgdGhlbSB1c2UgZm9yIGNoZWNrCiMgRXhhbXBsZTogIjguOC44Ljg6NTMsMS4xLjEuMTo1Myw3Ny44OC44Ljg6NTMsWzJhMDI6NmI4OjpmZWVkOjBmZl06NTMsWzIwMDE6NDg2MDo0ODYwOjo4ODg4XTo1MyIKUmVzb2x2ZXIgPSAiIgoKCgpbTGlzdGVuXQoKIyBCaW5kIGFkZHJlc3NlcyBmb3IgVExTIGxpc3RlbmVycwpUTFNBZGRyZXNzZXMgPSBbIjo0NDMiXQoKIyBCaW5kIGFkZHJlc3NlcyB3aXRob3V0IFRMUyBzZWN1cmUgKGZvciBIVFRQIHJldmVyc2UgcHJveHkgYW5kIGh0dHAtMDEgdmFsaWRhdGlvbiB3aXRob3V0IHJlZGlyZWN0IHRvIGh0dHBzKQpUQ1BBZGRyZXNzZXMgPSBbXQo=\"") + packr.PackJSONBytes("static", "default-config.toml", "\"IyMgQVRURU5USU9OCiMgaXQgaXMgZXhhbXBsZSBmaWxlIG9ubHkuIEl0IGJ1aWx0aW4gaW4gYmluYXJ5IGFuZCBkb24ndCByZWFkIGZyb20gZmlsZSBzeXN0ZW0uCiMgY2hhbmdlcyBpbiBjb25maWdfZGVmYXVsdC50b21sIGhhdmUgbm8gcmVhbCBlZmZlY3QuCgpbR2VuZXJhbF0KCiMgU2Vjb25kcyBmb3IgaXNzdWUgZXZlcnkgY2VydGlmaWNhdGUuIENhbmNlbCBpc3N1ZSBhbmQgcmV0dXJuIGVycm9yIGlmIHRpbWVvdXQuCklzc3VlVGltZW91dCA9IDMwMAoKIyBQYXRoIHRvIGRpciwgd2hpY2ggd2lsbCBzdG9yZSBzdGF0ZSBhbmQgY2VydGlmaWNhdGVzClN0b3JhZ2VEaXIgPSAic3RvcmFnZSIKCiMgU3RvcmUgLmpzb24gaW5mbyB3aXRoIGNlcnRpZmljYXRlIG1ldGFkYXRhIG5lYXIgY2VydGlmaWNhdGUuClN0b3JlSlNPTk1ldGFkYXRhID0gdHJ1ZQoKIyBEaXJlY3RvcnkgdXJsIG9mIGFjbWUgc2VydmVyLgojVGVzdCBzZXJ2ZXI6IGh0dHBzOi8vYWNtZS1zdGFnaW5nLXYwMi5hcGkubGV0c2VuY3J5cHQub3JnL2RpcmVjdG9yeQpBY21lU2VydmVyID0gImh0dHBzOi8vYWNtZS12MDIuYXBpLmxldHNlbmNyeXB0Lm9yZy9kaXJlY3RvcnkiCgojIEluY2x1ZGUgb3RoZXIgY29uZmlnIGZpbGVzCiMgSXQgc3VwcG9ydCBnbG9iIHN5bnRheAojIElmIGl0IGhhcyBwYXRoIHdpdGhvdXQgdGVtcGxhdGUgLSB0aGUgZmlsZSBtdXN0IGV4aXN0LgojIEZvciBhbGxvdyBvcHRpb25hbCBpbmNsdWRlIGZpbGUgLSBpdCBjYW4gY29udGFpbiBzb21lIGdsb2Igc3ltYm9sCiMgSW5jbHVkZWQgY29uZmlncyBtZXJnZSB3aXRoIGN1cnJlbnQgcmVhZGVkIHN0YXRlLgojIGV4YW1wbGU9WyAiY29uZmlnLnRvbVtsXSIgXQpJbmNsdWRlQ29uZmlncyA9IFtdCgojIEZvciBwcmV2ZW50IGluZmluaXRlIGxvb3AgYW5kIGNvbnN1bWUgYWxsIG1lbW9yeSBpZiBjeWNsZSBpbiBpbmNsdWRlcwpNYXhDb25maWdGaWxlc1JlYWQgPSAxMDAwMAoKW0xvZ10KRW5hYmxlTG9nVG9GaWxlID0gdHJ1ZQpFbmFibGVMb2dUb1N0ZEVyciA9IHRydWUKCiMgdmVyYm9zZSBsZXZlbCBvZiBsb2csIG9uZSBvZjogZGVidWcsIGluZm8sIHdhcm5pbmcsIGVycm9yLCBmYXRhbApMb2dMZXZlbCA9ICJpbmZvIgoKIyBFbmFibGUgc2VsZiBsb2cgcm90YXRpbmcKRW5hYmxlUm90YXRlID0gdHJ1ZQoKIyBFbmFibGUgZGV2ZWxvcGVyIG1vZGU6IG1vcmUgc3RhY2t0cmFjZXMgYW5kIHBhbmljIChzdG9wIHByb2dyYW0pIG9uIHNvbWUgaW50ZXJuYWwgZXJyb3JzLgpEZXZlbG9wZXJNb2RlID0gZmFsc2UKCiMgUGF0aCB0byBsb2cgZmlsZQpGaWxlID0gImxldHMtcHJveHkubG9nIgoKIyBSb3RhdGUgbG9nIGlmIGN1cnJlbnQgZmlsZSBzaXplIG1vcmUgdGhhbiBYIE1CClJvdGF0ZUJ5U2l6ZU1CID0gMTAwCgojIENvbXByZXNzIG9sZCBsb2cgd2l0aCBnemlwIGFmdGVyIHJvdGF0ZQpDb21wcmVzc1JvdGF0ZWQgPSBmYWxzZQoKIyBEZWxldGUgb2xkIGJhY2t1cHMgYWZ0ZXIgWCBkYXlzLiAwIGZvciBkaXNhYmxlLgpNYXhEYXlzID0gMTAKCiMgRGVsZXRlIG9sZCBiYWNrdXBzIGlmIG9sZCBmaWxlIG51bWJlciBtb3JlIHRoZW4gWC4gMCBmb3IgZGlzYWJsZS4KTWF4Q291bnQgPSAxMAoKW1Byb3h5XQoKIyBEZWZhdWx0IHJ1bGUgb2Ygc2VsZWN0IGRlc3RpbmF0aW9uIGFkZHJlc3MuCiNJdCBjYW4gYmU6IElQICh3aXRoIGRlZmF1bHQgcG9ydCA4MCksIDpQb3J0IChkZWZhdWx0IC0gc2FtZSBJUCBhcyByZWNlaXZlIGNvbm5lY3Rpb24pLCBJUHY0OlBvcnQgb3IgW0lQdjZdOlBvcnQKRGVmYXVsdFRhcmdldCA9ICI6ODAiCgojIEFmdGVyIEtlZXBBbGl2ZVRpbWVvdXRTZWNvbmRzIG9mIGluYWN0aXZlIGluY29taW5nIGNvbm5lY3Rpb24gd2lsbCBjbG9zZS4KS2VlcEFsaXZlVGltZW91dFNlY29uZHMgPSA5MDAKCiMgQXJyYXkgb2YgJy0nIHNlcGFyYXRlZCBwYWlycyBvciBJUDpQb3J0LiBGb3IgZXhhbXBsZToKIyBbCiMgICAiMS4yLjMuNDo0NDMtMi4yLjIuMjoxMjM0IiwKIyAgICIzLjMuMy4zOjMzMy1bOjoxXTo5NCIKIyAiXQojIE1lYW46IGNvbm5lY3Rpb25zLCBhY2NlcHRlZCBvbiAxLjIuMy40OjQ0MyBzZW5kIHRvIHNlcnZlciAyLjIuMi4yOjEyMzQKIyBhbmQgY29ubmVjdGlvbnMgYWNjZXB0ZWQgb24gMy4zLjMuMzozMzMgc2VuZCB0byBpcHY2IDo6MSBwb3J0IDk0ClRhcmdldE1hcCA9IFtdCgojIEFycmF5IG9mIGNvbG9uIHNlcGFyYXRlZCBIZWFkZXJOYW1lOkhlYWRlclZhbHVlIGZvciBhZGQgdG8gcmVxdWVzdCBmb3IgYmFja2VuZC4ge3tWYWx1ZX19IGlzIHNwZWNpYWwgZm9ybXMsIHdoaWNoIGNhbgojIGludGVybmFsbHkgcGFyc2luZy4gTm93IGl0IHN1cHBvcnQgb25seSBzcGVjaWFsIHZhbHVlczoKIyB7e0NPTk5FQ1RJT05fSUR9fSAtIElkIG9mIGFjY2VwdGVkIGNvbm5lY3Rpb24sIGdlbmVyYXRlZCBieSBsZXRzLXByb3h5CiMge3tIVFRQX1BST1RPfX0gLSBzZXQgdG8gaHR0cC9odHRwcyBkZXBlbmRlbmNlIGluY29taW5nIGNvbm5lY3Rpb25zIGhhbmRsZWQKIyB7e1NPVVJDRV9JUH19IC0gUmVtb3RlIElQIG9mIGluY29taW5nIGNvbm5lY3Rpb24KIyB7U09VUkNFX1BPUlR9fSAtIFJlbW90ZSBwb3J0IG9mIGluY29taW5nIGNvbm5lY3Rpb24KIyB7e1NPVVJDRV9JUH19Ont7U09VUkNFX1BPUlR9fSAtIFJlbW90ZSBJUDpQb3J0IG9mIGluY29taW5nIGNvbm5lY3Rpb24uCiMgTm93IGl0IGFjY2VwdGVkIG9ubHkgdGhpcyBzcGVjaWFsIHZhbHVlcywgd2hpY2ggbXVzdCBiZSBleGF4bHR5IGVxdWFsIHRvIGV4YW1wbGVzLiBBbGwgb3RoZXIgdmFsdWVzIHNlbmQgYXMgaXMuCiMgQnV0IGl0IGNhbiBjaGFuZ2UgYW5kIGV4dGVuZCBpbiBmdXR1cmUuIERvZXNuJ3QgdXNlIHt7Li4ufX0gYXMgb3duIHZhbHVlcy4KIyBFeGFtcGxlOgojIFsiSVA6e3tTT1VSQ0VfSVB9fSIsICJQcm94eTpsZXRzLXByb3h5IiwgIlByb3RvY29sOnt7SFRUUF9QUk9UT319IiBdCkhlYWRlcnMgPSBbXQoKW0NoZWNrRG9tYWluc10KCiMgQWxsb3cgZG9tYWluIGlmIGl0IHJlc29sdmVyIGZvciBvbmUgb2YgcHVibGljIElQcyBvZiB0aGlzIHNlcnZlci4KSVBTZWxmID0gdHJ1ZQoKIyBBbGxvdyBkb21haW4gaWYgaXQgcmVzb2x2ZXIgZm9yIG9uZSBvZiB0aGUgaXBzLgpJUFdoaXRlTGlzdCA9ICIiCgojIFJlZ2V4cCBpbiBnb2xhbmcgc3ludGF4IG9mIGJsYWNrbGlzdGVkIGRvbWFpbiBmb3IgaXNzdWUgY2VydGlmaWNhdGUuCiNUaGlzIGxpc3Qgb3ZlcnJpZGVkIGJ5IHdoaXRlbGlzdC4KQmxhY2tMaXN0ID0gIiIKCiMgUmVnZXhwIGluIGdvbGFuZyBzeW50YXggb2Ygd2hpdGVsaXN0IGRvbWFpbnMgZm9yIGlzc3VlIGNlcnRpZmljYXRlLgojV2hpdGVsaXN0IG5lZWQgZm9yIGFsbG93IHBhcnQgb2YgZG9tYWlucywgd2hpY2ggZXhjbHVkZWQgYnkgYmxhY2tsaXN0LgojCldoaXRlTGlzdCA9ICIiCgojIENvbW1hIHNlcGFyYXRlZCBkbnMgc2VydmVyLCB1c2VkIGZvciByZXNvbHZlIGlwOnBvcnQgYWRkcmVzcyBvZiBkb21haW5zIHdoaWxlIGNoZWNrIGl0LgojIGlmIGVtcHR5IC0gdXNlIHN5c3RlbSBkbnMgcmVzb2x2ZXIgKHVzdWFsbHkgaW5jbHVkZSBob3N0cyBmaWxlLCBjYWNoZSwgZXRjKQojIGlmIHNldCAtIHVzZSBkaXJlY3QgZG5zIHF1ZXJpZXMgZm9yIHNlcnZlcnMsIHdpdGhvdXQgc2VsZiBjYWNoZS4KIyBpZiBzZXQgbW9yZSwgdGhhbiBvbmUgZG5zIHNlcnZlciAtIHNlbmQgcXVlcmllcyBpbiBwYXJhbGxlbCB0byBhbGwgc2VydmVycy4KIyBlcnJvciByZXN1bHRzIGZyb20gcGFydCBvZiBzZXJ2ZXJzIC0gaWdub3JlLiBOZWVkIG1pbmltdW0gb25lIGFuc3dlci4KIyBpZiBkaWZmZXJlbnQgZG5zIHNlcnZlcnMgcmV0dXJuIGRpZmZlcmVudCBpcCBhZGRyZXNzZXMgLSBhbGwgb2YgdGhlbSB1c2UgZm9yIGNoZWNrCiMgRXhhbXBsZTogIjguOC44Ljg6NTMsMS4xLjEuMTo1Myw3Ny44OC44Ljg6NTMsWzJhMDI6NmI4OjpmZWVkOjBmZl06NTMsWzIwMDE6NDg2MDo0ODYwOjo4ODg4XTo1MyIKUmVzb2x2ZXIgPSAiIgoKCgpbTGlzdGVuXQoKIyBCaW5kIGFkZHJlc3NlcyBmb3IgVExTIGxpc3RlbmVycwpUTFNBZGRyZXNzZXMgPSBbIjo0NDMiXQoKIyBCaW5kIGFkZHJlc3NlcyB3aXRob3V0IFRMUyBzZWN1cmUgKGZvciBIVFRQIHJldmVyc2UgcHJveHkgYW5kIGh0dHAtMDEgdmFsaWRhdGlvbiB3aXRob3V0IHJlZGlyZWN0IHRvIGh0dHBzKQpUQ1BBZGRyZXNzZXMgPSBbXQoKW1Byb2ZpbGVyXQpFbmFibGUgPSBmYWxzZQoKIyBJUCBuZXR3b3JrcyBmb3IgYWxsb3cgdG8gdXNlIHByb2ZpbGVyLgojIERlZmF1bHQgLSBkZW55IGZyb20gYWxsLgojIEV4YW1wbGU6CiMgWyAiMS4yLjMuNC8zMiIsICIxOTIuMTY4LjAuMC8yNCIsICI6OjEvMTI4IiBdCkFsbG93ZWROZXR3b3JrcyA9IFtdCkJpbmRBZGRyZXNzID0gImxvY2FsaG9zdDozMTM0NCIK\"") } diff --git a/cmd/config.go b/cmd/config.go index a1f5e329..5ded6b61 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -32,7 +32,6 @@ type ConfigGeneral struct { StoreJSONMetadata bool IncludeConfigs []string MaxConfigFilesRead int - Profiler profiler.Config } //go:generate packr @@ -42,6 +41,7 @@ type configType struct { Proxy proxy.Config CheckDomains domain_checker.Config Listen tlslistener.Config + Profiler profiler.Config } //nolint:maligned diff --git a/cmd/main.go b/cmd/main.go index e3337c16..81d17d50 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -10,7 +10,10 @@ import ( "runtime" "time" + "go.uber.org/zap/zapcore" + "github.com/rekby/lets-proxy2/internal/cert_manager" + "github.com/rekby/lets-proxy2/internal/profiler" _ "github.com/kardianos/minwinsvc" "github.com/rekby/lets-proxy2/internal/acme_client_manager" @@ -57,6 +60,8 @@ func startProgram(config *configType) { logger.Info("StartAutoRenew program version", zap.String("version", version())) + startProfiler(ctx, config.Profiler) + err := os.MkdirAll(config.General.StorageDir, defaultDirMode) log.InfoFatal(logger, err, "Create storage dir", zap.String("dir", config.General.StorageDir)) @@ -98,3 +103,29 @@ func startProgram(config *configType) { } log.DebugErrorCtx(ctx, effectiveError, "Handle request stopped") } + +func startProfiler(ctx context.Context, config profiler.Config) { + logger := zc.L(ctx) + + if !config.Enable { + logger.Info("Profiler disabled") + return + } + + go func() { + httpServer := http.Server{ + Addr: config.BindAddress, + Handler: profiler.New(logger.Named("profiler"), config), + } + + logger.Info("Start profiler", zap.String("bind_address", httpServer.Addr)) + err := httpServer.ListenAndServe() + var logLevel zapcore.Level + if err == http.ErrServerClosed { + logLevel = zapcore.InfoLevel + } else { + logLevel = zapcore.ErrorLevel + } + log.LevelParam(logger, logLevel, "Profiler stopped") + }() +} diff --git a/cmd/static/default-config.toml b/cmd/static/default-config.toml index 7013846b..bacfab9f 100644 --- a/cmd/static/default-config.toml +++ b/cmd/static/default-config.toml @@ -122,3 +122,13 @@ TLSAddresses = [":443"] # Bind addresses without TLS secure (for HTTP reverse proxy and http-01 validation without redirect to https) TCPAddresses = [] + +[Profiler] +Enable = false + +# IP networks for allow to use profiler. +# Default - deny from all. +# Example: +# [ "1.2.3.4/32", "192.168.0.0/24", "::1/128" ] +AllowedNetworks = [] +BindAddress = "localhost:31344" diff --git a/internal/acme_client_manager/cache_bytes_mock_test.go b/internal/acme_client_manager/cache_bytes_mock_test.go index 2eb22fce..ef70dc35 100644 --- a/internal/acme_client_manager/cache_bytes_mock_test.go +++ b/internal/acme_client_manager/cache_bytes_mock_test.go @@ -1,15 +1,14 @@ package acme_client_manager -// DO NOT EDIT! -// The code below was generated with http://github.com/gojuno/minimock (dev) +// Code generated by http://github.com/gojuno/minimock (3.0.6). DO NOT EDIT. //go:generate minimock -i github.com/rekby/lets-proxy2/internal/cache.Bytes -o ./cache_bytes_mock_test.go import ( - "sync/atomic" - "time" - "context" + "sync" + mm_atomic "sync/atomic" + mm_time "time" "github.com/gojuno/minimock/v3" ) @@ -19,16 +18,19 @@ type BytesMock struct { t minimock.Tester funcDelete func(ctx context.Context, key string) (err error) + inspectFuncDelete func(ctx context.Context, key string) afterDeleteCounter uint64 beforeDeleteCounter uint64 DeleteMock mBytesMockDelete funcGet func(ctx context.Context, key string) (ba1 []byte, err error) + inspectFuncGet func(ctx context.Context, key string) afterGetCounter uint64 beforeGetCounter uint64 GetMock mBytesMockGet funcPut func(ctx context.Context, key string, data []byte) (err error) + inspectFuncPut func(ctx context.Context, key string, data []byte) afterPutCounter uint64 beforePutCounter uint64 PutMock mBytesMockPut @@ -40,9 +42,15 @@ func NewBytesMock(t minimock.Tester) *BytesMock { if controller, ok := t.(minimock.MockController); ok { controller.RegisterMocker(m) } + m.DeleteMock = mBytesMockDelete{mock: m} + m.DeleteMock.callArgs = []*BytesMockDeleteParams{} + m.GetMock = mBytesMockGet{mock: m} + m.GetMock.callArgs = []*BytesMockGetParams{} + m.PutMock = mBytesMockPut{mock: m} + m.PutMock.callArgs = []*BytesMockPutParams{} return m } @@ -51,6 +59,9 @@ type mBytesMockDelete struct { mock *BytesMock defaultExpectation *BytesMockDeleteExpectation expectations []*BytesMockDeleteExpectation + + callArgs []*BytesMockDeleteParams + mutex sync.RWMutex } // BytesMockDeleteExpectation specifies expectation struct of the Bytes.Delete @@ -73,64 +84,75 @@ type BytesMockDeleteResults struct { } // Expect sets up expected params for Bytes.Delete -func (m *mBytesMockDelete) Expect(ctx context.Context, key string) *mBytesMockDelete { - if m.mock.funcDelete != nil { - m.mock.t.Fatalf("BytesMock.Delete mock is already set by Set") +func (mmDelete *mBytesMockDelete) Expect(ctx context.Context, key string) *mBytesMockDelete { + if mmDelete.mock.funcDelete != nil { + mmDelete.mock.t.Fatalf("BytesMock.Delete mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &BytesMockDeleteExpectation{} + if mmDelete.defaultExpectation == nil { + mmDelete.defaultExpectation = &BytesMockDeleteExpectation{} } - m.defaultExpectation.params = &BytesMockDeleteParams{ctx, key} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmDelete.defaultExpectation.params = &BytesMockDeleteParams{ctx, key} + for _, e := range mmDelete.expectations { + if minimock.Equal(e.params, mmDelete.defaultExpectation.params) { + mmDelete.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmDelete.defaultExpectation.params) } } - return m + return mmDelete +} + +// Inspect accepts an inspector function that has same arguments as the Bytes.Delete +func (mmDelete *mBytesMockDelete) Inspect(f func(ctx context.Context, key string)) *mBytesMockDelete { + if mmDelete.mock.inspectFuncDelete != nil { + mmDelete.mock.t.Fatalf("Inspect function is already set for BytesMock.Delete") + } + + mmDelete.mock.inspectFuncDelete = f + + return mmDelete } // Return sets up results that will be returned by Bytes.Delete -func (m *mBytesMockDelete) Return(err error) *BytesMock { - if m.mock.funcDelete != nil { - m.mock.t.Fatalf("BytesMock.Delete mock is already set by Set") +func (mmDelete *mBytesMockDelete) Return(err error) *BytesMock { + if mmDelete.mock.funcDelete != nil { + mmDelete.mock.t.Fatalf("BytesMock.Delete mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &BytesMockDeleteExpectation{mock: m.mock} + if mmDelete.defaultExpectation == nil { + mmDelete.defaultExpectation = &BytesMockDeleteExpectation{mock: mmDelete.mock} } - m.defaultExpectation.results = &BytesMockDeleteResults{err} - return m.mock + mmDelete.defaultExpectation.results = &BytesMockDeleteResults{err} + return mmDelete.mock } //Set uses given function f to mock the Bytes.Delete method -func (m *mBytesMockDelete) Set(f func(ctx context.Context, key string) (err error)) *BytesMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Bytes.Delete method") +func (mmDelete *mBytesMockDelete) Set(f func(ctx context.Context, key string) (err error)) *BytesMock { + if mmDelete.defaultExpectation != nil { + mmDelete.mock.t.Fatalf("Default expectation is already set for the Bytes.Delete method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Bytes.Delete method") + if len(mmDelete.expectations) > 0 { + mmDelete.mock.t.Fatalf("Some expectations are already set for the Bytes.Delete method") } - m.mock.funcDelete = f - return m.mock + mmDelete.mock.funcDelete = f + return mmDelete.mock } // When sets expectation for the Bytes.Delete which will trigger the result defined by the following // Then helper -func (m *mBytesMockDelete) When(ctx context.Context, key string) *BytesMockDeleteExpectation { - if m.mock.funcDelete != nil { - m.mock.t.Fatalf("BytesMock.Delete mock is already set by Set") +func (mmDelete *mBytesMockDelete) When(ctx context.Context, key string) *BytesMockDeleteExpectation { + if mmDelete.mock.funcDelete != nil { + mmDelete.mock.t.Fatalf("BytesMock.Delete mock is already set by Set") } expectation := &BytesMockDeleteExpectation{ - mock: m.mock, + mock: mmDelete.mock, params: &BytesMockDeleteParams{ctx, key}, } - m.expectations = append(m.expectations, expectation) + mmDelete.expectations = append(mmDelete.expectations, expectation) return expectation } @@ -141,63 +163,87 @@ func (e *BytesMockDeleteExpectation) Then(err error) *BytesMock { } // Delete implements cache.Bytes -func (m *BytesMock) Delete(ctx context.Context, key string) (err error) { - atomic.AddUint64(&m.beforeDeleteCounter, 1) - defer atomic.AddUint64(&m.afterDeleteCounter, 1) +func (mmDelete *BytesMock) Delete(ctx context.Context, key string) (err error) { + mm_atomic.AddUint64(&mmDelete.beforeDeleteCounter, 1) + defer mm_atomic.AddUint64(&mmDelete.afterDeleteCounter, 1) - for _, e := range m.DeleteMock.expectations { - if minimock.Equal(*e.params, BytesMockDeleteParams{ctx, key}) { - atomic.AddUint64(&e.Counter, 1) + if mmDelete.inspectFuncDelete != nil { + mmDelete.inspectFuncDelete(ctx, key) + } + + mm_params := &BytesMockDeleteParams{ctx, key} + + // Record call args + mmDelete.DeleteMock.mutex.Lock() + mmDelete.DeleteMock.callArgs = append(mmDelete.DeleteMock.callArgs, mm_params) + mmDelete.DeleteMock.mutex.Unlock() + + for _, e := range mmDelete.DeleteMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.err } } - if m.DeleteMock.defaultExpectation != nil { - atomic.AddUint64(&m.DeleteMock.defaultExpectation.Counter, 1) - want := m.DeleteMock.defaultExpectation.params - got := BytesMockDeleteParams{ctx, key} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("BytesMock.Delete got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmDelete.DeleteMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmDelete.DeleteMock.defaultExpectation.Counter, 1) + mm_want := mmDelete.DeleteMock.defaultExpectation.params + mm_got := BytesMockDeleteParams{ctx, key} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmDelete.t.Errorf("BytesMock.Delete got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.DeleteMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the BytesMock.Delete") + mm_results := mmDelete.DeleteMock.defaultExpectation.results + if mm_results == nil { + mmDelete.t.Fatal("No results are set for the BytesMock.Delete") } - return (*results).err + return (*mm_results).err } - if m.funcDelete != nil { - return m.funcDelete(ctx, key) + if mmDelete.funcDelete != nil { + return mmDelete.funcDelete(ctx, key) } - m.t.Fatalf("Unexpected call to BytesMock.Delete. %v %v", ctx, key) + mmDelete.t.Fatalf("Unexpected call to BytesMock.Delete. %v %v", ctx, key) return } // DeleteAfterCounter returns a count of finished BytesMock.Delete invocations -func (m *BytesMock) DeleteAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterDeleteCounter) +func (mmDelete *BytesMock) DeleteAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmDelete.afterDeleteCounter) } // DeleteBeforeCounter returns a count of BytesMock.Delete invocations -func (m *BytesMock) DeleteBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeDeleteCounter) +func (mmDelete *BytesMock) DeleteBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmDelete.beforeDeleteCounter) +} + +// Calls returns a list of arguments used in each call to BytesMock.Delete. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmDelete *mBytesMockDelete) Calls() []*BytesMockDeleteParams { + mmDelete.mutex.RLock() + + argCopy := make([]*BytesMockDeleteParams, len(mmDelete.callArgs)) + copy(argCopy, mmDelete.callArgs) + + mmDelete.mutex.RUnlock() + + return argCopy } // MinimockDeleteDone returns true if the count of the Delete invocations corresponds // the number of defined expectations func (m *BytesMock) MinimockDeleteDone() bool { for _, e := range m.DeleteMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.DeleteMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterDeleteCounter) < 1 { + if m.DeleteMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterDeleteCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcDelete != nil && atomic.LoadUint64(&m.afterDeleteCounter) < 1 { + if m.funcDelete != nil && mm_atomic.LoadUint64(&m.afterDeleteCounter) < 1 { return false } return true @@ -206,17 +252,21 @@ func (m *BytesMock) MinimockDeleteDone() bool { // MinimockDeleteInspect logs each unmet expectation func (m *BytesMock) MinimockDeleteInspect() { for _, e := range m.DeleteMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to BytesMock.Delete with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.DeleteMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterDeleteCounter) < 1 { - m.t.Errorf("Expected call to BytesMock.Delete with params: %#v", *m.DeleteMock.defaultExpectation.params) + if m.DeleteMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterDeleteCounter) < 1 { + if m.DeleteMock.defaultExpectation.params == nil { + m.t.Error("Expected call to BytesMock.Delete") + } else { + m.t.Errorf("Expected call to BytesMock.Delete with params: %#v", *m.DeleteMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcDelete != nil && atomic.LoadUint64(&m.afterDeleteCounter) < 1 { + if m.funcDelete != nil && mm_atomic.LoadUint64(&m.afterDeleteCounter) < 1 { m.t.Error("Expected call to BytesMock.Delete") } } @@ -225,6 +275,9 @@ type mBytesMockGet struct { mock *BytesMock defaultExpectation *BytesMockGetExpectation expectations []*BytesMockGetExpectation + + callArgs []*BytesMockGetParams + mutex sync.RWMutex } // BytesMockGetExpectation specifies expectation struct of the Bytes.Get @@ -248,64 +301,75 @@ type BytesMockGetResults struct { } // Expect sets up expected params for Bytes.Get -func (m *mBytesMockGet) Expect(ctx context.Context, key string) *mBytesMockGet { - if m.mock.funcGet != nil { - m.mock.t.Fatalf("BytesMock.Get mock is already set by Set") +func (mmGet *mBytesMockGet) Expect(ctx context.Context, key string) *mBytesMockGet { + if mmGet.mock.funcGet != nil { + mmGet.mock.t.Fatalf("BytesMock.Get mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &BytesMockGetExpectation{} + if mmGet.defaultExpectation == nil { + mmGet.defaultExpectation = &BytesMockGetExpectation{} } - m.defaultExpectation.params = &BytesMockGetParams{ctx, key} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmGet.defaultExpectation.params = &BytesMockGetParams{ctx, key} + for _, e := range mmGet.expectations { + if minimock.Equal(e.params, mmGet.defaultExpectation.params) { + mmGet.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmGet.defaultExpectation.params) } } - return m + return mmGet +} + +// Inspect accepts an inspector function that has same arguments as the Bytes.Get +func (mmGet *mBytesMockGet) Inspect(f func(ctx context.Context, key string)) *mBytesMockGet { + if mmGet.mock.inspectFuncGet != nil { + mmGet.mock.t.Fatalf("Inspect function is already set for BytesMock.Get") + } + + mmGet.mock.inspectFuncGet = f + + return mmGet } // Return sets up results that will be returned by Bytes.Get -func (m *mBytesMockGet) Return(ba1 []byte, err error) *BytesMock { - if m.mock.funcGet != nil { - m.mock.t.Fatalf("BytesMock.Get mock is already set by Set") +func (mmGet *mBytesMockGet) Return(ba1 []byte, err error) *BytesMock { + if mmGet.mock.funcGet != nil { + mmGet.mock.t.Fatalf("BytesMock.Get mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &BytesMockGetExpectation{mock: m.mock} + if mmGet.defaultExpectation == nil { + mmGet.defaultExpectation = &BytesMockGetExpectation{mock: mmGet.mock} } - m.defaultExpectation.results = &BytesMockGetResults{ba1, err} - return m.mock + mmGet.defaultExpectation.results = &BytesMockGetResults{ba1, err} + return mmGet.mock } //Set uses given function f to mock the Bytes.Get method -func (m *mBytesMockGet) Set(f func(ctx context.Context, key string) (ba1 []byte, err error)) *BytesMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Bytes.Get method") +func (mmGet *mBytesMockGet) Set(f func(ctx context.Context, key string) (ba1 []byte, err error)) *BytesMock { + if mmGet.defaultExpectation != nil { + mmGet.mock.t.Fatalf("Default expectation is already set for the Bytes.Get method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Bytes.Get method") + if len(mmGet.expectations) > 0 { + mmGet.mock.t.Fatalf("Some expectations are already set for the Bytes.Get method") } - m.mock.funcGet = f - return m.mock + mmGet.mock.funcGet = f + return mmGet.mock } // When sets expectation for the Bytes.Get which will trigger the result defined by the following // Then helper -func (m *mBytesMockGet) When(ctx context.Context, key string) *BytesMockGetExpectation { - if m.mock.funcGet != nil { - m.mock.t.Fatalf("BytesMock.Get mock is already set by Set") +func (mmGet *mBytesMockGet) When(ctx context.Context, key string) *BytesMockGetExpectation { + if mmGet.mock.funcGet != nil { + mmGet.mock.t.Fatalf("BytesMock.Get mock is already set by Set") } expectation := &BytesMockGetExpectation{ - mock: m.mock, + mock: mmGet.mock, params: &BytesMockGetParams{ctx, key}, } - m.expectations = append(m.expectations, expectation) + mmGet.expectations = append(mmGet.expectations, expectation) return expectation } @@ -316,63 +380,87 @@ func (e *BytesMockGetExpectation) Then(ba1 []byte, err error) *BytesMock { } // Get implements cache.Bytes -func (m *BytesMock) Get(ctx context.Context, key string) (ba1 []byte, err error) { - atomic.AddUint64(&m.beforeGetCounter, 1) - defer atomic.AddUint64(&m.afterGetCounter, 1) +func (mmGet *BytesMock) Get(ctx context.Context, key string) (ba1 []byte, err error) { + mm_atomic.AddUint64(&mmGet.beforeGetCounter, 1) + defer mm_atomic.AddUint64(&mmGet.afterGetCounter, 1) - for _, e := range m.GetMock.expectations { - if minimock.Equal(*e.params, BytesMockGetParams{ctx, key}) { - atomic.AddUint64(&e.Counter, 1) + if mmGet.inspectFuncGet != nil { + mmGet.inspectFuncGet(ctx, key) + } + + mm_params := &BytesMockGetParams{ctx, key} + + // Record call args + mmGet.GetMock.mutex.Lock() + mmGet.GetMock.callArgs = append(mmGet.GetMock.callArgs, mm_params) + mmGet.GetMock.mutex.Unlock() + + for _, e := range mmGet.GetMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.ba1, e.results.err } } - if m.GetMock.defaultExpectation != nil { - atomic.AddUint64(&m.GetMock.defaultExpectation.Counter, 1) - want := m.GetMock.defaultExpectation.params - got := BytesMockGetParams{ctx, key} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("BytesMock.Get got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmGet.GetMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmGet.GetMock.defaultExpectation.Counter, 1) + mm_want := mmGet.GetMock.defaultExpectation.params + mm_got := BytesMockGetParams{ctx, key} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmGet.t.Errorf("BytesMock.Get got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.GetMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the BytesMock.Get") + mm_results := mmGet.GetMock.defaultExpectation.results + if mm_results == nil { + mmGet.t.Fatal("No results are set for the BytesMock.Get") } - return (*results).ba1, (*results).err + return (*mm_results).ba1, (*mm_results).err } - if m.funcGet != nil { - return m.funcGet(ctx, key) + if mmGet.funcGet != nil { + return mmGet.funcGet(ctx, key) } - m.t.Fatalf("Unexpected call to BytesMock.Get. %v %v", ctx, key) + mmGet.t.Fatalf("Unexpected call to BytesMock.Get. %v %v", ctx, key) return } // GetAfterCounter returns a count of finished BytesMock.Get invocations -func (m *BytesMock) GetAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterGetCounter) +func (mmGet *BytesMock) GetAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmGet.afterGetCounter) } // GetBeforeCounter returns a count of BytesMock.Get invocations -func (m *BytesMock) GetBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeGetCounter) +func (mmGet *BytesMock) GetBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmGet.beforeGetCounter) +} + +// Calls returns a list of arguments used in each call to BytesMock.Get. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmGet *mBytesMockGet) Calls() []*BytesMockGetParams { + mmGet.mutex.RLock() + + argCopy := make([]*BytesMockGetParams, len(mmGet.callArgs)) + copy(argCopy, mmGet.callArgs) + + mmGet.mutex.RUnlock() + + return argCopy } // MinimockGetDone returns true if the count of the Get invocations corresponds // the number of defined expectations func (m *BytesMock) MinimockGetDone() bool { for _, e := range m.GetMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.GetMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterGetCounter) < 1 { + if m.GetMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterGetCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcGet != nil && atomic.LoadUint64(&m.afterGetCounter) < 1 { + if m.funcGet != nil && mm_atomic.LoadUint64(&m.afterGetCounter) < 1 { return false } return true @@ -381,17 +469,21 @@ func (m *BytesMock) MinimockGetDone() bool { // MinimockGetInspect logs each unmet expectation func (m *BytesMock) MinimockGetInspect() { for _, e := range m.GetMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to BytesMock.Get with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.GetMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterGetCounter) < 1 { - m.t.Errorf("Expected call to BytesMock.Get with params: %#v", *m.GetMock.defaultExpectation.params) + if m.GetMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterGetCounter) < 1 { + if m.GetMock.defaultExpectation.params == nil { + m.t.Error("Expected call to BytesMock.Get") + } else { + m.t.Errorf("Expected call to BytesMock.Get with params: %#v", *m.GetMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcGet != nil && atomic.LoadUint64(&m.afterGetCounter) < 1 { + if m.funcGet != nil && mm_atomic.LoadUint64(&m.afterGetCounter) < 1 { m.t.Error("Expected call to BytesMock.Get") } } @@ -400,6 +492,9 @@ type mBytesMockPut struct { mock *BytesMock defaultExpectation *BytesMockPutExpectation expectations []*BytesMockPutExpectation + + callArgs []*BytesMockPutParams + mutex sync.RWMutex } // BytesMockPutExpectation specifies expectation struct of the Bytes.Put @@ -423,64 +518,75 @@ type BytesMockPutResults struct { } // Expect sets up expected params for Bytes.Put -func (m *mBytesMockPut) Expect(ctx context.Context, key string, data []byte) *mBytesMockPut { - if m.mock.funcPut != nil { - m.mock.t.Fatalf("BytesMock.Put mock is already set by Set") +func (mmPut *mBytesMockPut) Expect(ctx context.Context, key string, data []byte) *mBytesMockPut { + if mmPut.mock.funcPut != nil { + mmPut.mock.t.Fatalf("BytesMock.Put mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &BytesMockPutExpectation{} + if mmPut.defaultExpectation == nil { + mmPut.defaultExpectation = &BytesMockPutExpectation{} } - m.defaultExpectation.params = &BytesMockPutParams{ctx, key, data} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmPut.defaultExpectation.params = &BytesMockPutParams{ctx, key, data} + for _, e := range mmPut.expectations { + if minimock.Equal(e.params, mmPut.defaultExpectation.params) { + mmPut.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmPut.defaultExpectation.params) } } - return m + return mmPut +} + +// Inspect accepts an inspector function that has same arguments as the Bytes.Put +func (mmPut *mBytesMockPut) Inspect(f func(ctx context.Context, key string, data []byte)) *mBytesMockPut { + if mmPut.mock.inspectFuncPut != nil { + mmPut.mock.t.Fatalf("Inspect function is already set for BytesMock.Put") + } + + mmPut.mock.inspectFuncPut = f + + return mmPut } // Return sets up results that will be returned by Bytes.Put -func (m *mBytesMockPut) Return(err error) *BytesMock { - if m.mock.funcPut != nil { - m.mock.t.Fatalf("BytesMock.Put mock is already set by Set") +func (mmPut *mBytesMockPut) Return(err error) *BytesMock { + if mmPut.mock.funcPut != nil { + mmPut.mock.t.Fatalf("BytesMock.Put mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &BytesMockPutExpectation{mock: m.mock} + if mmPut.defaultExpectation == nil { + mmPut.defaultExpectation = &BytesMockPutExpectation{mock: mmPut.mock} } - m.defaultExpectation.results = &BytesMockPutResults{err} - return m.mock + mmPut.defaultExpectation.results = &BytesMockPutResults{err} + return mmPut.mock } //Set uses given function f to mock the Bytes.Put method -func (m *mBytesMockPut) Set(f func(ctx context.Context, key string, data []byte) (err error)) *BytesMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Bytes.Put method") +func (mmPut *mBytesMockPut) Set(f func(ctx context.Context, key string, data []byte) (err error)) *BytesMock { + if mmPut.defaultExpectation != nil { + mmPut.mock.t.Fatalf("Default expectation is already set for the Bytes.Put method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Bytes.Put method") + if len(mmPut.expectations) > 0 { + mmPut.mock.t.Fatalf("Some expectations are already set for the Bytes.Put method") } - m.mock.funcPut = f - return m.mock + mmPut.mock.funcPut = f + return mmPut.mock } // When sets expectation for the Bytes.Put which will trigger the result defined by the following // Then helper -func (m *mBytesMockPut) When(ctx context.Context, key string, data []byte) *BytesMockPutExpectation { - if m.mock.funcPut != nil { - m.mock.t.Fatalf("BytesMock.Put mock is already set by Set") +func (mmPut *mBytesMockPut) When(ctx context.Context, key string, data []byte) *BytesMockPutExpectation { + if mmPut.mock.funcPut != nil { + mmPut.mock.t.Fatalf("BytesMock.Put mock is already set by Set") } expectation := &BytesMockPutExpectation{ - mock: m.mock, + mock: mmPut.mock, params: &BytesMockPutParams{ctx, key, data}, } - m.expectations = append(m.expectations, expectation) + mmPut.expectations = append(mmPut.expectations, expectation) return expectation } @@ -491,63 +597,87 @@ func (e *BytesMockPutExpectation) Then(err error) *BytesMock { } // Put implements cache.Bytes -func (m *BytesMock) Put(ctx context.Context, key string, data []byte) (err error) { - atomic.AddUint64(&m.beforePutCounter, 1) - defer atomic.AddUint64(&m.afterPutCounter, 1) +func (mmPut *BytesMock) Put(ctx context.Context, key string, data []byte) (err error) { + mm_atomic.AddUint64(&mmPut.beforePutCounter, 1) + defer mm_atomic.AddUint64(&mmPut.afterPutCounter, 1) - for _, e := range m.PutMock.expectations { - if minimock.Equal(*e.params, BytesMockPutParams{ctx, key, data}) { - atomic.AddUint64(&e.Counter, 1) + if mmPut.inspectFuncPut != nil { + mmPut.inspectFuncPut(ctx, key, data) + } + + mm_params := &BytesMockPutParams{ctx, key, data} + + // Record call args + mmPut.PutMock.mutex.Lock() + mmPut.PutMock.callArgs = append(mmPut.PutMock.callArgs, mm_params) + mmPut.PutMock.mutex.Unlock() + + for _, e := range mmPut.PutMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.err } } - if m.PutMock.defaultExpectation != nil { - atomic.AddUint64(&m.PutMock.defaultExpectation.Counter, 1) - want := m.PutMock.defaultExpectation.params - got := BytesMockPutParams{ctx, key, data} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("BytesMock.Put got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmPut.PutMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmPut.PutMock.defaultExpectation.Counter, 1) + mm_want := mmPut.PutMock.defaultExpectation.params + mm_got := BytesMockPutParams{ctx, key, data} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmPut.t.Errorf("BytesMock.Put got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.PutMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the BytesMock.Put") + mm_results := mmPut.PutMock.defaultExpectation.results + if mm_results == nil { + mmPut.t.Fatal("No results are set for the BytesMock.Put") } - return (*results).err + return (*mm_results).err } - if m.funcPut != nil { - return m.funcPut(ctx, key, data) + if mmPut.funcPut != nil { + return mmPut.funcPut(ctx, key, data) } - m.t.Fatalf("Unexpected call to BytesMock.Put. %v %v %v", ctx, key, data) + mmPut.t.Fatalf("Unexpected call to BytesMock.Put. %v %v %v", ctx, key, data) return } // PutAfterCounter returns a count of finished BytesMock.Put invocations -func (m *BytesMock) PutAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterPutCounter) +func (mmPut *BytesMock) PutAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmPut.afterPutCounter) } // PutBeforeCounter returns a count of BytesMock.Put invocations -func (m *BytesMock) PutBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforePutCounter) +func (mmPut *BytesMock) PutBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmPut.beforePutCounter) +} + +// Calls returns a list of arguments used in each call to BytesMock.Put. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmPut *mBytesMockPut) Calls() []*BytesMockPutParams { + mmPut.mutex.RLock() + + argCopy := make([]*BytesMockPutParams, len(mmPut.callArgs)) + copy(argCopy, mmPut.callArgs) + + mmPut.mutex.RUnlock() + + return argCopy } // MinimockPutDone returns true if the count of the Put invocations corresponds // the number of defined expectations func (m *BytesMock) MinimockPutDone() bool { for _, e := range m.PutMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.PutMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterPutCounter) < 1 { + if m.PutMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterPutCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcPut != nil && atomic.LoadUint64(&m.afterPutCounter) < 1 { + if m.funcPut != nil && mm_atomic.LoadUint64(&m.afterPutCounter) < 1 { return false } return true @@ -556,17 +686,21 @@ func (m *BytesMock) MinimockPutDone() bool { // MinimockPutInspect logs each unmet expectation func (m *BytesMock) MinimockPutInspect() { for _, e := range m.PutMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to BytesMock.Put with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.PutMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterPutCounter) < 1 { - m.t.Errorf("Expected call to BytesMock.Put with params: %#v", *m.PutMock.defaultExpectation.params) + if m.PutMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterPutCounter) < 1 { + if m.PutMock.defaultExpectation.params == nil { + m.t.Error("Expected call to BytesMock.Put") + } else { + m.t.Errorf("Expected call to BytesMock.Put with params: %#v", *m.PutMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcPut != nil && atomic.LoadUint64(&m.afterPutCounter) < 1 { + if m.funcPut != nil && mm_atomic.LoadUint64(&m.afterPutCounter) < 1 { m.t.Error("Expected call to BytesMock.Put") } } @@ -584,8 +718,8 @@ func (m *BytesMock) MinimockFinish() { } // MinimockWait waits for all mocked methods to be called the expected number of times -func (m *BytesMock) MinimockWait(timeout time.Duration) { - timeoutCh := time.After(timeout) +func (m *BytesMock) MinimockWait(timeout mm_time.Duration) { + timeoutCh := mm_time.After(timeout) for { if m.minimockDone() { return @@ -594,7 +728,7 @@ func (m *BytesMock) MinimockWait(timeout time.Duration) { case <-timeoutCh: m.MinimockFinish() return - case <-time.After(10 * time.Millisecond): + case <-mm_time.After(10 * mm_time.Millisecond): } } } diff --git a/internal/cert_manager/acme_client_mock_test.go b/internal/cert_manager/acme_client_mock_test.go index c76f046c..df005e39 100644 --- a/internal/cert_manager/acme_client_mock_test.go +++ b/internal/cert_manager/acme_client_mock_test.go @@ -1,21 +1,18 @@ package cert_manager -// DO NOT EDIT! -// The code below was generated with http://github.com/gojuno/minimock (dev) +// Code generated by http://github.com/gojuno/minimock (3.0.6). DO NOT EDIT. //go:generate minimock -i github.com/rekby/lets-proxy2/internal/cert_manager.AcmeClient -o ./acme_client_mock_test.go import ( - "sync/atomic" - "time" - "context" - "crypto/tls" - - "golang.org/x/crypto/acme" + "sync" + mm_atomic "sync/atomic" + mm_time "time" "github.com/gojuno/minimock/v3" + "golang.org/x/crypto/acme" ) // AcmeClientMock implements AcmeClient @@ -23,46 +20,55 @@ type AcmeClientMock struct { t minimock.Tester funcAccept func(ctx context.Context, chal *acme.Challenge) (cp1 *acme.Challenge, err error) + inspectFuncAccept func(ctx context.Context, chal *acme.Challenge) afterAcceptCounter uint64 beforeAcceptCounter uint64 AcceptMock mAcmeClientMockAccept funcAuthorizeOrder func(ctx context.Context, id []acme.AuthzID, opt ...acme.OrderOption) (op1 *acme.Order, err error) + inspectFuncAuthorizeOrder func(ctx context.Context, id []acme.AuthzID, opt ...acme.OrderOption) afterAuthorizeOrderCounter uint64 beforeAuthorizeOrderCounter uint64 AuthorizeOrderMock mAcmeClientMockAuthorizeOrder funcCreateOrderCert func(ctx context.Context, url string, csr []byte, bundle bool) (der [][]byte, certURL string, err error) + inspectFuncCreateOrderCert func(ctx context.Context, url string, csr []byte, bundle bool) afterCreateOrderCertCounter uint64 beforeCreateOrderCertCounter uint64 CreateOrderCertMock mAcmeClientMockCreateOrderCert funcGetAuthorization func(ctx context.Context, url string) (ap1 *acme.Authorization, err error) + inspectFuncGetAuthorization func(ctx context.Context, url string) afterGetAuthorizationCounter uint64 beforeGetAuthorizationCounter uint64 GetAuthorizationMock mAcmeClientMockGetAuthorization funcHTTP01ChallengeResponse func(token string) (s1 string, err error) + inspectFuncHTTP01ChallengeResponse func(token string) afterHTTP01ChallengeResponseCounter uint64 beforeHTTP01ChallengeResponseCounter uint64 HTTP01ChallengeResponseMock mAcmeClientMockHTTP01ChallengeResponse funcRevokeAuthorization func(ctx context.Context, url string) (err error) + inspectFuncRevokeAuthorization func(ctx context.Context, url string) afterRevokeAuthorizationCounter uint64 beforeRevokeAuthorizationCounter uint64 RevokeAuthorizationMock mAcmeClientMockRevokeAuthorization funcTLSALPN01ChallengeCert func(token string, domain string, opt ...acme.CertOption) (cert tls.Certificate, err error) + inspectFuncTLSALPN01ChallengeCert func(token string, domain string, opt ...acme.CertOption) afterTLSALPN01ChallengeCertCounter uint64 beforeTLSALPN01ChallengeCertCounter uint64 TLSALPN01ChallengeCertMock mAcmeClientMockTLSALPN01ChallengeCert funcWaitAuthorization func(ctx context.Context, url string) (ap1 *acme.Authorization, err error) + inspectFuncWaitAuthorization func(ctx context.Context, url string) afterWaitAuthorizationCounter uint64 beforeWaitAuthorizationCounter uint64 WaitAuthorizationMock mAcmeClientMockWaitAuthorization funcWaitOrder func(ctx context.Context, url string) (op1 *acme.Order, err error) + inspectFuncWaitOrder func(ctx context.Context, url string) afterWaitOrderCounter uint64 beforeWaitOrderCounter uint64 WaitOrderMock mAcmeClientMockWaitOrder @@ -74,15 +80,33 @@ func NewAcmeClientMock(t minimock.Tester) *AcmeClientMock { if controller, ok := t.(minimock.MockController); ok { controller.RegisterMocker(m) } + m.AcceptMock = mAcmeClientMockAccept{mock: m} + m.AcceptMock.callArgs = []*AcmeClientMockAcceptParams{} + m.AuthorizeOrderMock = mAcmeClientMockAuthorizeOrder{mock: m} + m.AuthorizeOrderMock.callArgs = []*AcmeClientMockAuthorizeOrderParams{} + m.CreateOrderCertMock = mAcmeClientMockCreateOrderCert{mock: m} + m.CreateOrderCertMock.callArgs = []*AcmeClientMockCreateOrderCertParams{} + m.GetAuthorizationMock = mAcmeClientMockGetAuthorization{mock: m} + m.GetAuthorizationMock.callArgs = []*AcmeClientMockGetAuthorizationParams{} + m.HTTP01ChallengeResponseMock = mAcmeClientMockHTTP01ChallengeResponse{mock: m} + m.HTTP01ChallengeResponseMock.callArgs = []*AcmeClientMockHTTP01ChallengeResponseParams{} + m.RevokeAuthorizationMock = mAcmeClientMockRevokeAuthorization{mock: m} + m.RevokeAuthorizationMock.callArgs = []*AcmeClientMockRevokeAuthorizationParams{} + m.TLSALPN01ChallengeCertMock = mAcmeClientMockTLSALPN01ChallengeCert{mock: m} + m.TLSALPN01ChallengeCertMock.callArgs = []*AcmeClientMockTLSALPN01ChallengeCertParams{} + m.WaitAuthorizationMock = mAcmeClientMockWaitAuthorization{mock: m} + m.WaitAuthorizationMock.callArgs = []*AcmeClientMockWaitAuthorizationParams{} + m.WaitOrderMock = mAcmeClientMockWaitOrder{mock: m} + m.WaitOrderMock.callArgs = []*AcmeClientMockWaitOrderParams{} return m } @@ -91,6 +115,9 @@ type mAcmeClientMockAccept struct { mock *AcmeClientMock defaultExpectation *AcmeClientMockAcceptExpectation expectations []*AcmeClientMockAcceptExpectation + + callArgs []*AcmeClientMockAcceptParams + mutex sync.RWMutex } // AcmeClientMockAcceptExpectation specifies expectation struct of the AcmeClient.Accept @@ -114,64 +141,75 @@ type AcmeClientMockAcceptResults struct { } // Expect sets up expected params for AcmeClient.Accept -func (m *mAcmeClientMockAccept) Expect(ctx context.Context, chal *acme.Challenge) *mAcmeClientMockAccept { - if m.mock.funcAccept != nil { - m.mock.t.Fatalf("AcmeClientMock.Accept mock is already set by Set") +func (mmAccept *mAcmeClientMockAccept) Expect(ctx context.Context, chal *acme.Challenge) *mAcmeClientMockAccept { + if mmAccept.mock.funcAccept != nil { + mmAccept.mock.t.Fatalf("AcmeClientMock.Accept mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &AcmeClientMockAcceptExpectation{} + if mmAccept.defaultExpectation == nil { + mmAccept.defaultExpectation = &AcmeClientMockAcceptExpectation{} } - m.defaultExpectation.params = &AcmeClientMockAcceptParams{ctx, chal} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmAccept.defaultExpectation.params = &AcmeClientMockAcceptParams{ctx, chal} + for _, e := range mmAccept.expectations { + if minimock.Equal(e.params, mmAccept.defaultExpectation.params) { + mmAccept.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmAccept.defaultExpectation.params) } } - return m + return mmAccept +} + +// Inspect accepts an inspector function that has same arguments as the AcmeClient.Accept +func (mmAccept *mAcmeClientMockAccept) Inspect(f func(ctx context.Context, chal *acme.Challenge)) *mAcmeClientMockAccept { + if mmAccept.mock.inspectFuncAccept != nil { + mmAccept.mock.t.Fatalf("Inspect function is already set for AcmeClientMock.Accept") + } + + mmAccept.mock.inspectFuncAccept = f + + return mmAccept } // Return sets up results that will be returned by AcmeClient.Accept -func (m *mAcmeClientMockAccept) Return(cp1 *acme.Challenge, err error) *AcmeClientMock { - if m.mock.funcAccept != nil { - m.mock.t.Fatalf("AcmeClientMock.Accept mock is already set by Set") +func (mmAccept *mAcmeClientMockAccept) Return(cp1 *acme.Challenge, err error) *AcmeClientMock { + if mmAccept.mock.funcAccept != nil { + mmAccept.mock.t.Fatalf("AcmeClientMock.Accept mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &AcmeClientMockAcceptExpectation{mock: m.mock} + if mmAccept.defaultExpectation == nil { + mmAccept.defaultExpectation = &AcmeClientMockAcceptExpectation{mock: mmAccept.mock} } - m.defaultExpectation.results = &AcmeClientMockAcceptResults{cp1, err} - return m.mock + mmAccept.defaultExpectation.results = &AcmeClientMockAcceptResults{cp1, err} + return mmAccept.mock } //Set uses given function f to mock the AcmeClient.Accept method -func (m *mAcmeClientMockAccept) Set(f func(ctx context.Context, chal *acme.Challenge) (cp1 *acme.Challenge, err error)) *AcmeClientMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the AcmeClient.Accept method") +func (mmAccept *mAcmeClientMockAccept) Set(f func(ctx context.Context, chal *acme.Challenge) (cp1 *acme.Challenge, err error)) *AcmeClientMock { + if mmAccept.defaultExpectation != nil { + mmAccept.mock.t.Fatalf("Default expectation is already set for the AcmeClient.Accept method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the AcmeClient.Accept method") + if len(mmAccept.expectations) > 0 { + mmAccept.mock.t.Fatalf("Some expectations are already set for the AcmeClient.Accept method") } - m.mock.funcAccept = f - return m.mock + mmAccept.mock.funcAccept = f + return mmAccept.mock } // When sets expectation for the AcmeClient.Accept which will trigger the result defined by the following // Then helper -func (m *mAcmeClientMockAccept) When(ctx context.Context, chal *acme.Challenge) *AcmeClientMockAcceptExpectation { - if m.mock.funcAccept != nil { - m.mock.t.Fatalf("AcmeClientMock.Accept mock is already set by Set") +func (mmAccept *mAcmeClientMockAccept) When(ctx context.Context, chal *acme.Challenge) *AcmeClientMockAcceptExpectation { + if mmAccept.mock.funcAccept != nil { + mmAccept.mock.t.Fatalf("AcmeClientMock.Accept mock is already set by Set") } expectation := &AcmeClientMockAcceptExpectation{ - mock: m.mock, + mock: mmAccept.mock, params: &AcmeClientMockAcceptParams{ctx, chal}, } - m.expectations = append(m.expectations, expectation) + mmAccept.expectations = append(mmAccept.expectations, expectation) return expectation } @@ -182,63 +220,87 @@ func (e *AcmeClientMockAcceptExpectation) Then(cp1 *acme.Challenge, err error) * } // Accept implements AcmeClient -func (m *AcmeClientMock) Accept(ctx context.Context, chal *acme.Challenge) (cp1 *acme.Challenge, err error) { - atomic.AddUint64(&m.beforeAcceptCounter, 1) - defer atomic.AddUint64(&m.afterAcceptCounter, 1) +func (mmAccept *AcmeClientMock) Accept(ctx context.Context, chal *acme.Challenge) (cp1 *acme.Challenge, err error) { + mm_atomic.AddUint64(&mmAccept.beforeAcceptCounter, 1) + defer mm_atomic.AddUint64(&mmAccept.afterAcceptCounter, 1) - for _, e := range m.AcceptMock.expectations { - if minimock.Equal(*e.params, AcmeClientMockAcceptParams{ctx, chal}) { - atomic.AddUint64(&e.Counter, 1) + if mmAccept.inspectFuncAccept != nil { + mmAccept.inspectFuncAccept(ctx, chal) + } + + mm_params := &AcmeClientMockAcceptParams{ctx, chal} + + // Record call args + mmAccept.AcceptMock.mutex.Lock() + mmAccept.AcceptMock.callArgs = append(mmAccept.AcceptMock.callArgs, mm_params) + mmAccept.AcceptMock.mutex.Unlock() + + for _, e := range mmAccept.AcceptMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.cp1, e.results.err } } - if m.AcceptMock.defaultExpectation != nil { - atomic.AddUint64(&m.AcceptMock.defaultExpectation.Counter, 1) - want := m.AcceptMock.defaultExpectation.params - got := AcmeClientMockAcceptParams{ctx, chal} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("AcmeClientMock.Accept got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmAccept.AcceptMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmAccept.AcceptMock.defaultExpectation.Counter, 1) + mm_want := mmAccept.AcceptMock.defaultExpectation.params + mm_got := AcmeClientMockAcceptParams{ctx, chal} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmAccept.t.Errorf("AcmeClientMock.Accept got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.AcceptMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the AcmeClientMock.Accept") + mm_results := mmAccept.AcceptMock.defaultExpectation.results + if mm_results == nil { + mmAccept.t.Fatal("No results are set for the AcmeClientMock.Accept") } - return (*results).cp1, (*results).err + return (*mm_results).cp1, (*mm_results).err } - if m.funcAccept != nil { - return m.funcAccept(ctx, chal) + if mmAccept.funcAccept != nil { + return mmAccept.funcAccept(ctx, chal) } - m.t.Fatalf("Unexpected call to AcmeClientMock.Accept. %v %v", ctx, chal) + mmAccept.t.Fatalf("Unexpected call to AcmeClientMock.Accept. %v %v", ctx, chal) return } // AcceptAfterCounter returns a count of finished AcmeClientMock.Accept invocations -func (m *AcmeClientMock) AcceptAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterAcceptCounter) +func (mmAccept *AcmeClientMock) AcceptAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmAccept.afterAcceptCounter) } // AcceptBeforeCounter returns a count of AcmeClientMock.Accept invocations -func (m *AcmeClientMock) AcceptBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeAcceptCounter) +func (mmAccept *AcmeClientMock) AcceptBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmAccept.beforeAcceptCounter) +} + +// Calls returns a list of arguments used in each call to AcmeClientMock.Accept. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmAccept *mAcmeClientMockAccept) Calls() []*AcmeClientMockAcceptParams { + mmAccept.mutex.RLock() + + argCopy := make([]*AcmeClientMockAcceptParams, len(mmAccept.callArgs)) + copy(argCopy, mmAccept.callArgs) + + mmAccept.mutex.RUnlock() + + return argCopy } // MinimockAcceptDone returns true if the count of the Accept invocations corresponds // the number of defined expectations func (m *AcmeClientMock) MinimockAcceptDone() bool { for _, e := range m.AcceptMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.AcceptMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterAcceptCounter) < 1 { + if m.AcceptMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterAcceptCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcAccept != nil && atomic.LoadUint64(&m.afterAcceptCounter) < 1 { + if m.funcAccept != nil && mm_atomic.LoadUint64(&m.afterAcceptCounter) < 1 { return false } return true @@ -247,17 +309,21 @@ func (m *AcmeClientMock) MinimockAcceptDone() bool { // MinimockAcceptInspect logs each unmet expectation func (m *AcmeClientMock) MinimockAcceptInspect() { for _, e := range m.AcceptMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to AcmeClientMock.Accept with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.AcceptMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterAcceptCounter) < 1 { - m.t.Errorf("Expected call to AcmeClientMock.Accept with params: %#v", *m.AcceptMock.defaultExpectation.params) + if m.AcceptMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterAcceptCounter) < 1 { + if m.AcceptMock.defaultExpectation.params == nil { + m.t.Error("Expected call to AcmeClientMock.Accept") + } else { + m.t.Errorf("Expected call to AcmeClientMock.Accept with params: %#v", *m.AcceptMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcAccept != nil && atomic.LoadUint64(&m.afterAcceptCounter) < 1 { + if m.funcAccept != nil && mm_atomic.LoadUint64(&m.afterAcceptCounter) < 1 { m.t.Error("Expected call to AcmeClientMock.Accept") } } @@ -266,6 +332,9 @@ type mAcmeClientMockAuthorizeOrder struct { mock *AcmeClientMock defaultExpectation *AcmeClientMockAuthorizeOrderExpectation expectations []*AcmeClientMockAuthorizeOrderExpectation + + callArgs []*AcmeClientMockAuthorizeOrderParams + mutex sync.RWMutex } // AcmeClientMockAuthorizeOrderExpectation specifies expectation struct of the AcmeClient.AuthorizeOrder @@ -290,64 +359,75 @@ type AcmeClientMockAuthorizeOrderResults struct { } // Expect sets up expected params for AcmeClient.AuthorizeOrder -func (m *mAcmeClientMockAuthorizeOrder) Expect(ctx context.Context, id []acme.AuthzID, opt ...acme.OrderOption) *mAcmeClientMockAuthorizeOrder { - if m.mock.funcAuthorizeOrder != nil { - m.mock.t.Fatalf("AcmeClientMock.AuthorizeOrder mock is already set by Set") +func (mmAuthorizeOrder *mAcmeClientMockAuthorizeOrder) Expect(ctx context.Context, id []acme.AuthzID, opt ...acme.OrderOption) *mAcmeClientMockAuthorizeOrder { + if mmAuthorizeOrder.mock.funcAuthorizeOrder != nil { + mmAuthorizeOrder.mock.t.Fatalf("AcmeClientMock.AuthorizeOrder mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &AcmeClientMockAuthorizeOrderExpectation{} + if mmAuthorizeOrder.defaultExpectation == nil { + mmAuthorizeOrder.defaultExpectation = &AcmeClientMockAuthorizeOrderExpectation{} } - m.defaultExpectation.params = &AcmeClientMockAuthorizeOrderParams{ctx, id, opt} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmAuthorizeOrder.defaultExpectation.params = &AcmeClientMockAuthorizeOrderParams{ctx, id, opt} + for _, e := range mmAuthorizeOrder.expectations { + if minimock.Equal(e.params, mmAuthorizeOrder.defaultExpectation.params) { + mmAuthorizeOrder.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmAuthorizeOrder.defaultExpectation.params) } } - return m + return mmAuthorizeOrder +} + +// Inspect accepts an inspector function that has same arguments as the AcmeClient.AuthorizeOrder +func (mmAuthorizeOrder *mAcmeClientMockAuthorizeOrder) Inspect(f func(ctx context.Context, id []acme.AuthzID, opt ...acme.OrderOption)) *mAcmeClientMockAuthorizeOrder { + if mmAuthorizeOrder.mock.inspectFuncAuthorizeOrder != nil { + mmAuthorizeOrder.mock.t.Fatalf("Inspect function is already set for AcmeClientMock.AuthorizeOrder") + } + + mmAuthorizeOrder.mock.inspectFuncAuthorizeOrder = f + + return mmAuthorizeOrder } // Return sets up results that will be returned by AcmeClient.AuthorizeOrder -func (m *mAcmeClientMockAuthorizeOrder) Return(op1 *acme.Order, err error) *AcmeClientMock { - if m.mock.funcAuthorizeOrder != nil { - m.mock.t.Fatalf("AcmeClientMock.AuthorizeOrder mock is already set by Set") +func (mmAuthorizeOrder *mAcmeClientMockAuthorizeOrder) Return(op1 *acme.Order, err error) *AcmeClientMock { + if mmAuthorizeOrder.mock.funcAuthorizeOrder != nil { + mmAuthorizeOrder.mock.t.Fatalf("AcmeClientMock.AuthorizeOrder mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &AcmeClientMockAuthorizeOrderExpectation{mock: m.mock} + if mmAuthorizeOrder.defaultExpectation == nil { + mmAuthorizeOrder.defaultExpectation = &AcmeClientMockAuthorizeOrderExpectation{mock: mmAuthorizeOrder.mock} } - m.defaultExpectation.results = &AcmeClientMockAuthorizeOrderResults{op1, err} - return m.mock + mmAuthorizeOrder.defaultExpectation.results = &AcmeClientMockAuthorizeOrderResults{op1, err} + return mmAuthorizeOrder.mock } //Set uses given function f to mock the AcmeClient.AuthorizeOrder method -func (m *mAcmeClientMockAuthorizeOrder) Set(f func(ctx context.Context, id []acme.AuthzID, opt ...acme.OrderOption) (op1 *acme.Order, err error)) *AcmeClientMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the AcmeClient.AuthorizeOrder method") +func (mmAuthorizeOrder *mAcmeClientMockAuthorizeOrder) Set(f func(ctx context.Context, id []acme.AuthzID, opt ...acme.OrderOption) (op1 *acme.Order, err error)) *AcmeClientMock { + if mmAuthorizeOrder.defaultExpectation != nil { + mmAuthorizeOrder.mock.t.Fatalf("Default expectation is already set for the AcmeClient.AuthorizeOrder method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the AcmeClient.AuthorizeOrder method") + if len(mmAuthorizeOrder.expectations) > 0 { + mmAuthorizeOrder.mock.t.Fatalf("Some expectations are already set for the AcmeClient.AuthorizeOrder method") } - m.mock.funcAuthorizeOrder = f - return m.mock + mmAuthorizeOrder.mock.funcAuthorizeOrder = f + return mmAuthorizeOrder.mock } // When sets expectation for the AcmeClient.AuthorizeOrder which will trigger the result defined by the following // Then helper -func (m *mAcmeClientMockAuthorizeOrder) When(ctx context.Context, id []acme.AuthzID, opt ...acme.OrderOption) *AcmeClientMockAuthorizeOrderExpectation { - if m.mock.funcAuthorizeOrder != nil { - m.mock.t.Fatalf("AcmeClientMock.AuthorizeOrder mock is already set by Set") +func (mmAuthorizeOrder *mAcmeClientMockAuthorizeOrder) When(ctx context.Context, id []acme.AuthzID, opt ...acme.OrderOption) *AcmeClientMockAuthorizeOrderExpectation { + if mmAuthorizeOrder.mock.funcAuthorizeOrder != nil { + mmAuthorizeOrder.mock.t.Fatalf("AcmeClientMock.AuthorizeOrder mock is already set by Set") } expectation := &AcmeClientMockAuthorizeOrderExpectation{ - mock: m.mock, + mock: mmAuthorizeOrder.mock, params: &AcmeClientMockAuthorizeOrderParams{ctx, id, opt}, } - m.expectations = append(m.expectations, expectation) + mmAuthorizeOrder.expectations = append(mmAuthorizeOrder.expectations, expectation) return expectation } @@ -358,63 +438,87 @@ func (e *AcmeClientMockAuthorizeOrderExpectation) Then(op1 *acme.Order, err erro } // AuthorizeOrder implements AcmeClient -func (m *AcmeClientMock) AuthorizeOrder(ctx context.Context, id []acme.AuthzID, opt ...acme.OrderOption) (op1 *acme.Order, err error) { - atomic.AddUint64(&m.beforeAuthorizeOrderCounter, 1) - defer atomic.AddUint64(&m.afterAuthorizeOrderCounter, 1) +func (mmAuthorizeOrder *AcmeClientMock) AuthorizeOrder(ctx context.Context, id []acme.AuthzID, opt ...acme.OrderOption) (op1 *acme.Order, err error) { + mm_atomic.AddUint64(&mmAuthorizeOrder.beforeAuthorizeOrderCounter, 1) + defer mm_atomic.AddUint64(&mmAuthorizeOrder.afterAuthorizeOrderCounter, 1) - for _, e := range m.AuthorizeOrderMock.expectations { - if minimock.Equal(*e.params, AcmeClientMockAuthorizeOrderParams{ctx, id, opt}) { - atomic.AddUint64(&e.Counter, 1) + if mmAuthorizeOrder.inspectFuncAuthorizeOrder != nil { + mmAuthorizeOrder.inspectFuncAuthorizeOrder(ctx, id, opt...) + } + + mm_params := &AcmeClientMockAuthorizeOrderParams{ctx, id, opt} + + // Record call args + mmAuthorizeOrder.AuthorizeOrderMock.mutex.Lock() + mmAuthorizeOrder.AuthorizeOrderMock.callArgs = append(mmAuthorizeOrder.AuthorizeOrderMock.callArgs, mm_params) + mmAuthorizeOrder.AuthorizeOrderMock.mutex.Unlock() + + for _, e := range mmAuthorizeOrder.AuthorizeOrderMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.op1, e.results.err } } - if m.AuthorizeOrderMock.defaultExpectation != nil { - atomic.AddUint64(&m.AuthorizeOrderMock.defaultExpectation.Counter, 1) - want := m.AuthorizeOrderMock.defaultExpectation.params - got := AcmeClientMockAuthorizeOrderParams{ctx, id, opt} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("AcmeClientMock.AuthorizeOrder got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmAuthorizeOrder.AuthorizeOrderMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmAuthorizeOrder.AuthorizeOrderMock.defaultExpectation.Counter, 1) + mm_want := mmAuthorizeOrder.AuthorizeOrderMock.defaultExpectation.params + mm_got := AcmeClientMockAuthorizeOrderParams{ctx, id, opt} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmAuthorizeOrder.t.Errorf("AcmeClientMock.AuthorizeOrder got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.AuthorizeOrderMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the AcmeClientMock.AuthorizeOrder") + mm_results := mmAuthorizeOrder.AuthorizeOrderMock.defaultExpectation.results + if mm_results == nil { + mmAuthorizeOrder.t.Fatal("No results are set for the AcmeClientMock.AuthorizeOrder") } - return (*results).op1, (*results).err + return (*mm_results).op1, (*mm_results).err } - if m.funcAuthorizeOrder != nil { - return m.funcAuthorizeOrder(ctx, id, opt...) + if mmAuthorizeOrder.funcAuthorizeOrder != nil { + return mmAuthorizeOrder.funcAuthorizeOrder(ctx, id, opt...) } - m.t.Fatalf("Unexpected call to AcmeClientMock.AuthorizeOrder. %v %v %v", ctx, id, opt) + mmAuthorizeOrder.t.Fatalf("Unexpected call to AcmeClientMock.AuthorizeOrder. %v %v %v", ctx, id, opt) return } // AuthorizeOrderAfterCounter returns a count of finished AcmeClientMock.AuthorizeOrder invocations -func (m *AcmeClientMock) AuthorizeOrderAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterAuthorizeOrderCounter) +func (mmAuthorizeOrder *AcmeClientMock) AuthorizeOrderAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmAuthorizeOrder.afterAuthorizeOrderCounter) } // AuthorizeOrderBeforeCounter returns a count of AcmeClientMock.AuthorizeOrder invocations -func (m *AcmeClientMock) AuthorizeOrderBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeAuthorizeOrderCounter) +func (mmAuthorizeOrder *AcmeClientMock) AuthorizeOrderBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmAuthorizeOrder.beforeAuthorizeOrderCounter) +} + +// Calls returns a list of arguments used in each call to AcmeClientMock.AuthorizeOrder. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmAuthorizeOrder *mAcmeClientMockAuthorizeOrder) Calls() []*AcmeClientMockAuthorizeOrderParams { + mmAuthorizeOrder.mutex.RLock() + + argCopy := make([]*AcmeClientMockAuthorizeOrderParams, len(mmAuthorizeOrder.callArgs)) + copy(argCopy, mmAuthorizeOrder.callArgs) + + mmAuthorizeOrder.mutex.RUnlock() + + return argCopy } // MinimockAuthorizeOrderDone returns true if the count of the AuthorizeOrder invocations corresponds // the number of defined expectations func (m *AcmeClientMock) MinimockAuthorizeOrderDone() bool { for _, e := range m.AuthorizeOrderMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.AuthorizeOrderMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterAuthorizeOrderCounter) < 1 { + if m.AuthorizeOrderMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterAuthorizeOrderCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcAuthorizeOrder != nil && atomic.LoadUint64(&m.afterAuthorizeOrderCounter) < 1 { + if m.funcAuthorizeOrder != nil && mm_atomic.LoadUint64(&m.afterAuthorizeOrderCounter) < 1 { return false } return true @@ -423,17 +527,21 @@ func (m *AcmeClientMock) MinimockAuthorizeOrderDone() bool { // MinimockAuthorizeOrderInspect logs each unmet expectation func (m *AcmeClientMock) MinimockAuthorizeOrderInspect() { for _, e := range m.AuthorizeOrderMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to AcmeClientMock.AuthorizeOrder with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.AuthorizeOrderMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterAuthorizeOrderCounter) < 1 { - m.t.Errorf("Expected call to AcmeClientMock.AuthorizeOrder with params: %#v", *m.AuthorizeOrderMock.defaultExpectation.params) + if m.AuthorizeOrderMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterAuthorizeOrderCounter) < 1 { + if m.AuthorizeOrderMock.defaultExpectation.params == nil { + m.t.Error("Expected call to AcmeClientMock.AuthorizeOrder") + } else { + m.t.Errorf("Expected call to AcmeClientMock.AuthorizeOrder with params: %#v", *m.AuthorizeOrderMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcAuthorizeOrder != nil && atomic.LoadUint64(&m.afterAuthorizeOrderCounter) < 1 { + if m.funcAuthorizeOrder != nil && mm_atomic.LoadUint64(&m.afterAuthorizeOrderCounter) < 1 { m.t.Error("Expected call to AcmeClientMock.AuthorizeOrder") } } @@ -442,6 +550,9 @@ type mAcmeClientMockCreateOrderCert struct { mock *AcmeClientMock defaultExpectation *AcmeClientMockCreateOrderCertExpectation expectations []*AcmeClientMockCreateOrderCertExpectation + + callArgs []*AcmeClientMockCreateOrderCertParams + mutex sync.RWMutex } // AcmeClientMockCreateOrderCertExpectation specifies expectation struct of the AcmeClient.CreateOrderCert @@ -468,64 +579,75 @@ type AcmeClientMockCreateOrderCertResults struct { } // Expect sets up expected params for AcmeClient.CreateOrderCert -func (m *mAcmeClientMockCreateOrderCert) Expect(ctx context.Context, url string, csr []byte, bundle bool) *mAcmeClientMockCreateOrderCert { - if m.mock.funcCreateOrderCert != nil { - m.mock.t.Fatalf("AcmeClientMock.CreateOrderCert mock is already set by Set") +func (mmCreateOrderCert *mAcmeClientMockCreateOrderCert) Expect(ctx context.Context, url string, csr []byte, bundle bool) *mAcmeClientMockCreateOrderCert { + if mmCreateOrderCert.mock.funcCreateOrderCert != nil { + mmCreateOrderCert.mock.t.Fatalf("AcmeClientMock.CreateOrderCert mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &AcmeClientMockCreateOrderCertExpectation{} + if mmCreateOrderCert.defaultExpectation == nil { + mmCreateOrderCert.defaultExpectation = &AcmeClientMockCreateOrderCertExpectation{} } - m.defaultExpectation.params = &AcmeClientMockCreateOrderCertParams{ctx, url, csr, bundle} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmCreateOrderCert.defaultExpectation.params = &AcmeClientMockCreateOrderCertParams{ctx, url, csr, bundle} + for _, e := range mmCreateOrderCert.expectations { + if minimock.Equal(e.params, mmCreateOrderCert.defaultExpectation.params) { + mmCreateOrderCert.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmCreateOrderCert.defaultExpectation.params) } } - return m + return mmCreateOrderCert +} + +// Inspect accepts an inspector function that has same arguments as the AcmeClient.CreateOrderCert +func (mmCreateOrderCert *mAcmeClientMockCreateOrderCert) Inspect(f func(ctx context.Context, url string, csr []byte, bundle bool)) *mAcmeClientMockCreateOrderCert { + if mmCreateOrderCert.mock.inspectFuncCreateOrderCert != nil { + mmCreateOrderCert.mock.t.Fatalf("Inspect function is already set for AcmeClientMock.CreateOrderCert") + } + + mmCreateOrderCert.mock.inspectFuncCreateOrderCert = f + + return mmCreateOrderCert } // Return sets up results that will be returned by AcmeClient.CreateOrderCert -func (m *mAcmeClientMockCreateOrderCert) Return(der [][]byte, certURL string, err error) *AcmeClientMock { - if m.mock.funcCreateOrderCert != nil { - m.mock.t.Fatalf("AcmeClientMock.CreateOrderCert mock is already set by Set") +func (mmCreateOrderCert *mAcmeClientMockCreateOrderCert) Return(der [][]byte, certURL string, err error) *AcmeClientMock { + if mmCreateOrderCert.mock.funcCreateOrderCert != nil { + mmCreateOrderCert.mock.t.Fatalf("AcmeClientMock.CreateOrderCert mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &AcmeClientMockCreateOrderCertExpectation{mock: m.mock} + if mmCreateOrderCert.defaultExpectation == nil { + mmCreateOrderCert.defaultExpectation = &AcmeClientMockCreateOrderCertExpectation{mock: mmCreateOrderCert.mock} } - m.defaultExpectation.results = &AcmeClientMockCreateOrderCertResults{der, certURL, err} - return m.mock + mmCreateOrderCert.defaultExpectation.results = &AcmeClientMockCreateOrderCertResults{der, certURL, err} + return mmCreateOrderCert.mock } //Set uses given function f to mock the AcmeClient.CreateOrderCert method -func (m *mAcmeClientMockCreateOrderCert) Set(f func(ctx context.Context, url string, csr []byte, bundle bool) (der [][]byte, certURL string, err error)) *AcmeClientMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the AcmeClient.CreateOrderCert method") +func (mmCreateOrderCert *mAcmeClientMockCreateOrderCert) Set(f func(ctx context.Context, url string, csr []byte, bundle bool) (der [][]byte, certURL string, err error)) *AcmeClientMock { + if mmCreateOrderCert.defaultExpectation != nil { + mmCreateOrderCert.mock.t.Fatalf("Default expectation is already set for the AcmeClient.CreateOrderCert method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the AcmeClient.CreateOrderCert method") + if len(mmCreateOrderCert.expectations) > 0 { + mmCreateOrderCert.mock.t.Fatalf("Some expectations are already set for the AcmeClient.CreateOrderCert method") } - m.mock.funcCreateOrderCert = f - return m.mock + mmCreateOrderCert.mock.funcCreateOrderCert = f + return mmCreateOrderCert.mock } // When sets expectation for the AcmeClient.CreateOrderCert which will trigger the result defined by the following // Then helper -func (m *mAcmeClientMockCreateOrderCert) When(ctx context.Context, url string, csr []byte, bundle bool) *AcmeClientMockCreateOrderCertExpectation { - if m.mock.funcCreateOrderCert != nil { - m.mock.t.Fatalf("AcmeClientMock.CreateOrderCert mock is already set by Set") +func (mmCreateOrderCert *mAcmeClientMockCreateOrderCert) When(ctx context.Context, url string, csr []byte, bundle bool) *AcmeClientMockCreateOrderCertExpectation { + if mmCreateOrderCert.mock.funcCreateOrderCert != nil { + mmCreateOrderCert.mock.t.Fatalf("AcmeClientMock.CreateOrderCert mock is already set by Set") } expectation := &AcmeClientMockCreateOrderCertExpectation{ - mock: m.mock, + mock: mmCreateOrderCert.mock, params: &AcmeClientMockCreateOrderCertParams{ctx, url, csr, bundle}, } - m.expectations = append(m.expectations, expectation) + mmCreateOrderCert.expectations = append(mmCreateOrderCert.expectations, expectation) return expectation } @@ -536,63 +658,87 @@ func (e *AcmeClientMockCreateOrderCertExpectation) Then(der [][]byte, certURL st } // CreateOrderCert implements AcmeClient -func (m *AcmeClientMock) CreateOrderCert(ctx context.Context, url string, csr []byte, bundle bool) (der [][]byte, certURL string, err error) { - atomic.AddUint64(&m.beforeCreateOrderCertCounter, 1) - defer atomic.AddUint64(&m.afterCreateOrderCertCounter, 1) +func (mmCreateOrderCert *AcmeClientMock) CreateOrderCert(ctx context.Context, url string, csr []byte, bundle bool) (der [][]byte, certURL string, err error) { + mm_atomic.AddUint64(&mmCreateOrderCert.beforeCreateOrderCertCounter, 1) + defer mm_atomic.AddUint64(&mmCreateOrderCert.afterCreateOrderCertCounter, 1) - for _, e := range m.CreateOrderCertMock.expectations { - if minimock.Equal(*e.params, AcmeClientMockCreateOrderCertParams{ctx, url, csr, bundle}) { - atomic.AddUint64(&e.Counter, 1) + if mmCreateOrderCert.inspectFuncCreateOrderCert != nil { + mmCreateOrderCert.inspectFuncCreateOrderCert(ctx, url, csr, bundle) + } + + mm_params := &AcmeClientMockCreateOrderCertParams{ctx, url, csr, bundle} + + // Record call args + mmCreateOrderCert.CreateOrderCertMock.mutex.Lock() + mmCreateOrderCert.CreateOrderCertMock.callArgs = append(mmCreateOrderCert.CreateOrderCertMock.callArgs, mm_params) + mmCreateOrderCert.CreateOrderCertMock.mutex.Unlock() + + for _, e := range mmCreateOrderCert.CreateOrderCertMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.der, e.results.certURL, e.results.err } } - if m.CreateOrderCertMock.defaultExpectation != nil { - atomic.AddUint64(&m.CreateOrderCertMock.defaultExpectation.Counter, 1) - want := m.CreateOrderCertMock.defaultExpectation.params - got := AcmeClientMockCreateOrderCertParams{ctx, url, csr, bundle} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("AcmeClientMock.CreateOrderCert got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmCreateOrderCert.CreateOrderCertMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmCreateOrderCert.CreateOrderCertMock.defaultExpectation.Counter, 1) + mm_want := mmCreateOrderCert.CreateOrderCertMock.defaultExpectation.params + mm_got := AcmeClientMockCreateOrderCertParams{ctx, url, csr, bundle} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmCreateOrderCert.t.Errorf("AcmeClientMock.CreateOrderCert got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.CreateOrderCertMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the AcmeClientMock.CreateOrderCert") + mm_results := mmCreateOrderCert.CreateOrderCertMock.defaultExpectation.results + if mm_results == nil { + mmCreateOrderCert.t.Fatal("No results are set for the AcmeClientMock.CreateOrderCert") } - return (*results).der, (*results).certURL, (*results).err + return (*mm_results).der, (*mm_results).certURL, (*mm_results).err } - if m.funcCreateOrderCert != nil { - return m.funcCreateOrderCert(ctx, url, csr, bundle) + if mmCreateOrderCert.funcCreateOrderCert != nil { + return mmCreateOrderCert.funcCreateOrderCert(ctx, url, csr, bundle) } - m.t.Fatalf("Unexpected call to AcmeClientMock.CreateOrderCert. %v %v %v %v", ctx, url, csr, bundle) + mmCreateOrderCert.t.Fatalf("Unexpected call to AcmeClientMock.CreateOrderCert. %v %v %v %v", ctx, url, csr, bundle) return } // CreateOrderCertAfterCounter returns a count of finished AcmeClientMock.CreateOrderCert invocations -func (m *AcmeClientMock) CreateOrderCertAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterCreateOrderCertCounter) +func (mmCreateOrderCert *AcmeClientMock) CreateOrderCertAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmCreateOrderCert.afterCreateOrderCertCounter) } // CreateOrderCertBeforeCounter returns a count of AcmeClientMock.CreateOrderCert invocations -func (m *AcmeClientMock) CreateOrderCertBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeCreateOrderCertCounter) +func (mmCreateOrderCert *AcmeClientMock) CreateOrderCertBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmCreateOrderCert.beforeCreateOrderCertCounter) +} + +// Calls returns a list of arguments used in each call to AcmeClientMock.CreateOrderCert. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmCreateOrderCert *mAcmeClientMockCreateOrderCert) Calls() []*AcmeClientMockCreateOrderCertParams { + mmCreateOrderCert.mutex.RLock() + + argCopy := make([]*AcmeClientMockCreateOrderCertParams, len(mmCreateOrderCert.callArgs)) + copy(argCopy, mmCreateOrderCert.callArgs) + + mmCreateOrderCert.mutex.RUnlock() + + return argCopy } // MinimockCreateOrderCertDone returns true if the count of the CreateOrderCert invocations corresponds // the number of defined expectations func (m *AcmeClientMock) MinimockCreateOrderCertDone() bool { for _, e := range m.CreateOrderCertMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.CreateOrderCertMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterCreateOrderCertCounter) < 1 { + if m.CreateOrderCertMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterCreateOrderCertCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcCreateOrderCert != nil && atomic.LoadUint64(&m.afterCreateOrderCertCounter) < 1 { + if m.funcCreateOrderCert != nil && mm_atomic.LoadUint64(&m.afterCreateOrderCertCounter) < 1 { return false } return true @@ -601,17 +747,21 @@ func (m *AcmeClientMock) MinimockCreateOrderCertDone() bool { // MinimockCreateOrderCertInspect logs each unmet expectation func (m *AcmeClientMock) MinimockCreateOrderCertInspect() { for _, e := range m.CreateOrderCertMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to AcmeClientMock.CreateOrderCert with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.CreateOrderCertMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterCreateOrderCertCounter) < 1 { - m.t.Errorf("Expected call to AcmeClientMock.CreateOrderCert with params: %#v", *m.CreateOrderCertMock.defaultExpectation.params) + if m.CreateOrderCertMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterCreateOrderCertCounter) < 1 { + if m.CreateOrderCertMock.defaultExpectation.params == nil { + m.t.Error("Expected call to AcmeClientMock.CreateOrderCert") + } else { + m.t.Errorf("Expected call to AcmeClientMock.CreateOrderCert with params: %#v", *m.CreateOrderCertMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcCreateOrderCert != nil && atomic.LoadUint64(&m.afterCreateOrderCertCounter) < 1 { + if m.funcCreateOrderCert != nil && mm_atomic.LoadUint64(&m.afterCreateOrderCertCounter) < 1 { m.t.Error("Expected call to AcmeClientMock.CreateOrderCert") } } @@ -620,6 +770,9 @@ type mAcmeClientMockGetAuthorization struct { mock *AcmeClientMock defaultExpectation *AcmeClientMockGetAuthorizationExpectation expectations []*AcmeClientMockGetAuthorizationExpectation + + callArgs []*AcmeClientMockGetAuthorizationParams + mutex sync.RWMutex } // AcmeClientMockGetAuthorizationExpectation specifies expectation struct of the AcmeClient.GetAuthorization @@ -643,64 +796,75 @@ type AcmeClientMockGetAuthorizationResults struct { } // Expect sets up expected params for AcmeClient.GetAuthorization -func (m *mAcmeClientMockGetAuthorization) Expect(ctx context.Context, url string) *mAcmeClientMockGetAuthorization { - if m.mock.funcGetAuthorization != nil { - m.mock.t.Fatalf("AcmeClientMock.GetAuthorization mock is already set by Set") +func (mmGetAuthorization *mAcmeClientMockGetAuthorization) Expect(ctx context.Context, url string) *mAcmeClientMockGetAuthorization { + if mmGetAuthorization.mock.funcGetAuthorization != nil { + mmGetAuthorization.mock.t.Fatalf("AcmeClientMock.GetAuthorization mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &AcmeClientMockGetAuthorizationExpectation{} + if mmGetAuthorization.defaultExpectation == nil { + mmGetAuthorization.defaultExpectation = &AcmeClientMockGetAuthorizationExpectation{} } - m.defaultExpectation.params = &AcmeClientMockGetAuthorizationParams{ctx, url} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmGetAuthorization.defaultExpectation.params = &AcmeClientMockGetAuthorizationParams{ctx, url} + for _, e := range mmGetAuthorization.expectations { + if minimock.Equal(e.params, mmGetAuthorization.defaultExpectation.params) { + mmGetAuthorization.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmGetAuthorization.defaultExpectation.params) } } - return m + return mmGetAuthorization +} + +// Inspect accepts an inspector function that has same arguments as the AcmeClient.GetAuthorization +func (mmGetAuthorization *mAcmeClientMockGetAuthorization) Inspect(f func(ctx context.Context, url string)) *mAcmeClientMockGetAuthorization { + if mmGetAuthorization.mock.inspectFuncGetAuthorization != nil { + mmGetAuthorization.mock.t.Fatalf("Inspect function is already set for AcmeClientMock.GetAuthorization") + } + + mmGetAuthorization.mock.inspectFuncGetAuthorization = f + + return mmGetAuthorization } // Return sets up results that will be returned by AcmeClient.GetAuthorization -func (m *mAcmeClientMockGetAuthorization) Return(ap1 *acme.Authorization, err error) *AcmeClientMock { - if m.mock.funcGetAuthorization != nil { - m.mock.t.Fatalf("AcmeClientMock.GetAuthorization mock is already set by Set") +func (mmGetAuthorization *mAcmeClientMockGetAuthorization) Return(ap1 *acme.Authorization, err error) *AcmeClientMock { + if mmGetAuthorization.mock.funcGetAuthorization != nil { + mmGetAuthorization.mock.t.Fatalf("AcmeClientMock.GetAuthorization mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &AcmeClientMockGetAuthorizationExpectation{mock: m.mock} + if mmGetAuthorization.defaultExpectation == nil { + mmGetAuthorization.defaultExpectation = &AcmeClientMockGetAuthorizationExpectation{mock: mmGetAuthorization.mock} } - m.defaultExpectation.results = &AcmeClientMockGetAuthorizationResults{ap1, err} - return m.mock + mmGetAuthorization.defaultExpectation.results = &AcmeClientMockGetAuthorizationResults{ap1, err} + return mmGetAuthorization.mock } //Set uses given function f to mock the AcmeClient.GetAuthorization method -func (m *mAcmeClientMockGetAuthorization) Set(f func(ctx context.Context, url string) (ap1 *acme.Authorization, err error)) *AcmeClientMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the AcmeClient.GetAuthorization method") +func (mmGetAuthorization *mAcmeClientMockGetAuthorization) Set(f func(ctx context.Context, url string) (ap1 *acme.Authorization, err error)) *AcmeClientMock { + if mmGetAuthorization.defaultExpectation != nil { + mmGetAuthorization.mock.t.Fatalf("Default expectation is already set for the AcmeClient.GetAuthorization method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the AcmeClient.GetAuthorization method") + if len(mmGetAuthorization.expectations) > 0 { + mmGetAuthorization.mock.t.Fatalf("Some expectations are already set for the AcmeClient.GetAuthorization method") } - m.mock.funcGetAuthorization = f - return m.mock + mmGetAuthorization.mock.funcGetAuthorization = f + return mmGetAuthorization.mock } // When sets expectation for the AcmeClient.GetAuthorization which will trigger the result defined by the following // Then helper -func (m *mAcmeClientMockGetAuthorization) When(ctx context.Context, url string) *AcmeClientMockGetAuthorizationExpectation { - if m.mock.funcGetAuthorization != nil { - m.mock.t.Fatalf("AcmeClientMock.GetAuthorization mock is already set by Set") +func (mmGetAuthorization *mAcmeClientMockGetAuthorization) When(ctx context.Context, url string) *AcmeClientMockGetAuthorizationExpectation { + if mmGetAuthorization.mock.funcGetAuthorization != nil { + mmGetAuthorization.mock.t.Fatalf("AcmeClientMock.GetAuthorization mock is already set by Set") } expectation := &AcmeClientMockGetAuthorizationExpectation{ - mock: m.mock, + mock: mmGetAuthorization.mock, params: &AcmeClientMockGetAuthorizationParams{ctx, url}, } - m.expectations = append(m.expectations, expectation) + mmGetAuthorization.expectations = append(mmGetAuthorization.expectations, expectation) return expectation } @@ -711,63 +875,87 @@ func (e *AcmeClientMockGetAuthorizationExpectation) Then(ap1 *acme.Authorization } // GetAuthorization implements AcmeClient -func (m *AcmeClientMock) GetAuthorization(ctx context.Context, url string) (ap1 *acme.Authorization, err error) { - atomic.AddUint64(&m.beforeGetAuthorizationCounter, 1) - defer atomic.AddUint64(&m.afterGetAuthorizationCounter, 1) +func (mmGetAuthorization *AcmeClientMock) GetAuthorization(ctx context.Context, url string) (ap1 *acme.Authorization, err error) { + mm_atomic.AddUint64(&mmGetAuthorization.beforeGetAuthorizationCounter, 1) + defer mm_atomic.AddUint64(&mmGetAuthorization.afterGetAuthorizationCounter, 1) - for _, e := range m.GetAuthorizationMock.expectations { - if minimock.Equal(*e.params, AcmeClientMockGetAuthorizationParams{ctx, url}) { - atomic.AddUint64(&e.Counter, 1) + if mmGetAuthorization.inspectFuncGetAuthorization != nil { + mmGetAuthorization.inspectFuncGetAuthorization(ctx, url) + } + + mm_params := &AcmeClientMockGetAuthorizationParams{ctx, url} + + // Record call args + mmGetAuthorization.GetAuthorizationMock.mutex.Lock() + mmGetAuthorization.GetAuthorizationMock.callArgs = append(mmGetAuthorization.GetAuthorizationMock.callArgs, mm_params) + mmGetAuthorization.GetAuthorizationMock.mutex.Unlock() + + for _, e := range mmGetAuthorization.GetAuthorizationMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.ap1, e.results.err } } - if m.GetAuthorizationMock.defaultExpectation != nil { - atomic.AddUint64(&m.GetAuthorizationMock.defaultExpectation.Counter, 1) - want := m.GetAuthorizationMock.defaultExpectation.params - got := AcmeClientMockGetAuthorizationParams{ctx, url} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("AcmeClientMock.GetAuthorization got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmGetAuthorization.GetAuthorizationMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmGetAuthorization.GetAuthorizationMock.defaultExpectation.Counter, 1) + mm_want := mmGetAuthorization.GetAuthorizationMock.defaultExpectation.params + mm_got := AcmeClientMockGetAuthorizationParams{ctx, url} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmGetAuthorization.t.Errorf("AcmeClientMock.GetAuthorization got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.GetAuthorizationMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the AcmeClientMock.GetAuthorization") + mm_results := mmGetAuthorization.GetAuthorizationMock.defaultExpectation.results + if mm_results == nil { + mmGetAuthorization.t.Fatal("No results are set for the AcmeClientMock.GetAuthorization") } - return (*results).ap1, (*results).err + return (*mm_results).ap1, (*mm_results).err } - if m.funcGetAuthorization != nil { - return m.funcGetAuthorization(ctx, url) + if mmGetAuthorization.funcGetAuthorization != nil { + return mmGetAuthorization.funcGetAuthorization(ctx, url) } - m.t.Fatalf("Unexpected call to AcmeClientMock.GetAuthorization. %v %v", ctx, url) + mmGetAuthorization.t.Fatalf("Unexpected call to AcmeClientMock.GetAuthorization. %v %v", ctx, url) return } // GetAuthorizationAfterCounter returns a count of finished AcmeClientMock.GetAuthorization invocations -func (m *AcmeClientMock) GetAuthorizationAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterGetAuthorizationCounter) +func (mmGetAuthorization *AcmeClientMock) GetAuthorizationAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmGetAuthorization.afterGetAuthorizationCounter) } // GetAuthorizationBeforeCounter returns a count of AcmeClientMock.GetAuthorization invocations -func (m *AcmeClientMock) GetAuthorizationBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeGetAuthorizationCounter) +func (mmGetAuthorization *AcmeClientMock) GetAuthorizationBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmGetAuthorization.beforeGetAuthorizationCounter) +} + +// Calls returns a list of arguments used in each call to AcmeClientMock.GetAuthorization. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmGetAuthorization *mAcmeClientMockGetAuthorization) Calls() []*AcmeClientMockGetAuthorizationParams { + mmGetAuthorization.mutex.RLock() + + argCopy := make([]*AcmeClientMockGetAuthorizationParams, len(mmGetAuthorization.callArgs)) + copy(argCopy, mmGetAuthorization.callArgs) + + mmGetAuthorization.mutex.RUnlock() + + return argCopy } // MinimockGetAuthorizationDone returns true if the count of the GetAuthorization invocations corresponds // the number of defined expectations func (m *AcmeClientMock) MinimockGetAuthorizationDone() bool { for _, e := range m.GetAuthorizationMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.GetAuthorizationMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterGetAuthorizationCounter) < 1 { + if m.GetAuthorizationMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterGetAuthorizationCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcGetAuthorization != nil && atomic.LoadUint64(&m.afterGetAuthorizationCounter) < 1 { + if m.funcGetAuthorization != nil && mm_atomic.LoadUint64(&m.afterGetAuthorizationCounter) < 1 { return false } return true @@ -776,17 +964,21 @@ func (m *AcmeClientMock) MinimockGetAuthorizationDone() bool { // MinimockGetAuthorizationInspect logs each unmet expectation func (m *AcmeClientMock) MinimockGetAuthorizationInspect() { for _, e := range m.GetAuthorizationMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to AcmeClientMock.GetAuthorization with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.GetAuthorizationMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterGetAuthorizationCounter) < 1 { - m.t.Errorf("Expected call to AcmeClientMock.GetAuthorization with params: %#v", *m.GetAuthorizationMock.defaultExpectation.params) + if m.GetAuthorizationMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterGetAuthorizationCounter) < 1 { + if m.GetAuthorizationMock.defaultExpectation.params == nil { + m.t.Error("Expected call to AcmeClientMock.GetAuthorization") + } else { + m.t.Errorf("Expected call to AcmeClientMock.GetAuthorization with params: %#v", *m.GetAuthorizationMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcGetAuthorization != nil && atomic.LoadUint64(&m.afterGetAuthorizationCounter) < 1 { + if m.funcGetAuthorization != nil && mm_atomic.LoadUint64(&m.afterGetAuthorizationCounter) < 1 { m.t.Error("Expected call to AcmeClientMock.GetAuthorization") } } @@ -795,6 +987,9 @@ type mAcmeClientMockHTTP01ChallengeResponse struct { mock *AcmeClientMock defaultExpectation *AcmeClientMockHTTP01ChallengeResponseExpectation expectations []*AcmeClientMockHTTP01ChallengeResponseExpectation + + callArgs []*AcmeClientMockHTTP01ChallengeResponseParams + mutex sync.RWMutex } // AcmeClientMockHTTP01ChallengeResponseExpectation specifies expectation struct of the AcmeClient.HTTP01ChallengeResponse @@ -817,64 +1012,75 @@ type AcmeClientMockHTTP01ChallengeResponseResults struct { } // Expect sets up expected params for AcmeClient.HTTP01ChallengeResponse -func (m *mAcmeClientMockHTTP01ChallengeResponse) Expect(token string) *mAcmeClientMockHTTP01ChallengeResponse { - if m.mock.funcHTTP01ChallengeResponse != nil { - m.mock.t.Fatalf("AcmeClientMock.HTTP01ChallengeResponse mock is already set by Set") +func (mmHTTP01ChallengeResponse *mAcmeClientMockHTTP01ChallengeResponse) Expect(token string) *mAcmeClientMockHTTP01ChallengeResponse { + if mmHTTP01ChallengeResponse.mock.funcHTTP01ChallengeResponse != nil { + mmHTTP01ChallengeResponse.mock.t.Fatalf("AcmeClientMock.HTTP01ChallengeResponse mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &AcmeClientMockHTTP01ChallengeResponseExpectation{} + if mmHTTP01ChallengeResponse.defaultExpectation == nil { + mmHTTP01ChallengeResponse.defaultExpectation = &AcmeClientMockHTTP01ChallengeResponseExpectation{} } - m.defaultExpectation.params = &AcmeClientMockHTTP01ChallengeResponseParams{token} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmHTTP01ChallengeResponse.defaultExpectation.params = &AcmeClientMockHTTP01ChallengeResponseParams{token} + for _, e := range mmHTTP01ChallengeResponse.expectations { + if minimock.Equal(e.params, mmHTTP01ChallengeResponse.defaultExpectation.params) { + mmHTTP01ChallengeResponse.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmHTTP01ChallengeResponse.defaultExpectation.params) } } - return m + return mmHTTP01ChallengeResponse +} + +// Inspect accepts an inspector function that has same arguments as the AcmeClient.HTTP01ChallengeResponse +func (mmHTTP01ChallengeResponse *mAcmeClientMockHTTP01ChallengeResponse) Inspect(f func(token string)) *mAcmeClientMockHTTP01ChallengeResponse { + if mmHTTP01ChallengeResponse.mock.inspectFuncHTTP01ChallengeResponse != nil { + mmHTTP01ChallengeResponse.mock.t.Fatalf("Inspect function is already set for AcmeClientMock.HTTP01ChallengeResponse") + } + + mmHTTP01ChallengeResponse.mock.inspectFuncHTTP01ChallengeResponse = f + + return mmHTTP01ChallengeResponse } // Return sets up results that will be returned by AcmeClient.HTTP01ChallengeResponse -func (m *mAcmeClientMockHTTP01ChallengeResponse) Return(s1 string, err error) *AcmeClientMock { - if m.mock.funcHTTP01ChallengeResponse != nil { - m.mock.t.Fatalf("AcmeClientMock.HTTP01ChallengeResponse mock is already set by Set") +func (mmHTTP01ChallengeResponse *mAcmeClientMockHTTP01ChallengeResponse) Return(s1 string, err error) *AcmeClientMock { + if mmHTTP01ChallengeResponse.mock.funcHTTP01ChallengeResponse != nil { + mmHTTP01ChallengeResponse.mock.t.Fatalf("AcmeClientMock.HTTP01ChallengeResponse mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &AcmeClientMockHTTP01ChallengeResponseExpectation{mock: m.mock} + if mmHTTP01ChallengeResponse.defaultExpectation == nil { + mmHTTP01ChallengeResponse.defaultExpectation = &AcmeClientMockHTTP01ChallengeResponseExpectation{mock: mmHTTP01ChallengeResponse.mock} } - m.defaultExpectation.results = &AcmeClientMockHTTP01ChallengeResponseResults{s1, err} - return m.mock + mmHTTP01ChallengeResponse.defaultExpectation.results = &AcmeClientMockHTTP01ChallengeResponseResults{s1, err} + return mmHTTP01ChallengeResponse.mock } //Set uses given function f to mock the AcmeClient.HTTP01ChallengeResponse method -func (m *mAcmeClientMockHTTP01ChallengeResponse) Set(f func(token string) (s1 string, err error)) *AcmeClientMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the AcmeClient.HTTP01ChallengeResponse method") +func (mmHTTP01ChallengeResponse *mAcmeClientMockHTTP01ChallengeResponse) Set(f func(token string) (s1 string, err error)) *AcmeClientMock { + if mmHTTP01ChallengeResponse.defaultExpectation != nil { + mmHTTP01ChallengeResponse.mock.t.Fatalf("Default expectation is already set for the AcmeClient.HTTP01ChallengeResponse method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the AcmeClient.HTTP01ChallengeResponse method") + if len(mmHTTP01ChallengeResponse.expectations) > 0 { + mmHTTP01ChallengeResponse.mock.t.Fatalf("Some expectations are already set for the AcmeClient.HTTP01ChallengeResponse method") } - m.mock.funcHTTP01ChallengeResponse = f - return m.mock + mmHTTP01ChallengeResponse.mock.funcHTTP01ChallengeResponse = f + return mmHTTP01ChallengeResponse.mock } // When sets expectation for the AcmeClient.HTTP01ChallengeResponse which will trigger the result defined by the following // Then helper -func (m *mAcmeClientMockHTTP01ChallengeResponse) When(token string) *AcmeClientMockHTTP01ChallengeResponseExpectation { - if m.mock.funcHTTP01ChallengeResponse != nil { - m.mock.t.Fatalf("AcmeClientMock.HTTP01ChallengeResponse mock is already set by Set") +func (mmHTTP01ChallengeResponse *mAcmeClientMockHTTP01ChallengeResponse) When(token string) *AcmeClientMockHTTP01ChallengeResponseExpectation { + if mmHTTP01ChallengeResponse.mock.funcHTTP01ChallengeResponse != nil { + mmHTTP01ChallengeResponse.mock.t.Fatalf("AcmeClientMock.HTTP01ChallengeResponse mock is already set by Set") } expectation := &AcmeClientMockHTTP01ChallengeResponseExpectation{ - mock: m.mock, + mock: mmHTTP01ChallengeResponse.mock, params: &AcmeClientMockHTTP01ChallengeResponseParams{token}, } - m.expectations = append(m.expectations, expectation) + mmHTTP01ChallengeResponse.expectations = append(mmHTTP01ChallengeResponse.expectations, expectation) return expectation } @@ -885,63 +1091,87 @@ func (e *AcmeClientMockHTTP01ChallengeResponseExpectation) Then(s1 string, err e } // HTTP01ChallengeResponse implements AcmeClient -func (m *AcmeClientMock) HTTP01ChallengeResponse(token string) (s1 string, err error) { - atomic.AddUint64(&m.beforeHTTP01ChallengeResponseCounter, 1) - defer atomic.AddUint64(&m.afterHTTP01ChallengeResponseCounter, 1) +func (mmHTTP01ChallengeResponse *AcmeClientMock) HTTP01ChallengeResponse(token string) (s1 string, err error) { + mm_atomic.AddUint64(&mmHTTP01ChallengeResponse.beforeHTTP01ChallengeResponseCounter, 1) + defer mm_atomic.AddUint64(&mmHTTP01ChallengeResponse.afterHTTP01ChallengeResponseCounter, 1) - for _, e := range m.HTTP01ChallengeResponseMock.expectations { - if minimock.Equal(*e.params, AcmeClientMockHTTP01ChallengeResponseParams{token}) { - atomic.AddUint64(&e.Counter, 1) + if mmHTTP01ChallengeResponse.inspectFuncHTTP01ChallengeResponse != nil { + mmHTTP01ChallengeResponse.inspectFuncHTTP01ChallengeResponse(token) + } + + mm_params := &AcmeClientMockHTTP01ChallengeResponseParams{token} + + // Record call args + mmHTTP01ChallengeResponse.HTTP01ChallengeResponseMock.mutex.Lock() + mmHTTP01ChallengeResponse.HTTP01ChallengeResponseMock.callArgs = append(mmHTTP01ChallengeResponse.HTTP01ChallengeResponseMock.callArgs, mm_params) + mmHTTP01ChallengeResponse.HTTP01ChallengeResponseMock.mutex.Unlock() + + for _, e := range mmHTTP01ChallengeResponse.HTTP01ChallengeResponseMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.s1, e.results.err } } - if m.HTTP01ChallengeResponseMock.defaultExpectation != nil { - atomic.AddUint64(&m.HTTP01ChallengeResponseMock.defaultExpectation.Counter, 1) - want := m.HTTP01ChallengeResponseMock.defaultExpectation.params - got := AcmeClientMockHTTP01ChallengeResponseParams{token} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("AcmeClientMock.HTTP01ChallengeResponse got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmHTTP01ChallengeResponse.HTTP01ChallengeResponseMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmHTTP01ChallengeResponse.HTTP01ChallengeResponseMock.defaultExpectation.Counter, 1) + mm_want := mmHTTP01ChallengeResponse.HTTP01ChallengeResponseMock.defaultExpectation.params + mm_got := AcmeClientMockHTTP01ChallengeResponseParams{token} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmHTTP01ChallengeResponse.t.Errorf("AcmeClientMock.HTTP01ChallengeResponse got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.HTTP01ChallengeResponseMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the AcmeClientMock.HTTP01ChallengeResponse") + mm_results := mmHTTP01ChallengeResponse.HTTP01ChallengeResponseMock.defaultExpectation.results + if mm_results == nil { + mmHTTP01ChallengeResponse.t.Fatal("No results are set for the AcmeClientMock.HTTP01ChallengeResponse") } - return (*results).s1, (*results).err + return (*mm_results).s1, (*mm_results).err } - if m.funcHTTP01ChallengeResponse != nil { - return m.funcHTTP01ChallengeResponse(token) + if mmHTTP01ChallengeResponse.funcHTTP01ChallengeResponse != nil { + return mmHTTP01ChallengeResponse.funcHTTP01ChallengeResponse(token) } - m.t.Fatalf("Unexpected call to AcmeClientMock.HTTP01ChallengeResponse. %v", token) + mmHTTP01ChallengeResponse.t.Fatalf("Unexpected call to AcmeClientMock.HTTP01ChallengeResponse. %v", token) return } // HTTP01ChallengeResponseAfterCounter returns a count of finished AcmeClientMock.HTTP01ChallengeResponse invocations -func (m *AcmeClientMock) HTTP01ChallengeResponseAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterHTTP01ChallengeResponseCounter) +func (mmHTTP01ChallengeResponse *AcmeClientMock) HTTP01ChallengeResponseAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmHTTP01ChallengeResponse.afterHTTP01ChallengeResponseCounter) } // HTTP01ChallengeResponseBeforeCounter returns a count of AcmeClientMock.HTTP01ChallengeResponse invocations -func (m *AcmeClientMock) HTTP01ChallengeResponseBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeHTTP01ChallengeResponseCounter) +func (mmHTTP01ChallengeResponse *AcmeClientMock) HTTP01ChallengeResponseBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmHTTP01ChallengeResponse.beforeHTTP01ChallengeResponseCounter) +} + +// Calls returns a list of arguments used in each call to AcmeClientMock.HTTP01ChallengeResponse. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmHTTP01ChallengeResponse *mAcmeClientMockHTTP01ChallengeResponse) Calls() []*AcmeClientMockHTTP01ChallengeResponseParams { + mmHTTP01ChallengeResponse.mutex.RLock() + + argCopy := make([]*AcmeClientMockHTTP01ChallengeResponseParams, len(mmHTTP01ChallengeResponse.callArgs)) + copy(argCopy, mmHTTP01ChallengeResponse.callArgs) + + mmHTTP01ChallengeResponse.mutex.RUnlock() + + return argCopy } // MinimockHTTP01ChallengeResponseDone returns true if the count of the HTTP01ChallengeResponse invocations corresponds // the number of defined expectations func (m *AcmeClientMock) MinimockHTTP01ChallengeResponseDone() bool { for _, e := range m.HTTP01ChallengeResponseMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.HTTP01ChallengeResponseMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterHTTP01ChallengeResponseCounter) < 1 { + if m.HTTP01ChallengeResponseMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterHTTP01ChallengeResponseCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcHTTP01ChallengeResponse != nil && atomic.LoadUint64(&m.afterHTTP01ChallengeResponseCounter) < 1 { + if m.funcHTTP01ChallengeResponse != nil && mm_atomic.LoadUint64(&m.afterHTTP01ChallengeResponseCounter) < 1 { return false } return true @@ -950,17 +1180,21 @@ func (m *AcmeClientMock) MinimockHTTP01ChallengeResponseDone() bool { // MinimockHTTP01ChallengeResponseInspect logs each unmet expectation func (m *AcmeClientMock) MinimockHTTP01ChallengeResponseInspect() { for _, e := range m.HTTP01ChallengeResponseMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to AcmeClientMock.HTTP01ChallengeResponse with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.HTTP01ChallengeResponseMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterHTTP01ChallengeResponseCounter) < 1 { - m.t.Errorf("Expected call to AcmeClientMock.HTTP01ChallengeResponse with params: %#v", *m.HTTP01ChallengeResponseMock.defaultExpectation.params) + if m.HTTP01ChallengeResponseMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterHTTP01ChallengeResponseCounter) < 1 { + if m.HTTP01ChallengeResponseMock.defaultExpectation.params == nil { + m.t.Error("Expected call to AcmeClientMock.HTTP01ChallengeResponse") + } else { + m.t.Errorf("Expected call to AcmeClientMock.HTTP01ChallengeResponse with params: %#v", *m.HTTP01ChallengeResponseMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcHTTP01ChallengeResponse != nil && atomic.LoadUint64(&m.afterHTTP01ChallengeResponseCounter) < 1 { + if m.funcHTTP01ChallengeResponse != nil && mm_atomic.LoadUint64(&m.afterHTTP01ChallengeResponseCounter) < 1 { m.t.Error("Expected call to AcmeClientMock.HTTP01ChallengeResponse") } } @@ -969,6 +1203,9 @@ type mAcmeClientMockRevokeAuthorization struct { mock *AcmeClientMock defaultExpectation *AcmeClientMockRevokeAuthorizationExpectation expectations []*AcmeClientMockRevokeAuthorizationExpectation + + callArgs []*AcmeClientMockRevokeAuthorizationParams + mutex sync.RWMutex } // AcmeClientMockRevokeAuthorizationExpectation specifies expectation struct of the AcmeClient.RevokeAuthorization @@ -991,64 +1228,75 @@ type AcmeClientMockRevokeAuthorizationResults struct { } // Expect sets up expected params for AcmeClient.RevokeAuthorization -func (m *mAcmeClientMockRevokeAuthorization) Expect(ctx context.Context, url string) *mAcmeClientMockRevokeAuthorization { - if m.mock.funcRevokeAuthorization != nil { - m.mock.t.Fatalf("AcmeClientMock.RevokeAuthorization mock is already set by Set") +func (mmRevokeAuthorization *mAcmeClientMockRevokeAuthorization) Expect(ctx context.Context, url string) *mAcmeClientMockRevokeAuthorization { + if mmRevokeAuthorization.mock.funcRevokeAuthorization != nil { + mmRevokeAuthorization.mock.t.Fatalf("AcmeClientMock.RevokeAuthorization mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &AcmeClientMockRevokeAuthorizationExpectation{} + if mmRevokeAuthorization.defaultExpectation == nil { + mmRevokeAuthorization.defaultExpectation = &AcmeClientMockRevokeAuthorizationExpectation{} } - m.defaultExpectation.params = &AcmeClientMockRevokeAuthorizationParams{ctx, url} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmRevokeAuthorization.defaultExpectation.params = &AcmeClientMockRevokeAuthorizationParams{ctx, url} + for _, e := range mmRevokeAuthorization.expectations { + if minimock.Equal(e.params, mmRevokeAuthorization.defaultExpectation.params) { + mmRevokeAuthorization.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmRevokeAuthorization.defaultExpectation.params) } } - return m + return mmRevokeAuthorization +} + +// Inspect accepts an inspector function that has same arguments as the AcmeClient.RevokeAuthorization +func (mmRevokeAuthorization *mAcmeClientMockRevokeAuthorization) Inspect(f func(ctx context.Context, url string)) *mAcmeClientMockRevokeAuthorization { + if mmRevokeAuthorization.mock.inspectFuncRevokeAuthorization != nil { + mmRevokeAuthorization.mock.t.Fatalf("Inspect function is already set for AcmeClientMock.RevokeAuthorization") + } + + mmRevokeAuthorization.mock.inspectFuncRevokeAuthorization = f + + return mmRevokeAuthorization } // Return sets up results that will be returned by AcmeClient.RevokeAuthorization -func (m *mAcmeClientMockRevokeAuthorization) Return(err error) *AcmeClientMock { - if m.mock.funcRevokeAuthorization != nil { - m.mock.t.Fatalf("AcmeClientMock.RevokeAuthorization mock is already set by Set") +func (mmRevokeAuthorization *mAcmeClientMockRevokeAuthorization) Return(err error) *AcmeClientMock { + if mmRevokeAuthorization.mock.funcRevokeAuthorization != nil { + mmRevokeAuthorization.mock.t.Fatalf("AcmeClientMock.RevokeAuthorization mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &AcmeClientMockRevokeAuthorizationExpectation{mock: m.mock} + if mmRevokeAuthorization.defaultExpectation == nil { + mmRevokeAuthorization.defaultExpectation = &AcmeClientMockRevokeAuthorizationExpectation{mock: mmRevokeAuthorization.mock} } - m.defaultExpectation.results = &AcmeClientMockRevokeAuthorizationResults{err} - return m.mock + mmRevokeAuthorization.defaultExpectation.results = &AcmeClientMockRevokeAuthorizationResults{err} + return mmRevokeAuthorization.mock } //Set uses given function f to mock the AcmeClient.RevokeAuthorization method -func (m *mAcmeClientMockRevokeAuthorization) Set(f func(ctx context.Context, url string) (err error)) *AcmeClientMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the AcmeClient.RevokeAuthorization method") +func (mmRevokeAuthorization *mAcmeClientMockRevokeAuthorization) Set(f func(ctx context.Context, url string) (err error)) *AcmeClientMock { + if mmRevokeAuthorization.defaultExpectation != nil { + mmRevokeAuthorization.mock.t.Fatalf("Default expectation is already set for the AcmeClient.RevokeAuthorization method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the AcmeClient.RevokeAuthorization method") + if len(mmRevokeAuthorization.expectations) > 0 { + mmRevokeAuthorization.mock.t.Fatalf("Some expectations are already set for the AcmeClient.RevokeAuthorization method") } - m.mock.funcRevokeAuthorization = f - return m.mock + mmRevokeAuthorization.mock.funcRevokeAuthorization = f + return mmRevokeAuthorization.mock } // When sets expectation for the AcmeClient.RevokeAuthorization which will trigger the result defined by the following // Then helper -func (m *mAcmeClientMockRevokeAuthorization) When(ctx context.Context, url string) *AcmeClientMockRevokeAuthorizationExpectation { - if m.mock.funcRevokeAuthorization != nil { - m.mock.t.Fatalf("AcmeClientMock.RevokeAuthorization mock is already set by Set") +func (mmRevokeAuthorization *mAcmeClientMockRevokeAuthorization) When(ctx context.Context, url string) *AcmeClientMockRevokeAuthorizationExpectation { + if mmRevokeAuthorization.mock.funcRevokeAuthorization != nil { + mmRevokeAuthorization.mock.t.Fatalf("AcmeClientMock.RevokeAuthorization mock is already set by Set") } expectation := &AcmeClientMockRevokeAuthorizationExpectation{ - mock: m.mock, + mock: mmRevokeAuthorization.mock, params: &AcmeClientMockRevokeAuthorizationParams{ctx, url}, } - m.expectations = append(m.expectations, expectation) + mmRevokeAuthorization.expectations = append(mmRevokeAuthorization.expectations, expectation) return expectation } @@ -1059,63 +1307,87 @@ func (e *AcmeClientMockRevokeAuthorizationExpectation) Then(err error) *AcmeClie } // RevokeAuthorization implements AcmeClient -func (m *AcmeClientMock) RevokeAuthorization(ctx context.Context, url string) (err error) { - atomic.AddUint64(&m.beforeRevokeAuthorizationCounter, 1) - defer atomic.AddUint64(&m.afterRevokeAuthorizationCounter, 1) +func (mmRevokeAuthorization *AcmeClientMock) RevokeAuthorization(ctx context.Context, url string) (err error) { + mm_atomic.AddUint64(&mmRevokeAuthorization.beforeRevokeAuthorizationCounter, 1) + defer mm_atomic.AddUint64(&mmRevokeAuthorization.afterRevokeAuthorizationCounter, 1) - for _, e := range m.RevokeAuthorizationMock.expectations { - if minimock.Equal(*e.params, AcmeClientMockRevokeAuthorizationParams{ctx, url}) { - atomic.AddUint64(&e.Counter, 1) + if mmRevokeAuthorization.inspectFuncRevokeAuthorization != nil { + mmRevokeAuthorization.inspectFuncRevokeAuthorization(ctx, url) + } + + mm_params := &AcmeClientMockRevokeAuthorizationParams{ctx, url} + + // Record call args + mmRevokeAuthorization.RevokeAuthorizationMock.mutex.Lock() + mmRevokeAuthorization.RevokeAuthorizationMock.callArgs = append(mmRevokeAuthorization.RevokeAuthorizationMock.callArgs, mm_params) + mmRevokeAuthorization.RevokeAuthorizationMock.mutex.Unlock() + + for _, e := range mmRevokeAuthorization.RevokeAuthorizationMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.err } } - if m.RevokeAuthorizationMock.defaultExpectation != nil { - atomic.AddUint64(&m.RevokeAuthorizationMock.defaultExpectation.Counter, 1) - want := m.RevokeAuthorizationMock.defaultExpectation.params - got := AcmeClientMockRevokeAuthorizationParams{ctx, url} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("AcmeClientMock.RevokeAuthorization got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmRevokeAuthorization.RevokeAuthorizationMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmRevokeAuthorization.RevokeAuthorizationMock.defaultExpectation.Counter, 1) + mm_want := mmRevokeAuthorization.RevokeAuthorizationMock.defaultExpectation.params + mm_got := AcmeClientMockRevokeAuthorizationParams{ctx, url} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmRevokeAuthorization.t.Errorf("AcmeClientMock.RevokeAuthorization got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.RevokeAuthorizationMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the AcmeClientMock.RevokeAuthorization") + mm_results := mmRevokeAuthorization.RevokeAuthorizationMock.defaultExpectation.results + if mm_results == nil { + mmRevokeAuthorization.t.Fatal("No results are set for the AcmeClientMock.RevokeAuthorization") } - return (*results).err + return (*mm_results).err } - if m.funcRevokeAuthorization != nil { - return m.funcRevokeAuthorization(ctx, url) + if mmRevokeAuthorization.funcRevokeAuthorization != nil { + return mmRevokeAuthorization.funcRevokeAuthorization(ctx, url) } - m.t.Fatalf("Unexpected call to AcmeClientMock.RevokeAuthorization. %v %v", ctx, url) + mmRevokeAuthorization.t.Fatalf("Unexpected call to AcmeClientMock.RevokeAuthorization. %v %v", ctx, url) return } // RevokeAuthorizationAfterCounter returns a count of finished AcmeClientMock.RevokeAuthorization invocations -func (m *AcmeClientMock) RevokeAuthorizationAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterRevokeAuthorizationCounter) +func (mmRevokeAuthorization *AcmeClientMock) RevokeAuthorizationAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmRevokeAuthorization.afterRevokeAuthorizationCounter) } // RevokeAuthorizationBeforeCounter returns a count of AcmeClientMock.RevokeAuthorization invocations -func (m *AcmeClientMock) RevokeAuthorizationBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeRevokeAuthorizationCounter) +func (mmRevokeAuthorization *AcmeClientMock) RevokeAuthorizationBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmRevokeAuthorization.beforeRevokeAuthorizationCounter) +} + +// Calls returns a list of arguments used in each call to AcmeClientMock.RevokeAuthorization. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmRevokeAuthorization *mAcmeClientMockRevokeAuthorization) Calls() []*AcmeClientMockRevokeAuthorizationParams { + mmRevokeAuthorization.mutex.RLock() + + argCopy := make([]*AcmeClientMockRevokeAuthorizationParams, len(mmRevokeAuthorization.callArgs)) + copy(argCopy, mmRevokeAuthorization.callArgs) + + mmRevokeAuthorization.mutex.RUnlock() + + return argCopy } // MinimockRevokeAuthorizationDone returns true if the count of the RevokeAuthorization invocations corresponds // the number of defined expectations func (m *AcmeClientMock) MinimockRevokeAuthorizationDone() bool { for _, e := range m.RevokeAuthorizationMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.RevokeAuthorizationMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterRevokeAuthorizationCounter) < 1 { + if m.RevokeAuthorizationMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterRevokeAuthorizationCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcRevokeAuthorization != nil && atomic.LoadUint64(&m.afterRevokeAuthorizationCounter) < 1 { + if m.funcRevokeAuthorization != nil && mm_atomic.LoadUint64(&m.afterRevokeAuthorizationCounter) < 1 { return false } return true @@ -1124,17 +1396,21 @@ func (m *AcmeClientMock) MinimockRevokeAuthorizationDone() bool { // MinimockRevokeAuthorizationInspect logs each unmet expectation func (m *AcmeClientMock) MinimockRevokeAuthorizationInspect() { for _, e := range m.RevokeAuthorizationMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to AcmeClientMock.RevokeAuthorization with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.RevokeAuthorizationMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterRevokeAuthorizationCounter) < 1 { - m.t.Errorf("Expected call to AcmeClientMock.RevokeAuthorization with params: %#v", *m.RevokeAuthorizationMock.defaultExpectation.params) + if m.RevokeAuthorizationMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterRevokeAuthorizationCounter) < 1 { + if m.RevokeAuthorizationMock.defaultExpectation.params == nil { + m.t.Error("Expected call to AcmeClientMock.RevokeAuthorization") + } else { + m.t.Errorf("Expected call to AcmeClientMock.RevokeAuthorization with params: %#v", *m.RevokeAuthorizationMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcRevokeAuthorization != nil && atomic.LoadUint64(&m.afterRevokeAuthorizationCounter) < 1 { + if m.funcRevokeAuthorization != nil && mm_atomic.LoadUint64(&m.afterRevokeAuthorizationCounter) < 1 { m.t.Error("Expected call to AcmeClientMock.RevokeAuthorization") } } @@ -1143,6 +1419,9 @@ type mAcmeClientMockTLSALPN01ChallengeCert struct { mock *AcmeClientMock defaultExpectation *AcmeClientMockTLSALPN01ChallengeCertExpectation expectations []*AcmeClientMockTLSALPN01ChallengeCertExpectation + + callArgs []*AcmeClientMockTLSALPN01ChallengeCertParams + mutex sync.RWMutex } // AcmeClientMockTLSALPN01ChallengeCertExpectation specifies expectation struct of the AcmeClient.TLSALPN01ChallengeCert @@ -1167,64 +1446,75 @@ type AcmeClientMockTLSALPN01ChallengeCertResults struct { } // Expect sets up expected params for AcmeClient.TLSALPN01ChallengeCert -func (m *mAcmeClientMockTLSALPN01ChallengeCert) Expect(token string, domain string, opt ...acme.CertOption) *mAcmeClientMockTLSALPN01ChallengeCert { - if m.mock.funcTLSALPN01ChallengeCert != nil { - m.mock.t.Fatalf("AcmeClientMock.TLSALPN01ChallengeCert mock is already set by Set") +func (mmTLSALPN01ChallengeCert *mAcmeClientMockTLSALPN01ChallengeCert) Expect(token string, domain string, opt ...acme.CertOption) *mAcmeClientMockTLSALPN01ChallengeCert { + if mmTLSALPN01ChallengeCert.mock.funcTLSALPN01ChallengeCert != nil { + mmTLSALPN01ChallengeCert.mock.t.Fatalf("AcmeClientMock.TLSALPN01ChallengeCert mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &AcmeClientMockTLSALPN01ChallengeCertExpectation{} + if mmTLSALPN01ChallengeCert.defaultExpectation == nil { + mmTLSALPN01ChallengeCert.defaultExpectation = &AcmeClientMockTLSALPN01ChallengeCertExpectation{} } - m.defaultExpectation.params = &AcmeClientMockTLSALPN01ChallengeCertParams{token, domain, opt} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmTLSALPN01ChallengeCert.defaultExpectation.params = &AcmeClientMockTLSALPN01ChallengeCertParams{token, domain, opt} + for _, e := range mmTLSALPN01ChallengeCert.expectations { + if minimock.Equal(e.params, mmTLSALPN01ChallengeCert.defaultExpectation.params) { + mmTLSALPN01ChallengeCert.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmTLSALPN01ChallengeCert.defaultExpectation.params) } } - return m + return mmTLSALPN01ChallengeCert +} + +// Inspect accepts an inspector function that has same arguments as the AcmeClient.TLSALPN01ChallengeCert +func (mmTLSALPN01ChallengeCert *mAcmeClientMockTLSALPN01ChallengeCert) Inspect(f func(token string, domain string, opt ...acme.CertOption)) *mAcmeClientMockTLSALPN01ChallengeCert { + if mmTLSALPN01ChallengeCert.mock.inspectFuncTLSALPN01ChallengeCert != nil { + mmTLSALPN01ChallengeCert.mock.t.Fatalf("Inspect function is already set for AcmeClientMock.TLSALPN01ChallengeCert") + } + + mmTLSALPN01ChallengeCert.mock.inspectFuncTLSALPN01ChallengeCert = f + + return mmTLSALPN01ChallengeCert } // Return sets up results that will be returned by AcmeClient.TLSALPN01ChallengeCert -func (m *mAcmeClientMockTLSALPN01ChallengeCert) Return(cert tls.Certificate, err error) *AcmeClientMock { - if m.mock.funcTLSALPN01ChallengeCert != nil { - m.mock.t.Fatalf("AcmeClientMock.TLSALPN01ChallengeCert mock is already set by Set") +func (mmTLSALPN01ChallengeCert *mAcmeClientMockTLSALPN01ChallengeCert) Return(cert tls.Certificate, err error) *AcmeClientMock { + if mmTLSALPN01ChallengeCert.mock.funcTLSALPN01ChallengeCert != nil { + mmTLSALPN01ChallengeCert.mock.t.Fatalf("AcmeClientMock.TLSALPN01ChallengeCert mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &AcmeClientMockTLSALPN01ChallengeCertExpectation{mock: m.mock} + if mmTLSALPN01ChallengeCert.defaultExpectation == nil { + mmTLSALPN01ChallengeCert.defaultExpectation = &AcmeClientMockTLSALPN01ChallengeCertExpectation{mock: mmTLSALPN01ChallengeCert.mock} } - m.defaultExpectation.results = &AcmeClientMockTLSALPN01ChallengeCertResults{cert, err} - return m.mock + mmTLSALPN01ChallengeCert.defaultExpectation.results = &AcmeClientMockTLSALPN01ChallengeCertResults{cert, err} + return mmTLSALPN01ChallengeCert.mock } //Set uses given function f to mock the AcmeClient.TLSALPN01ChallengeCert method -func (m *mAcmeClientMockTLSALPN01ChallengeCert) Set(f func(token string, domain string, opt ...acme.CertOption) (cert tls.Certificate, err error)) *AcmeClientMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the AcmeClient.TLSALPN01ChallengeCert method") +func (mmTLSALPN01ChallengeCert *mAcmeClientMockTLSALPN01ChallengeCert) Set(f func(token string, domain string, opt ...acme.CertOption) (cert tls.Certificate, err error)) *AcmeClientMock { + if mmTLSALPN01ChallengeCert.defaultExpectation != nil { + mmTLSALPN01ChallengeCert.mock.t.Fatalf("Default expectation is already set for the AcmeClient.TLSALPN01ChallengeCert method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the AcmeClient.TLSALPN01ChallengeCert method") + if len(mmTLSALPN01ChallengeCert.expectations) > 0 { + mmTLSALPN01ChallengeCert.mock.t.Fatalf("Some expectations are already set for the AcmeClient.TLSALPN01ChallengeCert method") } - m.mock.funcTLSALPN01ChallengeCert = f - return m.mock + mmTLSALPN01ChallengeCert.mock.funcTLSALPN01ChallengeCert = f + return mmTLSALPN01ChallengeCert.mock } // When sets expectation for the AcmeClient.TLSALPN01ChallengeCert which will trigger the result defined by the following // Then helper -func (m *mAcmeClientMockTLSALPN01ChallengeCert) When(token string, domain string, opt ...acme.CertOption) *AcmeClientMockTLSALPN01ChallengeCertExpectation { - if m.mock.funcTLSALPN01ChallengeCert != nil { - m.mock.t.Fatalf("AcmeClientMock.TLSALPN01ChallengeCert mock is already set by Set") +func (mmTLSALPN01ChallengeCert *mAcmeClientMockTLSALPN01ChallengeCert) When(token string, domain string, opt ...acme.CertOption) *AcmeClientMockTLSALPN01ChallengeCertExpectation { + if mmTLSALPN01ChallengeCert.mock.funcTLSALPN01ChallengeCert != nil { + mmTLSALPN01ChallengeCert.mock.t.Fatalf("AcmeClientMock.TLSALPN01ChallengeCert mock is already set by Set") } expectation := &AcmeClientMockTLSALPN01ChallengeCertExpectation{ - mock: m.mock, + mock: mmTLSALPN01ChallengeCert.mock, params: &AcmeClientMockTLSALPN01ChallengeCertParams{token, domain, opt}, } - m.expectations = append(m.expectations, expectation) + mmTLSALPN01ChallengeCert.expectations = append(mmTLSALPN01ChallengeCert.expectations, expectation) return expectation } @@ -1235,63 +1525,87 @@ func (e *AcmeClientMockTLSALPN01ChallengeCertExpectation) Then(cert tls.Certific } // TLSALPN01ChallengeCert implements AcmeClient -func (m *AcmeClientMock) TLSALPN01ChallengeCert(token string, domain string, opt ...acme.CertOption) (cert tls.Certificate, err error) { - atomic.AddUint64(&m.beforeTLSALPN01ChallengeCertCounter, 1) - defer atomic.AddUint64(&m.afterTLSALPN01ChallengeCertCounter, 1) +func (mmTLSALPN01ChallengeCert *AcmeClientMock) TLSALPN01ChallengeCert(token string, domain string, opt ...acme.CertOption) (cert tls.Certificate, err error) { + mm_atomic.AddUint64(&mmTLSALPN01ChallengeCert.beforeTLSALPN01ChallengeCertCounter, 1) + defer mm_atomic.AddUint64(&mmTLSALPN01ChallengeCert.afterTLSALPN01ChallengeCertCounter, 1) - for _, e := range m.TLSALPN01ChallengeCertMock.expectations { - if minimock.Equal(*e.params, AcmeClientMockTLSALPN01ChallengeCertParams{token, domain, opt}) { - atomic.AddUint64(&e.Counter, 1) + if mmTLSALPN01ChallengeCert.inspectFuncTLSALPN01ChallengeCert != nil { + mmTLSALPN01ChallengeCert.inspectFuncTLSALPN01ChallengeCert(token, domain, opt...) + } + + mm_params := &AcmeClientMockTLSALPN01ChallengeCertParams{token, domain, opt} + + // Record call args + mmTLSALPN01ChallengeCert.TLSALPN01ChallengeCertMock.mutex.Lock() + mmTLSALPN01ChallengeCert.TLSALPN01ChallengeCertMock.callArgs = append(mmTLSALPN01ChallengeCert.TLSALPN01ChallengeCertMock.callArgs, mm_params) + mmTLSALPN01ChallengeCert.TLSALPN01ChallengeCertMock.mutex.Unlock() + + for _, e := range mmTLSALPN01ChallengeCert.TLSALPN01ChallengeCertMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.cert, e.results.err } } - if m.TLSALPN01ChallengeCertMock.defaultExpectation != nil { - atomic.AddUint64(&m.TLSALPN01ChallengeCertMock.defaultExpectation.Counter, 1) - want := m.TLSALPN01ChallengeCertMock.defaultExpectation.params - got := AcmeClientMockTLSALPN01ChallengeCertParams{token, domain, opt} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("AcmeClientMock.TLSALPN01ChallengeCert got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmTLSALPN01ChallengeCert.TLSALPN01ChallengeCertMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmTLSALPN01ChallengeCert.TLSALPN01ChallengeCertMock.defaultExpectation.Counter, 1) + mm_want := mmTLSALPN01ChallengeCert.TLSALPN01ChallengeCertMock.defaultExpectation.params + mm_got := AcmeClientMockTLSALPN01ChallengeCertParams{token, domain, opt} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmTLSALPN01ChallengeCert.t.Errorf("AcmeClientMock.TLSALPN01ChallengeCert got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.TLSALPN01ChallengeCertMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the AcmeClientMock.TLSALPN01ChallengeCert") + mm_results := mmTLSALPN01ChallengeCert.TLSALPN01ChallengeCertMock.defaultExpectation.results + if mm_results == nil { + mmTLSALPN01ChallengeCert.t.Fatal("No results are set for the AcmeClientMock.TLSALPN01ChallengeCert") } - return (*results).cert, (*results).err + return (*mm_results).cert, (*mm_results).err } - if m.funcTLSALPN01ChallengeCert != nil { - return m.funcTLSALPN01ChallengeCert(token, domain, opt...) + if mmTLSALPN01ChallengeCert.funcTLSALPN01ChallengeCert != nil { + return mmTLSALPN01ChallengeCert.funcTLSALPN01ChallengeCert(token, domain, opt...) } - m.t.Fatalf("Unexpected call to AcmeClientMock.TLSALPN01ChallengeCert. %v %v %v", token, domain, opt) + mmTLSALPN01ChallengeCert.t.Fatalf("Unexpected call to AcmeClientMock.TLSALPN01ChallengeCert. %v %v %v", token, domain, opt) return } // TLSALPN01ChallengeCertAfterCounter returns a count of finished AcmeClientMock.TLSALPN01ChallengeCert invocations -func (m *AcmeClientMock) TLSALPN01ChallengeCertAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterTLSALPN01ChallengeCertCounter) +func (mmTLSALPN01ChallengeCert *AcmeClientMock) TLSALPN01ChallengeCertAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmTLSALPN01ChallengeCert.afterTLSALPN01ChallengeCertCounter) } // TLSALPN01ChallengeCertBeforeCounter returns a count of AcmeClientMock.TLSALPN01ChallengeCert invocations -func (m *AcmeClientMock) TLSALPN01ChallengeCertBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeTLSALPN01ChallengeCertCounter) +func (mmTLSALPN01ChallengeCert *AcmeClientMock) TLSALPN01ChallengeCertBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmTLSALPN01ChallengeCert.beforeTLSALPN01ChallengeCertCounter) +} + +// Calls returns a list of arguments used in each call to AcmeClientMock.TLSALPN01ChallengeCert. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmTLSALPN01ChallengeCert *mAcmeClientMockTLSALPN01ChallengeCert) Calls() []*AcmeClientMockTLSALPN01ChallengeCertParams { + mmTLSALPN01ChallengeCert.mutex.RLock() + + argCopy := make([]*AcmeClientMockTLSALPN01ChallengeCertParams, len(mmTLSALPN01ChallengeCert.callArgs)) + copy(argCopy, mmTLSALPN01ChallengeCert.callArgs) + + mmTLSALPN01ChallengeCert.mutex.RUnlock() + + return argCopy } // MinimockTLSALPN01ChallengeCertDone returns true if the count of the TLSALPN01ChallengeCert invocations corresponds // the number of defined expectations func (m *AcmeClientMock) MinimockTLSALPN01ChallengeCertDone() bool { for _, e := range m.TLSALPN01ChallengeCertMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.TLSALPN01ChallengeCertMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterTLSALPN01ChallengeCertCounter) < 1 { + if m.TLSALPN01ChallengeCertMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterTLSALPN01ChallengeCertCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcTLSALPN01ChallengeCert != nil && atomic.LoadUint64(&m.afterTLSALPN01ChallengeCertCounter) < 1 { + if m.funcTLSALPN01ChallengeCert != nil && mm_atomic.LoadUint64(&m.afterTLSALPN01ChallengeCertCounter) < 1 { return false } return true @@ -1300,17 +1614,21 @@ func (m *AcmeClientMock) MinimockTLSALPN01ChallengeCertDone() bool { // MinimockTLSALPN01ChallengeCertInspect logs each unmet expectation func (m *AcmeClientMock) MinimockTLSALPN01ChallengeCertInspect() { for _, e := range m.TLSALPN01ChallengeCertMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to AcmeClientMock.TLSALPN01ChallengeCert with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.TLSALPN01ChallengeCertMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterTLSALPN01ChallengeCertCounter) < 1 { - m.t.Errorf("Expected call to AcmeClientMock.TLSALPN01ChallengeCert with params: %#v", *m.TLSALPN01ChallengeCertMock.defaultExpectation.params) + if m.TLSALPN01ChallengeCertMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterTLSALPN01ChallengeCertCounter) < 1 { + if m.TLSALPN01ChallengeCertMock.defaultExpectation.params == nil { + m.t.Error("Expected call to AcmeClientMock.TLSALPN01ChallengeCert") + } else { + m.t.Errorf("Expected call to AcmeClientMock.TLSALPN01ChallengeCert with params: %#v", *m.TLSALPN01ChallengeCertMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcTLSALPN01ChallengeCert != nil && atomic.LoadUint64(&m.afterTLSALPN01ChallengeCertCounter) < 1 { + if m.funcTLSALPN01ChallengeCert != nil && mm_atomic.LoadUint64(&m.afterTLSALPN01ChallengeCertCounter) < 1 { m.t.Error("Expected call to AcmeClientMock.TLSALPN01ChallengeCert") } } @@ -1319,6 +1637,9 @@ type mAcmeClientMockWaitAuthorization struct { mock *AcmeClientMock defaultExpectation *AcmeClientMockWaitAuthorizationExpectation expectations []*AcmeClientMockWaitAuthorizationExpectation + + callArgs []*AcmeClientMockWaitAuthorizationParams + mutex sync.RWMutex } // AcmeClientMockWaitAuthorizationExpectation specifies expectation struct of the AcmeClient.WaitAuthorization @@ -1342,64 +1663,75 @@ type AcmeClientMockWaitAuthorizationResults struct { } // Expect sets up expected params for AcmeClient.WaitAuthorization -func (m *mAcmeClientMockWaitAuthorization) Expect(ctx context.Context, url string) *mAcmeClientMockWaitAuthorization { - if m.mock.funcWaitAuthorization != nil { - m.mock.t.Fatalf("AcmeClientMock.WaitAuthorization mock is already set by Set") +func (mmWaitAuthorization *mAcmeClientMockWaitAuthorization) Expect(ctx context.Context, url string) *mAcmeClientMockWaitAuthorization { + if mmWaitAuthorization.mock.funcWaitAuthorization != nil { + mmWaitAuthorization.mock.t.Fatalf("AcmeClientMock.WaitAuthorization mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &AcmeClientMockWaitAuthorizationExpectation{} + if mmWaitAuthorization.defaultExpectation == nil { + mmWaitAuthorization.defaultExpectation = &AcmeClientMockWaitAuthorizationExpectation{} } - m.defaultExpectation.params = &AcmeClientMockWaitAuthorizationParams{ctx, url} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmWaitAuthorization.defaultExpectation.params = &AcmeClientMockWaitAuthorizationParams{ctx, url} + for _, e := range mmWaitAuthorization.expectations { + if minimock.Equal(e.params, mmWaitAuthorization.defaultExpectation.params) { + mmWaitAuthorization.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmWaitAuthorization.defaultExpectation.params) } } - return m + return mmWaitAuthorization +} + +// Inspect accepts an inspector function that has same arguments as the AcmeClient.WaitAuthorization +func (mmWaitAuthorization *mAcmeClientMockWaitAuthorization) Inspect(f func(ctx context.Context, url string)) *mAcmeClientMockWaitAuthorization { + if mmWaitAuthorization.mock.inspectFuncWaitAuthorization != nil { + mmWaitAuthorization.mock.t.Fatalf("Inspect function is already set for AcmeClientMock.WaitAuthorization") + } + + mmWaitAuthorization.mock.inspectFuncWaitAuthorization = f + + return mmWaitAuthorization } // Return sets up results that will be returned by AcmeClient.WaitAuthorization -func (m *mAcmeClientMockWaitAuthorization) Return(ap1 *acme.Authorization, err error) *AcmeClientMock { - if m.mock.funcWaitAuthorization != nil { - m.mock.t.Fatalf("AcmeClientMock.WaitAuthorization mock is already set by Set") +func (mmWaitAuthorization *mAcmeClientMockWaitAuthorization) Return(ap1 *acme.Authorization, err error) *AcmeClientMock { + if mmWaitAuthorization.mock.funcWaitAuthorization != nil { + mmWaitAuthorization.mock.t.Fatalf("AcmeClientMock.WaitAuthorization mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &AcmeClientMockWaitAuthorizationExpectation{mock: m.mock} + if mmWaitAuthorization.defaultExpectation == nil { + mmWaitAuthorization.defaultExpectation = &AcmeClientMockWaitAuthorizationExpectation{mock: mmWaitAuthorization.mock} } - m.defaultExpectation.results = &AcmeClientMockWaitAuthorizationResults{ap1, err} - return m.mock + mmWaitAuthorization.defaultExpectation.results = &AcmeClientMockWaitAuthorizationResults{ap1, err} + return mmWaitAuthorization.mock } //Set uses given function f to mock the AcmeClient.WaitAuthorization method -func (m *mAcmeClientMockWaitAuthorization) Set(f func(ctx context.Context, url string) (ap1 *acme.Authorization, err error)) *AcmeClientMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the AcmeClient.WaitAuthorization method") +func (mmWaitAuthorization *mAcmeClientMockWaitAuthorization) Set(f func(ctx context.Context, url string) (ap1 *acme.Authorization, err error)) *AcmeClientMock { + if mmWaitAuthorization.defaultExpectation != nil { + mmWaitAuthorization.mock.t.Fatalf("Default expectation is already set for the AcmeClient.WaitAuthorization method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the AcmeClient.WaitAuthorization method") + if len(mmWaitAuthorization.expectations) > 0 { + mmWaitAuthorization.mock.t.Fatalf("Some expectations are already set for the AcmeClient.WaitAuthorization method") } - m.mock.funcWaitAuthorization = f - return m.mock + mmWaitAuthorization.mock.funcWaitAuthorization = f + return mmWaitAuthorization.mock } // When sets expectation for the AcmeClient.WaitAuthorization which will trigger the result defined by the following // Then helper -func (m *mAcmeClientMockWaitAuthorization) When(ctx context.Context, url string) *AcmeClientMockWaitAuthorizationExpectation { - if m.mock.funcWaitAuthorization != nil { - m.mock.t.Fatalf("AcmeClientMock.WaitAuthorization mock is already set by Set") +func (mmWaitAuthorization *mAcmeClientMockWaitAuthorization) When(ctx context.Context, url string) *AcmeClientMockWaitAuthorizationExpectation { + if mmWaitAuthorization.mock.funcWaitAuthorization != nil { + mmWaitAuthorization.mock.t.Fatalf("AcmeClientMock.WaitAuthorization mock is already set by Set") } expectation := &AcmeClientMockWaitAuthorizationExpectation{ - mock: m.mock, + mock: mmWaitAuthorization.mock, params: &AcmeClientMockWaitAuthorizationParams{ctx, url}, } - m.expectations = append(m.expectations, expectation) + mmWaitAuthorization.expectations = append(mmWaitAuthorization.expectations, expectation) return expectation } @@ -1410,63 +1742,87 @@ func (e *AcmeClientMockWaitAuthorizationExpectation) Then(ap1 *acme.Authorizatio } // WaitAuthorization implements AcmeClient -func (m *AcmeClientMock) WaitAuthorization(ctx context.Context, url string) (ap1 *acme.Authorization, err error) { - atomic.AddUint64(&m.beforeWaitAuthorizationCounter, 1) - defer atomic.AddUint64(&m.afterWaitAuthorizationCounter, 1) +func (mmWaitAuthorization *AcmeClientMock) WaitAuthorization(ctx context.Context, url string) (ap1 *acme.Authorization, err error) { + mm_atomic.AddUint64(&mmWaitAuthorization.beforeWaitAuthorizationCounter, 1) + defer mm_atomic.AddUint64(&mmWaitAuthorization.afterWaitAuthorizationCounter, 1) - for _, e := range m.WaitAuthorizationMock.expectations { - if minimock.Equal(*e.params, AcmeClientMockWaitAuthorizationParams{ctx, url}) { - atomic.AddUint64(&e.Counter, 1) + if mmWaitAuthorization.inspectFuncWaitAuthorization != nil { + mmWaitAuthorization.inspectFuncWaitAuthorization(ctx, url) + } + + mm_params := &AcmeClientMockWaitAuthorizationParams{ctx, url} + + // Record call args + mmWaitAuthorization.WaitAuthorizationMock.mutex.Lock() + mmWaitAuthorization.WaitAuthorizationMock.callArgs = append(mmWaitAuthorization.WaitAuthorizationMock.callArgs, mm_params) + mmWaitAuthorization.WaitAuthorizationMock.mutex.Unlock() + + for _, e := range mmWaitAuthorization.WaitAuthorizationMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.ap1, e.results.err } } - if m.WaitAuthorizationMock.defaultExpectation != nil { - atomic.AddUint64(&m.WaitAuthorizationMock.defaultExpectation.Counter, 1) - want := m.WaitAuthorizationMock.defaultExpectation.params - got := AcmeClientMockWaitAuthorizationParams{ctx, url} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("AcmeClientMock.WaitAuthorization got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmWaitAuthorization.WaitAuthorizationMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmWaitAuthorization.WaitAuthorizationMock.defaultExpectation.Counter, 1) + mm_want := mmWaitAuthorization.WaitAuthorizationMock.defaultExpectation.params + mm_got := AcmeClientMockWaitAuthorizationParams{ctx, url} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmWaitAuthorization.t.Errorf("AcmeClientMock.WaitAuthorization got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.WaitAuthorizationMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the AcmeClientMock.WaitAuthorization") + mm_results := mmWaitAuthorization.WaitAuthorizationMock.defaultExpectation.results + if mm_results == nil { + mmWaitAuthorization.t.Fatal("No results are set for the AcmeClientMock.WaitAuthorization") } - return (*results).ap1, (*results).err + return (*mm_results).ap1, (*mm_results).err } - if m.funcWaitAuthorization != nil { - return m.funcWaitAuthorization(ctx, url) + if mmWaitAuthorization.funcWaitAuthorization != nil { + return mmWaitAuthorization.funcWaitAuthorization(ctx, url) } - m.t.Fatalf("Unexpected call to AcmeClientMock.WaitAuthorization. %v %v", ctx, url) + mmWaitAuthorization.t.Fatalf("Unexpected call to AcmeClientMock.WaitAuthorization. %v %v", ctx, url) return } // WaitAuthorizationAfterCounter returns a count of finished AcmeClientMock.WaitAuthorization invocations -func (m *AcmeClientMock) WaitAuthorizationAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterWaitAuthorizationCounter) +func (mmWaitAuthorization *AcmeClientMock) WaitAuthorizationAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmWaitAuthorization.afterWaitAuthorizationCounter) } // WaitAuthorizationBeforeCounter returns a count of AcmeClientMock.WaitAuthorization invocations -func (m *AcmeClientMock) WaitAuthorizationBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeWaitAuthorizationCounter) +func (mmWaitAuthorization *AcmeClientMock) WaitAuthorizationBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmWaitAuthorization.beforeWaitAuthorizationCounter) +} + +// Calls returns a list of arguments used in each call to AcmeClientMock.WaitAuthorization. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmWaitAuthorization *mAcmeClientMockWaitAuthorization) Calls() []*AcmeClientMockWaitAuthorizationParams { + mmWaitAuthorization.mutex.RLock() + + argCopy := make([]*AcmeClientMockWaitAuthorizationParams, len(mmWaitAuthorization.callArgs)) + copy(argCopy, mmWaitAuthorization.callArgs) + + mmWaitAuthorization.mutex.RUnlock() + + return argCopy } // MinimockWaitAuthorizationDone returns true if the count of the WaitAuthorization invocations corresponds // the number of defined expectations func (m *AcmeClientMock) MinimockWaitAuthorizationDone() bool { for _, e := range m.WaitAuthorizationMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.WaitAuthorizationMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterWaitAuthorizationCounter) < 1 { + if m.WaitAuthorizationMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterWaitAuthorizationCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcWaitAuthorization != nil && atomic.LoadUint64(&m.afterWaitAuthorizationCounter) < 1 { + if m.funcWaitAuthorization != nil && mm_atomic.LoadUint64(&m.afterWaitAuthorizationCounter) < 1 { return false } return true @@ -1475,17 +1831,21 @@ func (m *AcmeClientMock) MinimockWaitAuthorizationDone() bool { // MinimockWaitAuthorizationInspect logs each unmet expectation func (m *AcmeClientMock) MinimockWaitAuthorizationInspect() { for _, e := range m.WaitAuthorizationMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to AcmeClientMock.WaitAuthorization with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.WaitAuthorizationMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterWaitAuthorizationCounter) < 1 { - m.t.Errorf("Expected call to AcmeClientMock.WaitAuthorization with params: %#v", *m.WaitAuthorizationMock.defaultExpectation.params) + if m.WaitAuthorizationMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterWaitAuthorizationCounter) < 1 { + if m.WaitAuthorizationMock.defaultExpectation.params == nil { + m.t.Error("Expected call to AcmeClientMock.WaitAuthorization") + } else { + m.t.Errorf("Expected call to AcmeClientMock.WaitAuthorization with params: %#v", *m.WaitAuthorizationMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcWaitAuthorization != nil && atomic.LoadUint64(&m.afterWaitAuthorizationCounter) < 1 { + if m.funcWaitAuthorization != nil && mm_atomic.LoadUint64(&m.afterWaitAuthorizationCounter) < 1 { m.t.Error("Expected call to AcmeClientMock.WaitAuthorization") } } @@ -1494,6 +1854,9 @@ type mAcmeClientMockWaitOrder struct { mock *AcmeClientMock defaultExpectation *AcmeClientMockWaitOrderExpectation expectations []*AcmeClientMockWaitOrderExpectation + + callArgs []*AcmeClientMockWaitOrderParams + mutex sync.RWMutex } // AcmeClientMockWaitOrderExpectation specifies expectation struct of the AcmeClient.WaitOrder @@ -1517,64 +1880,75 @@ type AcmeClientMockWaitOrderResults struct { } // Expect sets up expected params for AcmeClient.WaitOrder -func (m *mAcmeClientMockWaitOrder) Expect(ctx context.Context, url string) *mAcmeClientMockWaitOrder { - if m.mock.funcWaitOrder != nil { - m.mock.t.Fatalf("AcmeClientMock.WaitOrder mock is already set by Set") +func (mmWaitOrder *mAcmeClientMockWaitOrder) Expect(ctx context.Context, url string) *mAcmeClientMockWaitOrder { + if mmWaitOrder.mock.funcWaitOrder != nil { + mmWaitOrder.mock.t.Fatalf("AcmeClientMock.WaitOrder mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &AcmeClientMockWaitOrderExpectation{} + if mmWaitOrder.defaultExpectation == nil { + mmWaitOrder.defaultExpectation = &AcmeClientMockWaitOrderExpectation{} } - m.defaultExpectation.params = &AcmeClientMockWaitOrderParams{ctx, url} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmWaitOrder.defaultExpectation.params = &AcmeClientMockWaitOrderParams{ctx, url} + for _, e := range mmWaitOrder.expectations { + if minimock.Equal(e.params, mmWaitOrder.defaultExpectation.params) { + mmWaitOrder.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmWaitOrder.defaultExpectation.params) } } - return m + return mmWaitOrder +} + +// Inspect accepts an inspector function that has same arguments as the AcmeClient.WaitOrder +func (mmWaitOrder *mAcmeClientMockWaitOrder) Inspect(f func(ctx context.Context, url string)) *mAcmeClientMockWaitOrder { + if mmWaitOrder.mock.inspectFuncWaitOrder != nil { + mmWaitOrder.mock.t.Fatalf("Inspect function is already set for AcmeClientMock.WaitOrder") + } + + mmWaitOrder.mock.inspectFuncWaitOrder = f + + return mmWaitOrder } // Return sets up results that will be returned by AcmeClient.WaitOrder -func (m *mAcmeClientMockWaitOrder) Return(op1 *acme.Order, err error) *AcmeClientMock { - if m.mock.funcWaitOrder != nil { - m.mock.t.Fatalf("AcmeClientMock.WaitOrder mock is already set by Set") +func (mmWaitOrder *mAcmeClientMockWaitOrder) Return(op1 *acme.Order, err error) *AcmeClientMock { + if mmWaitOrder.mock.funcWaitOrder != nil { + mmWaitOrder.mock.t.Fatalf("AcmeClientMock.WaitOrder mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &AcmeClientMockWaitOrderExpectation{mock: m.mock} + if mmWaitOrder.defaultExpectation == nil { + mmWaitOrder.defaultExpectation = &AcmeClientMockWaitOrderExpectation{mock: mmWaitOrder.mock} } - m.defaultExpectation.results = &AcmeClientMockWaitOrderResults{op1, err} - return m.mock + mmWaitOrder.defaultExpectation.results = &AcmeClientMockWaitOrderResults{op1, err} + return mmWaitOrder.mock } //Set uses given function f to mock the AcmeClient.WaitOrder method -func (m *mAcmeClientMockWaitOrder) Set(f func(ctx context.Context, url string) (op1 *acme.Order, err error)) *AcmeClientMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the AcmeClient.WaitOrder method") +func (mmWaitOrder *mAcmeClientMockWaitOrder) Set(f func(ctx context.Context, url string) (op1 *acme.Order, err error)) *AcmeClientMock { + if mmWaitOrder.defaultExpectation != nil { + mmWaitOrder.mock.t.Fatalf("Default expectation is already set for the AcmeClient.WaitOrder method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the AcmeClient.WaitOrder method") + if len(mmWaitOrder.expectations) > 0 { + mmWaitOrder.mock.t.Fatalf("Some expectations are already set for the AcmeClient.WaitOrder method") } - m.mock.funcWaitOrder = f - return m.mock + mmWaitOrder.mock.funcWaitOrder = f + return mmWaitOrder.mock } // When sets expectation for the AcmeClient.WaitOrder which will trigger the result defined by the following // Then helper -func (m *mAcmeClientMockWaitOrder) When(ctx context.Context, url string) *AcmeClientMockWaitOrderExpectation { - if m.mock.funcWaitOrder != nil { - m.mock.t.Fatalf("AcmeClientMock.WaitOrder mock is already set by Set") +func (mmWaitOrder *mAcmeClientMockWaitOrder) When(ctx context.Context, url string) *AcmeClientMockWaitOrderExpectation { + if mmWaitOrder.mock.funcWaitOrder != nil { + mmWaitOrder.mock.t.Fatalf("AcmeClientMock.WaitOrder mock is already set by Set") } expectation := &AcmeClientMockWaitOrderExpectation{ - mock: m.mock, + mock: mmWaitOrder.mock, params: &AcmeClientMockWaitOrderParams{ctx, url}, } - m.expectations = append(m.expectations, expectation) + mmWaitOrder.expectations = append(mmWaitOrder.expectations, expectation) return expectation } @@ -1585,63 +1959,87 @@ func (e *AcmeClientMockWaitOrderExpectation) Then(op1 *acme.Order, err error) *A } // WaitOrder implements AcmeClient -func (m *AcmeClientMock) WaitOrder(ctx context.Context, url string) (op1 *acme.Order, err error) { - atomic.AddUint64(&m.beforeWaitOrderCounter, 1) - defer atomic.AddUint64(&m.afterWaitOrderCounter, 1) +func (mmWaitOrder *AcmeClientMock) WaitOrder(ctx context.Context, url string) (op1 *acme.Order, err error) { + mm_atomic.AddUint64(&mmWaitOrder.beforeWaitOrderCounter, 1) + defer mm_atomic.AddUint64(&mmWaitOrder.afterWaitOrderCounter, 1) - for _, e := range m.WaitOrderMock.expectations { - if minimock.Equal(*e.params, AcmeClientMockWaitOrderParams{ctx, url}) { - atomic.AddUint64(&e.Counter, 1) + if mmWaitOrder.inspectFuncWaitOrder != nil { + mmWaitOrder.inspectFuncWaitOrder(ctx, url) + } + + mm_params := &AcmeClientMockWaitOrderParams{ctx, url} + + // Record call args + mmWaitOrder.WaitOrderMock.mutex.Lock() + mmWaitOrder.WaitOrderMock.callArgs = append(mmWaitOrder.WaitOrderMock.callArgs, mm_params) + mmWaitOrder.WaitOrderMock.mutex.Unlock() + + for _, e := range mmWaitOrder.WaitOrderMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.op1, e.results.err } } - if m.WaitOrderMock.defaultExpectation != nil { - atomic.AddUint64(&m.WaitOrderMock.defaultExpectation.Counter, 1) - want := m.WaitOrderMock.defaultExpectation.params - got := AcmeClientMockWaitOrderParams{ctx, url} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("AcmeClientMock.WaitOrder got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmWaitOrder.WaitOrderMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmWaitOrder.WaitOrderMock.defaultExpectation.Counter, 1) + mm_want := mmWaitOrder.WaitOrderMock.defaultExpectation.params + mm_got := AcmeClientMockWaitOrderParams{ctx, url} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmWaitOrder.t.Errorf("AcmeClientMock.WaitOrder got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.WaitOrderMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the AcmeClientMock.WaitOrder") + mm_results := mmWaitOrder.WaitOrderMock.defaultExpectation.results + if mm_results == nil { + mmWaitOrder.t.Fatal("No results are set for the AcmeClientMock.WaitOrder") } - return (*results).op1, (*results).err + return (*mm_results).op1, (*mm_results).err } - if m.funcWaitOrder != nil { - return m.funcWaitOrder(ctx, url) + if mmWaitOrder.funcWaitOrder != nil { + return mmWaitOrder.funcWaitOrder(ctx, url) } - m.t.Fatalf("Unexpected call to AcmeClientMock.WaitOrder. %v %v", ctx, url) + mmWaitOrder.t.Fatalf("Unexpected call to AcmeClientMock.WaitOrder. %v %v", ctx, url) return } // WaitOrderAfterCounter returns a count of finished AcmeClientMock.WaitOrder invocations -func (m *AcmeClientMock) WaitOrderAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterWaitOrderCounter) +func (mmWaitOrder *AcmeClientMock) WaitOrderAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmWaitOrder.afterWaitOrderCounter) } // WaitOrderBeforeCounter returns a count of AcmeClientMock.WaitOrder invocations -func (m *AcmeClientMock) WaitOrderBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeWaitOrderCounter) +func (mmWaitOrder *AcmeClientMock) WaitOrderBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmWaitOrder.beforeWaitOrderCounter) +} + +// Calls returns a list of arguments used in each call to AcmeClientMock.WaitOrder. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmWaitOrder *mAcmeClientMockWaitOrder) Calls() []*AcmeClientMockWaitOrderParams { + mmWaitOrder.mutex.RLock() + + argCopy := make([]*AcmeClientMockWaitOrderParams, len(mmWaitOrder.callArgs)) + copy(argCopy, mmWaitOrder.callArgs) + + mmWaitOrder.mutex.RUnlock() + + return argCopy } // MinimockWaitOrderDone returns true if the count of the WaitOrder invocations corresponds // the number of defined expectations func (m *AcmeClientMock) MinimockWaitOrderDone() bool { for _, e := range m.WaitOrderMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.WaitOrderMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterWaitOrderCounter) < 1 { + if m.WaitOrderMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterWaitOrderCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcWaitOrder != nil && atomic.LoadUint64(&m.afterWaitOrderCounter) < 1 { + if m.funcWaitOrder != nil && mm_atomic.LoadUint64(&m.afterWaitOrderCounter) < 1 { return false } return true @@ -1650,17 +2048,21 @@ func (m *AcmeClientMock) MinimockWaitOrderDone() bool { // MinimockWaitOrderInspect logs each unmet expectation func (m *AcmeClientMock) MinimockWaitOrderInspect() { for _, e := range m.WaitOrderMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to AcmeClientMock.WaitOrder with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.WaitOrderMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterWaitOrderCounter) < 1 { - m.t.Errorf("Expected call to AcmeClientMock.WaitOrder with params: %#v", *m.WaitOrderMock.defaultExpectation.params) + if m.WaitOrderMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterWaitOrderCounter) < 1 { + if m.WaitOrderMock.defaultExpectation.params == nil { + m.t.Error("Expected call to AcmeClientMock.WaitOrder") + } else { + m.t.Errorf("Expected call to AcmeClientMock.WaitOrder with params: %#v", *m.WaitOrderMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcWaitOrder != nil && atomic.LoadUint64(&m.afterWaitOrderCounter) < 1 { + if m.funcWaitOrder != nil && mm_atomic.LoadUint64(&m.afterWaitOrderCounter) < 1 { m.t.Error("Expected call to AcmeClientMock.WaitOrder") } } @@ -1690,8 +2092,8 @@ func (m *AcmeClientMock) MinimockFinish() { } // MinimockWait waits for all mocked methods to be called the expected number of times -func (m *AcmeClientMock) MinimockWait(timeout time.Duration) { - timeoutCh := time.After(timeout) +func (m *AcmeClientMock) MinimockWait(timeout mm_time.Duration) { + timeoutCh := mm_time.After(timeout) for { if m.minimockDone() { return @@ -1700,7 +2102,7 @@ func (m *AcmeClientMock) MinimockWait(timeout time.Duration) { case <-timeoutCh: m.MinimockFinish() return - case <-time.After(10 * time.Millisecond): + case <-mm_time.After(10 * mm_time.Millisecond): } } } diff --git a/internal/cert_manager/cache_bytes_mock_test.go b/internal/cert_manager/cache_bytes_mock_test.go index 1ab46dfe..a71711c9 100644 --- a/internal/cert_manager/cache_bytes_mock_test.go +++ b/internal/cert_manager/cache_bytes_mock_test.go @@ -1,15 +1,14 @@ package cert_manager -// DO NOT EDIT! -// The code below was generated with http://github.com/gojuno/minimock (dev) +// Code generated by http://github.com/gojuno/minimock (3.0.6). DO NOT EDIT. //go:generate minimock -i github.com/rekby/lets-proxy2/internal/cache.Bytes -o ./cache_bytes_mock_test.go import ( - "sync/atomic" - "time" - "context" + "sync" + mm_atomic "sync/atomic" + mm_time "time" "github.com/gojuno/minimock/v3" ) @@ -19,16 +18,19 @@ type BytesMock struct { t minimock.Tester funcDelete func(ctx context.Context, key string) (err error) + inspectFuncDelete func(ctx context.Context, key string) afterDeleteCounter uint64 beforeDeleteCounter uint64 DeleteMock mBytesMockDelete funcGet func(ctx context.Context, key string) (ba1 []byte, err error) + inspectFuncGet func(ctx context.Context, key string) afterGetCounter uint64 beforeGetCounter uint64 GetMock mBytesMockGet funcPut func(ctx context.Context, key string, data []byte) (err error) + inspectFuncPut func(ctx context.Context, key string, data []byte) afterPutCounter uint64 beforePutCounter uint64 PutMock mBytesMockPut @@ -40,9 +42,15 @@ func NewBytesMock(t minimock.Tester) *BytesMock { if controller, ok := t.(minimock.MockController); ok { controller.RegisterMocker(m) } + m.DeleteMock = mBytesMockDelete{mock: m} + m.DeleteMock.callArgs = []*BytesMockDeleteParams{} + m.GetMock = mBytesMockGet{mock: m} + m.GetMock.callArgs = []*BytesMockGetParams{} + m.PutMock = mBytesMockPut{mock: m} + m.PutMock.callArgs = []*BytesMockPutParams{} return m } @@ -51,6 +59,9 @@ type mBytesMockDelete struct { mock *BytesMock defaultExpectation *BytesMockDeleteExpectation expectations []*BytesMockDeleteExpectation + + callArgs []*BytesMockDeleteParams + mutex sync.RWMutex } // BytesMockDeleteExpectation specifies expectation struct of the Bytes.Delete @@ -73,64 +84,75 @@ type BytesMockDeleteResults struct { } // Expect sets up expected params for Bytes.Delete -func (m *mBytesMockDelete) Expect(ctx context.Context, key string) *mBytesMockDelete { - if m.mock.funcDelete != nil { - m.mock.t.Fatalf("BytesMock.Delete mock is already set by Set") +func (mmDelete *mBytesMockDelete) Expect(ctx context.Context, key string) *mBytesMockDelete { + if mmDelete.mock.funcDelete != nil { + mmDelete.mock.t.Fatalf("BytesMock.Delete mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &BytesMockDeleteExpectation{} + if mmDelete.defaultExpectation == nil { + mmDelete.defaultExpectation = &BytesMockDeleteExpectation{} } - m.defaultExpectation.params = &BytesMockDeleteParams{ctx, key} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmDelete.defaultExpectation.params = &BytesMockDeleteParams{ctx, key} + for _, e := range mmDelete.expectations { + if minimock.Equal(e.params, mmDelete.defaultExpectation.params) { + mmDelete.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmDelete.defaultExpectation.params) } } - return m + return mmDelete +} + +// Inspect accepts an inspector function that has same arguments as the Bytes.Delete +func (mmDelete *mBytesMockDelete) Inspect(f func(ctx context.Context, key string)) *mBytesMockDelete { + if mmDelete.mock.inspectFuncDelete != nil { + mmDelete.mock.t.Fatalf("Inspect function is already set for BytesMock.Delete") + } + + mmDelete.mock.inspectFuncDelete = f + + return mmDelete } // Return sets up results that will be returned by Bytes.Delete -func (m *mBytesMockDelete) Return(err error) *BytesMock { - if m.mock.funcDelete != nil { - m.mock.t.Fatalf("BytesMock.Delete mock is already set by Set") +func (mmDelete *mBytesMockDelete) Return(err error) *BytesMock { + if mmDelete.mock.funcDelete != nil { + mmDelete.mock.t.Fatalf("BytesMock.Delete mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &BytesMockDeleteExpectation{mock: m.mock} + if mmDelete.defaultExpectation == nil { + mmDelete.defaultExpectation = &BytesMockDeleteExpectation{mock: mmDelete.mock} } - m.defaultExpectation.results = &BytesMockDeleteResults{err} - return m.mock + mmDelete.defaultExpectation.results = &BytesMockDeleteResults{err} + return mmDelete.mock } //Set uses given function f to mock the Bytes.Delete method -func (m *mBytesMockDelete) Set(f func(ctx context.Context, key string) (err error)) *BytesMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Bytes.Delete method") +func (mmDelete *mBytesMockDelete) Set(f func(ctx context.Context, key string) (err error)) *BytesMock { + if mmDelete.defaultExpectation != nil { + mmDelete.mock.t.Fatalf("Default expectation is already set for the Bytes.Delete method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Bytes.Delete method") + if len(mmDelete.expectations) > 0 { + mmDelete.mock.t.Fatalf("Some expectations are already set for the Bytes.Delete method") } - m.mock.funcDelete = f - return m.mock + mmDelete.mock.funcDelete = f + return mmDelete.mock } // When sets expectation for the Bytes.Delete which will trigger the result defined by the following // Then helper -func (m *mBytesMockDelete) When(ctx context.Context, key string) *BytesMockDeleteExpectation { - if m.mock.funcDelete != nil { - m.mock.t.Fatalf("BytesMock.Delete mock is already set by Set") +func (mmDelete *mBytesMockDelete) When(ctx context.Context, key string) *BytesMockDeleteExpectation { + if mmDelete.mock.funcDelete != nil { + mmDelete.mock.t.Fatalf("BytesMock.Delete mock is already set by Set") } expectation := &BytesMockDeleteExpectation{ - mock: m.mock, + mock: mmDelete.mock, params: &BytesMockDeleteParams{ctx, key}, } - m.expectations = append(m.expectations, expectation) + mmDelete.expectations = append(mmDelete.expectations, expectation) return expectation } @@ -141,63 +163,87 @@ func (e *BytesMockDeleteExpectation) Then(err error) *BytesMock { } // Delete implements cache.Bytes -func (m *BytesMock) Delete(ctx context.Context, key string) (err error) { - atomic.AddUint64(&m.beforeDeleteCounter, 1) - defer atomic.AddUint64(&m.afterDeleteCounter, 1) +func (mmDelete *BytesMock) Delete(ctx context.Context, key string) (err error) { + mm_atomic.AddUint64(&mmDelete.beforeDeleteCounter, 1) + defer mm_atomic.AddUint64(&mmDelete.afterDeleteCounter, 1) - for _, e := range m.DeleteMock.expectations { - if minimock.Equal(*e.params, BytesMockDeleteParams{ctx, key}) { - atomic.AddUint64(&e.Counter, 1) + if mmDelete.inspectFuncDelete != nil { + mmDelete.inspectFuncDelete(ctx, key) + } + + mm_params := &BytesMockDeleteParams{ctx, key} + + // Record call args + mmDelete.DeleteMock.mutex.Lock() + mmDelete.DeleteMock.callArgs = append(mmDelete.DeleteMock.callArgs, mm_params) + mmDelete.DeleteMock.mutex.Unlock() + + for _, e := range mmDelete.DeleteMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.err } } - if m.DeleteMock.defaultExpectation != nil { - atomic.AddUint64(&m.DeleteMock.defaultExpectation.Counter, 1) - want := m.DeleteMock.defaultExpectation.params - got := BytesMockDeleteParams{ctx, key} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("BytesMock.Delete got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmDelete.DeleteMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmDelete.DeleteMock.defaultExpectation.Counter, 1) + mm_want := mmDelete.DeleteMock.defaultExpectation.params + mm_got := BytesMockDeleteParams{ctx, key} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmDelete.t.Errorf("BytesMock.Delete got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.DeleteMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the BytesMock.Delete") + mm_results := mmDelete.DeleteMock.defaultExpectation.results + if mm_results == nil { + mmDelete.t.Fatal("No results are set for the BytesMock.Delete") } - return (*results).err + return (*mm_results).err } - if m.funcDelete != nil { - return m.funcDelete(ctx, key) + if mmDelete.funcDelete != nil { + return mmDelete.funcDelete(ctx, key) } - m.t.Fatalf("Unexpected call to BytesMock.Delete. %v %v", ctx, key) + mmDelete.t.Fatalf("Unexpected call to BytesMock.Delete. %v %v", ctx, key) return } // DeleteAfterCounter returns a count of finished BytesMock.Delete invocations -func (m *BytesMock) DeleteAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterDeleteCounter) +func (mmDelete *BytesMock) DeleteAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmDelete.afterDeleteCounter) } // DeleteBeforeCounter returns a count of BytesMock.Delete invocations -func (m *BytesMock) DeleteBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeDeleteCounter) +func (mmDelete *BytesMock) DeleteBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmDelete.beforeDeleteCounter) +} + +// Calls returns a list of arguments used in each call to BytesMock.Delete. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmDelete *mBytesMockDelete) Calls() []*BytesMockDeleteParams { + mmDelete.mutex.RLock() + + argCopy := make([]*BytesMockDeleteParams, len(mmDelete.callArgs)) + copy(argCopy, mmDelete.callArgs) + + mmDelete.mutex.RUnlock() + + return argCopy } // MinimockDeleteDone returns true if the count of the Delete invocations corresponds // the number of defined expectations func (m *BytesMock) MinimockDeleteDone() bool { for _, e := range m.DeleteMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.DeleteMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterDeleteCounter) < 1 { + if m.DeleteMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterDeleteCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcDelete != nil && atomic.LoadUint64(&m.afterDeleteCounter) < 1 { + if m.funcDelete != nil && mm_atomic.LoadUint64(&m.afterDeleteCounter) < 1 { return false } return true @@ -206,17 +252,21 @@ func (m *BytesMock) MinimockDeleteDone() bool { // MinimockDeleteInspect logs each unmet expectation func (m *BytesMock) MinimockDeleteInspect() { for _, e := range m.DeleteMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to BytesMock.Delete with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.DeleteMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterDeleteCounter) < 1 { - m.t.Errorf("Expected call to BytesMock.Delete with params: %#v", *m.DeleteMock.defaultExpectation.params) + if m.DeleteMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterDeleteCounter) < 1 { + if m.DeleteMock.defaultExpectation.params == nil { + m.t.Error("Expected call to BytesMock.Delete") + } else { + m.t.Errorf("Expected call to BytesMock.Delete with params: %#v", *m.DeleteMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcDelete != nil && atomic.LoadUint64(&m.afterDeleteCounter) < 1 { + if m.funcDelete != nil && mm_atomic.LoadUint64(&m.afterDeleteCounter) < 1 { m.t.Error("Expected call to BytesMock.Delete") } } @@ -225,6 +275,9 @@ type mBytesMockGet struct { mock *BytesMock defaultExpectation *BytesMockGetExpectation expectations []*BytesMockGetExpectation + + callArgs []*BytesMockGetParams + mutex sync.RWMutex } // BytesMockGetExpectation specifies expectation struct of the Bytes.Get @@ -248,64 +301,75 @@ type BytesMockGetResults struct { } // Expect sets up expected params for Bytes.Get -func (m *mBytesMockGet) Expect(ctx context.Context, key string) *mBytesMockGet { - if m.mock.funcGet != nil { - m.mock.t.Fatalf("BytesMock.Get mock is already set by Set") +func (mmGet *mBytesMockGet) Expect(ctx context.Context, key string) *mBytesMockGet { + if mmGet.mock.funcGet != nil { + mmGet.mock.t.Fatalf("BytesMock.Get mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &BytesMockGetExpectation{} + if mmGet.defaultExpectation == nil { + mmGet.defaultExpectation = &BytesMockGetExpectation{} } - m.defaultExpectation.params = &BytesMockGetParams{ctx, key} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmGet.defaultExpectation.params = &BytesMockGetParams{ctx, key} + for _, e := range mmGet.expectations { + if minimock.Equal(e.params, mmGet.defaultExpectation.params) { + mmGet.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmGet.defaultExpectation.params) } } - return m + return mmGet +} + +// Inspect accepts an inspector function that has same arguments as the Bytes.Get +func (mmGet *mBytesMockGet) Inspect(f func(ctx context.Context, key string)) *mBytesMockGet { + if mmGet.mock.inspectFuncGet != nil { + mmGet.mock.t.Fatalf("Inspect function is already set for BytesMock.Get") + } + + mmGet.mock.inspectFuncGet = f + + return mmGet } // Return sets up results that will be returned by Bytes.Get -func (m *mBytesMockGet) Return(ba1 []byte, err error) *BytesMock { - if m.mock.funcGet != nil { - m.mock.t.Fatalf("BytesMock.Get mock is already set by Set") +func (mmGet *mBytesMockGet) Return(ba1 []byte, err error) *BytesMock { + if mmGet.mock.funcGet != nil { + mmGet.mock.t.Fatalf("BytesMock.Get mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &BytesMockGetExpectation{mock: m.mock} + if mmGet.defaultExpectation == nil { + mmGet.defaultExpectation = &BytesMockGetExpectation{mock: mmGet.mock} } - m.defaultExpectation.results = &BytesMockGetResults{ba1, err} - return m.mock + mmGet.defaultExpectation.results = &BytesMockGetResults{ba1, err} + return mmGet.mock } //Set uses given function f to mock the Bytes.Get method -func (m *mBytesMockGet) Set(f func(ctx context.Context, key string) (ba1 []byte, err error)) *BytesMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Bytes.Get method") +func (mmGet *mBytesMockGet) Set(f func(ctx context.Context, key string) (ba1 []byte, err error)) *BytesMock { + if mmGet.defaultExpectation != nil { + mmGet.mock.t.Fatalf("Default expectation is already set for the Bytes.Get method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Bytes.Get method") + if len(mmGet.expectations) > 0 { + mmGet.mock.t.Fatalf("Some expectations are already set for the Bytes.Get method") } - m.mock.funcGet = f - return m.mock + mmGet.mock.funcGet = f + return mmGet.mock } // When sets expectation for the Bytes.Get which will trigger the result defined by the following // Then helper -func (m *mBytesMockGet) When(ctx context.Context, key string) *BytesMockGetExpectation { - if m.mock.funcGet != nil { - m.mock.t.Fatalf("BytesMock.Get mock is already set by Set") +func (mmGet *mBytesMockGet) When(ctx context.Context, key string) *BytesMockGetExpectation { + if mmGet.mock.funcGet != nil { + mmGet.mock.t.Fatalf("BytesMock.Get mock is already set by Set") } expectation := &BytesMockGetExpectation{ - mock: m.mock, + mock: mmGet.mock, params: &BytesMockGetParams{ctx, key}, } - m.expectations = append(m.expectations, expectation) + mmGet.expectations = append(mmGet.expectations, expectation) return expectation } @@ -316,63 +380,87 @@ func (e *BytesMockGetExpectation) Then(ba1 []byte, err error) *BytesMock { } // Get implements cache.Bytes -func (m *BytesMock) Get(ctx context.Context, key string) (ba1 []byte, err error) { - atomic.AddUint64(&m.beforeGetCounter, 1) - defer atomic.AddUint64(&m.afterGetCounter, 1) +func (mmGet *BytesMock) Get(ctx context.Context, key string) (ba1 []byte, err error) { + mm_atomic.AddUint64(&mmGet.beforeGetCounter, 1) + defer mm_atomic.AddUint64(&mmGet.afterGetCounter, 1) - for _, e := range m.GetMock.expectations { - if minimock.Equal(*e.params, BytesMockGetParams{ctx, key}) { - atomic.AddUint64(&e.Counter, 1) + if mmGet.inspectFuncGet != nil { + mmGet.inspectFuncGet(ctx, key) + } + + mm_params := &BytesMockGetParams{ctx, key} + + // Record call args + mmGet.GetMock.mutex.Lock() + mmGet.GetMock.callArgs = append(mmGet.GetMock.callArgs, mm_params) + mmGet.GetMock.mutex.Unlock() + + for _, e := range mmGet.GetMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.ba1, e.results.err } } - if m.GetMock.defaultExpectation != nil { - atomic.AddUint64(&m.GetMock.defaultExpectation.Counter, 1) - want := m.GetMock.defaultExpectation.params - got := BytesMockGetParams{ctx, key} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("BytesMock.Get got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmGet.GetMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmGet.GetMock.defaultExpectation.Counter, 1) + mm_want := mmGet.GetMock.defaultExpectation.params + mm_got := BytesMockGetParams{ctx, key} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmGet.t.Errorf("BytesMock.Get got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.GetMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the BytesMock.Get") + mm_results := mmGet.GetMock.defaultExpectation.results + if mm_results == nil { + mmGet.t.Fatal("No results are set for the BytesMock.Get") } - return (*results).ba1, (*results).err + return (*mm_results).ba1, (*mm_results).err } - if m.funcGet != nil { - return m.funcGet(ctx, key) + if mmGet.funcGet != nil { + return mmGet.funcGet(ctx, key) } - m.t.Fatalf("Unexpected call to BytesMock.Get. %v %v", ctx, key) + mmGet.t.Fatalf("Unexpected call to BytesMock.Get. %v %v", ctx, key) return } // GetAfterCounter returns a count of finished BytesMock.Get invocations -func (m *BytesMock) GetAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterGetCounter) +func (mmGet *BytesMock) GetAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmGet.afterGetCounter) } // GetBeforeCounter returns a count of BytesMock.Get invocations -func (m *BytesMock) GetBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeGetCounter) +func (mmGet *BytesMock) GetBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmGet.beforeGetCounter) +} + +// Calls returns a list of arguments used in each call to BytesMock.Get. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmGet *mBytesMockGet) Calls() []*BytesMockGetParams { + mmGet.mutex.RLock() + + argCopy := make([]*BytesMockGetParams, len(mmGet.callArgs)) + copy(argCopy, mmGet.callArgs) + + mmGet.mutex.RUnlock() + + return argCopy } // MinimockGetDone returns true if the count of the Get invocations corresponds // the number of defined expectations func (m *BytesMock) MinimockGetDone() bool { for _, e := range m.GetMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.GetMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterGetCounter) < 1 { + if m.GetMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterGetCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcGet != nil && atomic.LoadUint64(&m.afterGetCounter) < 1 { + if m.funcGet != nil && mm_atomic.LoadUint64(&m.afterGetCounter) < 1 { return false } return true @@ -381,17 +469,21 @@ func (m *BytesMock) MinimockGetDone() bool { // MinimockGetInspect logs each unmet expectation func (m *BytesMock) MinimockGetInspect() { for _, e := range m.GetMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to BytesMock.Get with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.GetMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterGetCounter) < 1 { - m.t.Errorf("Expected call to BytesMock.Get with params: %#v", *m.GetMock.defaultExpectation.params) + if m.GetMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterGetCounter) < 1 { + if m.GetMock.defaultExpectation.params == nil { + m.t.Error("Expected call to BytesMock.Get") + } else { + m.t.Errorf("Expected call to BytesMock.Get with params: %#v", *m.GetMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcGet != nil && atomic.LoadUint64(&m.afterGetCounter) < 1 { + if m.funcGet != nil && mm_atomic.LoadUint64(&m.afterGetCounter) < 1 { m.t.Error("Expected call to BytesMock.Get") } } @@ -400,6 +492,9 @@ type mBytesMockPut struct { mock *BytesMock defaultExpectation *BytesMockPutExpectation expectations []*BytesMockPutExpectation + + callArgs []*BytesMockPutParams + mutex sync.RWMutex } // BytesMockPutExpectation specifies expectation struct of the Bytes.Put @@ -423,64 +518,75 @@ type BytesMockPutResults struct { } // Expect sets up expected params for Bytes.Put -func (m *mBytesMockPut) Expect(ctx context.Context, key string, data []byte) *mBytesMockPut { - if m.mock.funcPut != nil { - m.mock.t.Fatalf("BytesMock.Put mock is already set by Set") +func (mmPut *mBytesMockPut) Expect(ctx context.Context, key string, data []byte) *mBytesMockPut { + if mmPut.mock.funcPut != nil { + mmPut.mock.t.Fatalf("BytesMock.Put mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &BytesMockPutExpectation{} + if mmPut.defaultExpectation == nil { + mmPut.defaultExpectation = &BytesMockPutExpectation{} } - m.defaultExpectation.params = &BytesMockPutParams{ctx, key, data} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmPut.defaultExpectation.params = &BytesMockPutParams{ctx, key, data} + for _, e := range mmPut.expectations { + if minimock.Equal(e.params, mmPut.defaultExpectation.params) { + mmPut.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmPut.defaultExpectation.params) } } - return m + return mmPut +} + +// Inspect accepts an inspector function that has same arguments as the Bytes.Put +func (mmPut *mBytesMockPut) Inspect(f func(ctx context.Context, key string, data []byte)) *mBytesMockPut { + if mmPut.mock.inspectFuncPut != nil { + mmPut.mock.t.Fatalf("Inspect function is already set for BytesMock.Put") + } + + mmPut.mock.inspectFuncPut = f + + return mmPut } // Return sets up results that will be returned by Bytes.Put -func (m *mBytesMockPut) Return(err error) *BytesMock { - if m.mock.funcPut != nil { - m.mock.t.Fatalf("BytesMock.Put mock is already set by Set") +func (mmPut *mBytesMockPut) Return(err error) *BytesMock { + if mmPut.mock.funcPut != nil { + mmPut.mock.t.Fatalf("BytesMock.Put mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &BytesMockPutExpectation{mock: m.mock} + if mmPut.defaultExpectation == nil { + mmPut.defaultExpectation = &BytesMockPutExpectation{mock: mmPut.mock} } - m.defaultExpectation.results = &BytesMockPutResults{err} - return m.mock + mmPut.defaultExpectation.results = &BytesMockPutResults{err} + return mmPut.mock } //Set uses given function f to mock the Bytes.Put method -func (m *mBytesMockPut) Set(f func(ctx context.Context, key string, data []byte) (err error)) *BytesMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Bytes.Put method") +func (mmPut *mBytesMockPut) Set(f func(ctx context.Context, key string, data []byte) (err error)) *BytesMock { + if mmPut.defaultExpectation != nil { + mmPut.mock.t.Fatalf("Default expectation is already set for the Bytes.Put method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Bytes.Put method") + if len(mmPut.expectations) > 0 { + mmPut.mock.t.Fatalf("Some expectations are already set for the Bytes.Put method") } - m.mock.funcPut = f - return m.mock + mmPut.mock.funcPut = f + return mmPut.mock } // When sets expectation for the Bytes.Put which will trigger the result defined by the following // Then helper -func (m *mBytesMockPut) When(ctx context.Context, key string, data []byte) *BytesMockPutExpectation { - if m.mock.funcPut != nil { - m.mock.t.Fatalf("BytesMock.Put mock is already set by Set") +func (mmPut *mBytesMockPut) When(ctx context.Context, key string, data []byte) *BytesMockPutExpectation { + if mmPut.mock.funcPut != nil { + mmPut.mock.t.Fatalf("BytesMock.Put mock is already set by Set") } expectation := &BytesMockPutExpectation{ - mock: m.mock, + mock: mmPut.mock, params: &BytesMockPutParams{ctx, key, data}, } - m.expectations = append(m.expectations, expectation) + mmPut.expectations = append(mmPut.expectations, expectation) return expectation } @@ -491,63 +597,87 @@ func (e *BytesMockPutExpectation) Then(err error) *BytesMock { } // Put implements cache.Bytes -func (m *BytesMock) Put(ctx context.Context, key string, data []byte) (err error) { - atomic.AddUint64(&m.beforePutCounter, 1) - defer atomic.AddUint64(&m.afterPutCounter, 1) +func (mmPut *BytesMock) Put(ctx context.Context, key string, data []byte) (err error) { + mm_atomic.AddUint64(&mmPut.beforePutCounter, 1) + defer mm_atomic.AddUint64(&mmPut.afterPutCounter, 1) - for _, e := range m.PutMock.expectations { - if minimock.Equal(*e.params, BytesMockPutParams{ctx, key, data}) { - atomic.AddUint64(&e.Counter, 1) + if mmPut.inspectFuncPut != nil { + mmPut.inspectFuncPut(ctx, key, data) + } + + mm_params := &BytesMockPutParams{ctx, key, data} + + // Record call args + mmPut.PutMock.mutex.Lock() + mmPut.PutMock.callArgs = append(mmPut.PutMock.callArgs, mm_params) + mmPut.PutMock.mutex.Unlock() + + for _, e := range mmPut.PutMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.err } } - if m.PutMock.defaultExpectation != nil { - atomic.AddUint64(&m.PutMock.defaultExpectation.Counter, 1) - want := m.PutMock.defaultExpectation.params - got := BytesMockPutParams{ctx, key, data} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("BytesMock.Put got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmPut.PutMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmPut.PutMock.defaultExpectation.Counter, 1) + mm_want := mmPut.PutMock.defaultExpectation.params + mm_got := BytesMockPutParams{ctx, key, data} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmPut.t.Errorf("BytesMock.Put got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.PutMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the BytesMock.Put") + mm_results := mmPut.PutMock.defaultExpectation.results + if mm_results == nil { + mmPut.t.Fatal("No results are set for the BytesMock.Put") } - return (*results).err + return (*mm_results).err } - if m.funcPut != nil { - return m.funcPut(ctx, key, data) + if mmPut.funcPut != nil { + return mmPut.funcPut(ctx, key, data) } - m.t.Fatalf("Unexpected call to BytesMock.Put. %v %v %v", ctx, key, data) + mmPut.t.Fatalf("Unexpected call to BytesMock.Put. %v %v %v", ctx, key, data) return } // PutAfterCounter returns a count of finished BytesMock.Put invocations -func (m *BytesMock) PutAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterPutCounter) +func (mmPut *BytesMock) PutAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmPut.afterPutCounter) } // PutBeforeCounter returns a count of BytesMock.Put invocations -func (m *BytesMock) PutBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforePutCounter) +func (mmPut *BytesMock) PutBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmPut.beforePutCounter) +} + +// Calls returns a list of arguments used in each call to BytesMock.Put. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmPut *mBytesMockPut) Calls() []*BytesMockPutParams { + mmPut.mutex.RLock() + + argCopy := make([]*BytesMockPutParams, len(mmPut.callArgs)) + copy(argCopy, mmPut.callArgs) + + mmPut.mutex.RUnlock() + + return argCopy } // MinimockPutDone returns true if the count of the Put invocations corresponds // the number of defined expectations func (m *BytesMock) MinimockPutDone() bool { for _, e := range m.PutMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.PutMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterPutCounter) < 1 { + if m.PutMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterPutCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcPut != nil && atomic.LoadUint64(&m.afterPutCounter) < 1 { + if m.funcPut != nil && mm_atomic.LoadUint64(&m.afterPutCounter) < 1 { return false } return true @@ -556,17 +686,21 @@ func (m *BytesMock) MinimockPutDone() bool { // MinimockPutInspect logs each unmet expectation func (m *BytesMock) MinimockPutInspect() { for _, e := range m.PutMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to BytesMock.Put with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.PutMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterPutCounter) < 1 { - m.t.Errorf("Expected call to BytesMock.Put with params: %#v", *m.PutMock.defaultExpectation.params) + if m.PutMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterPutCounter) < 1 { + if m.PutMock.defaultExpectation.params == nil { + m.t.Error("Expected call to BytesMock.Put") + } else { + m.t.Errorf("Expected call to BytesMock.Put with params: %#v", *m.PutMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcPut != nil && atomic.LoadUint64(&m.afterPutCounter) < 1 { + if m.funcPut != nil && mm_atomic.LoadUint64(&m.afterPutCounter) < 1 { m.t.Error("Expected call to BytesMock.Put") } } @@ -584,8 +718,8 @@ func (m *BytesMock) MinimockFinish() { } // MinimockWait waits for all mocked methods to be called the expected number of times -func (m *BytesMock) MinimockWait(timeout time.Duration) { - timeoutCh := time.After(timeout) +func (m *BytesMock) MinimockWait(timeout mm_time.Duration) { + timeoutCh := mm_time.After(timeout) for { if m.minimockDone() { return @@ -594,7 +728,7 @@ func (m *BytesMock) MinimockWait(timeout time.Duration) { case <-timeoutCh: m.MinimockFinish() return - case <-time.After(10 * time.Millisecond): + case <-mm_time.After(10 * mm_time.Millisecond): } } } diff --git a/internal/cert_manager/conn_mock_test.go b/internal/cert_manager/conn_mock_test.go index 58171a07..f8a3ce54 100644 --- a/internal/cert_manager/conn_mock_test.go +++ b/internal/cert_manager/conn_mock_test.go @@ -1,14 +1,15 @@ package cert_manager -// DO NOT EDIT! -// The code below was generated with http://github.com/gojuno/minimock (dev) +// Code generated by http://github.com/gojuno/minimock (3.0.6). DO NOT EDIT. //go:generate minimock -i net.Conn -o ./conn_mock_test.go import ( - "net" - "sync/atomic" + mm_net "net" + "sync" + mm_atomic "sync/atomic" "time" + mm_time "time" "github.com/gojuno/minimock/v3" ) @@ -18,41 +19,49 @@ type ConnMock struct { t minimock.Tester funcClose func() (err error) + inspectFuncClose func() afterCloseCounter uint64 beforeCloseCounter uint64 CloseMock mConnMockClose - funcLocalAddr func() (a1 net.Addr) + funcLocalAddr func() (a1 mm_net.Addr) + inspectFuncLocalAddr func() afterLocalAddrCounter uint64 beforeLocalAddrCounter uint64 LocalAddrMock mConnMockLocalAddr funcRead func(b []byte) (n int, err error) + inspectFuncRead func(b []byte) afterReadCounter uint64 beforeReadCounter uint64 ReadMock mConnMockRead - funcRemoteAddr func() (a1 net.Addr) + funcRemoteAddr func() (a1 mm_net.Addr) + inspectFuncRemoteAddr func() afterRemoteAddrCounter uint64 beforeRemoteAddrCounter uint64 RemoteAddrMock mConnMockRemoteAddr funcSetDeadline func(t time.Time) (err error) + inspectFuncSetDeadline func(t time.Time) afterSetDeadlineCounter uint64 beforeSetDeadlineCounter uint64 SetDeadlineMock mConnMockSetDeadline funcSetReadDeadline func(t time.Time) (err error) + inspectFuncSetReadDeadline func(t time.Time) afterSetReadDeadlineCounter uint64 beforeSetReadDeadlineCounter uint64 SetReadDeadlineMock mConnMockSetReadDeadline funcSetWriteDeadline func(t time.Time) (err error) + inspectFuncSetWriteDeadline func(t time.Time) afterSetWriteDeadlineCounter uint64 beforeSetWriteDeadlineCounter uint64 SetWriteDeadlineMock mConnMockSetWriteDeadline funcWrite func(b []byte) (n int, err error) + inspectFuncWrite func(b []byte) afterWriteCounter uint64 beforeWriteCounter uint64 WriteMock mConnMockWrite @@ -64,14 +73,27 @@ func NewConnMock(t minimock.Tester) *ConnMock { if controller, ok := t.(minimock.MockController); ok { controller.RegisterMocker(m) } + m.CloseMock = mConnMockClose{mock: m} + m.LocalAddrMock = mConnMockLocalAddr{mock: m} + m.ReadMock = mConnMockRead{mock: m} + m.ReadMock.callArgs = []*ConnMockReadParams{} + m.RemoteAddrMock = mConnMockRemoteAddr{mock: m} + m.SetDeadlineMock = mConnMockSetDeadline{mock: m} + m.SetDeadlineMock.callArgs = []*ConnMockSetDeadlineParams{} + m.SetReadDeadlineMock = mConnMockSetReadDeadline{mock: m} + m.SetReadDeadlineMock.callArgs = []*ConnMockSetReadDeadlineParams{} + m.SetWriteDeadlineMock = mConnMockSetWriteDeadline{mock: m} + m.SetWriteDeadlineMock.callArgs = []*ConnMockSetWriteDeadlineParams{} + m.WriteMock = mConnMockWrite{mock: m} + m.WriteMock.callArgs = []*ConnMockWriteParams{} return m } @@ -96,91 +118,106 @@ type ConnMockCloseResults struct { } // Expect sets up expected params for Conn.Close -func (m *mConnMockClose) Expect() *mConnMockClose { - if m.mock.funcClose != nil { - m.mock.t.Fatalf("ConnMock.Close mock is already set by Set") +func (mmClose *mConnMockClose) Expect() *mConnMockClose { + if mmClose.mock.funcClose != nil { + mmClose.mock.t.Fatalf("ConnMock.Close mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockCloseExpectation{} + if mmClose.defaultExpectation == nil { + mmClose.defaultExpectation = &ConnMockCloseExpectation{} } - return m + return mmClose +} + +// Inspect accepts an inspector function that has same arguments as the Conn.Close +func (mmClose *mConnMockClose) Inspect(f func()) *mConnMockClose { + if mmClose.mock.inspectFuncClose != nil { + mmClose.mock.t.Fatalf("Inspect function is already set for ConnMock.Close") + } + + mmClose.mock.inspectFuncClose = f + + return mmClose } // Return sets up results that will be returned by Conn.Close -func (m *mConnMockClose) Return(err error) *ConnMock { - if m.mock.funcClose != nil { - m.mock.t.Fatalf("ConnMock.Close mock is already set by Set") +func (mmClose *mConnMockClose) Return(err error) *ConnMock { + if mmClose.mock.funcClose != nil { + mmClose.mock.t.Fatalf("ConnMock.Close mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockCloseExpectation{mock: m.mock} + if mmClose.defaultExpectation == nil { + mmClose.defaultExpectation = &ConnMockCloseExpectation{mock: mmClose.mock} } - m.defaultExpectation.results = &ConnMockCloseResults{err} - return m.mock + mmClose.defaultExpectation.results = &ConnMockCloseResults{err} + return mmClose.mock } //Set uses given function f to mock the Conn.Close method -func (m *mConnMockClose) Set(f func() (err error)) *ConnMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Conn.Close method") +func (mmClose *mConnMockClose) Set(f func() (err error)) *ConnMock { + if mmClose.defaultExpectation != nil { + mmClose.mock.t.Fatalf("Default expectation is already set for the Conn.Close method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Conn.Close method") + if len(mmClose.expectations) > 0 { + mmClose.mock.t.Fatalf("Some expectations are already set for the Conn.Close method") } - m.mock.funcClose = f - return m.mock + mmClose.mock.funcClose = f + return mmClose.mock } // Close implements net.Conn -func (m *ConnMock) Close() (err error) { - atomic.AddUint64(&m.beforeCloseCounter, 1) - defer atomic.AddUint64(&m.afterCloseCounter, 1) +func (mmClose *ConnMock) Close() (err error) { + mm_atomic.AddUint64(&mmClose.beforeCloseCounter, 1) + defer mm_atomic.AddUint64(&mmClose.afterCloseCounter, 1) + + if mmClose.inspectFuncClose != nil { + mmClose.inspectFuncClose() + } - if m.CloseMock.defaultExpectation != nil { - atomic.AddUint64(&m.CloseMock.defaultExpectation.Counter, 1) + if mmClose.CloseMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmClose.CloseMock.defaultExpectation.Counter, 1) - results := m.CloseMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the ConnMock.Close") + mm_results := mmClose.CloseMock.defaultExpectation.results + if mm_results == nil { + mmClose.t.Fatal("No results are set for the ConnMock.Close") } - return (*results).err + return (*mm_results).err } - if m.funcClose != nil { - return m.funcClose() + if mmClose.funcClose != nil { + return mmClose.funcClose() } - m.t.Fatalf("Unexpected call to ConnMock.Close.") + mmClose.t.Fatalf("Unexpected call to ConnMock.Close.") return } // CloseAfterCounter returns a count of finished ConnMock.Close invocations -func (m *ConnMock) CloseAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterCloseCounter) +func (mmClose *ConnMock) CloseAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmClose.afterCloseCounter) } // CloseBeforeCounter returns a count of ConnMock.Close invocations -func (m *ConnMock) CloseBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeCloseCounter) +func (mmClose *ConnMock) CloseBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmClose.beforeCloseCounter) } // MinimockCloseDone returns true if the count of the Close invocations corresponds // the number of defined expectations func (m *ConnMock) MinimockCloseDone() bool { for _, e := range m.CloseMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.CloseMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterCloseCounter) < 1 { + if m.CloseMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterCloseCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcClose != nil && atomic.LoadUint64(&m.afterCloseCounter) < 1 { + if m.funcClose != nil && mm_atomic.LoadUint64(&m.afterCloseCounter) < 1 { return false } return true @@ -189,17 +226,17 @@ func (m *ConnMock) MinimockCloseDone() bool { // MinimockCloseInspect logs each unmet expectation func (m *ConnMock) MinimockCloseInspect() { for _, e := range m.CloseMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Error("Expected call to ConnMock.Close") } } // if default expectation was set then invocations count should be greater than zero - if m.CloseMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterCloseCounter) < 1 { + if m.CloseMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterCloseCounter) < 1 { m.t.Error("Expected call to ConnMock.Close") } // if func was set then invocations count should be greater than zero - if m.funcClose != nil && atomic.LoadUint64(&m.afterCloseCounter) < 1 { + if m.funcClose != nil && mm_atomic.LoadUint64(&m.afterCloseCounter) < 1 { m.t.Error("Expected call to ConnMock.Close") } } @@ -220,95 +257,110 @@ type ConnMockLocalAddrExpectation struct { // ConnMockLocalAddrResults contains results of the Conn.LocalAddr type ConnMockLocalAddrResults struct { - a1 net.Addr + a1 mm_net.Addr } // Expect sets up expected params for Conn.LocalAddr -func (m *mConnMockLocalAddr) Expect() *mConnMockLocalAddr { - if m.mock.funcLocalAddr != nil { - m.mock.t.Fatalf("ConnMock.LocalAddr mock is already set by Set") +func (mmLocalAddr *mConnMockLocalAddr) Expect() *mConnMockLocalAddr { + if mmLocalAddr.mock.funcLocalAddr != nil { + mmLocalAddr.mock.t.Fatalf("ConnMock.LocalAddr mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockLocalAddrExpectation{} + if mmLocalAddr.defaultExpectation == nil { + mmLocalAddr.defaultExpectation = &ConnMockLocalAddrExpectation{} } - return m + return mmLocalAddr +} + +// Inspect accepts an inspector function that has same arguments as the Conn.LocalAddr +func (mmLocalAddr *mConnMockLocalAddr) Inspect(f func()) *mConnMockLocalAddr { + if mmLocalAddr.mock.inspectFuncLocalAddr != nil { + mmLocalAddr.mock.t.Fatalf("Inspect function is already set for ConnMock.LocalAddr") + } + + mmLocalAddr.mock.inspectFuncLocalAddr = f + + return mmLocalAddr } // Return sets up results that will be returned by Conn.LocalAddr -func (m *mConnMockLocalAddr) Return(a1 net.Addr) *ConnMock { - if m.mock.funcLocalAddr != nil { - m.mock.t.Fatalf("ConnMock.LocalAddr mock is already set by Set") +func (mmLocalAddr *mConnMockLocalAddr) Return(a1 mm_net.Addr) *ConnMock { + if mmLocalAddr.mock.funcLocalAddr != nil { + mmLocalAddr.mock.t.Fatalf("ConnMock.LocalAddr mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockLocalAddrExpectation{mock: m.mock} + if mmLocalAddr.defaultExpectation == nil { + mmLocalAddr.defaultExpectation = &ConnMockLocalAddrExpectation{mock: mmLocalAddr.mock} } - m.defaultExpectation.results = &ConnMockLocalAddrResults{a1} - return m.mock + mmLocalAddr.defaultExpectation.results = &ConnMockLocalAddrResults{a1} + return mmLocalAddr.mock } //Set uses given function f to mock the Conn.LocalAddr method -func (m *mConnMockLocalAddr) Set(f func() (a1 net.Addr)) *ConnMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Conn.LocalAddr method") +func (mmLocalAddr *mConnMockLocalAddr) Set(f func() (a1 mm_net.Addr)) *ConnMock { + if mmLocalAddr.defaultExpectation != nil { + mmLocalAddr.mock.t.Fatalf("Default expectation is already set for the Conn.LocalAddr method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Conn.LocalAddr method") + if len(mmLocalAddr.expectations) > 0 { + mmLocalAddr.mock.t.Fatalf("Some expectations are already set for the Conn.LocalAddr method") } - m.mock.funcLocalAddr = f - return m.mock + mmLocalAddr.mock.funcLocalAddr = f + return mmLocalAddr.mock } // LocalAddr implements net.Conn -func (m *ConnMock) LocalAddr() (a1 net.Addr) { - atomic.AddUint64(&m.beforeLocalAddrCounter, 1) - defer atomic.AddUint64(&m.afterLocalAddrCounter, 1) +func (mmLocalAddr *ConnMock) LocalAddr() (a1 mm_net.Addr) { + mm_atomic.AddUint64(&mmLocalAddr.beforeLocalAddrCounter, 1) + defer mm_atomic.AddUint64(&mmLocalAddr.afterLocalAddrCounter, 1) + + if mmLocalAddr.inspectFuncLocalAddr != nil { + mmLocalAddr.inspectFuncLocalAddr() + } - if m.LocalAddrMock.defaultExpectation != nil { - atomic.AddUint64(&m.LocalAddrMock.defaultExpectation.Counter, 1) + if mmLocalAddr.LocalAddrMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmLocalAddr.LocalAddrMock.defaultExpectation.Counter, 1) - results := m.LocalAddrMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the ConnMock.LocalAddr") + mm_results := mmLocalAddr.LocalAddrMock.defaultExpectation.results + if mm_results == nil { + mmLocalAddr.t.Fatal("No results are set for the ConnMock.LocalAddr") } - return (*results).a1 + return (*mm_results).a1 } - if m.funcLocalAddr != nil { - return m.funcLocalAddr() + if mmLocalAddr.funcLocalAddr != nil { + return mmLocalAddr.funcLocalAddr() } - m.t.Fatalf("Unexpected call to ConnMock.LocalAddr.") + mmLocalAddr.t.Fatalf("Unexpected call to ConnMock.LocalAddr.") return } // LocalAddrAfterCounter returns a count of finished ConnMock.LocalAddr invocations -func (m *ConnMock) LocalAddrAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterLocalAddrCounter) +func (mmLocalAddr *ConnMock) LocalAddrAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmLocalAddr.afterLocalAddrCounter) } // LocalAddrBeforeCounter returns a count of ConnMock.LocalAddr invocations -func (m *ConnMock) LocalAddrBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeLocalAddrCounter) +func (mmLocalAddr *ConnMock) LocalAddrBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmLocalAddr.beforeLocalAddrCounter) } // MinimockLocalAddrDone returns true if the count of the LocalAddr invocations corresponds // the number of defined expectations func (m *ConnMock) MinimockLocalAddrDone() bool { for _, e := range m.LocalAddrMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.LocalAddrMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterLocalAddrCounter) < 1 { + if m.LocalAddrMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterLocalAddrCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcLocalAddr != nil && atomic.LoadUint64(&m.afterLocalAddrCounter) < 1 { + if m.funcLocalAddr != nil && mm_atomic.LoadUint64(&m.afterLocalAddrCounter) < 1 { return false } return true @@ -317,17 +369,17 @@ func (m *ConnMock) MinimockLocalAddrDone() bool { // MinimockLocalAddrInspect logs each unmet expectation func (m *ConnMock) MinimockLocalAddrInspect() { for _, e := range m.LocalAddrMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Error("Expected call to ConnMock.LocalAddr") } } // if default expectation was set then invocations count should be greater than zero - if m.LocalAddrMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterLocalAddrCounter) < 1 { + if m.LocalAddrMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterLocalAddrCounter) < 1 { m.t.Error("Expected call to ConnMock.LocalAddr") } // if func was set then invocations count should be greater than zero - if m.funcLocalAddr != nil && atomic.LoadUint64(&m.afterLocalAddrCounter) < 1 { + if m.funcLocalAddr != nil && mm_atomic.LoadUint64(&m.afterLocalAddrCounter) < 1 { m.t.Error("Expected call to ConnMock.LocalAddr") } } @@ -336,6 +388,9 @@ type mConnMockRead struct { mock *ConnMock defaultExpectation *ConnMockReadExpectation expectations []*ConnMockReadExpectation + + callArgs []*ConnMockReadParams + mutex sync.RWMutex } // ConnMockReadExpectation specifies expectation struct of the Conn.Read @@ -358,64 +413,75 @@ type ConnMockReadResults struct { } // Expect sets up expected params for Conn.Read -func (m *mConnMockRead) Expect(b []byte) *mConnMockRead { - if m.mock.funcRead != nil { - m.mock.t.Fatalf("ConnMock.Read mock is already set by Set") +func (mmRead *mConnMockRead) Expect(b []byte) *mConnMockRead { + if mmRead.mock.funcRead != nil { + mmRead.mock.t.Fatalf("ConnMock.Read mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockReadExpectation{} + if mmRead.defaultExpectation == nil { + mmRead.defaultExpectation = &ConnMockReadExpectation{} } - m.defaultExpectation.params = &ConnMockReadParams{b} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmRead.defaultExpectation.params = &ConnMockReadParams{b} + for _, e := range mmRead.expectations { + if minimock.Equal(e.params, mmRead.defaultExpectation.params) { + mmRead.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmRead.defaultExpectation.params) } } - return m + return mmRead +} + +// Inspect accepts an inspector function that has same arguments as the Conn.Read +func (mmRead *mConnMockRead) Inspect(f func(b []byte)) *mConnMockRead { + if mmRead.mock.inspectFuncRead != nil { + mmRead.mock.t.Fatalf("Inspect function is already set for ConnMock.Read") + } + + mmRead.mock.inspectFuncRead = f + + return mmRead } // Return sets up results that will be returned by Conn.Read -func (m *mConnMockRead) Return(n int, err error) *ConnMock { - if m.mock.funcRead != nil { - m.mock.t.Fatalf("ConnMock.Read mock is already set by Set") +func (mmRead *mConnMockRead) Return(n int, err error) *ConnMock { + if mmRead.mock.funcRead != nil { + mmRead.mock.t.Fatalf("ConnMock.Read mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockReadExpectation{mock: m.mock} + if mmRead.defaultExpectation == nil { + mmRead.defaultExpectation = &ConnMockReadExpectation{mock: mmRead.mock} } - m.defaultExpectation.results = &ConnMockReadResults{n, err} - return m.mock + mmRead.defaultExpectation.results = &ConnMockReadResults{n, err} + return mmRead.mock } //Set uses given function f to mock the Conn.Read method -func (m *mConnMockRead) Set(f func(b []byte) (n int, err error)) *ConnMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Conn.Read method") +func (mmRead *mConnMockRead) Set(f func(b []byte) (n int, err error)) *ConnMock { + if mmRead.defaultExpectation != nil { + mmRead.mock.t.Fatalf("Default expectation is already set for the Conn.Read method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Conn.Read method") + if len(mmRead.expectations) > 0 { + mmRead.mock.t.Fatalf("Some expectations are already set for the Conn.Read method") } - m.mock.funcRead = f - return m.mock + mmRead.mock.funcRead = f + return mmRead.mock } // When sets expectation for the Conn.Read which will trigger the result defined by the following // Then helper -func (m *mConnMockRead) When(b []byte) *ConnMockReadExpectation { - if m.mock.funcRead != nil { - m.mock.t.Fatalf("ConnMock.Read mock is already set by Set") +func (mmRead *mConnMockRead) When(b []byte) *ConnMockReadExpectation { + if mmRead.mock.funcRead != nil { + mmRead.mock.t.Fatalf("ConnMock.Read mock is already set by Set") } expectation := &ConnMockReadExpectation{ - mock: m.mock, + mock: mmRead.mock, params: &ConnMockReadParams{b}, } - m.expectations = append(m.expectations, expectation) + mmRead.expectations = append(mmRead.expectations, expectation) return expectation } @@ -426,63 +492,87 @@ func (e *ConnMockReadExpectation) Then(n int, err error) *ConnMock { } // Read implements net.Conn -func (m *ConnMock) Read(b []byte) (n int, err error) { - atomic.AddUint64(&m.beforeReadCounter, 1) - defer atomic.AddUint64(&m.afterReadCounter, 1) +func (mmRead *ConnMock) Read(b []byte) (n int, err error) { + mm_atomic.AddUint64(&mmRead.beforeReadCounter, 1) + defer mm_atomic.AddUint64(&mmRead.afterReadCounter, 1) - for _, e := range m.ReadMock.expectations { - if minimock.Equal(*e.params, ConnMockReadParams{b}) { - atomic.AddUint64(&e.Counter, 1) + if mmRead.inspectFuncRead != nil { + mmRead.inspectFuncRead(b) + } + + mm_params := &ConnMockReadParams{b} + + // Record call args + mmRead.ReadMock.mutex.Lock() + mmRead.ReadMock.callArgs = append(mmRead.ReadMock.callArgs, mm_params) + mmRead.ReadMock.mutex.Unlock() + + for _, e := range mmRead.ReadMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.n, e.results.err } } - if m.ReadMock.defaultExpectation != nil { - atomic.AddUint64(&m.ReadMock.defaultExpectation.Counter, 1) - want := m.ReadMock.defaultExpectation.params - got := ConnMockReadParams{b} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("ConnMock.Read got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmRead.ReadMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmRead.ReadMock.defaultExpectation.Counter, 1) + mm_want := mmRead.ReadMock.defaultExpectation.params + mm_got := ConnMockReadParams{b} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmRead.t.Errorf("ConnMock.Read got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.ReadMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the ConnMock.Read") + mm_results := mmRead.ReadMock.defaultExpectation.results + if mm_results == nil { + mmRead.t.Fatal("No results are set for the ConnMock.Read") } - return (*results).n, (*results).err + return (*mm_results).n, (*mm_results).err } - if m.funcRead != nil { - return m.funcRead(b) + if mmRead.funcRead != nil { + return mmRead.funcRead(b) } - m.t.Fatalf("Unexpected call to ConnMock.Read. %v", b) + mmRead.t.Fatalf("Unexpected call to ConnMock.Read. %v", b) return } // ReadAfterCounter returns a count of finished ConnMock.Read invocations -func (m *ConnMock) ReadAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterReadCounter) +func (mmRead *ConnMock) ReadAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmRead.afterReadCounter) } // ReadBeforeCounter returns a count of ConnMock.Read invocations -func (m *ConnMock) ReadBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeReadCounter) +func (mmRead *ConnMock) ReadBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmRead.beforeReadCounter) +} + +// Calls returns a list of arguments used in each call to ConnMock.Read. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmRead *mConnMockRead) Calls() []*ConnMockReadParams { + mmRead.mutex.RLock() + + argCopy := make([]*ConnMockReadParams, len(mmRead.callArgs)) + copy(argCopy, mmRead.callArgs) + + mmRead.mutex.RUnlock() + + return argCopy } // MinimockReadDone returns true if the count of the Read invocations corresponds // the number of defined expectations func (m *ConnMock) MinimockReadDone() bool { for _, e := range m.ReadMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.ReadMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterReadCounter) < 1 { + if m.ReadMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterReadCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcRead != nil && atomic.LoadUint64(&m.afterReadCounter) < 1 { + if m.funcRead != nil && mm_atomic.LoadUint64(&m.afterReadCounter) < 1 { return false } return true @@ -491,17 +581,21 @@ func (m *ConnMock) MinimockReadDone() bool { // MinimockReadInspect logs each unmet expectation func (m *ConnMock) MinimockReadInspect() { for _, e := range m.ReadMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to ConnMock.Read with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.ReadMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterReadCounter) < 1 { - m.t.Errorf("Expected call to ConnMock.Read with params: %#v", *m.ReadMock.defaultExpectation.params) + if m.ReadMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterReadCounter) < 1 { + if m.ReadMock.defaultExpectation.params == nil { + m.t.Error("Expected call to ConnMock.Read") + } else { + m.t.Errorf("Expected call to ConnMock.Read with params: %#v", *m.ReadMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcRead != nil && atomic.LoadUint64(&m.afterReadCounter) < 1 { + if m.funcRead != nil && mm_atomic.LoadUint64(&m.afterReadCounter) < 1 { m.t.Error("Expected call to ConnMock.Read") } } @@ -522,95 +616,110 @@ type ConnMockRemoteAddrExpectation struct { // ConnMockRemoteAddrResults contains results of the Conn.RemoteAddr type ConnMockRemoteAddrResults struct { - a1 net.Addr + a1 mm_net.Addr } // Expect sets up expected params for Conn.RemoteAddr -func (m *mConnMockRemoteAddr) Expect() *mConnMockRemoteAddr { - if m.mock.funcRemoteAddr != nil { - m.mock.t.Fatalf("ConnMock.RemoteAddr mock is already set by Set") +func (mmRemoteAddr *mConnMockRemoteAddr) Expect() *mConnMockRemoteAddr { + if mmRemoteAddr.mock.funcRemoteAddr != nil { + mmRemoteAddr.mock.t.Fatalf("ConnMock.RemoteAddr mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockRemoteAddrExpectation{} + if mmRemoteAddr.defaultExpectation == nil { + mmRemoteAddr.defaultExpectation = &ConnMockRemoteAddrExpectation{} } - return m + return mmRemoteAddr +} + +// Inspect accepts an inspector function that has same arguments as the Conn.RemoteAddr +func (mmRemoteAddr *mConnMockRemoteAddr) Inspect(f func()) *mConnMockRemoteAddr { + if mmRemoteAddr.mock.inspectFuncRemoteAddr != nil { + mmRemoteAddr.mock.t.Fatalf("Inspect function is already set for ConnMock.RemoteAddr") + } + + mmRemoteAddr.mock.inspectFuncRemoteAddr = f + + return mmRemoteAddr } // Return sets up results that will be returned by Conn.RemoteAddr -func (m *mConnMockRemoteAddr) Return(a1 net.Addr) *ConnMock { - if m.mock.funcRemoteAddr != nil { - m.mock.t.Fatalf("ConnMock.RemoteAddr mock is already set by Set") +func (mmRemoteAddr *mConnMockRemoteAddr) Return(a1 mm_net.Addr) *ConnMock { + if mmRemoteAddr.mock.funcRemoteAddr != nil { + mmRemoteAddr.mock.t.Fatalf("ConnMock.RemoteAddr mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockRemoteAddrExpectation{mock: m.mock} + if mmRemoteAddr.defaultExpectation == nil { + mmRemoteAddr.defaultExpectation = &ConnMockRemoteAddrExpectation{mock: mmRemoteAddr.mock} } - m.defaultExpectation.results = &ConnMockRemoteAddrResults{a1} - return m.mock + mmRemoteAddr.defaultExpectation.results = &ConnMockRemoteAddrResults{a1} + return mmRemoteAddr.mock } //Set uses given function f to mock the Conn.RemoteAddr method -func (m *mConnMockRemoteAddr) Set(f func() (a1 net.Addr)) *ConnMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Conn.RemoteAddr method") +func (mmRemoteAddr *mConnMockRemoteAddr) Set(f func() (a1 mm_net.Addr)) *ConnMock { + if mmRemoteAddr.defaultExpectation != nil { + mmRemoteAddr.mock.t.Fatalf("Default expectation is already set for the Conn.RemoteAddr method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Conn.RemoteAddr method") + if len(mmRemoteAddr.expectations) > 0 { + mmRemoteAddr.mock.t.Fatalf("Some expectations are already set for the Conn.RemoteAddr method") } - m.mock.funcRemoteAddr = f - return m.mock + mmRemoteAddr.mock.funcRemoteAddr = f + return mmRemoteAddr.mock } // RemoteAddr implements net.Conn -func (m *ConnMock) RemoteAddr() (a1 net.Addr) { - atomic.AddUint64(&m.beforeRemoteAddrCounter, 1) - defer atomic.AddUint64(&m.afterRemoteAddrCounter, 1) +func (mmRemoteAddr *ConnMock) RemoteAddr() (a1 mm_net.Addr) { + mm_atomic.AddUint64(&mmRemoteAddr.beforeRemoteAddrCounter, 1) + defer mm_atomic.AddUint64(&mmRemoteAddr.afterRemoteAddrCounter, 1) + + if mmRemoteAddr.inspectFuncRemoteAddr != nil { + mmRemoteAddr.inspectFuncRemoteAddr() + } - if m.RemoteAddrMock.defaultExpectation != nil { - atomic.AddUint64(&m.RemoteAddrMock.defaultExpectation.Counter, 1) + if mmRemoteAddr.RemoteAddrMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmRemoteAddr.RemoteAddrMock.defaultExpectation.Counter, 1) - results := m.RemoteAddrMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the ConnMock.RemoteAddr") + mm_results := mmRemoteAddr.RemoteAddrMock.defaultExpectation.results + if mm_results == nil { + mmRemoteAddr.t.Fatal("No results are set for the ConnMock.RemoteAddr") } - return (*results).a1 + return (*mm_results).a1 } - if m.funcRemoteAddr != nil { - return m.funcRemoteAddr() + if mmRemoteAddr.funcRemoteAddr != nil { + return mmRemoteAddr.funcRemoteAddr() } - m.t.Fatalf("Unexpected call to ConnMock.RemoteAddr.") + mmRemoteAddr.t.Fatalf("Unexpected call to ConnMock.RemoteAddr.") return } // RemoteAddrAfterCounter returns a count of finished ConnMock.RemoteAddr invocations -func (m *ConnMock) RemoteAddrAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterRemoteAddrCounter) +func (mmRemoteAddr *ConnMock) RemoteAddrAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmRemoteAddr.afterRemoteAddrCounter) } // RemoteAddrBeforeCounter returns a count of ConnMock.RemoteAddr invocations -func (m *ConnMock) RemoteAddrBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeRemoteAddrCounter) +func (mmRemoteAddr *ConnMock) RemoteAddrBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmRemoteAddr.beforeRemoteAddrCounter) } // MinimockRemoteAddrDone returns true if the count of the RemoteAddr invocations corresponds // the number of defined expectations func (m *ConnMock) MinimockRemoteAddrDone() bool { for _, e := range m.RemoteAddrMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.RemoteAddrMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterRemoteAddrCounter) < 1 { + if m.RemoteAddrMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterRemoteAddrCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcRemoteAddr != nil && atomic.LoadUint64(&m.afterRemoteAddrCounter) < 1 { + if m.funcRemoteAddr != nil && mm_atomic.LoadUint64(&m.afterRemoteAddrCounter) < 1 { return false } return true @@ -619,17 +728,17 @@ func (m *ConnMock) MinimockRemoteAddrDone() bool { // MinimockRemoteAddrInspect logs each unmet expectation func (m *ConnMock) MinimockRemoteAddrInspect() { for _, e := range m.RemoteAddrMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Error("Expected call to ConnMock.RemoteAddr") } } // if default expectation was set then invocations count should be greater than zero - if m.RemoteAddrMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterRemoteAddrCounter) < 1 { + if m.RemoteAddrMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterRemoteAddrCounter) < 1 { m.t.Error("Expected call to ConnMock.RemoteAddr") } // if func was set then invocations count should be greater than zero - if m.funcRemoteAddr != nil && atomic.LoadUint64(&m.afterRemoteAddrCounter) < 1 { + if m.funcRemoteAddr != nil && mm_atomic.LoadUint64(&m.afterRemoteAddrCounter) < 1 { m.t.Error("Expected call to ConnMock.RemoteAddr") } } @@ -638,6 +747,9 @@ type mConnMockSetDeadline struct { mock *ConnMock defaultExpectation *ConnMockSetDeadlineExpectation expectations []*ConnMockSetDeadlineExpectation + + callArgs []*ConnMockSetDeadlineParams + mutex sync.RWMutex } // ConnMockSetDeadlineExpectation specifies expectation struct of the Conn.SetDeadline @@ -659,64 +771,75 @@ type ConnMockSetDeadlineResults struct { } // Expect sets up expected params for Conn.SetDeadline -func (m *mConnMockSetDeadline) Expect(t time.Time) *mConnMockSetDeadline { - if m.mock.funcSetDeadline != nil { - m.mock.t.Fatalf("ConnMock.SetDeadline mock is already set by Set") +func (mmSetDeadline *mConnMockSetDeadline) Expect(t time.Time) *mConnMockSetDeadline { + if mmSetDeadline.mock.funcSetDeadline != nil { + mmSetDeadline.mock.t.Fatalf("ConnMock.SetDeadline mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockSetDeadlineExpectation{} + if mmSetDeadline.defaultExpectation == nil { + mmSetDeadline.defaultExpectation = &ConnMockSetDeadlineExpectation{} } - m.defaultExpectation.params = &ConnMockSetDeadlineParams{t} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmSetDeadline.defaultExpectation.params = &ConnMockSetDeadlineParams{t} + for _, e := range mmSetDeadline.expectations { + if minimock.Equal(e.params, mmSetDeadline.defaultExpectation.params) { + mmSetDeadline.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmSetDeadline.defaultExpectation.params) } } - return m + return mmSetDeadline +} + +// Inspect accepts an inspector function that has same arguments as the Conn.SetDeadline +func (mmSetDeadline *mConnMockSetDeadline) Inspect(f func(t time.Time)) *mConnMockSetDeadline { + if mmSetDeadline.mock.inspectFuncSetDeadline != nil { + mmSetDeadline.mock.t.Fatalf("Inspect function is already set for ConnMock.SetDeadline") + } + + mmSetDeadline.mock.inspectFuncSetDeadline = f + + return mmSetDeadline } // Return sets up results that will be returned by Conn.SetDeadline -func (m *mConnMockSetDeadline) Return(err error) *ConnMock { - if m.mock.funcSetDeadline != nil { - m.mock.t.Fatalf("ConnMock.SetDeadline mock is already set by Set") +func (mmSetDeadline *mConnMockSetDeadline) Return(err error) *ConnMock { + if mmSetDeadline.mock.funcSetDeadline != nil { + mmSetDeadline.mock.t.Fatalf("ConnMock.SetDeadline mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockSetDeadlineExpectation{mock: m.mock} + if mmSetDeadline.defaultExpectation == nil { + mmSetDeadline.defaultExpectation = &ConnMockSetDeadlineExpectation{mock: mmSetDeadline.mock} } - m.defaultExpectation.results = &ConnMockSetDeadlineResults{err} - return m.mock + mmSetDeadline.defaultExpectation.results = &ConnMockSetDeadlineResults{err} + return mmSetDeadline.mock } //Set uses given function f to mock the Conn.SetDeadline method -func (m *mConnMockSetDeadline) Set(f func(t time.Time) (err error)) *ConnMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Conn.SetDeadline method") +func (mmSetDeadline *mConnMockSetDeadline) Set(f func(t time.Time) (err error)) *ConnMock { + if mmSetDeadline.defaultExpectation != nil { + mmSetDeadline.mock.t.Fatalf("Default expectation is already set for the Conn.SetDeadline method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Conn.SetDeadline method") + if len(mmSetDeadline.expectations) > 0 { + mmSetDeadline.mock.t.Fatalf("Some expectations are already set for the Conn.SetDeadline method") } - m.mock.funcSetDeadline = f - return m.mock + mmSetDeadline.mock.funcSetDeadline = f + return mmSetDeadline.mock } // When sets expectation for the Conn.SetDeadline which will trigger the result defined by the following // Then helper -func (m *mConnMockSetDeadline) When(t time.Time) *ConnMockSetDeadlineExpectation { - if m.mock.funcSetDeadline != nil { - m.mock.t.Fatalf("ConnMock.SetDeadline mock is already set by Set") +func (mmSetDeadline *mConnMockSetDeadline) When(t time.Time) *ConnMockSetDeadlineExpectation { + if mmSetDeadline.mock.funcSetDeadline != nil { + mmSetDeadline.mock.t.Fatalf("ConnMock.SetDeadline mock is already set by Set") } expectation := &ConnMockSetDeadlineExpectation{ - mock: m.mock, + mock: mmSetDeadline.mock, params: &ConnMockSetDeadlineParams{t}, } - m.expectations = append(m.expectations, expectation) + mmSetDeadline.expectations = append(mmSetDeadline.expectations, expectation) return expectation } @@ -727,63 +850,87 @@ func (e *ConnMockSetDeadlineExpectation) Then(err error) *ConnMock { } // SetDeadline implements net.Conn -func (m *ConnMock) SetDeadline(t time.Time) (err error) { - atomic.AddUint64(&m.beforeSetDeadlineCounter, 1) - defer atomic.AddUint64(&m.afterSetDeadlineCounter, 1) +func (mmSetDeadline *ConnMock) SetDeadline(t time.Time) (err error) { + mm_atomic.AddUint64(&mmSetDeadline.beforeSetDeadlineCounter, 1) + defer mm_atomic.AddUint64(&mmSetDeadline.afterSetDeadlineCounter, 1) - for _, e := range m.SetDeadlineMock.expectations { - if minimock.Equal(*e.params, ConnMockSetDeadlineParams{t}) { - atomic.AddUint64(&e.Counter, 1) + if mmSetDeadline.inspectFuncSetDeadline != nil { + mmSetDeadline.inspectFuncSetDeadline(t) + } + + mm_params := &ConnMockSetDeadlineParams{t} + + // Record call args + mmSetDeadline.SetDeadlineMock.mutex.Lock() + mmSetDeadline.SetDeadlineMock.callArgs = append(mmSetDeadline.SetDeadlineMock.callArgs, mm_params) + mmSetDeadline.SetDeadlineMock.mutex.Unlock() + + for _, e := range mmSetDeadline.SetDeadlineMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.err } } - if m.SetDeadlineMock.defaultExpectation != nil { - atomic.AddUint64(&m.SetDeadlineMock.defaultExpectation.Counter, 1) - want := m.SetDeadlineMock.defaultExpectation.params - got := ConnMockSetDeadlineParams{t} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("ConnMock.SetDeadline got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmSetDeadline.SetDeadlineMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmSetDeadline.SetDeadlineMock.defaultExpectation.Counter, 1) + mm_want := mmSetDeadline.SetDeadlineMock.defaultExpectation.params + mm_got := ConnMockSetDeadlineParams{t} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmSetDeadline.t.Errorf("ConnMock.SetDeadline got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.SetDeadlineMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the ConnMock.SetDeadline") + mm_results := mmSetDeadline.SetDeadlineMock.defaultExpectation.results + if mm_results == nil { + mmSetDeadline.t.Fatal("No results are set for the ConnMock.SetDeadline") } - return (*results).err + return (*mm_results).err } - if m.funcSetDeadline != nil { - return m.funcSetDeadline(t) + if mmSetDeadline.funcSetDeadline != nil { + return mmSetDeadline.funcSetDeadline(t) } - m.t.Fatalf("Unexpected call to ConnMock.SetDeadline. %v", t) + mmSetDeadline.t.Fatalf("Unexpected call to ConnMock.SetDeadline. %v", t) return } // SetDeadlineAfterCounter returns a count of finished ConnMock.SetDeadline invocations -func (m *ConnMock) SetDeadlineAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterSetDeadlineCounter) +func (mmSetDeadline *ConnMock) SetDeadlineAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmSetDeadline.afterSetDeadlineCounter) } // SetDeadlineBeforeCounter returns a count of ConnMock.SetDeadline invocations -func (m *ConnMock) SetDeadlineBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeSetDeadlineCounter) +func (mmSetDeadline *ConnMock) SetDeadlineBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmSetDeadline.beforeSetDeadlineCounter) +} + +// Calls returns a list of arguments used in each call to ConnMock.SetDeadline. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmSetDeadline *mConnMockSetDeadline) Calls() []*ConnMockSetDeadlineParams { + mmSetDeadline.mutex.RLock() + + argCopy := make([]*ConnMockSetDeadlineParams, len(mmSetDeadline.callArgs)) + copy(argCopy, mmSetDeadline.callArgs) + + mmSetDeadline.mutex.RUnlock() + + return argCopy } // MinimockSetDeadlineDone returns true if the count of the SetDeadline invocations corresponds // the number of defined expectations func (m *ConnMock) MinimockSetDeadlineDone() bool { for _, e := range m.SetDeadlineMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.SetDeadlineMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterSetDeadlineCounter) < 1 { + if m.SetDeadlineMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSetDeadlineCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcSetDeadline != nil && atomic.LoadUint64(&m.afterSetDeadlineCounter) < 1 { + if m.funcSetDeadline != nil && mm_atomic.LoadUint64(&m.afterSetDeadlineCounter) < 1 { return false } return true @@ -792,17 +939,21 @@ func (m *ConnMock) MinimockSetDeadlineDone() bool { // MinimockSetDeadlineInspect logs each unmet expectation func (m *ConnMock) MinimockSetDeadlineInspect() { for _, e := range m.SetDeadlineMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to ConnMock.SetDeadline with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.SetDeadlineMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterSetDeadlineCounter) < 1 { - m.t.Errorf("Expected call to ConnMock.SetDeadline with params: %#v", *m.SetDeadlineMock.defaultExpectation.params) + if m.SetDeadlineMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSetDeadlineCounter) < 1 { + if m.SetDeadlineMock.defaultExpectation.params == nil { + m.t.Error("Expected call to ConnMock.SetDeadline") + } else { + m.t.Errorf("Expected call to ConnMock.SetDeadline with params: %#v", *m.SetDeadlineMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcSetDeadline != nil && atomic.LoadUint64(&m.afterSetDeadlineCounter) < 1 { + if m.funcSetDeadline != nil && mm_atomic.LoadUint64(&m.afterSetDeadlineCounter) < 1 { m.t.Error("Expected call to ConnMock.SetDeadline") } } @@ -811,6 +962,9 @@ type mConnMockSetReadDeadline struct { mock *ConnMock defaultExpectation *ConnMockSetReadDeadlineExpectation expectations []*ConnMockSetReadDeadlineExpectation + + callArgs []*ConnMockSetReadDeadlineParams + mutex sync.RWMutex } // ConnMockSetReadDeadlineExpectation specifies expectation struct of the Conn.SetReadDeadline @@ -832,64 +986,75 @@ type ConnMockSetReadDeadlineResults struct { } // Expect sets up expected params for Conn.SetReadDeadline -func (m *mConnMockSetReadDeadline) Expect(t time.Time) *mConnMockSetReadDeadline { - if m.mock.funcSetReadDeadline != nil { - m.mock.t.Fatalf("ConnMock.SetReadDeadline mock is already set by Set") +func (mmSetReadDeadline *mConnMockSetReadDeadline) Expect(t time.Time) *mConnMockSetReadDeadline { + if mmSetReadDeadline.mock.funcSetReadDeadline != nil { + mmSetReadDeadline.mock.t.Fatalf("ConnMock.SetReadDeadline mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockSetReadDeadlineExpectation{} + if mmSetReadDeadline.defaultExpectation == nil { + mmSetReadDeadline.defaultExpectation = &ConnMockSetReadDeadlineExpectation{} } - m.defaultExpectation.params = &ConnMockSetReadDeadlineParams{t} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmSetReadDeadline.defaultExpectation.params = &ConnMockSetReadDeadlineParams{t} + for _, e := range mmSetReadDeadline.expectations { + if minimock.Equal(e.params, mmSetReadDeadline.defaultExpectation.params) { + mmSetReadDeadline.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmSetReadDeadline.defaultExpectation.params) } } - return m + return mmSetReadDeadline +} + +// Inspect accepts an inspector function that has same arguments as the Conn.SetReadDeadline +func (mmSetReadDeadline *mConnMockSetReadDeadline) Inspect(f func(t time.Time)) *mConnMockSetReadDeadline { + if mmSetReadDeadline.mock.inspectFuncSetReadDeadline != nil { + mmSetReadDeadline.mock.t.Fatalf("Inspect function is already set for ConnMock.SetReadDeadline") + } + + mmSetReadDeadline.mock.inspectFuncSetReadDeadline = f + + return mmSetReadDeadline } // Return sets up results that will be returned by Conn.SetReadDeadline -func (m *mConnMockSetReadDeadline) Return(err error) *ConnMock { - if m.mock.funcSetReadDeadline != nil { - m.mock.t.Fatalf("ConnMock.SetReadDeadline mock is already set by Set") +func (mmSetReadDeadline *mConnMockSetReadDeadline) Return(err error) *ConnMock { + if mmSetReadDeadline.mock.funcSetReadDeadline != nil { + mmSetReadDeadline.mock.t.Fatalf("ConnMock.SetReadDeadline mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockSetReadDeadlineExpectation{mock: m.mock} + if mmSetReadDeadline.defaultExpectation == nil { + mmSetReadDeadline.defaultExpectation = &ConnMockSetReadDeadlineExpectation{mock: mmSetReadDeadline.mock} } - m.defaultExpectation.results = &ConnMockSetReadDeadlineResults{err} - return m.mock + mmSetReadDeadline.defaultExpectation.results = &ConnMockSetReadDeadlineResults{err} + return mmSetReadDeadline.mock } //Set uses given function f to mock the Conn.SetReadDeadline method -func (m *mConnMockSetReadDeadline) Set(f func(t time.Time) (err error)) *ConnMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Conn.SetReadDeadline method") +func (mmSetReadDeadline *mConnMockSetReadDeadline) Set(f func(t time.Time) (err error)) *ConnMock { + if mmSetReadDeadline.defaultExpectation != nil { + mmSetReadDeadline.mock.t.Fatalf("Default expectation is already set for the Conn.SetReadDeadline method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Conn.SetReadDeadline method") + if len(mmSetReadDeadline.expectations) > 0 { + mmSetReadDeadline.mock.t.Fatalf("Some expectations are already set for the Conn.SetReadDeadline method") } - m.mock.funcSetReadDeadline = f - return m.mock + mmSetReadDeadline.mock.funcSetReadDeadline = f + return mmSetReadDeadline.mock } // When sets expectation for the Conn.SetReadDeadline which will trigger the result defined by the following // Then helper -func (m *mConnMockSetReadDeadline) When(t time.Time) *ConnMockSetReadDeadlineExpectation { - if m.mock.funcSetReadDeadline != nil { - m.mock.t.Fatalf("ConnMock.SetReadDeadline mock is already set by Set") +func (mmSetReadDeadline *mConnMockSetReadDeadline) When(t time.Time) *ConnMockSetReadDeadlineExpectation { + if mmSetReadDeadline.mock.funcSetReadDeadline != nil { + mmSetReadDeadline.mock.t.Fatalf("ConnMock.SetReadDeadline mock is already set by Set") } expectation := &ConnMockSetReadDeadlineExpectation{ - mock: m.mock, + mock: mmSetReadDeadline.mock, params: &ConnMockSetReadDeadlineParams{t}, } - m.expectations = append(m.expectations, expectation) + mmSetReadDeadline.expectations = append(mmSetReadDeadline.expectations, expectation) return expectation } @@ -900,63 +1065,87 @@ func (e *ConnMockSetReadDeadlineExpectation) Then(err error) *ConnMock { } // SetReadDeadline implements net.Conn -func (m *ConnMock) SetReadDeadline(t time.Time) (err error) { - atomic.AddUint64(&m.beforeSetReadDeadlineCounter, 1) - defer atomic.AddUint64(&m.afterSetReadDeadlineCounter, 1) +func (mmSetReadDeadline *ConnMock) SetReadDeadline(t time.Time) (err error) { + mm_atomic.AddUint64(&mmSetReadDeadline.beforeSetReadDeadlineCounter, 1) + defer mm_atomic.AddUint64(&mmSetReadDeadline.afterSetReadDeadlineCounter, 1) - for _, e := range m.SetReadDeadlineMock.expectations { - if minimock.Equal(*e.params, ConnMockSetReadDeadlineParams{t}) { - atomic.AddUint64(&e.Counter, 1) + if mmSetReadDeadline.inspectFuncSetReadDeadline != nil { + mmSetReadDeadline.inspectFuncSetReadDeadline(t) + } + + mm_params := &ConnMockSetReadDeadlineParams{t} + + // Record call args + mmSetReadDeadline.SetReadDeadlineMock.mutex.Lock() + mmSetReadDeadline.SetReadDeadlineMock.callArgs = append(mmSetReadDeadline.SetReadDeadlineMock.callArgs, mm_params) + mmSetReadDeadline.SetReadDeadlineMock.mutex.Unlock() + + for _, e := range mmSetReadDeadline.SetReadDeadlineMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.err } } - if m.SetReadDeadlineMock.defaultExpectation != nil { - atomic.AddUint64(&m.SetReadDeadlineMock.defaultExpectation.Counter, 1) - want := m.SetReadDeadlineMock.defaultExpectation.params - got := ConnMockSetReadDeadlineParams{t} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("ConnMock.SetReadDeadline got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmSetReadDeadline.SetReadDeadlineMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmSetReadDeadline.SetReadDeadlineMock.defaultExpectation.Counter, 1) + mm_want := mmSetReadDeadline.SetReadDeadlineMock.defaultExpectation.params + mm_got := ConnMockSetReadDeadlineParams{t} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmSetReadDeadline.t.Errorf("ConnMock.SetReadDeadline got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.SetReadDeadlineMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the ConnMock.SetReadDeadline") + mm_results := mmSetReadDeadline.SetReadDeadlineMock.defaultExpectation.results + if mm_results == nil { + mmSetReadDeadline.t.Fatal("No results are set for the ConnMock.SetReadDeadline") } - return (*results).err + return (*mm_results).err } - if m.funcSetReadDeadline != nil { - return m.funcSetReadDeadline(t) + if mmSetReadDeadline.funcSetReadDeadline != nil { + return mmSetReadDeadline.funcSetReadDeadline(t) } - m.t.Fatalf("Unexpected call to ConnMock.SetReadDeadline. %v", t) + mmSetReadDeadline.t.Fatalf("Unexpected call to ConnMock.SetReadDeadline. %v", t) return } // SetReadDeadlineAfterCounter returns a count of finished ConnMock.SetReadDeadline invocations -func (m *ConnMock) SetReadDeadlineAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterSetReadDeadlineCounter) +func (mmSetReadDeadline *ConnMock) SetReadDeadlineAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmSetReadDeadline.afterSetReadDeadlineCounter) } // SetReadDeadlineBeforeCounter returns a count of ConnMock.SetReadDeadline invocations -func (m *ConnMock) SetReadDeadlineBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeSetReadDeadlineCounter) +func (mmSetReadDeadline *ConnMock) SetReadDeadlineBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmSetReadDeadline.beforeSetReadDeadlineCounter) +} + +// Calls returns a list of arguments used in each call to ConnMock.SetReadDeadline. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmSetReadDeadline *mConnMockSetReadDeadline) Calls() []*ConnMockSetReadDeadlineParams { + mmSetReadDeadline.mutex.RLock() + + argCopy := make([]*ConnMockSetReadDeadlineParams, len(mmSetReadDeadline.callArgs)) + copy(argCopy, mmSetReadDeadline.callArgs) + + mmSetReadDeadline.mutex.RUnlock() + + return argCopy } // MinimockSetReadDeadlineDone returns true if the count of the SetReadDeadline invocations corresponds // the number of defined expectations func (m *ConnMock) MinimockSetReadDeadlineDone() bool { for _, e := range m.SetReadDeadlineMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.SetReadDeadlineMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterSetReadDeadlineCounter) < 1 { + if m.SetReadDeadlineMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSetReadDeadlineCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcSetReadDeadline != nil && atomic.LoadUint64(&m.afterSetReadDeadlineCounter) < 1 { + if m.funcSetReadDeadline != nil && mm_atomic.LoadUint64(&m.afterSetReadDeadlineCounter) < 1 { return false } return true @@ -965,17 +1154,21 @@ func (m *ConnMock) MinimockSetReadDeadlineDone() bool { // MinimockSetReadDeadlineInspect logs each unmet expectation func (m *ConnMock) MinimockSetReadDeadlineInspect() { for _, e := range m.SetReadDeadlineMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to ConnMock.SetReadDeadline with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.SetReadDeadlineMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterSetReadDeadlineCounter) < 1 { - m.t.Errorf("Expected call to ConnMock.SetReadDeadline with params: %#v", *m.SetReadDeadlineMock.defaultExpectation.params) + if m.SetReadDeadlineMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSetReadDeadlineCounter) < 1 { + if m.SetReadDeadlineMock.defaultExpectation.params == nil { + m.t.Error("Expected call to ConnMock.SetReadDeadline") + } else { + m.t.Errorf("Expected call to ConnMock.SetReadDeadline with params: %#v", *m.SetReadDeadlineMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcSetReadDeadline != nil && atomic.LoadUint64(&m.afterSetReadDeadlineCounter) < 1 { + if m.funcSetReadDeadline != nil && mm_atomic.LoadUint64(&m.afterSetReadDeadlineCounter) < 1 { m.t.Error("Expected call to ConnMock.SetReadDeadline") } } @@ -984,6 +1177,9 @@ type mConnMockSetWriteDeadline struct { mock *ConnMock defaultExpectation *ConnMockSetWriteDeadlineExpectation expectations []*ConnMockSetWriteDeadlineExpectation + + callArgs []*ConnMockSetWriteDeadlineParams + mutex sync.RWMutex } // ConnMockSetWriteDeadlineExpectation specifies expectation struct of the Conn.SetWriteDeadline @@ -1005,64 +1201,75 @@ type ConnMockSetWriteDeadlineResults struct { } // Expect sets up expected params for Conn.SetWriteDeadline -func (m *mConnMockSetWriteDeadline) Expect(t time.Time) *mConnMockSetWriteDeadline { - if m.mock.funcSetWriteDeadline != nil { - m.mock.t.Fatalf("ConnMock.SetWriteDeadline mock is already set by Set") +func (mmSetWriteDeadline *mConnMockSetWriteDeadline) Expect(t time.Time) *mConnMockSetWriteDeadline { + if mmSetWriteDeadline.mock.funcSetWriteDeadline != nil { + mmSetWriteDeadline.mock.t.Fatalf("ConnMock.SetWriteDeadline mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockSetWriteDeadlineExpectation{} + if mmSetWriteDeadline.defaultExpectation == nil { + mmSetWriteDeadline.defaultExpectation = &ConnMockSetWriteDeadlineExpectation{} } - m.defaultExpectation.params = &ConnMockSetWriteDeadlineParams{t} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmSetWriteDeadline.defaultExpectation.params = &ConnMockSetWriteDeadlineParams{t} + for _, e := range mmSetWriteDeadline.expectations { + if minimock.Equal(e.params, mmSetWriteDeadline.defaultExpectation.params) { + mmSetWriteDeadline.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmSetWriteDeadline.defaultExpectation.params) } } - return m + return mmSetWriteDeadline +} + +// Inspect accepts an inspector function that has same arguments as the Conn.SetWriteDeadline +func (mmSetWriteDeadline *mConnMockSetWriteDeadline) Inspect(f func(t time.Time)) *mConnMockSetWriteDeadline { + if mmSetWriteDeadline.mock.inspectFuncSetWriteDeadline != nil { + mmSetWriteDeadline.mock.t.Fatalf("Inspect function is already set for ConnMock.SetWriteDeadline") + } + + mmSetWriteDeadline.mock.inspectFuncSetWriteDeadline = f + + return mmSetWriteDeadline } // Return sets up results that will be returned by Conn.SetWriteDeadline -func (m *mConnMockSetWriteDeadline) Return(err error) *ConnMock { - if m.mock.funcSetWriteDeadline != nil { - m.mock.t.Fatalf("ConnMock.SetWriteDeadline mock is already set by Set") +func (mmSetWriteDeadline *mConnMockSetWriteDeadline) Return(err error) *ConnMock { + if mmSetWriteDeadline.mock.funcSetWriteDeadline != nil { + mmSetWriteDeadline.mock.t.Fatalf("ConnMock.SetWriteDeadline mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockSetWriteDeadlineExpectation{mock: m.mock} + if mmSetWriteDeadline.defaultExpectation == nil { + mmSetWriteDeadline.defaultExpectation = &ConnMockSetWriteDeadlineExpectation{mock: mmSetWriteDeadline.mock} } - m.defaultExpectation.results = &ConnMockSetWriteDeadlineResults{err} - return m.mock + mmSetWriteDeadline.defaultExpectation.results = &ConnMockSetWriteDeadlineResults{err} + return mmSetWriteDeadline.mock } //Set uses given function f to mock the Conn.SetWriteDeadline method -func (m *mConnMockSetWriteDeadline) Set(f func(t time.Time) (err error)) *ConnMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Conn.SetWriteDeadline method") +func (mmSetWriteDeadline *mConnMockSetWriteDeadline) Set(f func(t time.Time) (err error)) *ConnMock { + if mmSetWriteDeadline.defaultExpectation != nil { + mmSetWriteDeadline.mock.t.Fatalf("Default expectation is already set for the Conn.SetWriteDeadline method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Conn.SetWriteDeadline method") + if len(mmSetWriteDeadline.expectations) > 0 { + mmSetWriteDeadline.mock.t.Fatalf("Some expectations are already set for the Conn.SetWriteDeadline method") } - m.mock.funcSetWriteDeadline = f - return m.mock + mmSetWriteDeadline.mock.funcSetWriteDeadline = f + return mmSetWriteDeadline.mock } // When sets expectation for the Conn.SetWriteDeadline which will trigger the result defined by the following // Then helper -func (m *mConnMockSetWriteDeadline) When(t time.Time) *ConnMockSetWriteDeadlineExpectation { - if m.mock.funcSetWriteDeadline != nil { - m.mock.t.Fatalf("ConnMock.SetWriteDeadline mock is already set by Set") +func (mmSetWriteDeadline *mConnMockSetWriteDeadline) When(t time.Time) *ConnMockSetWriteDeadlineExpectation { + if mmSetWriteDeadline.mock.funcSetWriteDeadline != nil { + mmSetWriteDeadline.mock.t.Fatalf("ConnMock.SetWriteDeadline mock is already set by Set") } expectation := &ConnMockSetWriteDeadlineExpectation{ - mock: m.mock, + mock: mmSetWriteDeadline.mock, params: &ConnMockSetWriteDeadlineParams{t}, } - m.expectations = append(m.expectations, expectation) + mmSetWriteDeadline.expectations = append(mmSetWriteDeadline.expectations, expectation) return expectation } @@ -1073,63 +1280,87 @@ func (e *ConnMockSetWriteDeadlineExpectation) Then(err error) *ConnMock { } // SetWriteDeadline implements net.Conn -func (m *ConnMock) SetWriteDeadline(t time.Time) (err error) { - atomic.AddUint64(&m.beforeSetWriteDeadlineCounter, 1) - defer atomic.AddUint64(&m.afterSetWriteDeadlineCounter, 1) +func (mmSetWriteDeadline *ConnMock) SetWriteDeadline(t time.Time) (err error) { + mm_atomic.AddUint64(&mmSetWriteDeadline.beforeSetWriteDeadlineCounter, 1) + defer mm_atomic.AddUint64(&mmSetWriteDeadline.afterSetWriteDeadlineCounter, 1) - for _, e := range m.SetWriteDeadlineMock.expectations { - if minimock.Equal(*e.params, ConnMockSetWriteDeadlineParams{t}) { - atomic.AddUint64(&e.Counter, 1) + if mmSetWriteDeadline.inspectFuncSetWriteDeadline != nil { + mmSetWriteDeadline.inspectFuncSetWriteDeadline(t) + } + + mm_params := &ConnMockSetWriteDeadlineParams{t} + + // Record call args + mmSetWriteDeadline.SetWriteDeadlineMock.mutex.Lock() + mmSetWriteDeadline.SetWriteDeadlineMock.callArgs = append(mmSetWriteDeadline.SetWriteDeadlineMock.callArgs, mm_params) + mmSetWriteDeadline.SetWriteDeadlineMock.mutex.Unlock() + + for _, e := range mmSetWriteDeadline.SetWriteDeadlineMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.err } } - if m.SetWriteDeadlineMock.defaultExpectation != nil { - atomic.AddUint64(&m.SetWriteDeadlineMock.defaultExpectation.Counter, 1) - want := m.SetWriteDeadlineMock.defaultExpectation.params - got := ConnMockSetWriteDeadlineParams{t} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("ConnMock.SetWriteDeadline got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmSetWriteDeadline.SetWriteDeadlineMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmSetWriteDeadline.SetWriteDeadlineMock.defaultExpectation.Counter, 1) + mm_want := mmSetWriteDeadline.SetWriteDeadlineMock.defaultExpectation.params + mm_got := ConnMockSetWriteDeadlineParams{t} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmSetWriteDeadline.t.Errorf("ConnMock.SetWriteDeadline got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.SetWriteDeadlineMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the ConnMock.SetWriteDeadline") + mm_results := mmSetWriteDeadline.SetWriteDeadlineMock.defaultExpectation.results + if mm_results == nil { + mmSetWriteDeadline.t.Fatal("No results are set for the ConnMock.SetWriteDeadline") } - return (*results).err + return (*mm_results).err } - if m.funcSetWriteDeadline != nil { - return m.funcSetWriteDeadline(t) + if mmSetWriteDeadline.funcSetWriteDeadline != nil { + return mmSetWriteDeadline.funcSetWriteDeadline(t) } - m.t.Fatalf("Unexpected call to ConnMock.SetWriteDeadline. %v", t) + mmSetWriteDeadline.t.Fatalf("Unexpected call to ConnMock.SetWriteDeadline. %v", t) return } // SetWriteDeadlineAfterCounter returns a count of finished ConnMock.SetWriteDeadline invocations -func (m *ConnMock) SetWriteDeadlineAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterSetWriteDeadlineCounter) +func (mmSetWriteDeadline *ConnMock) SetWriteDeadlineAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmSetWriteDeadline.afterSetWriteDeadlineCounter) } // SetWriteDeadlineBeforeCounter returns a count of ConnMock.SetWriteDeadline invocations -func (m *ConnMock) SetWriteDeadlineBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeSetWriteDeadlineCounter) +func (mmSetWriteDeadline *ConnMock) SetWriteDeadlineBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmSetWriteDeadline.beforeSetWriteDeadlineCounter) +} + +// Calls returns a list of arguments used in each call to ConnMock.SetWriteDeadline. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmSetWriteDeadline *mConnMockSetWriteDeadline) Calls() []*ConnMockSetWriteDeadlineParams { + mmSetWriteDeadline.mutex.RLock() + + argCopy := make([]*ConnMockSetWriteDeadlineParams, len(mmSetWriteDeadline.callArgs)) + copy(argCopy, mmSetWriteDeadline.callArgs) + + mmSetWriteDeadline.mutex.RUnlock() + + return argCopy } // MinimockSetWriteDeadlineDone returns true if the count of the SetWriteDeadline invocations corresponds // the number of defined expectations func (m *ConnMock) MinimockSetWriteDeadlineDone() bool { for _, e := range m.SetWriteDeadlineMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.SetWriteDeadlineMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterSetWriteDeadlineCounter) < 1 { + if m.SetWriteDeadlineMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSetWriteDeadlineCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcSetWriteDeadline != nil && atomic.LoadUint64(&m.afterSetWriteDeadlineCounter) < 1 { + if m.funcSetWriteDeadline != nil && mm_atomic.LoadUint64(&m.afterSetWriteDeadlineCounter) < 1 { return false } return true @@ -1138,17 +1369,21 @@ func (m *ConnMock) MinimockSetWriteDeadlineDone() bool { // MinimockSetWriteDeadlineInspect logs each unmet expectation func (m *ConnMock) MinimockSetWriteDeadlineInspect() { for _, e := range m.SetWriteDeadlineMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to ConnMock.SetWriteDeadline with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.SetWriteDeadlineMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterSetWriteDeadlineCounter) < 1 { - m.t.Errorf("Expected call to ConnMock.SetWriteDeadline with params: %#v", *m.SetWriteDeadlineMock.defaultExpectation.params) + if m.SetWriteDeadlineMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSetWriteDeadlineCounter) < 1 { + if m.SetWriteDeadlineMock.defaultExpectation.params == nil { + m.t.Error("Expected call to ConnMock.SetWriteDeadline") + } else { + m.t.Errorf("Expected call to ConnMock.SetWriteDeadline with params: %#v", *m.SetWriteDeadlineMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcSetWriteDeadline != nil && atomic.LoadUint64(&m.afterSetWriteDeadlineCounter) < 1 { + if m.funcSetWriteDeadline != nil && mm_atomic.LoadUint64(&m.afterSetWriteDeadlineCounter) < 1 { m.t.Error("Expected call to ConnMock.SetWriteDeadline") } } @@ -1157,6 +1392,9 @@ type mConnMockWrite struct { mock *ConnMock defaultExpectation *ConnMockWriteExpectation expectations []*ConnMockWriteExpectation + + callArgs []*ConnMockWriteParams + mutex sync.RWMutex } // ConnMockWriteExpectation specifies expectation struct of the Conn.Write @@ -1179,64 +1417,75 @@ type ConnMockWriteResults struct { } // Expect sets up expected params for Conn.Write -func (m *mConnMockWrite) Expect(b []byte) *mConnMockWrite { - if m.mock.funcWrite != nil { - m.mock.t.Fatalf("ConnMock.Write mock is already set by Set") +func (mmWrite *mConnMockWrite) Expect(b []byte) *mConnMockWrite { + if mmWrite.mock.funcWrite != nil { + mmWrite.mock.t.Fatalf("ConnMock.Write mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockWriteExpectation{} + if mmWrite.defaultExpectation == nil { + mmWrite.defaultExpectation = &ConnMockWriteExpectation{} } - m.defaultExpectation.params = &ConnMockWriteParams{b} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmWrite.defaultExpectation.params = &ConnMockWriteParams{b} + for _, e := range mmWrite.expectations { + if minimock.Equal(e.params, mmWrite.defaultExpectation.params) { + mmWrite.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmWrite.defaultExpectation.params) } } - return m + return mmWrite +} + +// Inspect accepts an inspector function that has same arguments as the Conn.Write +func (mmWrite *mConnMockWrite) Inspect(f func(b []byte)) *mConnMockWrite { + if mmWrite.mock.inspectFuncWrite != nil { + mmWrite.mock.t.Fatalf("Inspect function is already set for ConnMock.Write") + } + + mmWrite.mock.inspectFuncWrite = f + + return mmWrite } // Return sets up results that will be returned by Conn.Write -func (m *mConnMockWrite) Return(n int, err error) *ConnMock { - if m.mock.funcWrite != nil { - m.mock.t.Fatalf("ConnMock.Write mock is already set by Set") +func (mmWrite *mConnMockWrite) Return(n int, err error) *ConnMock { + if mmWrite.mock.funcWrite != nil { + mmWrite.mock.t.Fatalf("ConnMock.Write mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockWriteExpectation{mock: m.mock} + if mmWrite.defaultExpectation == nil { + mmWrite.defaultExpectation = &ConnMockWriteExpectation{mock: mmWrite.mock} } - m.defaultExpectation.results = &ConnMockWriteResults{n, err} - return m.mock + mmWrite.defaultExpectation.results = &ConnMockWriteResults{n, err} + return mmWrite.mock } //Set uses given function f to mock the Conn.Write method -func (m *mConnMockWrite) Set(f func(b []byte) (n int, err error)) *ConnMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Conn.Write method") +func (mmWrite *mConnMockWrite) Set(f func(b []byte) (n int, err error)) *ConnMock { + if mmWrite.defaultExpectation != nil { + mmWrite.mock.t.Fatalf("Default expectation is already set for the Conn.Write method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Conn.Write method") + if len(mmWrite.expectations) > 0 { + mmWrite.mock.t.Fatalf("Some expectations are already set for the Conn.Write method") } - m.mock.funcWrite = f - return m.mock + mmWrite.mock.funcWrite = f + return mmWrite.mock } // When sets expectation for the Conn.Write which will trigger the result defined by the following // Then helper -func (m *mConnMockWrite) When(b []byte) *ConnMockWriteExpectation { - if m.mock.funcWrite != nil { - m.mock.t.Fatalf("ConnMock.Write mock is already set by Set") +func (mmWrite *mConnMockWrite) When(b []byte) *ConnMockWriteExpectation { + if mmWrite.mock.funcWrite != nil { + mmWrite.mock.t.Fatalf("ConnMock.Write mock is already set by Set") } expectation := &ConnMockWriteExpectation{ - mock: m.mock, + mock: mmWrite.mock, params: &ConnMockWriteParams{b}, } - m.expectations = append(m.expectations, expectation) + mmWrite.expectations = append(mmWrite.expectations, expectation) return expectation } @@ -1247,63 +1496,87 @@ func (e *ConnMockWriteExpectation) Then(n int, err error) *ConnMock { } // Write implements net.Conn -func (m *ConnMock) Write(b []byte) (n int, err error) { - atomic.AddUint64(&m.beforeWriteCounter, 1) - defer atomic.AddUint64(&m.afterWriteCounter, 1) +func (mmWrite *ConnMock) Write(b []byte) (n int, err error) { + mm_atomic.AddUint64(&mmWrite.beforeWriteCounter, 1) + defer mm_atomic.AddUint64(&mmWrite.afterWriteCounter, 1) - for _, e := range m.WriteMock.expectations { - if minimock.Equal(*e.params, ConnMockWriteParams{b}) { - atomic.AddUint64(&e.Counter, 1) + if mmWrite.inspectFuncWrite != nil { + mmWrite.inspectFuncWrite(b) + } + + mm_params := &ConnMockWriteParams{b} + + // Record call args + mmWrite.WriteMock.mutex.Lock() + mmWrite.WriteMock.callArgs = append(mmWrite.WriteMock.callArgs, mm_params) + mmWrite.WriteMock.mutex.Unlock() + + for _, e := range mmWrite.WriteMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.n, e.results.err } } - if m.WriteMock.defaultExpectation != nil { - atomic.AddUint64(&m.WriteMock.defaultExpectation.Counter, 1) - want := m.WriteMock.defaultExpectation.params - got := ConnMockWriteParams{b} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("ConnMock.Write got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmWrite.WriteMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmWrite.WriteMock.defaultExpectation.Counter, 1) + mm_want := mmWrite.WriteMock.defaultExpectation.params + mm_got := ConnMockWriteParams{b} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmWrite.t.Errorf("ConnMock.Write got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.WriteMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the ConnMock.Write") + mm_results := mmWrite.WriteMock.defaultExpectation.results + if mm_results == nil { + mmWrite.t.Fatal("No results are set for the ConnMock.Write") } - return (*results).n, (*results).err + return (*mm_results).n, (*mm_results).err } - if m.funcWrite != nil { - return m.funcWrite(b) + if mmWrite.funcWrite != nil { + return mmWrite.funcWrite(b) } - m.t.Fatalf("Unexpected call to ConnMock.Write. %v", b) + mmWrite.t.Fatalf("Unexpected call to ConnMock.Write. %v", b) return } // WriteAfterCounter returns a count of finished ConnMock.Write invocations -func (m *ConnMock) WriteAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterWriteCounter) +func (mmWrite *ConnMock) WriteAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmWrite.afterWriteCounter) } // WriteBeforeCounter returns a count of ConnMock.Write invocations -func (m *ConnMock) WriteBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeWriteCounter) +func (mmWrite *ConnMock) WriteBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmWrite.beforeWriteCounter) +} + +// Calls returns a list of arguments used in each call to ConnMock.Write. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmWrite *mConnMockWrite) Calls() []*ConnMockWriteParams { + mmWrite.mutex.RLock() + + argCopy := make([]*ConnMockWriteParams, len(mmWrite.callArgs)) + copy(argCopy, mmWrite.callArgs) + + mmWrite.mutex.RUnlock() + + return argCopy } // MinimockWriteDone returns true if the count of the Write invocations corresponds // the number of defined expectations func (m *ConnMock) MinimockWriteDone() bool { for _, e := range m.WriteMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.WriteMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterWriteCounter) < 1 { + if m.WriteMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterWriteCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcWrite != nil && atomic.LoadUint64(&m.afterWriteCounter) < 1 { + if m.funcWrite != nil && mm_atomic.LoadUint64(&m.afterWriteCounter) < 1 { return false } return true @@ -1312,17 +1585,21 @@ func (m *ConnMock) MinimockWriteDone() bool { // MinimockWriteInspect logs each unmet expectation func (m *ConnMock) MinimockWriteInspect() { for _, e := range m.WriteMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to ConnMock.Write with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.WriteMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterWriteCounter) < 1 { - m.t.Errorf("Expected call to ConnMock.Write with params: %#v", *m.WriteMock.defaultExpectation.params) + if m.WriteMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterWriteCounter) < 1 { + if m.WriteMock.defaultExpectation.params == nil { + m.t.Error("Expected call to ConnMock.Write") + } else { + m.t.Errorf("Expected call to ConnMock.Write with params: %#v", *m.WriteMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcWrite != nil && atomic.LoadUint64(&m.afterWriteCounter) < 1 { + if m.funcWrite != nil && mm_atomic.LoadUint64(&m.afterWriteCounter) < 1 { m.t.Error("Expected call to ConnMock.Write") } } @@ -1350,8 +1627,8 @@ func (m *ConnMock) MinimockFinish() { } // MinimockWait waits for all mocked methods to be called the expected number of times -func (m *ConnMock) MinimockWait(timeout time.Duration) { - timeoutCh := time.After(timeout) +func (m *ConnMock) MinimockWait(timeout mm_time.Duration) { + timeoutCh := mm_time.After(timeout) for { if m.minimockDone() { return @@ -1360,7 +1637,7 @@ func (m *ConnMock) MinimockWait(timeout time.Duration) { case <-timeoutCh: m.MinimockFinish() return - case <-time.After(10 * time.Millisecond): + case <-mm_time.After(10 * mm_time.Millisecond): } } } diff --git a/internal/cert_manager/domain_checker_mock_test.go b/internal/cert_manager/domain_checker_mock_test.go index 7233fe5c..e7578932 100644 --- a/internal/cert_manager/domain_checker_mock_test.go +++ b/internal/cert_manager/domain_checker_mock_test.go @@ -1,15 +1,14 @@ package cert_manager -// DO NOT EDIT! -// The code below was generated with http://github.com/gojuno/minimock (dev) +// Code generated by http://github.com/gojuno/minimock (3.0.6). DO NOT EDIT. //go:generate minimock -i github.com/rekby/lets-proxy2/internal/cert_manager.DomainChecker -o ./domain_checker_mock_test.go import ( - "sync/atomic" - "time" - "context" + "sync" + mm_atomic "sync/atomic" + mm_time "time" "github.com/gojuno/minimock/v3" ) @@ -19,6 +18,7 @@ type DomainCheckerMock struct { t minimock.Tester funcIsDomainAllowed func(ctx context.Context, domain string) (b1 bool, err error) + inspectFuncIsDomainAllowed func(ctx context.Context, domain string) afterIsDomainAllowedCounter uint64 beforeIsDomainAllowedCounter uint64 IsDomainAllowedMock mDomainCheckerMockIsDomainAllowed @@ -30,7 +30,9 @@ func NewDomainCheckerMock(t minimock.Tester) *DomainCheckerMock { if controller, ok := t.(minimock.MockController); ok { controller.RegisterMocker(m) } + m.IsDomainAllowedMock = mDomainCheckerMockIsDomainAllowed{mock: m} + m.IsDomainAllowedMock.callArgs = []*DomainCheckerMockIsDomainAllowedParams{} return m } @@ -39,6 +41,9 @@ type mDomainCheckerMockIsDomainAllowed struct { mock *DomainCheckerMock defaultExpectation *DomainCheckerMockIsDomainAllowedExpectation expectations []*DomainCheckerMockIsDomainAllowedExpectation + + callArgs []*DomainCheckerMockIsDomainAllowedParams + mutex sync.RWMutex } // DomainCheckerMockIsDomainAllowedExpectation specifies expectation struct of the DomainChecker.IsDomainAllowed @@ -62,64 +67,75 @@ type DomainCheckerMockIsDomainAllowedResults struct { } // Expect sets up expected params for DomainChecker.IsDomainAllowed -func (m *mDomainCheckerMockIsDomainAllowed) Expect(ctx context.Context, domain string) *mDomainCheckerMockIsDomainAllowed { - if m.mock.funcIsDomainAllowed != nil { - m.mock.t.Fatalf("DomainCheckerMock.IsDomainAllowed mock is already set by Set") +func (mmIsDomainAllowed *mDomainCheckerMockIsDomainAllowed) Expect(ctx context.Context, domain string) *mDomainCheckerMockIsDomainAllowed { + if mmIsDomainAllowed.mock.funcIsDomainAllowed != nil { + mmIsDomainAllowed.mock.t.Fatalf("DomainCheckerMock.IsDomainAllowed mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &DomainCheckerMockIsDomainAllowedExpectation{} + if mmIsDomainAllowed.defaultExpectation == nil { + mmIsDomainAllowed.defaultExpectation = &DomainCheckerMockIsDomainAllowedExpectation{} } - m.defaultExpectation.params = &DomainCheckerMockIsDomainAllowedParams{ctx, domain} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmIsDomainAllowed.defaultExpectation.params = &DomainCheckerMockIsDomainAllowedParams{ctx, domain} + for _, e := range mmIsDomainAllowed.expectations { + if minimock.Equal(e.params, mmIsDomainAllowed.defaultExpectation.params) { + mmIsDomainAllowed.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmIsDomainAllowed.defaultExpectation.params) } } - return m + return mmIsDomainAllowed +} + +// Inspect accepts an inspector function that has same arguments as the DomainChecker.IsDomainAllowed +func (mmIsDomainAllowed *mDomainCheckerMockIsDomainAllowed) Inspect(f func(ctx context.Context, domain string)) *mDomainCheckerMockIsDomainAllowed { + if mmIsDomainAllowed.mock.inspectFuncIsDomainAllowed != nil { + mmIsDomainAllowed.mock.t.Fatalf("Inspect function is already set for DomainCheckerMock.IsDomainAllowed") + } + + mmIsDomainAllowed.mock.inspectFuncIsDomainAllowed = f + + return mmIsDomainAllowed } // Return sets up results that will be returned by DomainChecker.IsDomainAllowed -func (m *mDomainCheckerMockIsDomainAllowed) Return(b1 bool, err error) *DomainCheckerMock { - if m.mock.funcIsDomainAllowed != nil { - m.mock.t.Fatalf("DomainCheckerMock.IsDomainAllowed mock is already set by Set") +func (mmIsDomainAllowed *mDomainCheckerMockIsDomainAllowed) Return(b1 bool, err error) *DomainCheckerMock { + if mmIsDomainAllowed.mock.funcIsDomainAllowed != nil { + mmIsDomainAllowed.mock.t.Fatalf("DomainCheckerMock.IsDomainAllowed mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &DomainCheckerMockIsDomainAllowedExpectation{mock: m.mock} + if mmIsDomainAllowed.defaultExpectation == nil { + mmIsDomainAllowed.defaultExpectation = &DomainCheckerMockIsDomainAllowedExpectation{mock: mmIsDomainAllowed.mock} } - m.defaultExpectation.results = &DomainCheckerMockIsDomainAllowedResults{b1, err} - return m.mock + mmIsDomainAllowed.defaultExpectation.results = &DomainCheckerMockIsDomainAllowedResults{b1, err} + return mmIsDomainAllowed.mock } //Set uses given function f to mock the DomainChecker.IsDomainAllowed method -func (m *mDomainCheckerMockIsDomainAllowed) Set(f func(ctx context.Context, domain string) (b1 bool, err error)) *DomainCheckerMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the DomainChecker.IsDomainAllowed method") +func (mmIsDomainAllowed *mDomainCheckerMockIsDomainAllowed) Set(f func(ctx context.Context, domain string) (b1 bool, err error)) *DomainCheckerMock { + if mmIsDomainAllowed.defaultExpectation != nil { + mmIsDomainAllowed.mock.t.Fatalf("Default expectation is already set for the DomainChecker.IsDomainAllowed method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the DomainChecker.IsDomainAllowed method") + if len(mmIsDomainAllowed.expectations) > 0 { + mmIsDomainAllowed.mock.t.Fatalf("Some expectations are already set for the DomainChecker.IsDomainAllowed method") } - m.mock.funcIsDomainAllowed = f - return m.mock + mmIsDomainAllowed.mock.funcIsDomainAllowed = f + return mmIsDomainAllowed.mock } // When sets expectation for the DomainChecker.IsDomainAllowed which will trigger the result defined by the following // Then helper -func (m *mDomainCheckerMockIsDomainAllowed) When(ctx context.Context, domain string) *DomainCheckerMockIsDomainAllowedExpectation { - if m.mock.funcIsDomainAllowed != nil { - m.mock.t.Fatalf("DomainCheckerMock.IsDomainAllowed mock is already set by Set") +func (mmIsDomainAllowed *mDomainCheckerMockIsDomainAllowed) When(ctx context.Context, domain string) *DomainCheckerMockIsDomainAllowedExpectation { + if mmIsDomainAllowed.mock.funcIsDomainAllowed != nil { + mmIsDomainAllowed.mock.t.Fatalf("DomainCheckerMock.IsDomainAllowed mock is already set by Set") } expectation := &DomainCheckerMockIsDomainAllowedExpectation{ - mock: m.mock, + mock: mmIsDomainAllowed.mock, params: &DomainCheckerMockIsDomainAllowedParams{ctx, domain}, } - m.expectations = append(m.expectations, expectation) + mmIsDomainAllowed.expectations = append(mmIsDomainAllowed.expectations, expectation) return expectation } @@ -130,63 +146,87 @@ func (e *DomainCheckerMockIsDomainAllowedExpectation) Then(b1 bool, err error) * } // IsDomainAllowed implements DomainChecker -func (m *DomainCheckerMock) IsDomainAllowed(ctx context.Context, domain string) (b1 bool, err error) { - atomic.AddUint64(&m.beforeIsDomainAllowedCounter, 1) - defer atomic.AddUint64(&m.afterIsDomainAllowedCounter, 1) +func (mmIsDomainAllowed *DomainCheckerMock) IsDomainAllowed(ctx context.Context, domain string) (b1 bool, err error) { + mm_atomic.AddUint64(&mmIsDomainAllowed.beforeIsDomainAllowedCounter, 1) + defer mm_atomic.AddUint64(&mmIsDomainAllowed.afterIsDomainAllowedCounter, 1) - for _, e := range m.IsDomainAllowedMock.expectations { - if minimock.Equal(*e.params, DomainCheckerMockIsDomainAllowedParams{ctx, domain}) { - atomic.AddUint64(&e.Counter, 1) + if mmIsDomainAllowed.inspectFuncIsDomainAllowed != nil { + mmIsDomainAllowed.inspectFuncIsDomainAllowed(ctx, domain) + } + + mm_params := &DomainCheckerMockIsDomainAllowedParams{ctx, domain} + + // Record call args + mmIsDomainAllowed.IsDomainAllowedMock.mutex.Lock() + mmIsDomainAllowed.IsDomainAllowedMock.callArgs = append(mmIsDomainAllowed.IsDomainAllowedMock.callArgs, mm_params) + mmIsDomainAllowed.IsDomainAllowedMock.mutex.Unlock() + + for _, e := range mmIsDomainAllowed.IsDomainAllowedMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.b1, e.results.err } } - if m.IsDomainAllowedMock.defaultExpectation != nil { - atomic.AddUint64(&m.IsDomainAllowedMock.defaultExpectation.Counter, 1) - want := m.IsDomainAllowedMock.defaultExpectation.params - got := DomainCheckerMockIsDomainAllowedParams{ctx, domain} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("DomainCheckerMock.IsDomainAllowed got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmIsDomainAllowed.IsDomainAllowedMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmIsDomainAllowed.IsDomainAllowedMock.defaultExpectation.Counter, 1) + mm_want := mmIsDomainAllowed.IsDomainAllowedMock.defaultExpectation.params + mm_got := DomainCheckerMockIsDomainAllowedParams{ctx, domain} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmIsDomainAllowed.t.Errorf("DomainCheckerMock.IsDomainAllowed got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.IsDomainAllowedMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the DomainCheckerMock.IsDomainAllowed") + mm_results := mmIsDomainAllowed.IsDomainAllowedMock.defaultExpectation.results + if mm_results == nil { + mmIsDomainAllowed.t.Fatal("No results are set for the DomainCheckerMock.IsDomainAllowed") } - return (*results).b1, (*results).err + return (*mm_results).b1, (*mm_results).err } - if m.funcIsDomainAllowed != nil { - return m.funcIsDomainAllowed(ctx, domain) + if mmIsDomainAllowed.funcIsDomainAllowed != nil { + return mmIsDomainAllowed.funcIsDomainAllowed(ctx, domain) } - m.t.Fatalf("Unexpected call to DomainCheckerMock.IsDomainAllowed. %v %v", ctx, domain) + mmIsDomainAllowed.t.Fatalf("Unexpected call to DomainCheckerMock.IsDomainAllowed. %v %v", ctx, domain) return } // IsDomainAllowedAfterCounter returns a count of finished DomainCheckerMock.IsDomainAllowed invocations -func (m *DomainCheckerMock) IsDomainAllowedAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterIsDomainAllowedCounter) +func (mmIsDomainAllowed *DomainCheckerMock) IsDomainAllowedAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmIsDomainAllowed.afterIsDomainAllowedCounter) } // IsDomainAllowedBeforeCounter returns a count of DomainCheckerMock.IsDomainAllowed invocations -func (m *DomainCheckerMock) IsDomainAllowedBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeIsDomainAllowedCounter) +func (mmIsDomainAllowed *DomainCheckerMock) IsDomainAllowedBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmIsDomainAllowed.beforeIsDomainAllowedCounter) +} + +// Calls returns a list of arguments used in each call to DomainCheckerMock.IsDomainAllowed. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmIsDomainAllowed *mDomainCheckerMockIsDomainAllowed) Calls() []*DomainCheckerMockIsDomainAllowedParams { + mmIsDomainAllowed.mutex.RLock() + + argCopy := make([]*DomainCheckerMockIsDomainAllowedParams, len(mmIsDomainAllowed.callArgs)) + copy(argCopy, mmIsDomainAllowed.callArgs) + + mmIsDomainAllowed.mutex.RUnlock() + + return argCopy } // MinimockIsDomainAllowedDone returns true if the count of the IsDomainAllowed invocations corresponds // the number of defined expectations func (m *DomainCheckerMock) MinimockIsDomainAllowedDone() bool { for _, e := range m.IsDomainAllowedMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.IsDomainAllowedMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterIsDomainAllowedCounter) < 1 { + if m.IsDomainAllowedMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterIsDomainAllowedCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcIsDomainAllowed != nil && atomic.LoadUint64(&m.afterIsDomainAllowedCounter) < 1 { + if m.funcIsDomainAllowed != nil && mm_atomic.LoadUint64(&m.afterIsDomainAllowedCounter) < 1 { return false } return true @@ -195,17 +235,21 @@ func (m *DomainCheckerMock) MinimockIsDomainAllowedDone() bool { // MinimockIsDomainAllowedInspect logs each unmet expectation func (m *DomainCheckerMock) MinimockIsDomainAllowedInspect() { for _, e := range m.IsDomainAllowedMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to DomainCheckerMock.IsDomainAllowed with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.IsDomainAllowedMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterIsDomainAllowedCounter) < 1 { - m.t.Errorf("Expected call to DomainCheckerMock.IsDomainAllowed with params: %#v", *m.IsDomainAllowedMock.defaultExpectation.params) + if m.IsDomainAllowedMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterIsDomainAllowedCounter) < 1 { + if m.IsDomainAllowedMock.defaultExpectation.params == nil { + m.t.Error("Expected call to DomainCheckerMock.IsDomainAllowed") + } else { + m.t.Errorf("Expected call to DomainCheckerMock.IsDomainAllowed with params: %#v", *m.IsDomainAllowedMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcIsDomainAllowed != nil && atomic.LoadUint64(&m.afterIsDomainAllowedCounter) < 1 { + if m.funcIsDomainAllowed != nil && mm_atomic.LoadUint64(&m.afterIsDomainAllowedCounter) < 1 { m.t.Error("Expected call to DomainCheckerMock.IsDomainAllowed") } } @@ -219,8 +263,8 @@ func (m *DomainCheckerMock) MinimockFinish() { } // MinimockWait waits for all mocked methods to be called the expected number of times -func (m *DomainCheckerMock) MinimockWait(timeout time.Duration) { - timeoutCh := time.After(timeout) +func (m *DomainCheckerMock) MinimockWait(timeout mm_time.Duration) { + timeoutCh := mm_time.After(timeout) for { if m.minimockDone() { return @@ -229,7 +273,7 @@ func (m *DomainCheckerMock) MinimockWait(timeout time.Duration) { case <-timeoutCh: m.MinimockFinish() return - case <-time.After(10 * time.Millisecond): + case <-mm_time.After(10 * mm_time.Millisecond): } } } diff --git a/internal/cert_manager/value_mock_test.go b/internal/cert_manager/value_mock_test.go index e4623efc..2bd501d9 100644 --- a/internal/cert_manager/value_mock_test.go +++ b/internal/cert_manager/value_mock_test.go @@ -1,15 +1,14 @@ package cert_manager -// DO NOT EDIT! -// The code below was generated with http://github.com/gojuno/minimock (dev) +// Code generated by http://github.com/gojuno/minimock (3.0.6). DO NOT EDIT. //go:generate minimock -i github.com/rekby/lets-proxy2/internal/cache.Value -o ./value_mock_test.go import ( - "sync/atomic" - "time" - "context" + "sync" + mm_atomic "sync/atomic" + mm_time "time" "github.com/gojuno/minimock/v3" ) @@ -19,16 +18,19 @@ type ValueMock struct { t minimock.Tester funcDelete func(ctx context.Context, key string) (err error) + inspectFuncDelete func(ctx context.Context, key string) afterDeleteCounter uint64 beforeDeleteCounter uint64 DeleteMock mValueMockDelete funcGet func(ctx context.Context, key string) (p1 interface{}, err error) + inspectFuncGet func(ctx context.Context, key string) afterGetCounter uint64 beforeGetCounter uint64 GetMock mValueMockGet funcPut func(ctx context.Context, key string, value interface{}) (err error) + inspectFuncPut func(ctx context.Context, key string, value interface{}) afterPutCounter uint64 beforePutCounter uint64 PutMock mValueMockPut @@ -40,9 +42,15 @@ func NewValueMock(t minimock.Tester) *ValueMock { if controller, ok := t.(minimock.MockController); ok { controller.RegisterMocker(m) } + m.DeleteMock = mValueMockDelete{mock: m} + m.DeleteMock.callArgs = []*ValueMockDeleteParams{} + m.GetMock = mValueMockGet{mock: m} + m.GetMock.callArgs = []*ValueMockGetParams{} + m.PutMock = mValueMockPut{mock: m} + m.PutMock.callArgs = []*ValueMockPutParams{} return m } @@ -51,6 +59,9 @@ type mValueMockDelete struct { mock *ValueMock defaultExpectation *ValueMockDeleteExpectation expectations []*ValueMockDeleteExpectation + + callArgs []*ValueMockDeleteParams + mutex sync.RWMutex } // ValueMockDeleteExpectation specifies expectation struct of the Value.Delete @@ -73,64 +84,75 @@ type ValueMockDeleteResults struct { } // Expect sets up expected params for Value.Delete -func (m *mValueMockDelete) Expect(ctx context.Context, key string) *mValueMockDelete { - if m.mock.funcDelete != nil { - m.mock.t.Fatalf("ValueMock.Delete mock is already set by Set") +func (mmDelete *mValueMockDelete) Expect(ctx context.Context, key string) *mValueMockDelete { + if mmDelete.mock.funcDelete != nil { + mmDelete.mock.t.Fatalf("ValueMock.Delete mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ValueMockDeleteExpectation{} + if mmDelete.defaultExpectation == nil { + mmDelete.defaultExpectation = &ValueMockDeleteExpectation{} } - m.defaultExpectation.params = &ValueMockDeleteParams{ctx, key} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmDelete.defaultExpectation.params = &ValueMockDeleteParams{ctx, key} + for _, e := range mmDelete.expectations { + if minimock.Equal(e.params, mmDelete.defaultExpectation.params) { + mmDelete.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmDelete.defaultExpectation.params) } } - return m + return mmDelete +} + +// Inspect accepts an inspector function that has same arguments as the Value.Delete +func (mmDelete *mValueMockDelete) Inspect(f func(ctx context.Context, key string)) *mValueMockDelete { + if mmDelete.mock.inspectFuncDelete != nil { + mmDelete.mock.t.Fatalf("Inspect function is already set for ValueMock.Delete") + } + + mmDelete.mock.inspectFuncDelete = f + + return mmDelete } // Return sets up results that will be returned by Value.Delete -func (m *mValueMockDelete) Return(err error) *ValueMock { - if m.mock.funcDelete != nil { - m.mock.t.Fatalf("ValueMock.Delete mock is already set by Set") +func (mmDelete *mValueMockDelete) Return(err error) *ValueMock { + if mmDelete.mock.funcDelete != nil { + mmDelete.mock.t.Fatalf("ValueMock.Delete mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ValueMockDeleteExpectation{mock: m.mock} + if mmDelete.defaultExpectation == nil { + mmDelete.defaultExpectation = &ValueMockDeleteExpectation{mock: mmDelete.mock} } - m.defaultExpectation.results = &ValueMockDeleteResults{err} - return m.mock + mmDelete.defaultExpectation.results = &ValueMockDeleteResults{err} + return mmDelete.mock } //Set uses given function f to mock the Value.Delete method -func (m *mValueMockDelete) Set(f func(ctx context.Context, key string) (err error)) *ValueMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Value.Delete method") +func (mmDelete *mValueMockDelete) Set(f func(ctx context.Context, key string) (err error)) *ValueMock { + if mmDelete.defaultExpectation != nil { + mmDelete.mock.t.Fatalf("Default expectation is already set for the Value.Delete method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Value.Delete method") + if len(mmDelete.expectations) > 0 { + mmDelete.mock.t.Fatalf("Some expectations are already set for the Value.Delete method") } - m.mock.funcDelete = f - return m.mock + mmDelete.mock.funcDelete = f + return mmDelete.mock } // When sets expectation for the Value.Delete which will trigger the result defined by the following // Then helper -func (m *mValueMockDelete) When(ctx context.Context, key string) *ValueMockDeleteExpectation { - if m.mock.funcDelete != nil { - m.mock.t.Fatalf("ValueMock.Delete mock is already set by Set") +func (mmDelete *mValueMockDelete) When(ctx context.Context, key string) *ValueMockDeleteExpectation { + if mmDelete.mock.funcDelete != nil { + mmDelete.mock.t.Fatalf("ValueMock.Delete mock is already set by Set") } expectation := &ValueMockDeleteExpectation{ - mock: m.mock, + mock: mmDelete.mock, params: &ValueMockDeleteParams{ctx, key}, } - m.expectations = append(m.expectations, expectation) + mmDelete.expectations = append(mmDelete.expectations, expectation) return expectation } @@ -141,63 +163,87 @@ func (e *ValueMockDeleteExpectation) Then(err error) *ValueMock { } // Delete implements cache.Value -func (m *ValueMock) Delete(ctx context.Context, key string) (err error) { - atomic.AddUint64(&m.beforeDeleteCounter, 1) - defer atomic.AddUint64(&m.afterDeleteCounter, 1) +func (mmDelete *ValueMock) Delete(ctx context.Context, key string) (err error) { + mm_atomic.AddUint64(&mmDelete.beforeDeleteCounter, 1) + defer mm_atomic.AddUint64(&mmDelete.afterDeleteCounter, 1) - for _, e := range m.DeleteMock.expectations { - if minimock.Equal(*e.params, ValueMockDeleteParams{ctx, key}) { - atomic.AddUint64(&e.Counter, 1) + if mmDelete.inspectFuncDelete != nil { + mmDelete.inspectFuncDelete(ctx, key) + } + + mm_params := &ValueMockDeleteParams{ctx, key} + + // Record call args + mmDelete.DeleteMock.mutex.Lock() + mmDelete.DeleteMock.callArgs = append(mmDelete.DeleteMock.callArgs, mm_params) + mmDelete.DeleteMock.mutex.Unlock() + + for _, e := range mmDelete.DeleteMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.err } } - if m.DeleteMock.defaultExpectation != nil { - atomic.AddUint64(&m.DeleteMock.defaultExpectation.Counter, 1) - want := m.DeleteMock.defaultExpectation.params - got := ValueMockDeleteParams{ctx, key} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("ValueMock.Delete got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmDelete.DeleteMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmDelete.DeleteMock.defaultExpectation.Counter, 1) + mm_want := mmDelete.DeleteMock.defaultExpectation.params + mm_got := ValueMockDeleteParams{ctx, key} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmDelete.t.Errorf("ValueMock.Delete got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.DeleteMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the ValueMock.Delete") + mm_results := mmDelete.DeleteMock.defaultExpectation.results + if mm_results == nil { + mmDelete.t.Fatal("No results are set for the ValueMock.Delete") } - return (*results).err + return (*mm_results).err } - if m.funcDelete != nil { - return m.funcDelete(ctx, key) + if mmDelete.funcDelete != nil { + return mmDelete.funcDelete(ctx, key) } - m.t.Fatalf("Unexpected call to ValueMock.Delete. %v %v", ctx, key) + mmDelete.t.Fatalf("Unexpected call to ValueMock.Delete. %v %v", ctx, key) return } // DeleteAfterCounter returns a count of finished ValueMock.Delete invocations -func (m *ValueMock) DeleteAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterDeleteCounter) +func (mmDelete *ValueMock) DeleteAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmDelete.afterDeleteCounter) } // DeleteBeforeCounter returns a count of ValueMock.Delete invocations -func (m *ValueMock) DeleteBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeDeleteCounter) +func (mmDelete *ValueMock) DeleteBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmDelete.beforeDeleteCounter) +} + +// Calls returns a list of arguments used in each call to ValueMock.Delete. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmDelete *mValueMockDelete) Calls() []*ValueMockDeleteParams { + mmDelete.mutex.RLock() + + argCopy := make([]*ValueMockDeleteParams, len(mmDelete.callArgs)) + copy(argCopy, mmDelete.callArgs) + + mmDelete.mutex.RUnlock() + + return argCopy } // MinimockDeleteDone returns true if the count of the Delete invocations corresponds // the number of defined expectations func (m *ValueMock) MinimockDeleteDone() bool { for _, e := range m.DeleteMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.DeleteMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterDeleteCounter) < 1 { + if m.DeleteMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterDeleteCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcDelete != nil && atomic.LoadUint64(&m.afterDeleteCounter) < 1 { + if m.funcDelete != nil && mm_atomic.LoadUint64(&m.afterDeleteCounter) < 1 { return false } return true @@ -206,17 +252,21 @@ func (m *ValueMock) MinimockDeleteDone() bool { // MinimockDeleteInspect logs each unmet expectation func (m *ValueMock) MinimockDeleteInspect() { for _, e := range m.DeleteMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to ValueMock.Delete with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.DeleteMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterDeleteCounter) < 1 { - m.t.Errorf("Expected call to ValueMock.Delete with params: %#v", *m.DeleteMock.defaultExpectation.params) + if m.DeleteMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterDeleteCounter) < 1 { + if m.DeleteMock.defaultExpectation.params == nil { + m.t.Error("Expected call to ValueMock.Delete") + } else { + m.t.Errorf("Expected call to ValueMock.Delete with params: %#v", *m.DeleteMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcDelete != nil && atomic.LoadUint64(&m.afterDeleteCounter) < 1 { + if m.funcDelete != nil && mm_atomic.LoadUint64(&m.afterDeleteCounter) < 1 { m.t.Error("Expected call to ValueMock.Delete") } } @@ -225,6 +275,9 @@ type mValueMockGet struct { mock *ValueMock defaultExpectation *ValueMockGetExpectation expectations []*ValueMockGetExpectation + + callArgs []*ValueMockGetParams + mutex sync.RWMutex } // ValueMockGetExpectation specifies expectation struct of the Value.Get @@ -248,64 +301,75 @@ type ValueMockGetResults struct { } // Expect sets up expected params for Value.Get -func (m *mValueMockGet) Expect(ctx context.Context, key string) *mValueMockGet { - if m.mock.funcGet != nil { - m.mock.t.Fatalf("ValueMock.Get mock is already set by Set") +func (mmGet *mValueMockGet) Expect(ctx context.Context, key string) *mValueMockGet { + if mmGet.mock.funcGet != nil { + mmGet.mock.t.Fatalf("ValueMock.Get mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ValueMockGetExpectation{} + if mmGet.defaultExpectation == nil { + mmGet.defaultExpectation = &ValueMockGetExpectation{} } - m.defaultExpectation.params = &ValueMockGetParams{ctx, key} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmGet.defaultExpectation.params = &ValueMockGetParams{ctx, key} + for _, e := range mmGet.expectations { + if minimock.Equal(e.params, mmGet.defaultExpectation.params) { + mmGet.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmGet.defaultExpectation.params) } } - return m + return mmGet +} + +// Inspect accepts an inspector function that has same arguments as the Value.Get +func (mmGet *mValueMockGet) Inspect(f func(ctx context.Context, key string)) *mValueMockGet { + if mmGet.mock.inspectFuncGet != nil { + mmGet.mock.t.Fatalf("Inspect function is already set for ValueMock.Get") + } + + mmGet.mock.inspectFuncGet = f + + return mmGet } // Return sets up results that will be returned by Value.Get -func (m *mValueMockGet) Return(p1 interface{}, err error) *ValueMock { - if m.mock.funcGet != nil { - m.mock.t.Fatalf("ValueMock.Get mock is already set by Set") +func (mmGet *mValueMockGet) Return(p1 interface{}, err error) *ValueMock { + if mmGet.mock.funcGet != nil { + mmGet.mock.t.Fatalf("ValueMock.Get mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ValueMockGetExpectation{mock: m.mock} + if mmGet.defaultExpectation == nil { + mmGet.defaultExpectation = &ValueMockGetExpectation{mock: mmGet.mock} } - m.defaultExpectation.results = &ValueMockGetResults{p1, err} - return m.mock + mmGet.defaultExpectation.results = &ValueMockGetResults{p1, err} + return mmGet.mock } //Set uses given function f to mock the Value.Get method -func (m *mValueMockGet) Set(f func(ctx context.Context, key string) (p1 interface{}, err error)) *ValueMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Value.Get method") +func (mmGet *mValueMockGet) Set(f func(ctx context.Context, key string) (p1 interface{}, err error)) *ValueMock { + if mmGet.defaultExpectation != nil { + mmGet.mock.t.Fatalf("Default expectation is already set for the Value.Get method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Value.Get method") + if len(mmGet.expectations) > 0 { + mmGet.mock.t.Fatalf("Some expectations are already set for the Value.Get method") } - m.mock.funcGet = f - return m.mock + mmGet.mock.funcGet = f + return mmGet.mock } // When sets expectation for the Value.Get which will trigger the result defined by the following // Then helper -func (m *mValueMockGet) When(ctx context.Context, key string) *ValueMockGetExpectation { - if m.mock.funcGet != nil { - m.mock.t.Fatalf("ValueMock.Get mock is already set by Set") +func (mmGet *mValueMockGet) When(ctx context.Context, key string) *ValueMockGetExpectation { + if mmGet.mock.funcGet != nil { + mmGet.mock.t.Fatalf("ValueMock.Get mock is already set by Set") } expectation := &ValueMockGetExpectation{ - mock: m.mock, + mock: mmGet.mock, params: &ValueMockGetParams{ctx, key}, } - m.expectations = append(m.expectations, expectation) + mmGet.expectations = append(mmGet.expectations, expectation) return expectation } @@ -316,63 +380,87 @@ func (e *ValueMockGetExpectation) Then(p1 interface{}, err error) *ValueMock { } // Get implements cache.Value -func (m *ValueMock) Get(ctx context.Context, key string) (p1 interface{}, err error) { - atomic.AddUint64(&m.beforeGetCounter, 1) - defer atomic.AddUint64(&m.afterGetCounter, 1) +func (mmGet *ValueMock) Get(ctx context.Context, key string) (p1 interface{}, err error) { + mm_atomic.AddUint64(&mmGet.beforeGetCounter, 1) + defer mm_atomic.AddUint64(&mmGet.afterGetCounter, 1) - for _, e := range m.GetMock.expectations { - if minimock.Equal(*e.params, ValueMockGetParams{ctx, key}) { - atomic.AddUint64(&e.Counter, 1) + if mmGet.inspectFuncGet != nil { + mmGet.inspectFuncGet(ctx, key) + } + + mm_params := &ValueMockGetParams{ctx, key} + + // Record call args + mmGet.GetMock.mutex.Lock() + mmGet.GetMock.callArgs = append(mmGet.GetMock.callArgs, mm_params) + mmGet.GetMock.mutex.Unlock() + + for _, e := range mmGet.GetMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.p1, e.results.err } } - if m.GetMock.defaultExpectation != nil { - atomic.AddUint64(&m.GetMock.defaultExpectation.Counter, 1) - want := m.GetMock.defaultExpectation.params - got := ValueMockGetParams{ctx, key} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("ValueMock.Get got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmGet.GetMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmGet.GetMock.defaultExpectation.Counter, 1) + mm_want := mmGet.GetMock.defaultExpectation.params + mm_got := ValueMockGetParams{ctx, key} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmGet.t.Errorf("ValueMock.Get got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.GetMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the ValueMock.Get") + mm_results := mmGet.GetMock.defaultExpectation.results + if mm_results == nil { + mmGet.t.Fatal("No results are set for the ValueMock.Get") } - return (*results).p1, (*results).err + return (*mm_results).p1, (*mm_results).err } - if m.funcGet != nil { - return m.funcGet(ctx, key) + if mmGet.funcGet != nil { + return mmGet.funcGet(ctx, key) } - m.t.Fatalf("Unexpected call to ValueMock.Get. %v %v", ctx, key) + mmGet.t.Fatalf("Unexpected call to ValueMock.Get. %v %v", ctx, key) return } // GetAfterCounter returns a count of finished ValueMock.Get invocations -func (m *ValueMock) GetAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterGetCounter) +func (mmGet *ValueMock) GetAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmGet.afterGetCounter) } // GetBeforeCounter returns a count of ValueMock.Get invocations -func (m *ValueMock) GetBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeGetCounter) +func (mmGet *ValueMock) GetBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmGet.beforeGetCounter) +} + +// Calls returns a list of arguments used in each call to ValueMock.Get. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmGet *mValueMockGet) Calls() []*ValueMockGetParams { + mmGet.mutex.RLock() + + argCopy := make([]*ValueMockGetParams, len(mmGet.callArgs)) + copy(argCopy, mmGet.callArgs) + + mmGet.mutex.RUnlock() + + return argCopy } // MinimockGetDone returns true if the count of the Get invocations corresponds // the number of defined expectations func (m *ValueMock) MinimockGetDone() bool { for _, e := range m.GetMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.GetMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterGetCounter) < 1 { + if m.GetMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterGetCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcGet != nil && atomic.LoadUint64(&m.afterGetCounter) < 1 { + if m.funcGet != nil && mm_atomic.LoadUint64(&m.afterGetCounter) < 1 { return false } return true @@ -381,17 +469,21 @@ func (m *ValueMock) MinimockGetDone() bool { // MinimockGetInspect logs each unmet expectation func (m *ValueMock) MinimockGetInspect() { for _, e := range m.GetMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to ValueMock.Get with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.GetMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterGetCounter) < 1 { - m.t.Errorf("Expected call to ValueMock.Get with params: %#v", *m.GetMock.defaultExpectation.params) + if m.GetMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterGetCounter) < 1 { + if m.GetMock.defaultExpectation.params == nil { + m.t.Error("Expected call to ValueMock.Get") + } else { + m.t.Errorf("Expected call to ValueMock.Get with params: %#v", *m.GetMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcGet != nil && atomic.LoadUint64(&m.afterGetCounter) < 1 { + if m.funcGet != nil && mm_atomic.LoadUint64(&m.afterGetCounter) < 1 { m.t.Error("Expected call to ValueMock.Get") } } @@ -400,6 +492,9 @@ type mValueMockPut struct { mock *ValueMock defaultExpectation *ValueMockPutExpectation expectations []*ValueMockPutExpectation + + callArgs []*ValueMockPutParams + mutex sync.RWMutex } // ValueMockPutExpectation specifies expectation struct of the Value.Put @@ -423,64 +518,75 @@ type ValueMockPutResults struct { } // Expect sets up expected params for Value.Put -func (m *mValueMockPut) Expect(ctx context.Context, key string, value interface{}) *mValueMockPut { - if m.mock.funcPut != nil { - m.mock.t.Fatalf("ValueMock.Put mock is already set by Set") +func (mmPut *mValueMockPut) Expect(ctx context.Context, key string, value interface{}) *mValueMockPut { + if mmPut.mock.funcPut != nil { + mmPut.mock.t.Fatalf("ValueMock.Put mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ValueMockPutExpectation{} + if mmPut.defaultExpectation == nil { + mmPut.defaultExpectation = &ValueMockPutExpectation{} } - m.defaultExpectation.params = &ValueMockPutParams{ctx, key, value} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmPut.defaultExpectation.params = &ValueMockPutParams{ctx, key, value} + for _, e := range mmPut.expectations { + if minimock.Equal(e.params, mmPut.defaultExpectation.params) { + mmPut.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmPut.defaultExpectation.params) } } - return m + return mmPut +} + +// Inspect accepts an inspector function that has same arguments as the Value.Put +func (mmPut *mValueMockPut) Inspect(f func(ctx context.Context, key string, value interface{})) *mValueMockPut { + if mmPut.mock.inspectFuncPut != nil { + mmPut.mock.t.Fatalf("Inspect function is already set for ValueMock.Put") + } + + mmPut.mock.inspectFuncPut = f + + return mmPut } // Return sets up results that will be returned by Value.Put -func (m *mValueMockPut) Return(err error) *ValueMock { - if m.mock.funcPut != nil { - m.mock.t.Fatalf("ValueMock.Put mock is already set by Set") +func (mmPut *mValueMockPut) Return(err error) *ValueMock { + if mmPut.mock.funcPut != nil { + mmPut.mock.t.Fatalf("ValueMock.Put mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ValueMockPutExpectation{mock: m.mock} + if mmPut.defaultExpectation == nil { + mmPut.defaultExpectation = &ValueMockPutExpectation{mock: mmPut.mock} } - m.defaultExpectation.results = &ValueMockPutResults{err} - return m.mock + mmPut.defaultExpectation.results = &ValueMockPutResults{err} + return mmPut.mock } //Set uses given function f to mock the Value.Put method -func (m *mValueMockPut) Set(f func(ctx context.Context, key string, value interface{}) (err error)) *ValueMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Value.Put method") +func (mmPut *mValueMockPut) Set(f func(ctx context.Context, key string, value interface{}) (err error)) *ValueMock { + if mmPut.defaultExpectation != nil { + mmPut.mock.t.Fatalf("Default expectation is already set for the Value.Put method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Value.Put method") + if len(mmPut.expectations) > 0 { + mmPut.mock.t.Fatalf("Some expectations are already set for the Value.Put method") } - m.mock.funcPut = f - return m.mock + mmPut.mock.funcPut = f + return mmPut.mock } // When sets expectation for the Value.Put which will trigger the result defined by the following // Then helper -func (m *mValueMockPut) When(ctx context.Context, key string, value interface{}) *ValueMockPutExpectation { - if m.mock.funcPut != nil { - m.mock.t.Fatalf("ValueMock.Put mock is already set by Set") +func (mmPut *mValueMockPut) When(ctx context.Context, key string, value interface{}) *ValueMockPutExpectation { + if mmPut.mock.funcPut != nil { + mmPut.mock.t.Fatalf("ValueMock.Put mock is already set by Set") } expectation := &ValueMockPutExpectation{ - mock: m.mock, + mock: mmPut.mock, params: &ValueMockPutParams{ctx, key, value}, } - m.expectations = append(m.expectations, expectation) + mmPut.expectations = append(mmPut.expectations, expectation) return expectation } @@ -491,63 +597,87 @@ func (e *ValueMockPutExpectation) Then(err error) *ValueMock { } // Put implements cache.Value -func (m *ValueMock) Put(ctx context.Context, key string, value interface{}) (err error) { - atomic.AddUint64(&m.beforePutCounter, 1) - defer atomic.AddUint64(&m.afterPutCounter, 1) +func (mmPut *ValueMock) Put(ctx context.Context, key string, value interface{}) (err error) { + mm_atomic.AddUint64(&mmPut.beforePutCounter, 1) + defer mm_atomic.AddUint64(&mmPut.afterPutCounter, 1) - for _, e := range m.PutMock.expectations { - if minimock.Equal(*e.params, ValueMockPutParams{ctx, key, value}) { - atomic.AddUint64(&e.Counter, 1) + if mmPut.inspectFuncPut != nil { + mmPut.inspectFuncPut(ctx, key, value) + } + + mm_params := &ValueMockPutParams{ctx, key, value} + + // Record call args + mmPut.PutMock.mutex.Lock() + mmPut.PutMock.callArgs = append(mmPut.PutMock.callArgs, mm_params) + mmPut.PutMock.mutex.Unlock() + + for _, e := range mmPut.PutMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.err } } - if m.PutMock.defaultExpectation != nil { - atomic.AddUint64(&m.PutMock.defaultExpectation.Counter, 1) - want := m.PutMock.defaultExpectation.params - got := ValueMockPutParams{ctx, key, value} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("ValueMock.Put got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmPut.PutMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmPut.PutMock.defaultExpectation.Counter, 1) + mm_want := mmPut.PutMock.defaultExpectation.params + mm_got := ValueMockPutParams{ctx, key, value} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmPut.t.Errorf("ValueMock.Put got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.PutMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the ValueMock.Put") + mm_results := mmPut.PutMock.defaultExpectation.results + if mm_results == nil { + mmPut.t.Fatal("No results are set for the ValueMock.Put") } - return (*results).err + return (*mm_results).err } - if m.funcPut != nil { - return m.funcPut(ctx, key, value) + if mmPut.funcPut != nil { + return mmPut.funcPut(ctx, key, value) } - m.t.Fatalf("Unexpected call to ValueMock.Put. %v %v %v", ctx, key, value) + mmPut.t.Fatalf("Unexpected call to ValueMock.Put. %v %v %v", ctx, key, value) return } // PutAfterCounter returns a count of finished ValueMock.Put invocations -func (m *ValueMock) PutAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterPutCounter) +func (mmPut *ValueMock) PutAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmPut.afterPutCounter) } // PutBeforeCounter returns a count of ValueMock.Put invocations -func (m *ValueMock) PutBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforePutCounter) +func (mmPut *ValueMock) PutBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmPut.beforePutCounter) +} + +// Calls returns a list of arguments used in each call to ValueMock.Put. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmPut *mValueMockPut) Calls() []*ValueMockPutParams { + mmPut.mutex.RLock() + + argCopy := make([]*ValueMockPutParams, len(mmPut.callArgs)) + copy(argCopy, mmPut.callArgs) + + mmPut.mutex.RUnlock() + + return argCopy } // MinimockPutDone returns true if the count of the Put invocations corresponds // the number of defined expectations func (m *ValueMock) MinimockPutDone() bool { for _, e := range m.PutMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.PutMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterPutCounter) < 1 { + if m.PutMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterPutCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcPut != nil && atomic.LoadUint64(&m.afterPutCounter) < 1 { + if m.funcPut != nil && mm_atomic.LoadUint64(&m.afterPutCounter) < 1 { return false } return true @@ -556,17 +686,21 @@ func (m *ValueMock) MinimockPutDone() bool { // MinimockPutInspect logs each unmet expectation func (m *ValueMock) MinimockPutInspect() { for _, e := range m.PutMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to ValueMock.Put with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.PutMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterPutCounter) < 1 { - m.t.Errorf("Expected call to ValueMock.Put with params: %#v", *m.PutMock.defaultExpectation.params) + if m.PutMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterPutCounter) < 1 { + if m.PutMock.defaultExpectation.params == nil { + m.t.Error("Expected call to ValueMock.Put") + } else { + m.t.Errorf("Expected call to ValueMock.Put with params: %#v", *m.PutMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcPut != nil && atomic.LoadUint64(&m.afterPutCounter) < 1 { + if m.funcPut != nil && mm_atomic.LoadUint64(&m.afterPutCounter) < 1 { m.t.Error("Expected call to ValueMock.Put") } } @@ -584,8 +718,8 @@ func (m *ValueMock) MinimockFinish() { } // MinimockWait waits for all mocked methods to be called the expected number of times -func (m *ValueMock) MinimockWait(timeout time.Duration) { - timeoutCh := time.After(timeout) +func (m *ValueMock) MinimockWait(timeout mm_time.Duration) { + timeoutCh := mm_time.After(timeout) for { if m.minimockDone() { return @@ -594,7 +728,7 @@ func (m *ValueMock) MinimockWait(timeout time.Duration) { case <-timeoutCh: m.MinimockFinish() return - case <-time.After(10 * time.Millisecond): + case <-mm_time.After(10 * mm_time.Millisecond): } } } diff --git a/internal/dns/m_dns_client_mock_test.go b/internal/dns/m_dns_client_mock_test.go index e9eaf459..1d6a8f3a 100644 --- a/internal/dns/m_dns_client_mock_test.go +++ b/internal/dns/m_dns_client_mock_test.go @@ -1,17 +1,17 @@ package dns -// DO NOT EDIT! -// The code below was generated with http://github.com/gojuno/minimock (dev) +// Code generated by http://github.com/gojuno/minimock (3.0.6). DO NOT EDIT. //go:generate minimock -i github.com/rekby/lets-proxy2/internal/dns.mDNSClient -o ./m_dns_client_mock_test.go import ( - "sync/atomic" + "sync" + mm_atomic "sync/atomic" "time" - - mdns "github.com/miekg/dns" + mm_time "time" "github.com/gojuno/minimock/v3" + mdns "github.com/miekg/dns" ) // MDNSClientMock implements mDNSClient @@ -19,6 +19,7 @@ type MDNSClientMock struct { t minimock.Tester funcExchange func(msg *mdns.Msg, address string) (r *mdns.Msg, rtt time.Duration, err error) + inspectFuncExchange func(msg *mdns.Msg, address string) afterExchangeCounter uint64 beforeExchangeCounter uint64 ExchangeMock mMDNSClientMockExchange @@ -30,7 +31,9 @@ func NewMDNSClientMock(t minimock.Tester) *MDNSClientMock { if controller, ok := t.(minimock.MockController); ok { controller.RegisterMocker(m) } + m.ExchangeMock = mMDNSClientMockExchange{mock: m} + m.ExchangeMock.callArgs = []*MDNSClientMockExchangeParams{} return m } @@ -39,6 +42,9 @@ type mMDNSClientMockExchange struct { mock *MDNSClientMock defaultExpectation *MDNSClientMockExchangeExpectation expectations []*MDNSClientMockExchangeExpectation + + callArgs []*MDNSClientMockExchangeParams + mutex sync.RWMutex } // MDNSClientMockExchangeExpectation specifies expectation struct of the mDNSClient.Exchange @@ -63,64 +69,75 @@ type MDNSClientMockExchangeResults struct { } // Expect sets up expected params for mDNSClient.Exchange -func (m *mMDNSClientMockExchange) Expect(msg *mdns.Msg, address string) *mMDNSClientMockExchange { - if m.mock.funcExchange != nil { - m.mock.t.Fatalf("MDNSClientMock.Exchange mock is already set by Set") +func (mmExchange *mMDNSClientMockExchange) Expect(msg *mdns.Msg, address string) *mMDNSClientMockExchange { + if mmExchange.mock.funcExchange != nil { + mmExchange.mock.t.Fatalf("MDNSClientMock.Exchange mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &MDNSClientMockExchangeExpectation{} + if mmExchange.defaultExpectation == nil { + mmExchange.defaultExpectation = &MDNSClientMockExchangeExpectation{} } - m.defaultExpectation.params = &MDNSClientMockExchangeParams{msg, address} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmExchange.defaultExpectation.params = &MDNSClientMockExchangeParams{msg, address} + for _, e := range mmExchange.expectations { + if minimock.Equal(e.params, mmExchange.defaultExpectation.params) { + mmExchange.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmExchange.defaultExpectation.params) } } - return m + return mmExchange +} + +// Inspect accepts an inspector function that has same arguments as the mDNSClient.Exchange +func (mmExchange *mMDNSClientMockExchange) Inspect(f func(msg *mdns.Msg, address string)) *mMDNSClientMockExchange { + if mmExchange.mock.inspectFuncExchange != nil { + mmExchange.mock.t.Fatalf("Inspect function is already set for MDNSClientMock.Exchange") + } + + mmExchange.mock.inspectFuncExchange = f + + return mmExchange } // Return sets up results that will be returned by mDNSClient.Exchange -func (m *mMDNSClientMockExchange) Return(r *mdns.Msg, rtt time.Duration, err error) *MDNSClientMock { - if m.mock.funcExchange != nil { - m.mock.t.Fatalf("MDNSClientMock.Exchange mock is already set by Set") +func (mmExchange *mMDNSClientMockExchange) Return(r *mdns.Msg, rtt time.Duration, err error) *MDNSClientMock { + if mmExchange.mock.funcExchange != nil { + mmExchange.mock.t.Fatalf("MDNSClientMock.Exchange mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &MDNSClientMockExchangeExpectation{mock: m.mock} + if mmExchange.defaultExpectation == nil { + mmExchange.defaultExpectation = &MDNSClientMockExchangeExpectation{mock: mmExchange.mock} } - m.defaultExpectation.results = &MDNSClientMockExchangeResults{r, rtt, err} - return m.mock + mmExchange.defaultExpectation.results = &MDNSClientMockExchangeResults{r, rtt, err} + return mmExchange.mock } //Set uses given function f to mock the mDNSClient.Exchange method -func (m *mMDNSClientMockExchange) Set(f func(msg *mdns.Msg, address string) (r *mdns.Msg, rtt time.Duration, err error)) *MDNSClientMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the mDNSClient.Exchange method") +func (mmExchange *mMDNSClientMockExchange) Set(f func(msg *mdns.Msg, address string) (r *mdns.Msg, rtt time.Duration, err error)) *MDNSClientMock { + if mmExchange.defaultExpectation != nil { + mmExchange.mock.t.Fatalf("Default expectation is already set for the mDNSClient.Exchange method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the mDNSClient.Exchange method") + if len(mmExchange.expectations) > 0 { + mmExchange.mock.t.Fatalf("Some expectations are already set for the mDNSClient.Exchange method") } - m.mock.funcExchange = f - return m.mock + mmExchange.mock.funcExchange = f + return mmExchange.mock } // When sets expectation for the mDNSClient.Exchange which will trigger the result defined by the following // Then helper -func (m *mMDNSClientMockExchange) When(msg *mdns.Msg, address string) *MDNSClientMockExchangeExpectation { - if m.mock.funcExchange != nil { - m.mock.t.Fatalf("MDNSClientMock.Exchange mock is already set by Set") +func (mmExchange *mMDNSClientMockExchange) When(msg *mdns.Msg, address string) *MDNSClientMockExchangeExpectation { + if mmExchange.mock.funcExchange != nil { + mmExchange.mock.t.Fatalf("MDNSClientMock.Exchange mock is already set by Set") } expectation := &MDNSClientMockExchangeExpectation{ - mock: m.mock, + mock: mmExchange.mock, params: &MDNSClientMockExchangeParams{msg, address}, } - m.expectations = append(m.expectations, expectation) + mmExchange.expectations = append(mmExchange.expectations, expectation) return expectation } @@ -131,63 +148,87 @@ func (e *MDNSClientMockExchangeExpectation) Then(r *mdns.Msg, rtt time.Duration, } // Exchange implements mDNSClient -func (m *MDNSClientMock) Exchange(msg *mdns.Msg, address string) (r *mdns.Msg, rtt time.Duration, err error) { - atomic.AddUint64(&m.beforeExchangeCounter, 1) - defer atomic.AddUint64(&m.afterExchangeCounter, 1) +func (mmExchange *MDNSClientMock) Exchange(msg *mdns.Msg, address string) (r *mdns.Msg, rtt time.Duration, err error) { + mm_atomic.AddUint64(&mmExchange.beforeExchangeCounter, 1) + defer mm_atomic.AddUint64(&mmExchange.afterExchangeCounter, 1) - for _, e := range m.ExchangeMock.expectations { - if minimock.Equal(*e.params, MDNSClientMockExchangeParams{msg, address}) { - atomic.AddUint64(&e.Counter, 1) + if mmExchange.inspectFuncExchange != nil { + mmExchange.inspectFuncExchange(msg, address) + } + + mm_params := &MDNSClientMockExchangeParams{msg, address} + + // Record call args + mmExchange.ExchangeMock.mutex.Lock() + mmExchange.ExchangeMock.callArgs = append(mmExchange.ExchangeMock.callArgs, mm_params) + mmExchange.ExchangeMock.mutex.Unlock() + + for _, e := range mmExchange.ExchangeMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.r, e.results.rtt, e.results.err } } - if m.ExchangeMock.defaultExpectation != nil { - atomic.AddUint64(&m.ExchangeMock.defaultExpectation.Counter, 1) - want := m.ExchangeMock.defaultExpectation.params - got := MDNSClientMockExchangeParams{msg, address} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("MDNSClientMock.Exchange got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmExchange.ExchangeMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmExchange.ExchangeMock.defaultExpectation.Counter, 1) + mm_want := mmExchange.ExchangeMock.defaultExpectation.params + mm_got := MDNSClientMockExchangeParams{msg, address} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmExchange.t.Errorf("MDNSClientMock.Exchange got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.ExchangeMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the MDNSClientMock.Exchange") + mm_results := mmExchange.ExchangeMock.defaultExpectation.results + if mm_results == nil { + mmExchange.t.Fatal("No results are set for the MDNSClientMock.Exchange") } - return (*results).r, (*results).rtt, (*results).err + return (*mm_results).r, (*mm_results).rtt, (*mm_results).err } - if m.funcExchange != nil { - return m.funcExchange(msg, address) + if mmExchange.funcExchange != nil { + return mmExchange.funcExchange(msg, address) } - m.t.Fatalf("Unexpected call to MDNSClientMock.Exchange. %v %v", msg, address) + mmExchange.t.Fatalf("Unexpected call to MDNSClientMock.Exchange. %v %v", msg, address) return } // ExchangeAfterCounter returns a count of finished MDNSClientMock.Exchange invocations -func (m *MDNSClientMock) ExchangeAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterExchangeCounter) +func (mmExchange *MDNSClientMock) ExchangeAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmExchange.afterExchangeCounter) } // ExchangeBeforeCounter returns a count of MDNSClientMock.Exchange invocations -func (m *MDNSClientMock) ExchangeBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeExchangeCounter) +func (mmExchange *MDNSClientMock) ExchangeBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmExchange.beforeExchangeCounter) +} + +// Calls returns a list of arguments used in each call to MDNSClientMock.Exchange. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmExchange *mMDNSClientMockExchange) Calls() []*MDNSClientMockExchangeParams { + mmExchange.mutex.RLock() + + argCopy := make([]*MDNSClientMockExchangeParams, len(mmExchange.callArgs)) + copy(argCopy, mmExchange.callArgs) + + mmExchange.mutex.RUnlock() + + return argCopy } // MinimockExchangeDone returns true if the count of the Exchange invocations corresponds // the number of defined expectations func (m *MDNSClientMock) MinimockExchangeDone() bool { for _, e := range m.ExchangeMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.ExchangeMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterExchangeCounter) < 1 { + if m.ExchangeMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterExchangeCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcExchange != nil && atomic.LoadUint64(&m.afterExchangeCounter) < 1 { + if m.funcExchange != nil && mm_atomic.LoadUint64(&m.afterExchangeCounter) < 1 { return false } return true @@ -196,17 +237,21 @@ func (m *MDNSClientMock) MinimockExchangeDone() bool { // MinimockExchangeInspect logs each unmet expectation func (m *MDNSClientMock) MinimockExchangeInspect() { for _, e := range m.ExchangeMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to MDNSClientMock.Exchange with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.ExchangeMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterExchangeCounter) < 1 { - m.t.Errorf("Expected call to MDNSClientMock.Exchange with params: %#v", *m.ExchangeMock.defaultExpectation.params) + if m.ExchangeMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterExchangeCounter) < 1 { + if m.ExchangeMock.defaultExpectation.params == nil { + m.t.Error("Expected call to MDNSClientMock.Exchange") + } else { + m.t.Errorf("Expected call to MDNSClientMock.Exchange with params: %#v", *m.ExchangeMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcExchange != nil && atomic.LoadUint64(&m.afterExchangeCounter) < 1 { + if m.funcExchange != nil && mm_atomic.LoadUint64(&m.afterExchangeCounter) < 1 { m.t.Error("Expected call to MDNSClientMock.Exchange") } } @@ -220,8 +265,8 @@ func (m *MDNSClientMock) MinimockFinish() { } // MinimockWait waits for all mocked methods to be called the expected number of times -func (m *MDNSClientMock) MinimockWait(timeout time.Duration) { - timeoutCh := time.After(timeout) +func (m *MDNSClientMock) MinimockWait(timeout mm_time.Duration) { + timeoutCh := mm_time.After(timeout) for { if m.minimockDone() { return @@ -230,7 +275,7 @@ func (m *MDNSClientMock) MinimockWait(timeout time.Duration) { case <-timeoutCh: m.MinimockFinish() return - case <-time.After(10 * time.Millisecond): + case <-mm_time.After(10 * mm_time.Millisecond): } } } diff --git a/internal/dns/resolver_interface_mock_test.go b/internal/dns/resolver_interface_mock_test.go index ce2130fd..6a5ca254 100644 --- a/internal/dns/resolver_interface_mock_test.go +++ b/internal/dns/resolver_interface_mock_test.go @@ -1,17 +1,15 @@ package dns -// DO NOT EDIT! -// The code below was generated with http://github.com/gojuno/minimock (dev) +// Code generated by http://github.com/gojuno/minimock (3.0.6). DO NOT EDIT. //go:generate minimock -i github.com/rekby/lets-proxy2/internal/dns.ResolverInterface -o ./resolver_interface_mock_test.go import ( - "sync/atomic" - "time" - "context" - "net" + "sync" + mm_atomic "sync/atomic" + mm_time "time" "github.com/gojuno/minimock/v3" ) @@ -21,6 +19,7 @@ type ResolverInterfaceMock struct { t minimock.Tester funcLookupIPAddr func(ctx context.Context, host string) (ia1 []net.IPAddr, err error) + inspectFuncLookupIPAddr func(ctx context.Context, host string) afterLookupIPAddrCounter uint64 beforeLookupIPAddrCounter uint64 LookupIPAddrMock mResolverInterfaceMockLookupIPAddr @@ -32,7 +31,9 @@ func NewResolverInterfaceMock(t minimock.Tester) *ResolverInterfaceMock { if controller, ok := t.(minimock.MockController); ok { controller.RegisterMocker(m) } + m.LookupIPAddrMock = mResolverInterfaceMockLookupIPAddr{mock: m} + m.LookupIPAddrMock.callArgs = []*ResolverInterfaceMockLookupIPAddrParams{} return m } @@ -41,6 +42,9 @@ type mResolverInterfaceMockLookupIPAddr struct { mock *ResolverInterfaceMock defaultExpectation *ResolverInterfaceMockLookupIPAddrExpectation expectations []*ResolverInterfaceMockLookupIPAddrExpectation + + callArgs []*ResolverInterfaceMockLookupIPAddrParams + mutex sync.RWMutex } // ResolverInterfaceMockLookupIPAddrExpectation specifies expectation struct of the ResolverInterface.LookupIPAddr @@ -64,64 +68,75 @@ type ResolverInterfaceMockLookupIPAddrResults struct { } // Expect sets up expected params for ResolverInterface.LookupIPAddr -func (m *mResolverInterfaceMockLookupIPAddr) Expect(ctx context.Context, host string) *mResolverInterfaceMockLookupIPAddr { - if m.mock.funcLookupIPAddr != nil { - m.mock.t.Fatalf("ResolverInterfaceMock.LookupIPAddr mock is already set by Set") +func (mmLookupIPAddr *mResolverInterfaceMockLookupIPAddr) Expect(ctx context.Context, host string) *mResolverInterfaceMockLookupIPAddr { + if mmLookupIPAddr.mock.funcLookupIPAddr != nil { + mmLookupIPAddr.mock.t.Fatalf("ResolverInterfaceMock.LookupIPAddr mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ResolverInterfaceMockLookupIPAddrExpectation{} + if mmLookupIPAddr.defaultExpectation == nil { + mmLookupIPAddr.defaultExpectation = &ResolverInterfaceMockLookupIPAddrExpectation{} } - m.defaultExpectation.params = &ResolverInterfaceMockLookupIPAddrParams{ctx, host} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmLookupIPAddr.defaultExpectation.params = &ResolverInterfaceMockLookupIPAddrParams{ctx, host} + for _, e := range mmLookupIPAddr.expectations { + if minimock.Equal(e.params, mmLookupIPAddr.defaultExpectation.params) { + mmLookupIPAddr.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmLookupIPAddr.defaultExpectation.params) } } - return m + return mmLookupIPAddr +} + +// Inspect accepts an inspector function that has same arguments as the ResolverInterface.LookupIPAddr +func (mmLookupIPAddr *mResolverInterfaceMockLookupIPAddr) Inspect(f func(ctx context.Context, host string)) *mResolverInterfaceMockLookupIPAddr { + if mmLookupIPAddr.mock.inspectFuncLookupIPAddr != nil { + mmLookupIPAddr.mock.t.Fatalf("Inspect function is already set for ResolverInterfaceMock.LookupIPAddr") + } + + mmLookupIPAddr.mock.inspectFuncLookupIPAddr = f + + return mmLookupIPAddr } // Return sets up results that will be returned by ResolverInterface.LookupIPAddr -func (m *mResolverInterfaceMockLookupIPAddr) Return(ia1 []net.IPAddr, err error) *ResolverInterfaceMock { - if m.mock.funcLookupIPAddr != nil { - m.mock.t.Fatalf("ResolverInterfaceMock.LookupIPAddr mock is already set by Set") +func (mmLookupIPAddr *mResolverInterfaceMockLookupIPAddr) Return(ia1 []net.IPAddr, err error) *ResolverInterfaceMock { + if mmLookupIPAddr.mock.funcLookupIPAddr != nil { + mmLookupIPAddr.mock.t.Fatalf("ResolverInterfaceMock.LookupIPAddr mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ResolverInterfaceMockLookupIPAddrExpectation{mock: m.mock} + if mmLookupIPAddr.defaultExpectation == nil { + mmLookupIPAddr.defaultExpectation = &ResolverInterfaceMockLookupIPAddrExpectation{mock: mmLookupIPAddr.mock} } - m.defaultExpectation.results = &ResolverInterfaceMockLookupIPAddrResults{ia1, err} - return m.mock + mmLookupIPAddr.defaultExpectation.results = &ResolverInterfaceMockLookupIPAddrResults{ia1, err} + return mmLookupIPAddr.mock } //Set uses given function f to mock the ResolverInterface.LookupIPAddr method -func (m *mResolverInterfaceMockLookupIPAddr) Set(f func(ctx context.Context, host string) (ia1 []net.IPAddr, err error)) *ResolverInterfaceMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the ResolverInterface.LookupIPAddr method") +func (mmLookupIPAddr *mResolverInterfaceMockLookupIPAddr) Set(f func(ctx context.Context, host string) (ia1 []net.IPAddr, err error)) *ResolverInterfaceMock { + if mmLookupIPAddr.defaultExpectation != nil { + mmLookupIPAddr.mock.t.Fatalf("Default expectation is already set for the ResolverInterface.LookupIPAddr method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the ResolverInterface.LookupIPAddr method") + if len(mmLookupIPAddr.expectations) > 0 { + mmLookupIPAddr.mock.t.Fatalf("Some expectations are already set for the ResolverInterface.LookupIPAddr method") } - m.mock.funcLookupIPAddr = f - return m.mock + mmLookupIPAddr.mock.funcLookupIPAddr = f + return mmLookupIPAddr.mock } // When sets expectation for the ResolverInterface.LookupIPAddr which will trigger the result defined by the following // Then helper -func (m *mResolverInterfaceMockLookupIPAddr) When(ctx context.Context, host string) *ResolverInterfaceMockLookupIPAddrExpectation { - if m.mock.funcLookupIPAddr != nil { - m.mock.t.Fatalf("ResolverInterfaceMock.LookupIPAddr mock is already set by Set") +func (mmLookupIPAddr *mResolverInterfaceMockLookupIPAddr) When(ctx context.Context, host string) *ResolverInterfaceMockLookupIPAddrExpectation { + if mmLookupIPAddr.mock.funcLookupIPAddr != nil { + mmLookupIPAddr.mock.t.Fatalf("ResolverInterfaceMock.LookupIPAddr mock is already set by Set") } expectation := &ResolverInterfaceMockLookupIPAddrExpectation{ - mock: m.mock, + mock: mmLookupIPAddr.mock, params: &ResolverInterfaceMockLookupIPAddrParams{ctx, host}, } - m.expectations = append(m.expectations, expectation) + mmLookupIPAddr.expectations = append(mmLookupIPAddr.expectations, expectation) return expectation } @@ -132,63 +147,87 @@ func (e *ResolverInterfaceMockLookupIPAddrExpectation) Then(ia1 []net.IPAddr, er } // LookupIPAddr implements ResolverInterface -func (m *ResolverInterfaceMock) LookupIPAddr(ctx context.Context, host string) (ia1 []net.IPAddr, err error) { - atomic.AddUint64(&m.beforeLookupIPAddrCounter, 1) - defer atomic.AddUint64(&m.afterLookupIPAddrCounter, 1) +func (mmLookupIPAddr *ResolverInterfaceMock) LookupIPAddr(ctx context.Context, host string) (ia1 []net.IPAddr, err error) { + mm_atomic.AddUint64(&mmLookupIPAddr.beforeLookupIPAddrCounter, 1) + defer mm_atomic.AddUint64(&mmLookupIPAddr.afterLookupIPAddrCounter, 1) - for _, e := range m.LookupIPAddrMock.expectations { - if minimock.Equal(*e.params, ResolverInterfaceMockLookupIPAddrParams{ctx, host}) { - atomic.AddUint64(&e.Counter, 1) + if mmLookupIPAddr.inspectFuncLookupIPAddr != nil { + mmLookupIPAddr.inspectFuncLookupIPAddr(ctx, host) + } + + mm_params := &ResolverInterfaceMockLookupIPAddrParams{ctx, host} + + // Record call args + mmLookupIPAddr.LookupIPAddrMock.mutex.Lock() + mmLookupIPAddr.LookupIPAddrMock.callArgs = append(mmLookupIPAddr.LookupIPAddrMock.callArgs, mm_params) + mmLookupIPAddr.LookupIPAddrMock.mutex.Unlock() + + for _, e := range mmLookupIPAddr.LookupIPAddrMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.ia1, e.results.err } } - if m.LookupIPAddrMock.defaultExpectation != nil { - atomic.AddUint64(&m.LookupIPAddrMock.defaultExpectation.Counter, 1) - want := m.LookupIPAddrMock.defaultExpectation.params - got := ResolverInterfaceMockLookupIPAddrParams{ctx, host} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("ResolverInterfaceMock.LookupIPAddr got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmLookupIPAddr.LookupIPAddrMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmLookupIPAddr.LookupIPAddrMock.defaultExpectation.Counter, 1) + mm_want := mmLookupIPAddr.LookupIPAddrMock.defaultExpectation.params + mm_got := ResolverInterfaceMockLookupIPAddrParams{ctx, host} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmLookupIPAddr.t.Errorf("ResolverInterfaceMock.LookupIPAddr got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.LookupIPAddrMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the ResolverInterfaceMock.LookupIPAddr") + mm_results := mmLookupIPAddr.LookupIPAddrMock.defaultExpectation.results + if mm_results == nil { + mmLookupIPAddr.t.Fatal("No results are set for the ResolverInterfaceMock.LookupIPAddr") } - return (*results).ia1, (*results).err + return (*mm_results).ia1, (*mm_results).err } - if m.funcLookupIPAddr != nil { - return m.funcLookupIPAddr(ctx, host) + if mmLookupIPAddr.funcLookupIPAddr != nil { + return mmLookupIPAddr.funcLookupIPAddr(ctx, host) } - m.t.Fatalf("Unexpected call to ResolverInterfaceMock.LookupIPAddr. %v %v", ctx, host) + mmLookupIPAddr.t.Fatalf("Unexpected call to ResolverInterfaceMock.LookupIPAddr. %v %v", ctx, host) return } // LookupIPAddrAfterCounter returns a count of finished ResolverInterfaceMock.LookupIPAddr invocations -func (m *ResolverInterfaceMock) LookupIPAddrAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterLookupIPAddrCounter) +func (mmLookupIPAddr *ResolverInterfaceMock) LookupIPAddrAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmLookupIPAddr.afterLookupIPAddrCounter) } // LookupIPAddrBeforeCounter returns a count of ResolverInterfaceMock.LookupIPAddr invocations -func (m *ResolverInterfaceMock) LookupIPAddrBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeLookupIPAddrCounter) +func (mmLookupIPAddr *ResolverInterfaceMock) LookupIPAddrBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmLookupIPAddr.beforeLookupIPAddrCounter) +} + +// Calls returns a list of arguments used in each call to ResolverInterfaceMock.LookupIPAddr. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmLookupIPAddr *mResolverInterfaceMockLookupIPAddr) Calls() []*ResolverInterfaceMockLookupIPAddrParams { + mmLookupIPAddr.mutex.RLock() + + argCopy := make([]*ResolverInterfaceMockLookupIPAddrParams, len(mmLookupIPAddr.callArgs)) + copy(argCopy, mmLookupIPAddr.callArgs) + + mmLookupIPAddr.mutex.RUnlock() + + return argCopy } // MinimockLookupIPAddrDone returns true if the count of the LookupIPAddr invocations corresponds // the number of defined expectations func (m *ResolverInterfaceMock) MinimockLookupIPAddrDone() bool { for _, e := range m.LookupIPAddrMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.LookupIPAddrMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterLookupIPAddrCounter) < 1 { + if m.LookupIPAddrMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterLookupIPAddrCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcLookupIPAddr != nil && atomic.LoadUint64(&m.afterLookupIPAddrCounter) < 1 { + if m.funcLookupIPAddr != nil && mm_atomic.LoadUint64(&m.afterLookupIPAddrCounter) < 1 { return false } return true @@ -197,17 +236,21 @@ func (m *ResolverInterfaceMock) MinimockLookupIPAddrDone() bool { // MinimockLookupIPAddrInspect logs each unmet expectation func (m *ResolverInterfaceMock) MinimockLookupIPAddrInspect() { for _, e := range m.LookupIPAddrMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to ResolverInterfaceMock.LookupIPAddr with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.LookupIPAddrMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterLookupIPAddrCounter) < 1 { - m.t.Errorf("Expected call to ResolverInterfaceMock.LookupIPAddr with params: %#v", *m.LookupIPAddrMock.defaultExpectation.params) + if m.LookupIPAddrMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterLookupIPAddrCounter) < 1 { + if m.LookupIPAddrMock.defaultExpectation.params == nil { + m.t.Error("Expected call to ResolverInterfaceMock.LookupIPAddr") + } else { + m.t.Errorf("Expected call to ResolverInterfaceMock.LookupIPAddr with params: %#v", *m.LookupIPAddrMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcLookupIPAddr != nil && atomic.LoadUint64(&m.afterLookupIPAddrCounter) < 1 { + if m.funcLookupIPAddr != nil && mm_atomic.LoadUint64(&m.afterLookupIPAddrCounter) < 1 { m.t.Error("Expected call to ResolverInterfaceMock.LookupIPAddr") } } @@ -221,8 +264,8 @@ func (m *ResolverInterfaceMock) MinimockFinish() { } // MinimockWait waits for all mocked methods to be called the expected number of times -func (m *ResolverInterfaceMock) MinimockWait(timeout time.Duration) { - timeoutCh := time.After(timeout) +func (m *ResolverInterfaceMock) MinimockWait(timeout mm_time.Duration) { + timeoutCh := mm_time.After(timeout) for { if m.minimockDone() { return @@ -231,7 +274,7 @@ func (m *ResolverInterfaceMock) MinimockWait(timeout time.Duration) { case <-timeoutCh: m.MinimockFinish() return - case <-time.After(10 * time.Millisecond): + case <-mm_time.After(10 * mm_time.Millisecond): } } } diff --git a/internal/domain_checker/domain_checker_mock_test.go b/internal/domain_checker/domain_checker_mock_test.go index da35a44c..c05d5b76 100644 --- a/internal/domain_checker/domain_checker_mock_test.go +++ b/internal/domain_checker/domain_checker_mock_test.go @@ -1,15 +1,14 @@ package domain_checker -// DO NOT EDIT! -// The code below was generated with http://github.com/gojuno/minimock (dev) +// Code generated by http://github.com/gojuno/minimock (3.0.6). DO NOT EDIT. //go:generate minimock -i github.com/rekby/lets-proxy2/internal/domain_checker.DomainChecker -o ./domain_checker_mock_test.go import ( - "sync/atomic" - "time" - "context" + "sync" + mm_atomic "sync/atomic" + mm_time "time" "github.com/gojuno/minimock/v3" ) @@ -19,6 +18,7 @@ type DomainCheckerMock struct { t minimock.Tester funcIsDomainAllowed func(ctx context.Context, domain string) (b1 bool, err error) + inspectFuncIsDomainAllowed func(ctx context.Context, domain string) afterIsDomainAllowedCounter uint64 beforeIsDomainAllowedCounter uint64 IsDomainAllowedMock mDomainCheckerMockIsDomainAllowed @@ -30,7 +30,9 @@ func NewDomainCheckerMock(t minimock.Tester) *DomainCheckerMock { if controller, ok := t.(minimock.MockController); ok { controller.RegisterMocker(m) } + m.IsDomainAllowedMock = mDomainCheckerMockIsDomainAllowed{mock: m} + m.IsDomainAllowedMock.callArgs = []*DomainCheckerMockIsDomainAllowedParams{} return m } @@ -39,6 +41,9 @@ type mDomainCheckerMockIsDomainAllowed struct { mock *DomainCheckerMock defaultExpectation *DomainCheckerMockIsDomainAllowedExpectation expectations []*DomainCheckerMockIsDomainAllowedExpectation + + callArgs []*DomainCheckerMockIsDomainAllowedParams + mutex sync.RWMutex } // DomainCheckerMockIsDomainAllowedExpectation specifies expectation struct of the DomainChecker.IsDomainAllowed @@ -62,64 +67,75 @@ type DomainCheckerMockIsDomainAllowedResults struct { } // Expect sets up expected params for DomainChecker.IsDomainAllowed -func (m *mDomainCheckerMockIsDomainAllowed) Expect(ctx context.Context, domain string) *mDomainCheckerMockIsDomainAllowed { - if m.mock.funcIsDomainAllowed != nil { - m.mock.t.Fatalf("DomainCheckerMock.IsDomainAllowed mock is already set by Set") +func (mmIsDomainAllowed *mDomainCheckerMockIsDomainAllowed) Expect(ctx context.Context, domain string) *mDomainCheckerMockIsDomainAllowed { + if mmIsDomainAllowed.mock.funcIsDomainAllowed != nil { + mmIsDomainAllowed.mock.t.Fatalf("DomainCheckerMock.IsDomainAllowed mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &DomainCheckerMockIsDomainAllowedExpectation{} + if mmIsDomainAllowed.defaultExpectation == nil { + mmIsDomainAllowed.defaultExpectation = &DomainCheckerMockIsDomainAllowedExpectation{} } - m.defaultExpectation.params = &DomainCheckerMockIsDomainAllowedParams{ctx, domain} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmIsDomainAllowed.defaultExpectation.params = &DomainCheckerMockIsDomainAllowedParams{ctx, domain} + for _, e := range mmIsDomainAllowed.expectations { + if minimock.Equal(e.params, mmIsDomainAllowed.defaultExpectation.params) { + mmIsDomainAllowed.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmIsDomainAllowed.defaultExpectation.params) } } - return m + return mmIsDomainAllowed +} + +// Inspect accepts an inspector function that has same arguments as the DomainChecker.IsDomainAllowed +func (mmIsDomainAllowed *mDomainCheckerMockIsDomainAllowed) Inspect(f func(ctx context.Context, domain string)) *mDomainCheckerMockIsDomainAllowed { + if mmIsDomainAllowed.mock.inspectFuncIsDomainAllowed != nil { + mmIsDomainAllowed.mock.t.Fatalf("Inspect function is already set for DomainCheckerMock.IsDomainAllowed") + } + + mmIsDomainAllowed.mock.inspectFuncIsDomainAllowed = f + + return mmIsDomainAllowed } // Return sets up results that will be returned by DomainChecker.IsDomainAllowed -func (m *mDomainCheckerMockIsDomainAllowed) Return(b1 bool, err error) *DomainCheckerMock { - if m.mock.funcIsDomainAllowed != nil { - m.mock.t.Fatalf("DomainCheckerMock.IsDomainAllowed mock is already set by Set") +func (mmIsDomainAllowed *mDomainCheckerMockIsDomainAllowed) Return(b1 bool, err error) *DomainCheckerMock { + if mmIsDomainAllowed.mock.funcIsDomainAllowed != nil { + mmIsDomainAllowed.mock.t.Fatalf("DomainCheckerMock.IsDomainAllowed mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &DomainCheckerMockIsDomainAllowedExpectation{mock: m.mock} + if mmIsDomainAllowed.defaultExpectation == nil { + mmIsDomainAllowed.defaultExpectation = &DomainCheckerMockIsDomainAllowedExpectation{mock: mmIsDomainAllowed.mock} } - m.defaultExpectation.results = &DomainCheckerMockIsDomainAllowedResults{b1, err} - return m.mock + mmIsDomainAllowed.defaultExpectation.results = &DomainCheckerMockIsDomainAllowedResults{b1, err} + return mmIsDomainAllowed.mock } //Set uses given function f to mock the DomainChecker.IsDomainAllowed method -func (m *mDomainCheckerMockIsDomainAllowed) Set(f func(ctx context.Context, domain string) (b1 bool, err error)) *DomainCheckerMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the DomainChecker.IsDomainAllowed method") +func (mmIsDomainAllowed *mDomainCheckerMockIsDomainAllowed) Set(f func(ctx context.Context, domain string) (b1 bool, err error)) *DomainCheckerMock { + if mmIsDomainAllowed.defaultExpectation != nil { + mmIsDomainAllowed.mock.t.Fatalf("Default expectation is already set for the DomainChecker.IsDomainAllowed method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the DomainChecker.IsDomainAllowed method") + if len(mmIsDomainAllowed.expectations) > 0 { + mmIsDomainAllowed.mock.t.Fatalf("Some expectations are already set for the DomainChecker.IsDomainAllowed method") } - m.mock.funcIsDomainAllowed = f - return m.mock + mmIsDomainAllowed.mock.funcIsDomainAllowed = f + return mmIsDomainAllowed.mock } // When sets expectation for the DomainChecker.IsDomainAllowed which will trigger the result defined by the following // Then helper -func (m *mDomainCheckerMockIsDomainAllowed) When(ctx context.Context, domain string) *DomainCheckerMockIsDomainAllowedExpectation { - if m.mock.funcIsDomainAllowed != nil { - m.mock.t.Fatalf("DomainCheckerMock.IsDomainAllowed mock is already set by Set") +func (mmIsDomainAllowed *mDomainCheckerMockIsDomainAllowed) When(ctx context.Context, domain string) *DomainCheckerMockIsDomainAllowedExpectation { + if mmIsDomainAllowed.mock.funcIsDomainAllowed != nil { + mmIsDomainAllowed.mock.t.Fatalf("DomainCheckerMock.IsDomainAllowed mock is already set by Set") } expectation := &DomainCheckerMockIsDomainAllowedExpectation{ - mock: m.mock, + mock: mmIsDomainAllowed.mock, params: &DomainCheckerMockIsDomainAllowedParams{ctx, domain}, } - m.expectations = append(m.expectations, expectation) + mmIsDomainAllowed.expectations = append(mmIsDomainAllowed.expectations, expectation) return expectation } @@ -130,63 +146,87 @@ func (e *DomainCheckerMockIsDomainAllowedExpectation) Then(b1 bool, err error) * } // IsDomainAllowed implements DomainChecker -func (m *DomainCheckerMock) IsDomainAllowed(ctx context.Context, domain string) (b1 bool, err error) { - atomic.AddUint64(&m.beforeIsDomainAllowedCounter, 1) - defer atomic.AddUint64(&m.afterIsDomainAllowedCounter, 1) +func (mmIsDomainAllowed *DomainCheckerMock) IsDomainAllowed(ctx context.Context, domain string) (b1 bool, err error) { + mm_atomic.AddUint64(&mmIsDomainAllowed.beforeIsDomainAllowedCounter, 1) + defer mm_atomic.AddUint64(&mmIsDomainAllowed.afterIsDomainAllowedCounter, 1) - for _, e := range m.IsDomainAllowedMock.expectations { - if minimock.Equal(*e.params, DomainCheckerMockIsDomainAllowedParams{ctx, domain}) { - atomic.AddUint64(&e.Counter, 1) + if mmIsDomainAllowed.inspectFuncIsDomainAllowed != nil { + mmIsDomainAllowed.inspectFuncIsDomainAllowed(ctx, domain) + } + + mm_params := &DomainCheckerMockIsDomainAllowedParams{ctx, domain} + + // Record call args + mmIsDomainAllowed.IsDomainAllowedMock.mutex.Lock() + mmIsDomainAllowed.IsDomainAllowedMock.callArgs = append(mmIsDomainAllowed.IsDomainAllowedMock.callArgs, mm_params) + mmIsDomainAllowed.IsDomainAllowedMock.mutex.Unlock() + + for _, e := range mmIsDomainAllowed.IsDomainAllowedMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.b1, e.results.err } } - if m.IsDomainAllowedMock.defaultExpectation != nil { - atomic.AddUint64(&m.IsDomainAllowedMock.defaultExpectation.Counter, 1) - want := m.IsDomainAllowedMock.defaultExpectation.params - got := DomainCheckerMockIsDomainAllowedParams{ctx, domain} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("DomainCheckerMock.IsDomainAllowed got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmIsDomainAllowed.IsDomainAllowedMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmIsDomainAllowed.IsDomainAllowedMock.defaultExpectation.Counter, 1) + mm_want := mmIsDomainAllowed.IsDomainAllowedMock.defaultExpectation.params + mm_got := DomainCheckerMockIsDomainAllowedParams{ctx, domain} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmIsDomainAllowed.t.Errorf("DomainCheckerMock.IsDomainAllowed got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.IsDomainAllowedMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the DomainCheckerMock.IsDomainAllowed") + mm_results := mmIsDomainAllowed.IsDomainAllowedMock.defaultExpectation.results + if mm_results == nil { + mmIsDomainAllowed.t.Fatal("No results are set for the DomainCheckerMock.IsDomainAllowed") } - return (*results).b1, (*results).err + return (*mm_results).b1, (*mm_results).err } - if m.funcIsDomainAllowed != nil { - return m.funcIsDomainAllowed(ctx, domain) + if mmIsDomainAllowed.funcIsDomainAllowed != nil { + return mmIsDomainAllowed.funcIsDomainAllowed(ctx, domain) } - m.t.Fatalf("Unexpected call to DomainCheckerMock.IsDomainAllowed. %v %v", ctx, domain) + mmIsDomainAllowed.t.Fatalf("Unexpected call to DomainCheckerMock.IsDomainAllowed. %v %v", ctx, domain) return } // IsDomainAllowedAfterCounter returns a count of finished DomainCheckerMock.IsDomainAllowed invocations -func (m *DomainCheckerMock) IsDomainAllowedAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterIsDomainAllowedCounter) +func (mmIsDomainAllowed *DomainCheckerMock) IsDomainAllowedAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmIsDomainAllowed.afterIsDomainAllowedCounter) } // IsDomainAllowedBeforeCounter returns a count of DomainCheckerMock.IsDomainAllowed invocations -func (m *DomainCheckerMock) IsDomainAllowedBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeIsDomainAllowedCounter) +func (mmIsDomainAllowed *DomainCheckerMock) IsDomainAllowedBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmIsDomainAllowed.beforeIsDomainAllowedCounter) +} + +// Calls returns a list of arguments used in each call to DomainCheckerMock.IsDomainAllowed. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmIsDomainAllowed *mDomainCheckerMockIsDomainAllowed) Calls() []*DomainCheckerMockIsDomainAllowedParams { + mmIsDomainAllowed.mutex.RLock() + + argCopy := make([]*DomainCheckerMockIsDomainAllowedParams, len(mmIsDomainAllowed.callArgs)) + copy(argCopy, mmIsDomainAllowed.callArgs) + + mmIsDomainAllowed.mutex.RUnlock() + + return argCopy } // MinimockIsDomainAllowedDone returns true if the count of the IsDomainAllowed invocations corresponds // the number of defined expectations func (m *DomainCheckerMock) MinimockIsDomainAllowedDone() bool { for _, e := range m.IsDomainAllowedMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.IsDomainAllowedMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterIsDomainAllowedCounter) < 1 { + if m.IsDomainAllowedMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterIsDomainAllowedCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcIsDomainAllowed != nil && atomic.LoadUint64(&m.afterIsDomainAllowedCounter) < 1 { + if m.funcIsDomainAllowed != nil && mm_atomic.LoadUint64(&m.afterIsDomainAllowedCounter) < 1 { return false } return true @@ -195,17 +235,21 @@ func (m *DomainCheckerMock) MinimockIsDomainAllowedDone() bool { // MinimockIsDomainAllowedInspect logs each unmet expectation func (m *DomainCheckerMock) MinimockIsDomainAllowedInspect() { for _, e := range m.IsDomainAllowedMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to DomainCheckerMock.IsDomainAllowed with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.IsDomainAllowedMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterIsDomainAllowedCounter) < 1 { - m.t.Errorf("Expected call to DomainCheckerMock.IsDomainAllowed with params: %#v", *m.IsDomainAllowedMock.defaultExpectation.params) + if m.IsDomainAllowedMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterIsDomainAllowedCounter) < 1 { + if m.IsDomainAllowedMock.defaultExpectation.params == nil { + m.t.Error("Expected call to DomainCheckerMock.IsDomainAllowed") + } else { + m.t.Errorf("Expected call to DomainCheckerMock.IsDomainAllowed with params: %#v", *m.IsDomainAllowedMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcIsDomainAllowed != nil && atomic.LoadUint64(&m.afterIsDomainAllowedCounter) < 1 { + if m.funcIsDomainAllowed != nil && mm_atomic.LoadUint64(&m.afterIsDomainAllowedCounter) < 1 { m.t.Error("Expected call to DomainCheckerMock.IsDomainAllowed") } } @@ -219,8 +263,8 @@ func (m *DomainCheckerMock) MinimockFinish() { } // MinimockWait waits for all mocked methods to be called the expected number of times -func (m *DomainCheckerMock) MinimockWait(timeout time.Duration) { - timeoutCh := time.After(timeout) +func (m *DomainCheckerMock) MinimockWait(timeout mm_time.Duration) { + timeoutCh := mm_time.After(timeout) for { if m.minimockDone() { return @@ -229,7 +273,7 @@ func (m *DomainCheckerMock) MinimockWait(timeout time.Duration) { case <-timeoutCh: m.MinimockFinish() return - case <-time.After(10 * time.Millisecond): + case <-mm_time.After(10 * mm_time.Millisecond): } } } diff --git a/internal/domain_checker/resolver_mock_test.go b/internal/domain_checker/resolver_mock_test.go index 36475fe1..9ad2ab04 100644 --- a/internal/domain_checker/resolver_mock_test.go +++ b/internal/domain_checker/resolver_mock_test.go @@ -1,17 +1,15 @@ package domain_checker -// DO NOT EDIT! -// The code below was generated with http://github.com/gojuno/minimock (dev) +// Code generated by http://github.com/gojuno/minimock (3.0.6). DO NOT EDIT. //go:generate minimock -i github.com/rekby/lets-proxy2/internal/domain_checker.Resolver -o ./resolver_mock_test.go import ( - "sync/atomic" - "time" - "context" - "net" + "sync" + mm_atomic "sync/atomic" + mm_time "time" "github.com/gojuno/minimock/v3" ) @@ -21,6 +19,7 @@ type ResolverMock struct { t minimock.Tester funcLookupIPAddr func(ctx context.Context, host string) (ia1 []net.IPAddr, err error) + inspectFuncLookupIPAddr func(ctx context.Context, host string) afterLookupIPAddrCounter uint64 beforeLookupIPAddrCounter uint64 LookupIPAddrMock mResolverMockLookupIPAddr @@ -32,7 +31,9 @@ func NewResolverMock(t minimock.Tester) *ResolverMock { if controller, ok := t.(minimock.MockController); ok { controller.RegisterMocker(m) } + m.LookupIPAddrMock = mResolverMockLookupIPAddr{mock: m} + m.LookupIPAddrMock.callArgs = []*ResolverMockLookupIPAddrParams{} return m } @@ -41,6 +42,9 @@ type mResolverMockLookupIPAddr struct { mock *ResolverMock defaultExpectation *ResolverMockLookupIPAddrExpectation expectations []*ResolverMockLookupIPAddrExpectation + + callArgs []*ResolverMockLookupIPAddrParams + mutex sync.RWMutex } // ResolverMockLookupIPAddrExpectation specifies expectation struct of the Resolver.LookupIPAddr @@ -64,64 +68,75 @@ type ResolverMockLookupIPAddrResults struct { } // Expect sets up expected params for Resolver.LookupIPAddr -func (m *mResolverMockLookupIPAddr) Expect(ctx context.Context, host string) *mResolverMockLookupIPAddr { - if m.mock.funcLookupIPAddr != nil { - m.mock.t.Fatalf("ResolverMock.LookupIPAddr mock is already set by Set") +func (mmLookupIPAddr *mResolverMockLookupIPAddr) Expect(ctx context.Context, host string) *mResolverMockLookupIPAddr { + if mmLookupIPAddr.mock.funcLookupIPAddr != nil { + mmLookupIPAddr.mock.t.Fatalf("ResolverMock.LookupIPAddr mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ResolverMockLookupIPAddrExpectation{} + if mmLookupIPAddr.defaultExpectation == nil { + mmLookupIPAddr.defaultExpectation = &ResolverMockLookupIPAddrExpectation{} } - m.defaultExpectation.params = &ResolverMockLookupIPAddrParams{ctx, host} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmLookupIPAddr.defaultExpectation.params = &ResolverMockLookupIPAddrParams{ctx, host} + for _, e := range mmLookupIPAddr.expectations { + if minimock.Equal(e.params, mmLookupIPAddr.defaultExpectation.params) { + mmLookupIPAddr.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmLookupIPAddr.defaultExpectation.params) } } - return m + return mmLookupIPAddr +} + +// Inspect accepts an inspector function that has same arguments as the Resolver.LookupIPAddr +func (mmLookupIPAddr *mResolverMockLookupIPAddr) Inspect(f func(ctx context.Context, host string)) *mResolverMockLookupIPAddr { + if mmLookupIPAddr.mock.inspectFuncLookupIPAddr != nil { + mmLookupIPAddr.mock.t.Fatalf("Inspect function is already set for ResolverMock.LookupIPAddr") + } + + mmLookupIPAddr.mock.inspectFuncLookupIPAddr = f + + return mmLookupIPAddr } // Return sets up results that will be returned by Resolver.LookupIPAddr -func (m *mResolverMockLookupIPAddr) Return(ia1 []net.IPAddr, err error) *ResolverMock { - if m.mock.funcLookupIPAddr != nil { - m.mock.t.Fatalf("ResolverMock.LookupIPAddr mock is already set by Set") +func (mmLookupIPAddr *mResolverMockLookupIPAddr) Return(ia1 []net.IPAddr, err error) *ResolverMock { + if mmLookupIPAddr.mock.funcLookupIPAddr != nil { + mmLookupIPAddr.mock.t.Fatalf("ResolverMock.LookupIPAddr mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ResolverMockLookupIPAddrExpectation{mock: m.mock} + if mmLookupIPAddr.defaultExpectation == nil { + mmLookupIPAddr.defaultExpectation = &ResolverMockLookupIPAddrExpectation{mock: mmLookupIPAddr.mock} } - m.defaultExpectation.results = &ResolverMockLookupIPAddrResults{ia1, err} - return m.mock + mmLookupIPAddr.defaultExpectation.results = &ResolverMockLookupIPAddrResults{ia1, err} + return mmLookupIPAddr.mock } //Set uses given function f to mock the Resolver.LookupIPAddr method -func (m *mResolverMockLookupIPAddr) Set(f func(ctx context.Context, host string) (ia1 []net.IPAddr, err error)) *ResolverMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Resolver.LookupIPAddr method") +func (mmLookupIPAddr *mResolverMockLookupIPAddr) Set(f func(ctx context.Context, host string) (ia1 []net.IPAddr, err error)) *ResolverMock { + if mmLookupIPAddr.defaultExpectation != nil { + mmLookupIPAddr.mock.t.Fatalf("Default expectation is already set for the Resolver.LookupIPAddr method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Resolver.LookupIPAddr method") + if len(mmLookupIPAddr.expectations) > 0 { + mmLookupIPAddr.mock.t.Fatalf("Some expectations are already set for the Resolver.LookupIPAddr method") } - m.mock.funcLookupIPAddr = f - return m.mock + mmLookupIPAddr.mock.funcLookupIPAddr = f + return mmLookupIPAddr.mock } // When sets expectation for the Resolver.LookupIPAddr which will trigger the result defined by the following // Then helper -func (m *mResolverMockLookupIPAddr) When(ctx context.Context, host string) *ResolverMockLookupIPAddrExpectation { - if m.mock.funcLookupIPAddr != nil { - m.mock.t.Fatalf("ResolverMock.LookupIPAddr mock is already set by Set") +func (mmLookupIPAddr *mResolverMockLookupIPAddr) When(ctx context.Context, host string) *ResolverMockLookupIPAddrExpectation { + if mmLookupIPAddr.mock.funcLookupIPAddr != nil { + mmLookupIPAddr.mock.t.Fatalf("ResolverMock.LookupIPAddr mock is already set by Set") } expectation := &ResolverMockLookupIPAddrExpectation{ - mock: m.mock, + mock: mmLookupIPAddr.mock, params: &ResolverMockLookupIPAddrParams{ctx, host}, } - m.expectations = append(m.expectations, expectation) + mmLookupIPAddr.expectations = append(mmLookupIPAddr.expectations, expectation) return expectation } @@ -132,63 +147,87 @@ func (e *ResolverMockLookupIPAddrExpectation) Then(ia1 []net.IPAddr, err error) } // LookupIPAddr implements Resolver -func (m *ResolverMock) LookupIPAddr(ctx context.Context, host string) (ia1 []net.IPAddr, err error) { - atomic.AddUint64(&m.beforeLookupIPAddrCounter, 1) - defer atomic.AddUint64(&m.afterLookupIPAddrCounter, 1) +func (mmLookupIPAddr *ResolverMock) LookupIPAddr(ctx context.Context, host string) (ia1 []net.IPAddr, err error) { + mm_atomic.AddUint64(&mmLookupIPAddr.beforeLookupIPAddrCounter, 1) + defer mm_atomic.AddUint64(&mmLookupIPAddr.afterLookupIPAddrCounter, 1) - for _, e := range m.LookupIPAddrMock.expectations { - if minimock.Equal(*e.params, ResolverMockLookupIPAddrParams{ctx, host}) { - atomic.AddUint64(&e.Counter, 1) + if mmLookupIPAddr.inspectFuncLookupIPAddr != nil { + mmLookupIPAddr.inspectFuncLookupIPAddr(ctx, host) + } + + mm_params := &ResolverMockLookupIPAddrParams{ctx, host} + + // Record call args + mmLookupIPAddr.LookupIPAddrMock.mutex.Lock() + mmLookupIPAddr.LookupIPAddrMock.callArgs = append(mmLookupIPAddr.LookupIPAddrMock.callArgs, mm_params) + mmLookupIPAddr.LookupIPAddrMock.mutex.Unlock() + + for _, e := range mmLookupIPAddr.LookupIPAddrMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.ia1, e.results.err } } - if m.LookupIPAddrMock.defaultExpectation != nil { - atomic.AddUint64(&m.LookupIPAddrMock.defaultExpectation.Counter, 1) - want := m.LookupIPAddrMock.defaultExpectation.params - got := ResolverMockLookupIPAddrParams{ctx, host} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("ResolverMock.LookupIPAddr got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmLookupIPAddr.LookupIPAddrMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmLookupIPAddr.LookupIPAddrMock.defaultExpectation.Counter, 1) + mm_want := mmLookupIPAddr.LookupIPAddrMock.defaultExpectation.params + mm_got := ResolverMockLookupIPAddrParams{ctx, host} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmLookupIPAddr.t.Errorf("ResolverMock.LookupIPAddr got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.LookupIPAddrMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the ResolverMock.LookupIPAddr") + mm_results := mmLookupIPAddr.LookupIPAddrMock.defaultExpectation.results + if mm_results == nil { + mmLookupIPAddr.t.Fatal("No results are set for the ResolverMock.LookupIPAddr") } - return (*results).ia1, (*results).err + return (*mm_results).ia1, (*mm_results).err } - if m.funcLookupIPAddr != nil { - return m.funcLookupIPAddr(ctx, host) + if mmLookupIPAddr.funcLookupIPAddr != nil { + return mmLookupIPAddr.funcLookupIPAddr(ctx, host) } - m.t.Fatalf("Unexpected call to ResolverMock.LookupIPAddr. %v %v", ctx, host) + mmLookupIPAddr.t.Fatalf("Unexpected call to ResolverMock.LookupIPAddr. %v %v", ctx, host) return } // LookupIPAddrAfterCounter returns a count of finished ResolverMock.LookupIPAddr invocations -func (m *ResolverMock) LookupIPAddrAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterLookupIPAddrCounter) +func (mmLookupIPAddr *ResolverMock) LookupIPAddrAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmLookupIPAddr.afterLookupIPAddrCounter) } // LookupIPAddrBeforeCounter returns a count of ResolverMock.LookupIPAddr invocations -func (m *ResolverMock) LookupIPAddrBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeLookupIPAddrCounter) +func (mmLookupIPAddr *ResolverMock) LookupIPAddrBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmLookupIPAddr.beforeLookupIPAddrCounter) +} + +// Calls returns a list of arguments used in each call to ResolverMock.LookupIPAddr. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmLookupIPAddr *mResolverMockLookupIPAddr) Calls() []*ResolverMockLookupIPAddrParams { + mmLookupIPAddr.mutex.RLock() + + argCopy := make([]*ResolverMockLookupIPAddrParams, len(mmLookupIPAddr.callArgs)) + copy(argCopy, mmLookupIPAddr.callArgs) + + mmLookupIPAddr.mutex.RUnlock() + + return argCopy } // MinimockLookupIPAddrDone returns true if the count of the LookupIPAddr invocations corresponds // the number of defined expectations func (m *ResolverMock) MinimockLookupIPAddrDone() bool { for _, e := range m.LookupIPAddrMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.LookupIPAddrMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterLookupIPAddrCounter) < 1 { + if m.LookupIPAddrMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterLookupIPAddrCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcLookupIPAddr != nil && atomic.LoadUint64(&m.afterLookupIPAddrCounter) < 1 { + if m.funcLookupIPAddr != nil && mm_atomic.LoadUint64(&m.afterLookupIPAddrCounter) < 1 { return false } return true @@ -197,17 +236,21 @@ func (m *ResolverMock) MinimockLookupIPAddrDone() bool { // MinimockLookupIPAddrInspect logs each unmet expectation func (m *ResolverMock) MinimockLookupIPAddrInspect() { for _, e := range m.LookupIPAddrMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to ResolverMock.LookupIPAddr with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.LookupIPAddrMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterLookupIPAddrCounter) < 1 { - m.t.Errorf("Expected call to ResolverMock.LookupIPAddr with params: %#v", *m.LookupIPAddrMock.defaultExpectation.params) + if m.LookupIPAddrMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterLookupIPAddrCounter) < 1 { + if m.LookupIPAddrMock.defaultExpectation.params == nil { + m.t.Error("Expected call to ResolverMock.LookupIPAddr") + } else { + m.t.Errorf("Expected call to ResolverMock.LookupIPAddr with params: %#v", *m.LookupIPAddrMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcLookupIPAddr != nil && atomic.LoadUint64(&m.afterLookupIPAddrCounter) < 1 { + if m.funcLookupIPAddr != nil && mm_atomic.LoadUint64(&m.afterLookupIPAddrCounter) < 1 { m.t.Error("Expected call to ResolverMock.LookupIPAddr") } } @@ -221,8 +264,8 @@ func (m *ResolverMock) MinimockFinish() { } // MinimockWait waits for all mocked methods to be called the expected number of times -func (m *ResolverMock) MinimockWait(timeout time.Duration) { - timeoutCh := time.After(timeout) +func (m *ResolverMock) MinimockWait(timeout mm_time.Duration) { + timeoutCh := mm_time.After(timeout) for { if m.minimockDone() { return @@ -231,7 +274,7 @@ func (m *ResolverMock) MinimockWait(timeout time.Duration) { case <-timeoutCh: m.MinimockFinish() return - case <-time.After(10 * time.Millisecond): + case <-mm_time.After(10 * mm_time.Millisecond): } } } diff --git a/internal/proxy/director_mock_test.go b/internal/proxy/director_mock_test.go index 83edf2f6..95910533 100644 --- a/internal/proxy/director_mock_test.go +++ b/internal/proxy/director_mock_test.go @@ -1,15 +1,14 @@ package proxy -// DO NOT EDIT! -// The code below was generated with http://github.com/gojuno/minimock (dev) +// Code generated by http://github.com/gojuno/minimock (3.0.6). DO NOT EDIT. //go:generate minimock -i github.com/rekby/lets-proxy2/internal/proxy.Director -o ./director_mock_test.go import ( - "sync/atomic" - "time" - "net/http" + "sync" + mm_atomic "sync/atomic" + mm_time "time" "github.com/gojuno/minimock/v3" ) @@ -19,6 +18,7 @@ type DirectorMock struct { t minimock.Tester funcDirector func(request *http.Request) + inspectFuncDirector func(request *http.Request) afterDirectorCounter uint64 beforeDirectorCounter uint64 DirectorMock mDirectorMockDirector @@ -30,7 +30,9 @@ func NewDirectorMock(t minimock.Tester) *DirectorMock { if controller, ok := t.(minimock.MockController); ok { controller.RegisterMocker(m) } + m.DirectorMock = mDirectorMockDirector{mock: m} + m.DirectorMock.callArgs = []*DirectorMockDirectorParams{} return m } @@ -39,6 +41,9 @@ type mDirectorMockDirector struct { mock *DirectorMock defaultExpectation *DirectorMockDirectorExpectation expectations []*DirectorMockDirectorExpectation + + callArgs []*DirectorMockDirectorParams + mutex sync.RWMutex } // DirectorMockDirectorExpectation specifies expectation struct of the Director.Director @@ -55,108 +60,143 @@ type DirectorMockDirectorParams struct { } // Expect sets up expected params for Director.Director -func (m *mDirectorMockDirector) Expect(request *http.Request) *mDirectorMockDirector { - if m.mock.funcDirector != nil { - m.mock.t.Fatalf("DirectorMock.Director mock is already set by Set") +func (mmDirector *mDirectorMockDirector) Expect(request *http.Request) *mDirectorMockDirector { + if mmDirector.mock.funcDirector != nil { + mmDirector.mock.t.Fatalf("DirectorMock.Director mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &DirectorMockDirectorExpectation{} + if mmDirector.defaultExpectation == nil { + mmDirector.defaultExpectation = &DirectorMockDirectorExpectation{} } - m.defaultExpectation.params = &DirectorMockDirectorParams{request} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmDirector.defaultExpectation.params = &DirectorMockDirectorParams{request} + for _, e := range mmDirector.expectations { + if minimock.Equal(e.params, mmDirector.defaultExpectation.params) { + mmDirector.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmDirector.defaultExpectation.params) } } - return m + return mmDirector +} + +// Inspect accepts an inspector function that has same arguments as the Director.Director +func (mmDirector *mDirectorMockDirector) Inspect(f func(request *http.Request)) *mDirectorMockDirector { + if mmDirector.mock.inspectFuncDirector != nil { + mmDirector.mock.t.Fatalf("Inspect function is already set for DirectorMock.Director") + } + + mmDirector.mock.inspectFuncDirector = f + + return mmDirector } // Return sets up results that will be returned by Director.Director -func (m *mDirectorMockDirector) Return() *DirectorMock { - if m.mock.funcDirector != nil { - m.mock.t.Fatalf("DirectorMock.Director mock is already set by Set") +func (mmDirector *mDirectorMockDirector) Return() *DirectorMock { + if mmDirector.mock.funcDirector != nil { + mmDirector.mock.t.Fatalf("DirectorMock.Director mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &DirectorMockDirectorExpectation{mock: m.mock} + if mmDirector.defaultExpectation == nil { + mmDirector.defaultExpectation = &DirectorMockDirectorExpectation{mock: mmDirector.mock} } - return m.mock + return mmDirector.mock } //Set uses given function f to mock the Director.Director method -func (m *mDirectorMockDirector) Set(f func(request *http.Request)) *DirectorMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Director.Director method") +func (mmDirector *mDirectorMockDirector) Set(f func(request *http.Request)) *DirectorMock { + if mmDirector.defaultExpectation != nil { + mmDirector.mock.t.Fatalf("Default expectation is already set for the Director.Director method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Director.Director method") + if len(mmDirector.expectations) > 0 { + mmDirector.mock.t.Fatalf("Some expectations are already set for the Director.Director method") } - m.mock.funcDirector = f - return m.mock + mmDirector.mock.funcDirector = f + return mmDirector.mock } // Director implements Director -func (m *DirectorMock) Director(request *http.Request) { - atomic.AddUint64(&m.beforeDirectorCounter, 1) - defer atomic.AddUint64(&m.afterDirectorCounter, 1) +func (mmDirector *DirectorMock) Director(request *http.Request) { + mm_atomic.AddUint64(&mmDirector.beforeDirectorCounter, 1) + defer mm_atomic.AddUint64(&mmDirector.afterDirectorCounter, 1) - for _, e := range m.DirectorMock.expectations { - if minimock.Equal(*e.params, DirectorMockDirectorParams{request}) { - atomic.AddUint64(&e.Counter, 1) + if mmDirector.inspectFuncDirector != nil { + mmDirector.inspectFuncDirector(request) + } + + mm_params := &DirectorMockDirectorParams{request} + + // Record call args + mmDirector.DirectorMock.mutex.Lock() + mmDirector.DirectorMock.callArgs = append(mmDirector.DirectorMock.callArgs, mm_params) + mmDirector.DirectorMock.mutex.Unlock() + + for _, e := range mmDirector.DirectorMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return } } - if m.DirectorMock.defaultExpectation != nil { - atomic.AddUint64(&m.DirectorMock.defaultExpectation.Counter, 1) - want := m.DirectorMock.defaultExpectation.params - got := DirectorMockDirectorParams{request} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("DirectorMock.Director got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmDirector.DirectorMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmDirector.DirectorMock.defaultExpectation.Counter, 1) + mm_want := mmDirector.DirectorMock.defaultExpectation.params + mm_got := DirectorMockDirectorParams{request} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmDirector.t.Errorf("DirectorMock.Director got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } return } - if m.funcDirector != nil { - m.funcDirector(request) + if mmDirector.funcDirector != nil { + mmDirector.funcDirector(request) return } - m.t.Fatalf("Unexpected call to DirectorMock.Director. %v", request) + mmDirector.t.Fatalf("Unexpected call to DirectorMock.Director. %v", request) } // DirectorAfterCounter returns a count of finished DirectorMock.Director invocations -func (m *DirectorMock) DirectorAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterDirectorCounter) +func (mmDirector *DirectorMock) DirectorAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmDirector.afterDirectorCounter) } // DirectorBeforeCounter returns a count of DirectorMock.Director invocations -func (m *DirectorMock) DirectorBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeDirectorCounter) +func (mmDirector *DirectorMock) DirectorBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmDirector.beforeDirectorCounter) +} + +// Calls returns a list of arguments used in each call to DirectorMock.Director. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmDirector *mDirectorMockDirector) Calls() []*DirectorMockDirectorParams { + mmDirector.mutex.RLock() + + argCopy := make([]*DirectorMockDirectorParams, len(mmDirector.callArgs)) + copy(argCopy, mmDirector.callArgs) + + mmDirector.mutex.RUnlock() + + return argCopy } // MinimockDirectorDone returns true if the count of the Director invocations corresponds // the number of defined expectations func (m *DirectorMock) MinimockDirectorDone() bool { for _, e := range m.DirectorMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.DirectorMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterDirectorCounter) < 1 { + if m.DirectorMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterDirectorCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcDirector != nil && atomic.LoadUint64(&m.afterDirectorCounter) < 1 { + if m.funcDirector != nil && mm_atomic.LoadUint64(&m.afterDirectorCounter) < 1 { return false } return true @@ -165,17 +205,21 @@ func (m *DirectorMock) MinimockDirectorDone() bool { // MinimockDirectorInspect logs each unmet expectation func (m *DirectorMock) MinimockDirectorInspect() { for _, e := range m.DirectorMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to DirectorMock.Director with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.DirectorMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterDirectorCounter) < 1 { - m.t.Errorf("Expected call to DirectorMock.Director with params: %#v", *m.DirectorMock.defaultExpectation.params) + if m.DirectorMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterDirectorCounter) < 1 { + if m.DirectorMock.defaultExpectation.params == nil { + m.t.Error("Expected call to DirectorMock.Director") + } else { + m.t.Errorf("Expected call to DirectorMock.Director with params: %#v", *m.DirectorMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcDirector != nil && atomic.LoadUint64(&m.afterDirectorCounter) < 1 { + if m.funcDirector != nil && mm_atomic.LoadUint64(&m.afterDirectorCounter) < 1 { m.t.Error("Expected call to DirectorMock.Director") } } @@ -189,8 +233,8 @@ func (m *DirectorMock) MinimockFinish() { } // MinimockWait waits for all mocked methods to be called the expected number of times -func (m *DirectorMock) MinimockWait(timeout time.Duration) { - timeoutCh := time.After(timeout) +func (m *DirectorMock) MinimockWait(timeout mm_time.Duration) { + timeoutCh := mm_time.After(timeout) for { if m.minimockDone() { return @@ -199,7 +243,7 @@ func (m *DirectorMock) MinimockWait(timeout time.Duration) { case <-timeoutCh: m.MinimockFinish() return - case <-time.After(10 * time.Millisecond): + case <-mm_time.After(10 * mm_time.Millisecond): } } } diff --git a/internal/proxy/http_proxy_test_mock_test.go b/internal/proxy/http_proxy_test_mock_test.go index b25e222a..a589b655 100644 --- a/internal/proxy/http_proxy_test_mock_test.go +++ b/internal/proxy/http_proxy_test_mock_test.go @@ -1,17 +1,15 @@ package proxy -// DO NOT EDIT! -// The code below was generated with http://github.com/gojuno/minimock (dev) +// Code generated by http://github.com/gojuno/minimock (3.0.6). DO NOT EDIT. //go:generate minimock -i github.com/rekby/lets-proxy2/internal/proxy.HTTPProxyTest -o ./http_proxy_test_mock_test.go import ( - "sync/atomic" - "time" - "context" - "net/http" + "sync" + mm_atomic "sync/atomic" + mm_time "time" "github.com/gojuno/minimock/v3" ) @@ -21,11 +19,13 @@ type HTTPProxyTestMock struct { t minimock.Tester funcGetContext func(req *http.Request) (c1 context.Context, err error) + inspectFuncGetContext func(req *http.Request) afterGetContextCounter uint64 beforeGetContextCounter uint64 GetContextMock mHTTPProxyTestMockGetContext funcHandleHTTPValidation func(w http.ResponseWriter, r *http.Request) (b1 bool) + inspectFuncHandleHTTPValidation func(w http.ResponseWriter, r *http.Request) afterHandleHTTPValidationCounter uint64 beforeHandleHTTPValidationCounter uint64 HandleHTTPValidationMock mHTTPProxyTestMockHandleHTTPValidation @@ -37,8 +37,12 @@ func NewHTTPProxyTestMock(t minimock.Tester) *HTTPProxyTestMock { if controller, ok := t.(minimock.MockController); ok { controller.RegisterMocker(m) } + m.GetContextMock = mHTTPProxyTestMockGetContext{mock: m} + m.GetContextMock.callArgs = []*HTTPProxyTestMockGetContextParams{} + m.HandleHTTPValidationMock = mHTTPProxyTestMockHandleHTTPValidation{mock: m} + m.HandleHTTPValidationMock.callArgs = []*HTTPProxyTestMockHandleHTTPValidationParams{} return m } @@ -47,6 +51,9 @@ type mHTTPProxyTestMockGetContext struct { mock *HTTPProxyTestMock defaultExpectation *HTTPProxyTestMockGetContextExpectation expectations []*HTTPProxyTestMockGetContextExpectation + + callArgs []*HTTPProxyTestMockGetContextParams + mutex sync.RWMutex } // HTTPProxyTestMockGetContextExpectation specifies expectation struct of the HTTPProxyTest.GetContext @@ -69,64 +76,75 @@ type HTTPProxyTestMockGetContextResults struct { } // Expect sets up expected params for HTTPProxyTest.GetContext -func (m *mHTTPProxyTestMockGetContext) Expect(req *http.Request) *mHTTPProxyTestMockGetContext { - if m.mock.funcGetContext != nil { - m.mock.t.Fatalf("HTTPProxyTestMock.GetContext mock is already set by Set") +func (mmGetContext *mHTTPProxyTestMockGetContext) Expect(req *http.Request) *mHTTPProxyTestMockGetContext { + if mmGetContext.mock.funcGetContext != nil { + mmGetContext.mock.t.Fatalf("HTTPProxyTestMock.GetContext mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &HTTPProxyTestMockGetContextExpectation{} + if mmGetContext.defaultExpectation == nil { + mmGetContext.defaultExpectation = &HTTPProxyTestMockGetContextExpectation{} } - m.defaultExpectation.params = &HTTPProxyTestMockGetContextParams{req} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmGetContext.defaultExpectation.params = &HTTPProxyTestMockGetContextParams{req} + for _, e := range mmGetContext.expectations { + if minimock.Equal(e.params, mmGetContext.defaultExpectation.params) { + mmGetContext.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmGetContext.defaultExpectation.params) } } - return m + return mmGetContext +} + +// Inspect accepts an inspector function that has same arguments as the HTTPProxyTest.GetContext +func (mmGetContext *mHTTPProxyTestMockGetContext) Inspect(f func(req *http.Request)) *mHTTPProxyTestMockGetContext { + if mmGetContext.mock.inspectFuncGetContext != nil { + mmGetContext.mock.t.Fatalf("Inspect function is already set for HTTPProxyTestMock.GetContext") + } + + mmGetContext.mock.inspectFuncGetContext = f + + return mmGetContext } // Return sets up results that will be returned by HTTPProxyTest.GetContext -func (m *mHTTPProxyTestMockGetContext) Return(c1 context.Context, err error) *HTTPProxyTestMock { - if m.mock.funcGetContext != nil { - m.mock.t.Fatalf("HTTPProxyTestMock.GetContext mock is already set by Set") +func (mmGetContext *mHTTPProxyTestMockGetContext) Return(c1 context.Context, err error) *HTTPProxyTestMock { + if mmGetContext.mock.funcGetContext != nil { + mmGetContext.mock.t.Fatalf("HTTPProxyTestMock.GetContext mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &HTTPProxyTestMockGetContextExpectation{mock: m.mock} + if mmGetContext.defaultExpectation == nil { + mmGetContext.defaultExpectation = &HTTPProxyTestMockGetContextExpectation{mock: mmGetContext.mock} } - m.defaultExpectation.results = &HTTPProxyTestMockGetContextResults{c1, err} - return m.mock + mmGetContext.defaultExpectation.results = &HTTPProxyTestMockGetContextResults{c1, err} + return mmGetContext.mock } //Set uses given function f to mock the HTTPProxyTest.GetContext method -func (m *mHTTPProxyTestMockGetContext) Set(f func(req *http.Request) (c1 context.Context, err error)) *HTTPProxyTestMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the HTTPProxyTest.GetContext method") +func (mmGetContext *mHTTPProxyTestMockGetContext) Set(f func(req *http.Request) (c1 context.Context, err error)) *HTTPProxyTestMock { + if mmGetContext.defaultExpectation != nil { + mmGetContext.mock.t.Fatalf("Default expectation is already set for the HTTPProxyTest.GetContext method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the HTTPProxyTest.GetContext method") + if len(mmGetContext.expectations) > 0 { + mmGetContext.mock.t.Fatalf("Some expectations are already set for the HTTPProxyTest.GetContext method") } - m.mock.funcGetContext = f - return m.mock + mmGetContext.mock.funcGetContext = f + return mmGetContext.mock } // When sets expectation for the HTTPProxyTest.GetContext which will trigger the result defined by the following // Then helper -func (m *mHTTPProxyTestMockGetContext) When(req *http.Request) *HTTPProxyTestMockGetContextExpectation { - if m.mock.funcGetContext != nil { - m.mock.t.Fatalf("HTTPProxyTestMock.GetContext mock is already set by Set") +func (mmGetContext *mHTTPProxyTestMockGetContext) When(req *http.Request) *HTTPProxyTestMockGetContextExpectation { + if mmGetContext.mock.funcGetContext != nil { + mmGetContext.mock.t.Fatalf("HTTPProxyTestMock.GetContext mock is already set by Set") } expectation := &HTTPProxyTestMockGetContextExpectation{ - mock: m.mock, + mock: mmGetContext.mock, params: &HTTPProxyTestMockGetContextParams{req}, } - m.expectations = append(m.expectations, expectation) + mmGetContext.expectations = append(mmGetContext.expectations, expectation) return expectation } @@ -137,63 +155,87 @@ func (e *HTTPProxyTestMockGetContextExpectation) Then(c1 context.Context, err er } // GetContext implements HTTPProxyTest -func (m *HTTPProxyTestMock) GetContext(req *http.Request) (c1 context.Context, err error) { - atomic.AddUint64(&m.beforeGetContextCounter, 1) - defer atomic.AddUint64(&m.afterGetContextCounter, 1) +func (mmGetContext *HTTPProxyTestMock) GetContext(req *http.Request) (c1 context.Context, err error) { + mm_atomic.AddUint64(&mmGetContext.beforeGetContextCounter, 1) + defer mm_atomic.AddUint64(&mmGetContext.afterGetContextCounter, 1) - for _, e := range m.GetContextMock.expectations { - if minimock.Equal(*e.params, HTTPProxyTestMockGetContextParams{req}) { - atomic.AddUint64(&e.Counter, 1) + if mmGetContext.inspectFuncGetContext != nil { + mmGetContext.inspectFuncGetContext(req) + } + + mm_params := &HTTPProxyTestMockGetContextParams{req} + + // Record call args + mmGetContext.GetContextMock.mutex.Lock() + mmGetContext.GetContextMock.callArgs = append(mmGetContext.GetContextMock.callArgs, mm_params) + mmGetContext.GetContextMock.mutex.Unlock() + + for _, e := range mmGetContext.GetContextMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.c1, e.results.err } } - if m.GetContextMock.defaultExpectation != nil { - atomic.AddUint64(&m.GetContextMock.defaultExpectation.Counter, 1) - want := m.GetContextMock.defaultExpectation.params - got := HTTPProxyTestMockGetContextParams{req} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("HTTPProxyTestMock.GetContext got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmGetContext.GetContextMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmGetContext.GetContextMock.defaultExpectation.Counter, 1) + mm_want := mmGetContext.GetContextMock.defaultExpectation.params + mm_got := HTTPProxyTestMockGetContextParams{req} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmGetContext.t.Errorf("HTTPProxyTestMock.GetContext got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.GetContextMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the HTTPProxyTestMock.GetContext") + mm_results := mmGetContext.GetContextMock.defaultExpectation.results + if mm_results == nil { + mmGetContext.t.Fatal("No results are set for the HTTPProxyTestMock.GetContext") } - return (*results).c1, (*results).err + return (*mm_results).c1, (*mm_results).err } - if m.funcGetContext != nil { - return m.funcGetContext(req) + if mmGetContext.funcGetContext != nil { + return mmGetContext.funcGetContext(req) } - m.t.Fatalf("Unexpected call to HTTPProxyTestMock.GetContext. %v", req) + mmGetContext.t.Fatalf("Unexpected call to HTTPProxyTestMock.GetContext. %v", req) return } // GetContextAfterCounter returns a count of finished HTTPProxyTestMock.GetContext invocations -func (m *HTTPProxyTestMock) GetContextAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterGetContextCounter) +func (mmGetContext *HTTPProxyTestMock) GetContextAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmGetContext.afterGetContextCounter) } // GetContextBeforeCounter returns a count of HTTPProxyTestMock.GetContext invocations -func (m *HTTPProxyTestMock) GetContextBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeGetContextCounter) +func (mmGetContext *HTTPProxyTestMock) GetContextBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmGetContext.beforeGetContextCounter) +} + +// Calls returns a list of arguments used in each call to HTTPProxyTestMock.GetContext. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmGetContext *mHTTPProxyTestMockGetContext) Calls() []*HTTPProxyTestMockGetContextParams { + mmGetContext.mutex.RLock() + + argCopy := make([]*HTTPProxyTestMockGetContextParams, len(mmGetContext.callArgs)) + copy(argCopy, mmGetContext.callArgs) + + mmGetContext.mutex.RUnlock() + + return argCopy } // MinimockGetContextDone returns true if the count of the GetContext invocations corresponds // the number of defined expectations func (m *HTTPProxyTestMock) MinimockGetContextDone() bool { for _, e := range m.GetContextMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.GetContextMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterGetContextCounter) < 1 { + if m.GetContextMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterGetContextCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcGetContext != nil && atomic.LoadUint64(&m.afterGetContextCounter) < 1 { + if m.funcGetContext != nil && mm_atomic.LoadUint64(&m.afterGetContextCounter) < 1 { return false } return true @@ -202,17 +244,21 @@ func (m *HTTPProxyTestMock) MinimockGetContextDone() bool { // MinimockGetContextInspect logs each unmet expectation func (m *HTTPProxyTestMock) MinimockGetContextInspect() { for _, e := range m.GetContextMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to HTTPProxyTestMock.GetContext with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.GetContextMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterGetContextCounter) < 1 { - m.t.Errorf("Expected call to HTTPProxyTestMock.GetContext with params: %#v", *m.GetContextMock.defaultExpectation.params) + if m.GetContextMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterGetContextCounter) < 1 { + if m.GetContextMock.defaultExpectation.params == nil { + m.t.Error("Expected call to HTTPProxyTestMock.GetContext") + } else { + m.t.Errorf("Expected call to HTTPProxyTestMock.GetContext with params: %#v", *m.GetContextMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcGetContext != nil && atomic.LoadUint64(&m.afterGetContextCounter) < 1 { + if m.funcGetContext != nil && mm_atomic.LoadUint64(&m.afterGetContextCounter) < 1 { m.t.Error("Expected call to HTTPProxyTestMock.GetContext") } } @@ -221,6 +267,9 @@ type mHTTPProxyTestMockHandleHTTPValidation struct { mock *HTTPProxyTestMock defaultExpectation *HTTPProxyTestMockHandleHTTPValidationExpectation expectations []*HTTPProxyTestMockHandleHTTPValidationExpectation + + callArgs []*HTTPProxyTestMockHandleHTTPValidationParams + mutex sync.RWMutex } // HTTPProxyTestMockHandleHTTPValidationExpectation specifies expectation struct of the HTTPProxyTest.HandleHTTPValidation @@ -243,64 +292,75 @@ type HTTPProxyTestMockHandleHTTPValidationResults struct { } // Expect sets up expected params for HTTPProxyTest.HandleHTTPValidation -func (m *mHTTPProxyTestMockHandleHTTPValidation) Expect(w http.ResponseWriter, r *http.Request) *mHTTPProxyTestMockHandleHTTPValidation { - if m.mock.funcHandleHTTPValidation != nil { - m.mock.t.Fatalf("HTTPProxyTestMock.HandleHTTPValidation mock is already set by Set") +func (mmHandleHTTPValidation *mHTTPProxyTestMockHandleHTTPValidation) Expect(w http.ResponseWriter, r *http.Request) *mHTTPProxyTestMockHandleHTTPValidation { + if mmHandleHTTPValidation.mock.funcHandleHTTPValidation != nil { + mmHandleHTTPValidation.mock.t.Fatalf("HTTPProxyTestMock.HandleHTTPValidation mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &HTTPProxyTestMockHandleHTTPValidationExpectation{} + if mmHandleHTTPValidation.defaultExpectation == nil { + mmHandleHTTPValidation.defaultExpectation = &HTTPProxyTestMockHandleHTTPValidationExpectation{} } - m.defaultExpectation.params = &HTTPProxyTestMockHandleHTTPValidationParams{w, r} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmHandleHTTPValidation.defaultExpectation.params = &HTTPProxyTestMockHandleHTTPValidationParams{w, r} + for _, e := range mmHandleHTTPValidation.expectations { + if minimock.Equal(e.params, mmHandleHTTPValidation.defaultExpectation.params) { + mmHandleHTTPValidation.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmHandleHTTPValidation.defaultExpectation.params) } } - return m + return mmHandleHTTPValidation +} + +// Inspect accepts an inspector function that has same arguments as the HTTPProxyTest.HandleHTTPValidation +func (mmHandleHTTPValidation *mHTTPProxyTestMockHandleHTTPValidation) Inspect(f func(w http.ResponseWriter, r *http.Request)) *mHTTPProxyTestMockHandleHTTPValidation { + if mmHandleHTTPValidation.mock.inspectFuncHandleHTTPValidation != nil { + mmHandleHTTPValidation.mock.t.Fatalf("Inspect function is already set for HTTPProxyTestMock.HandleHTTPValidation") + } + + mmHandleHTTPValidation.mock.inspectFuncHandleHTTPValidation = f + + return mmHandleHTTPValidation } // Return sets up results that will be returned by HTTPProxyTest.HandleHTTPValidation -func (m *mHTTPProxyTestMockHandleHTTPValidation) Return(b1 bool) *HTTPProxyTestMock { - if m.mock.funcHandleHTTPValidation != nil { - m.mock.t.Fatalf("HTTPProxyTestMock.HandleHTTPValidation mock is already set by Set") +func (mmHandleHTTPValidation *mHTTPProxyTestMockHandleHTTPValidation) Return(b1 bool) *HTTPProxyTestMock { + if mmHandleHTTPValidation.mock.funcHandleHTTPValidation != nil { + mmHandleHTTPValidation.mock.t.Fatalf("HTTPProxyTestMock.HandleHTTPValidation mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &HTTPProxyTestMockHandleHTTPValidationExpectation{mock: m.mock} + if mmHandleHTTPValidation.defaultExpectation == nil { + mmHandleHTTPValidation.defaultExpectation = &HTTPProxyTestMockHandleHTTPValidationExpectation{mock: mmHandleHTTPValidation.mock} } - m.defaultExpectation.results = &HTTPProxyTestMockHandleHTTPValidationResults{b1} - return m.mock + mmHandleHTTPValidation.defaultExpectation.results = &HTTPProxyTestMockHandleHTTPValidationResults{b1} + return mmHandleHTTPValidation.mock } //Set uses given function f to mock the HTTPProxyTest.HandleHTTPValidation method -func (m *mHTTPProxyTestMockHandleHTTPValidation) Set(f func(w http.ResponseWriter, r *http.Request) (b1 bool)) *HTTPProxyTestMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the HTTPProxyTest.HandleHTTPValidation method") +func (mmHandleHTTPValidation *mHTTPProxyTestMockHandleHTTPValidation) Set(f func(w http.ResponseWriter, r *http.Request) (b1 bool)) *HTTPProxyTestMock { + if mmHandleHTTPValidation.defaultExpectation != nil { + mmHandleHTTPValidation.mock.t.Fatalf("Default expectation is already set for the HTTPProxyTest.HandleHTTPValidation method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the HTTPProxyTest.HandleHTTPValidation method") + if len(mmHandleHTTPValidation.expectations) > 0 { + mmHandleHTTPValidation.mock.t.Fatalf("Some expectations are already set for the HTTPProxyTest.HandleHTTPValidation method") } - m.mock.funcHandleHTTPValidation = f - return m.mock + mmHandleHTTPValidation.mock.funcHandleHTTPValidation = f + return mmHandleHTTPValidation.mock } // When sets expectation for the HTTPProxyTest.HandleHTTPValidation which will trigger the result defined by the following // Then helper -func (m *mHTTPProxyTestMockHandleHTTPValidation) When(w http.ResponseWriter, r *http.Request) *HTTPProxyTestMockHandleHTTPValidationExpectation { - if m.mock.funcHandleHTTPValidation != nil { - m.mock.t.Fatalf("HTTPProxyTestMock.HandleHTTPValidation mock is already set by Set") +func (mmHandleHTTPValidation *mHTTPProxyTestMockHandleHTTPValidation) When(w http.ResponseWriter, r *http.Request) *HTTPProxyTestMockHandleHTTPValidationExpectation { + if mmHandleHTTPValidation.mock.funcHandleHTTPValidation != nil { + mmHandleHTTPValidation.mock.t.Fatalf("HTTPProxyTestMock.HandleHTTPValidation mock is already set by Set") } expectation := &HTTPProxyTestMockHandleHTTPValidationExpectation{ - mock: m.mock, + mock: mmHandleHTTPValidation.mock, params: &HTTPProxyTestMockHandleHTTPValidationParams{w, r}, } - m.expectations = append(m.expectations, expectation) + mmHandleHTTPValidation.expectations = append(mmHandleHTTPValidation.expectations, expectation) return expectation } @@ -311,63 +371,87 @@ func (e *HTTPProxyTestMockHandleHTTPValidationExpectation) Then(b1 bool) *HTTPPr } // HandleHTTPValidation implements HTTPProxyTest -func (m *HTTPProxyTestMock) HandleHTTPValidation(w http.ResponseWriter, r *http.Request) (b1 bool) { - atomic.AddUint64(&m.beforeHandleHTTPValidationCounter, 1) - defer atomic.AddUint64(&m.afterHandleHTTPValidationCounter, 1) +func (mmHandleHTTPValidation *HTTPProxyTestMock) HandleHTTPValidation(w http.ResponseWriter, r *http.Request) (b1 bool) { + mm_atomic.AddUint64(&mmHandleHTTPValidation.beforeHandleHTTPValidationCounter, 1) + defer mm_atomic.AddUint64(&mmHandleHTTPValidation.afterHandleHTTPValidationCounter, 1) - for _, e := range m.HandleHTTPValidationMock.expectations { - if minimock.Equal(*e.params, HTTPProxyTestMockHandleHTTPValidationParams{w, r}) { - atomic.AddUint64(&e.Counter, 1) + if mmHandleHTTPValidation.inspectFuncHandleHTTPValidation != nil { + mmHandleHTTPValidation.inspectFuncHandleHTTPValidation(w, r) + } + + mm_params := &HTTPProxyTestMockHandleHTTPValidationParams{w, r} + + // Record call args + mmHandleHTTPValidation.HandleHTTPValidationMock.mutex.Lock() + mmHandleHTTPValidation.HandleHTTPValidationMock.callArgs = append(mmHandleHTTPValidation.HandleHTTPValidationMock.callArgs, mm_params) + mmHandleHTTPValidation.HandleHTTPValidationMock.mutex.Unlock() + + for _, e := range mmHandleHTTPValidation.HandleHTTPValidationMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.b1 } } - if m.HandleHTTPValidationMock.defaultExpectation != nil { - atomic.AddUint64(&m.HandleHTTPValidationMock.defaultExpectation.Counter, 1) - want := m.HandleHTTPValidationMock.defaultExpectation.params - got := HTTPProxyTestMockHandleHTTPValidationParams{w, r} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("HTTPProxyTestMock.HandleHTTPValidation got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmHandleHTTPValidation.HandleHTTPValidationMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmHandleHTTPValidation.HandleHTTPValidationMock.defaultExpectation.Counter, 1) + mm_want := mmHandleHTTPValidation.HandleHTTPValidationMock.defaultExpectation.params + mm_got := HTTPProxyTestMockHandleHTTPValidationParams{w, r} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmHandleHTTPValidation.t.Errorf("HTTPProxyTestMock.HandleHTTPValidation got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.HandleHTTPValidationMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the HTTPProxyTestMock.HandleHTTPValidation") + mm_results := mmHandleHTTPValidation.HandleHTTPValidationMock.defaultExpectation.results + if mm_results == nil { + mmHandleHTTPValidation.t.Fatal("No results are set for the HTTPProxyTestMock.HandleHTTPValidation") } - return (*results).b1 + return (*mm_results).b1 } - if m.funcHandleHTTPValidation != nil { - return m.funcHandleHTTPValidation(w, r) + if mmHandleHTTPValidation.funcHandleHTTPValidation != nil { + return mmHandleHTTPValidation.funcHandleHTTPValidation(w, r) } - m.t.Fatalf("Unexpected call to HTTPProxyTestMock.HandleHTTPValidation. %v %v", w, r) + mmHandleHTTPValidation.t.Fatalf("Unexpected call to HTTPProxyTestMock.HandleHTTPValidation. %v %v", w, r) return } // HandleHTTPValidationAfterCounter returns a count of finished HTTPProxyTestMock.HandleHTTPValidation invocations -func (m *HTTPProxyTestMock) HandleHTTPValidationAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterHandleHTTPValidationCounter) +func (mmHandleHTTPValidation *HTTPProxyTestMock) HandleHTTPValidationAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmHandleHTTPValidation.afterHandleHTTPValidationCounter) } // HandleHTTPValidationBeforeCounter returns a count of HTTPProxyTestMock.HandleHTTPValidation invocations -func (m *HTTPProxyTestMock) HandleHTTPValidationBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeHandleHTTPValidationCounter) +func (mmHandleHTTPValidation *HTTPProxyTestMock) HandleHTTPValidationBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmHandleHTTPValidation.beforeHandleHTTPValidationCounter) +} + +// Calls returns a list of arguments used in each call to HTTPProxyTestMock.HandleHTTPValidation. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmHandleHTTPValidation *mHTTPProxyTestMockHandleHTTPValidation) Calls() []*HTTPProxyTestMockHandleHTTPValidationParams { + mmHandleHTTPValidation.mutex.RLock() + + argCopy := make([]*HTTPProxyTestMockHandleHTTPValidationParams, len(mmHandleHTTPValidation.callArgs)) + copy(argCopy, mmHandleHTTPValidation.callArgs) + + mmHandleHTTPValidation.mutex.RUnlock() + + return argCopy } // MinimockHandleHTTPValidationDone returns true if the count of the HandleHTTPValidation invocations corresponds // the number of defined expectations func (m *HTTPProxyTestMock) MinimockHandleHTTPValidationDone() bool { for _, e := range m.HandleHTTPValidationMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.HandleHTTPValidationMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterHandleHTTPValidationCounter) < 1 { + if m.HandleHTTPValidationMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterHandleHTTPValidationCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcHandleHTTPValidation != nil && atomic.LoadUint64(&m.afterHandleHTTPValidationCounter) < 1 { + if m.funcHandleHTTPValidation != nil && mm_atomic.LoadUint64(&m.afterHandleHTTPValidationCounter) < 1 { return false } return true @@ -376,17 +460,21 @@ func (m *HTTPProxyTestMock) MinimockHandleHTTPValidationDone() bool { // MinimockHandleHTTPValidationInspect logs each unmet expectation func (m *HTTPProxyTestMock) MinimockHandleHTTPValidationInspect() { for _, e := range m.HandleHTTPValidationMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to HTTPProxyTestMock.HandleHTTPValidation with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.HandleHTTPValidationMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterHandleHTTPValidationCounter) < 1 { - m.t.Errorf("Expected call to HTTPProxyTestMock.HandleHTTPValidation with params: %#v", *m.HandleHTTPValidationMock.defaultExpectation.params) + if m.HandleHTTPValidationMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterHandleHTTPValidationCounter) < 1 { + if m.HandleHTTPValidationMock.defaultExpectation.params == nil { + m.t.Error("Expected call to HTTPProxyTestMock.HandleHTTPValidation") + } else { + m.t.Errorf("Expected call to HTTPProxyTestMock.HandleHTTPValidation with params: %#v", *m.HandleHTTPValidationMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcHandleHTTPValidation != nil && atomic.LoadUint64(&m.afterHandleHTTPValidationCounter) < 1 { + if m.funcHandleHTTPValidation != nil && mm_atomic.LoadUint64(&m.afterHandleHTTPValidationCounter) < 1 { m.t.Error("Expected call to HTTPProxyTestMock.HandleHTTPValidation") } } @@ -402,8 +490,8 @@ func (m *HTTPProxyTestMock) MinimockFinish() { } // MinimockWait waits for all mocked methods to be called the expected number of times -func (m *HTTPProxyTestMock) MinimockWait(timeout time.Duration) { - timeoutCh := time.After(timeout) +func (m *HTTPProxyTestMock) MinimockWait(timeout mm_time.Duration) { + timeoutCh := mm_time.After(timeout) for { if m.minimockDone() { return @@ -412,7 +500,7 @@ func (m *HTTPProxyTestMock) MinimockWait(timeout time.Duration) { case <-timeoutCh: m.MinimockFinish() return - case <-time.After(10 * time.Millisecond): + case <-mm_time.After(10 * mm_time.Millisecond): } } } diff --git a/internal/proxy/http_round_tripper_mock_test.go b/internal/proxy/http_round_tripper_mock_test.go index cc8fb42d..60058927 100644 --- a/internal/proxy/http_round_tripper_mock_test.go +++ b/internal/proxy/http_round_tripper_mock_test.go @@ -1,14 +1,14 @@ package proxy -// DO NOT EDIT! -// The code below was generated with http://github.com/gojuno/minimock (dev) +// Code generated by http://github.com/gojuno/minimock (3.0.6). DO NOT EDIT. //go:generate minimock -i net/http.RoundTripper -o ./http_round_tripper_mock_test.go import ( - "net/http" - "sync/atomic" - "time" + mm_http "net/http" + "sync" + mm_atomic "sync/atomic" + mm_time "time" "github.com/gojuno/minimock/v3" ) @@ -17,7 +17,8 @@ import ( type RoundTripperMock struct { t minimock.Tester - funcRoundTrip func(rp1 *http.Request) (rp2 *http.Response, err error) + funcRoundTrip func(rp1 *mm_http.Request) (rp2 *mm_http.Response, err error) + inspectFuncRoundTrip func(rp1 *mm_http.Request) afterRoundTripCounter uint64 beforeRoundTripCounter uint64 RoundTripMock mRoundTripperMockRoundTrip @@ -29,7 +30,9 @@ func NewRoundTripperMock(t minimock.Tester) *RoundTripperMock { if controller, ok := t.(minimock.MockController); ok { controller.RegisterMocker(m) } + m.RoundTripMock = mRoundTripperMockRoundTrip{mock: m} + m.RoundTripMock.callArgs = []*RoundTripperMockRoundTripParams{} return m } @@ -38,6 +41,9 @@ type mRoundTripperMockRoundTrip struct { mock *RoundTripperMock defaultExpectation *RoundTripperMockRoundTripExpectation expectations []*RoundTripperMockRoundTripExpectation + + callArgs []*RoundTripperMockRoundTripParams + mutex sync.RWMutex } // RoundTripperMockRoundTripExpectation specifies expectation struct of the RoundTripper.RoundTrip @@ -50,141 +56,176 @@ type RoundTripperMockRoundTripExpectation struct { // RoundTripperMockRoundTripParams contains parameters of the RoundTripper.RoundTrip type RoundTripperMockRoundTripParams struct { - rp1 *http.Request + rp1 *mm_http.Request } // RoundTripperMockRoundTripResults contains results of the RoundTripper.RoundTrip type RoundTripperMockRoundTripResults struct { - rp2 *http.Response + rp2 *mm_http.Response err error } // Expect sets up expected params for RoundTripper.RoundTrip -func (m *mRoundTripperMockRoundTrip) Expect(rp1 *http.Request) *mRoundTripperMockRoundTrip { - if m.mock.funcRoundTrip != nil { - m.mock.t.Fatalf("RoundTripperMock.RoundTrip mock is already set by Set") +func (mmRoundTrip *mRoundTripperMockRoundTrip) Expect(rp1 *mm_http.Request) *mRoundTripperMockRoundTrip { + if mmRoundTrip.mock.funcRoundTrip != nil { + mmRoundTrip.mock.t.Fatalf("RoundTripperMock.RoundTrip mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &RoundTripperMockRoundTripExpectation{} + if mmRoundTrip.defaultExpectation == nil { + mmRoundTrip.defaultExpectation = &RoundTripperMockRoundTripExpectation{} } - m.defaultExpectation.params = &RoundTripperMockRoundTripParams{rp1} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmRoundTrip.defaultExpectation.params = &RoundTripperMockRoundTripParams{rp1} + for _, e := range mmRoundTrip.expectations { + if minimock.Equal(e.params, mmRoundTrip.defaultExpectation.params) { + mmRoundTrip.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmRoundTrip.defaultExpectation.params) } } - return m + return mmRoundTrip +} + +// Inspect accepts an inspector function that has same arguments as the RoundTripper.RoundTrip +func (mmRoundTrip *mRoundTripperMockRoundTrip) Inspect(f func(rp1 *mm_http.Request)) *mRoundTripperMockRoundTrip { + if mmRoundTrip.mock.inspectFuncRoundTrip != nil { + mmRoundTrip.mock.t.Fatalf("Inspect function is already set for RoundTripperMock.RoundTrip") + } + + mmRoundTrip.mock.inspectFuncRoundTrip = f + + return mmRoundTrip } // Return sets up results that will be returned by RoundTripper.RoundTrip -func (m *mRoundTripperMockRoundTrip) Return(rp2 *http.Response, err error) *RoundTripperMock { - if m.mock.funcRoundTrip != nil { - m.mock.t.Fatalf("RoundTripperMock.RoundTrip mock is already set by Set") +func (mmRoundTrip *mRoundTripperMockRoundTrip) Return(rp2 *mm_http.Response, err error) *RoundTripperMock { + if mmRoundTrip.mock.funcRoundTrip != nil { + mmRoundTrip.mock.t.Fatalf("RoundTripperMock.RoundTrip mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &RoundTripperMockRoundTripExpectation{mock: m.mock} + if mmRoundTrip.defaultExpectation == nil { + mmRoundTrip.defaultExpectation = &RoundTripperMockRoundTripExpectation{mock: mmRoundTrip.mock} } - m.defaultExpectation.results = &RoundTripperMockRoundTripResults{rp2, err} - return m.mock + mmRoundTrip.defaultExpectation.results = &RoundTripperMockRoundTripResults{rp2, err} + return mmRoundTrip.mock } //Set uses given function f to mock the RoundTripper.RoundTrip method -func (m *mRoundTripperMockRoundTrip) Set(f func(rp1 *http.Request) (rp2 *http.Response, err error)) *RoundTripperMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the RoundTripper.RoundTrip method") +func (mmRoundTrip *mRoundTripperMockRoundTrip) Set(f func(rp1 *mm_http.Request) (rp2 *mm_http.Response, err error)) *RoundTripperMock { + if mmRoundTrip.defaultExpectation != nil { + mmRoundTrip.mock.t.Fatalf("Default expectation is already set for the RoundTripper.RoundTrip method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the RoundTripper.RoundTrip method") + if len(mmRoundTrip.expectations) > 0 { + mmRoundTrip.mock.t.Fatalf("Some expectations are already set for the RoundTripper.RoundTrip method") } - m.mock.funcRoundTrip = f - return m.mock + mmRoundTrip.mock.funcRoundTrip = f + return mmRoundTrip.mock } // When sets expectation for the RoundTripper.RoundTrip which will trigger the result defined by the following // Then helper -func (m *mRoundTripperMockRoundTrip) When(rp1 *http.Request) *RoundTripperMockRoundTripExpectation { - if m.mock.funcRoundTrip != nil { - m.mock.t.Fatalf("RoundTripperMock.RoundTrip mock is already set by Set") +func (mmRoundTrip *mRoundTripperMockRoundTrip) When(rp1 *mm_http.Request) *RoundTripperMockRoundTripExpectation { + if mmRoundTrip.mock.funcRoundTrip != nil { + mmRoundTrip.mock.t.Fatalf("RoundTripperMock.RoundTrip mock is already set by Set") } expectation := &RoundTripperMockRoundTripExpectation{ - mock: m.mock, + mock: mmRoundTrip.mock, params: &RoundTripperMockRoundTripParams{rp1}, } - m.expectations = append(m.expectations, expectation) + mmRoundTrip.expectations = append(mmRoundTrip.expectations, expectation) return expectation } // Then sets up RoundTripper.RoundTrip return parameters for the expectation previously defined by the When method -func (e *RoundTripperMockRoundTripExpectation) Then(rp2 *http.Response, err error) *RoundTripperMock { +func (e *RoundTripperMockRoundTripExpectation) Then(rp2 *mm_http.Response, err error) *RoundTripperMock { e.results = &RoundTripperMockRoundTripResults{rp2, err} return e.mock } // RoundTrip implements http.RoundTripper -func (m *RoundTripperMock) RoundTrip(rp1 *http.Request) (rp2 *http.Response, err error) { - atomic.AddUint64(&m.beforeRoundTripCounter, 1) - defer atomic.AddUint64(&m.afterRoundTripCounter, 1) +func (mmRoundTrip *RoundTripperMock) RoundTrip(rp1 *mm_http.Request) (rp2 *mm_http.Response, err error) { + mm_atomic.AddUint64(&mmRoundTrip.beforeRoundTripCounter, 1) + defer mm_atomic.AddUint64(&mmRoundTrip.afterRoundTripCounter, 1) - for _, e := range m.RoundTripMock.expectations { - if minimock.Equal(*e.params, RoundTripperMockRoundTripParams{rp1}) { - atomic.AddUint64(&e.Counter, 1) + if mmRoundTrip.inspectFuncRoundTrip != nil { + mmRoundTrip.inspectFuncRoundTrip(rp1) + } + + mm_params := &RoundTripperMockRoundTripParams{rp1} + + // Record call args + mmRoundTrip.RoundTripMock.mutex.Lock() + mmRoundTrip.RoundTripMock.callArgs = append(mmRoundTrip.RoundTripMock.callArgs, mm_params) + mmRoundTrip.RoundTripMock.mutex.Unlock() + + for _, e := range mmRoundTrip.RoundTripMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.rp2, e.results.err } } - if m.RoundTripMock.defaultExpectation != nil { - atomic.AddUint64(&m.RoundTripMock.defaultExpectation.Counter, 1) - want := m.RoundTripMock.defaultExpectation.params - got := RoundTripperMockRoundTripParams{rp1} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("RoundTripperMock.RoundTrip got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmRoundTrip.RoundTripMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmRoundTrip.RoundTripMock.defaultExpectation.Counter, 1) + mm_want := mmRoundTrip.RoundTripMock.defaultExpectation.params + mm_got := RoundTripperMockRoundTripParams{rp1} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmRoundTrip.t.Errorf("RoundTripperMock.RoundTrip got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.RoundTripMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the RoundTripperMock.RoundTrip") + mm_results := mmRoundTrip.RoundTripMock.defaultExpectation.results + if mm_results == nil { + mmRoundTrip.t.Fatal("No results are set for the RoundTripperMock.RoundTrip") } - return (*results).rp2, (*results).err + return (*mm_results).rp2, (*mm_results).err } - if m.funcRoundTrip != nil { - return m.funcRoundTrip(rp1) + if mmRoundTrip.funcRoundTrip != nil { + return mmRoundTrip.funcRoundTrip(rp1) } - m.t.Fatalf("Unexpected call to RoundTripperMock.RoundTrip. %v", rp1) + mmRoundTrip.t.Fatalf("Unexpected call to RoundTripperMock.RoundTrip. %v", rp1) return } // RoundTripAfterCounter returns a count of finished RoundTripperMock.RoundTrip invocations -func (m *RoundTripperMock) RoundTripAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterRoundTripCounter) +func (mmRoundTrip *RoundTripperMock) RoundTripAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmRoundTrip.afterRoundTripCounter) } // RoundTripBeforeCounter returns a count of RoundTripperMock.RoundTrip invocations -func (m *RoundTripperMock) RoundTripBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeRoundTripCounter) +func (mmRoundTrip *RoundTripperMock) RoundTripBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmRoundTrip.beforeRoundTripCounter) +} + +// Calls returns a list of arguments used in each call to RoundTripperMock.RoundTrip. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmRoundTrip *mRoundTripperMockRoundTrip) Calls() []*RoundTripperMockRoundTripParams { + mmRoundTrip.mutex.RLock() + + argCopy := make([]*RoundTripperMockRoundTripParams, len(mmRoundTrip.callArgs)) + copy(argCopy, mmRoundTrip.callArgs) + + mmRoundTrip.mutex.RUnlock() + + return argCopy } // MinimockRoundTripDone returns true if the count of the RoundTrip invocations corresponds // the number of defined expectations func (m *RoundTripperMock) MinimockRoundTripDone() bool { for _, e := range m.RoundTripMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.RoundTripMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterRoundTripCounter) < 1 { + if m.RoundTripMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterRoundTripCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcRoundTrip != nil && atomic.LoadUint64(&m.afterRoundTripCounter) < 1 { + if m.funcRoundTrip != nil && mm_atomic.LoadUint64(&m.afterRoundTripCounter) < 1 { return false } return true @@ -193,17 +234,21 @@ func (m *RoundTripperMock) MinimockRoundTripDone() bool { // MinimockRoundTripInspect logs each unmet expectation func (m *RoundTripperMock) MinimockRoundTripInspect() { for _, e := range m.RoundTripMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to RoundTripperMock.RoundTrip with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.RoundTripMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterRoundTripCounter) < 1 { - m.t.Errorf("Expected call to RoundTripperMock.RoundTrip with params: %#v", *m.RoundTripMock.defaultExpectation.params) + if m.RoundTripMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterRoundTripCounter) < 1 { + if m.RoundTripMock.defaultExpectation.params == nil { + m.t.Error("Expected call to RoundTripperMock.RoundTrip") + } else { + m.t.Errorf("Expected call to RoundTripperMock.RoundTrip with params: %#v", *m.RoundTripMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcRoundTrip != nil && atomic.LoadUint64(&m.afterRoundTripCounter) < 1 { + if m.funcRoundTrip != nil && mm_atomic.LoadUint64(&m.afterRoundTripCounter) < 1 { m.t.Error("Expected call to RoundTripperMock.RoundTrip") } } @@ -217,8 +262,8 @@ func (m *RoundTripperMock) MinimockFinish() { } // MinimockWait waits for all mocked methods to be called the expected number of times -func (m *RoundTripperMock) MinimockWait(timeout time.Duration) { - timeoutCh := time.After(timeout) +func (m *RoundTripperMock) MinimockWait(timeout mm_time.Duration) { + timeoutCh := mm_time.After(timeout) for { if m.minimockDone() { return @@ -227,7 +272,7 @@ func (m *RoundTripperMock) MinimockWait(timeout time.Duration) { case <-timeoutCh: m.MinimockFinish() return - case <-time.After(10 * time.Millisecond): + case <-mm_time.After(10 * mm_time.Millisecond): } } } diff --git a/internal/tlslistener/net_conn_mock_test.go b/internal/tlslistener/net_conn_mock_test.go index 1dc49ab5..af4a0782 100644 --- a/internal/tlslistener/net_conn_mock_test.go +++ b/internal/tlslistener/net_conn_mock_test.go @@ -1,14 +1,15 @@ package tlslistener -// DO NOT EDIT! -// The code below was generated with http://github.com/gojuno/minimock (dev) +// Code generated by http://github.com/gojuno/minimock (3.0.6). DO NOT EDIT. //go:generate minimock -i net.Conn -o ./net_conn_mock_test.go import ( - "net" - "sync/atomic" + mm_net "net" + "sync" + mm_atomic "sync/atomic" "time" + mm_time "time" "github.com/gojuno/minimock/v3" ) @@ -18,41 +19,49 @@ type ConnMock struct { t minimock.Tester funcClose func() (err error) + inspectFuncClose func() afterCloseCounter uint64 beforeCloseCounter uint64 CloseMock mConnMockClose - funcLocalAddr func() (a1 net.Addr) + funcLocalAddr func() (a1 mm_net.Addr) + inspectFuncLocalAddr func() afterLocalAddrCounter uint64 beforeLocalAddrCounter uint64 LocalAddrMock mConnMockLocalAddr funcRead func(b []byte) (n int, err error) + inspectFuncRead func(b []byte) afterReadCounter uint64 beforeReadCounter uint64 ReadMock mConnMockRead - funcRemoteAddr func() (a1 net.Addr) + funcRemoteAddr func() (a1 mm_net.Addr) + inspectFuncRemoteAddr func() afterRemoteAddrCounter uint64 beforeRemoteAddrCounter uint64 RemoteAddrMock mConnMockRemoteAddr funcSetDeadline func(t time.Time) (err error) + inspectFuncSetDeadline func(t time.Time) afterSetDeadlineCounter uint64 beforeSetDeadlineCounter uint64 SetDeadlineMock mConnMockSetDeadline funcSetReadDeadline func(t time.Time) (err error) + inspectFuncSetReadDeadline func(t time.Time) afterSetReadDeadlineCounter uint64 beforeSetReadDeadlineCounter uint64 SetReadDeadlineMock mConnMockSetReadDeadline funcSetWriteDeadline func(t time.Time) (err error) + inspectFuncSetWriteDeadline func(t time.Time) afterSetWriteDeadlineCounter uint64 beforeSetWriteDeadlineCounter uint64 SetWriteDeadlineMock mConnMockSetWriteDeadline funcWrite func(b []byte) (n int, err error) + inspectFuncWrite func(b []byte) afterWriteCounter uint64 beforeWriteCounter uint64 WriteMock mConnMockWrite @@ -64,14 +73,27 @@ func NewConnMock(t minimock.Tester) *ConnMock { if controller, ok := t.(minimock.MockController); ok { controller.RegisterMocker(m) } + m.CloseMock = mConnMockClose{mock: m} + m.LocalAddrMock = mConnMockLocalAddr{mock: m} + m.ReadMock = mConnMockRead{mock: m} + m.ReadMock.callArgs = []*ConnMockReadParams{} + m.RemoteAddrMock = mConnMockRemoteAddr{mock: m} + m.SetDeadlineMock = mConnMockSetDeadline{mock: m} + m.SetDeadlineMock.callArgs = []*ConnMockSetDeadlineParams{} + m.SetReadDeadlineMock = mConnMockSetReadDeadline{mock: m} + m.SetReadDeadlineMock.callArgs = []*ConnMockSetReadDeadlineParams{} + m.SetWriteDeadlineMock = mConnMockSetWriteDeadline{mock: m} + m.SetWriteDeadlineMock.callArgs = []*ConnMockSetWriteDeadlineParams{} + m.WriteMock = mConnMockWrite{mock: m} + m.WriteMock.callArgs = []*ConnMockWriteParams{} return m } @@ -96,91 +118,106 @@ type ConnMockCloseResults struct { } // Expect sets up expected params for Conn.Close -func (m *mConnMockClose) Expect() *mConnMockClose { - if m.mock.funcClose != nil { - m.mock.t.Fatalf("ConnMock.Close mock is already set by Set") +func (mmClose *mConnMockClose) Expect() *mConnMockClose { + if mmClose.mock.funcClose != nil { + mmClose.mock.t.Fatalf("ConnMock.Close mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockCloseExpectation{} + if mmClose.defaultExpectation == nil { + mmClose.defaultExpectation = &ConnMockCloseExpectation{} } - return m + return mmClose +} + +// Inspect accepts an inspector function that has same arguments as the Conn.Close +func (mmClose *mConnMockClose) Inspect(f func()) *mConnMockClose { + if mmClose.mock.inspectFuncClose != nil { + mmClose.mock.t.Fatalf("Inspect function is already set for ConnMock.Close") + } + + mmClose.mock.inspectFuncClose = f + + return mmClose } // Return sets up results that will be returned by Conn.Close -func (m *mConnMockClose) Return(err error) *ConnMock { - if m.mock.funcClose != nil { - m.mock.t.Fatalf("ConnMock.Close mock is already set by Set") +func (mmClose *mConnMockClose) Return(err error) *ConnMock { + if mmClose.mock.funcClose != nil { + mmClose.mock.t.Fatalf("ConnMock.Close mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockCloseExpectation{mock: m.mock} + if mmClose.defaultExpectation == nil { + mmClose.defaultExpectation = &ConnMockCloseExpectation{mock: mmClose.mock} } - m.defaultExpectation.results = &ConnMockCloseResults{err} - return m.mock + mmClose.defaultExpectation.results = &ConnMockCloseResults{err} + return mmClose.mock } //Set uses given function f to mock the Conn.Close method -func (m *mConnMockClose) Set(f func() (err error)) *ConnMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Conn.Close method") +func (mmClose *mConnMockClose) Set(f func() (err error)) *ConnMock { + if mmClose.defaultExpectation != nil { + mmClose.mock.t.Fatalf("Default expectation is already set for the Conn.Close method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Conn.Close method") + if len(mmClose.expectations) > 0 { + mmClose.mock.t.Fatalf("Some expectations are already set for the Conn.Close method") } - m.mock.funcClose = f - return m.mock + mmClose.mock.funcClose = f + return mmClose.mock } // Close implements net.Conn -func (m *ConnMock) Close() (err error) { - atomic.AddUint64(&m.beforeCloseCounter, 1) - defer atomic.AddUint64(&m.afterCloseCounter, 1) +func (mmClose *ConnMock) Close() (err error) { + mm_atomic.AddUint64(&mmClose.beforeCloseCounter, 1) + defer mm_atomic.AddUint64(&mmClose.afterCloseCounter, 1) + + if mmClose.inspectFuncClose != nil { + mmClose.inspectFuncClose() + } - if m.CloseMock.defaultExpectation != nil { - atomic.AddUint64(&m.CloseMock.defaultExpectation.Counter, 1) + if mmClose.CloseMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmClose.CloseMock.defaultExpectation.Counter, 1) - results := m.CloseMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the ConnMock.Close") + mm_results := mmClose.CloseMock.defaultExpectation.results + if mm_results == nil { + mmClose.t.Fatal("No results are set for the ConnMock.Close") } - return (*results).err + return (*mm_results).err } - if m.funcClose != nil { - return m.funcClose() + if mmClose.funcClose != nil { + return mmClose.funcClose() } - m.t.Fatalf("Unexpected call to ConnMock.Close.") + mmClose.t.Fatalf("Unexpected call to ConnMock.Close.") return } // CloseAfterCounter returns a count of finished ConnMock.Close invocations -func (m *ConnMock) CloseAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterCloseCounter) +func (mmClose *ConnMock) CloseAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmClose.afterCloseCounter) } // CloseBeforeCounter returns a count of ConnMock.Close invocations -func (m *ConnMock) CloseBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeCloseCounter) +func (mmClose *ConnMock) CloseBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmClose.beforeCloseCounter) } // MinimockCloseDone returns true if the count of the Close invocations corresponds // the number of defined expectations func (m *ConnMock) MinimockCloseDone() bool { for _, e := range m.CloseMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.CloseMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterCloseCounter) < 1 { + if m.CloseMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterCloseCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcClose != nil && atomic.LoadUint64(&m.afterCloseCounter) < 1 { + if m.funcClose != nil && mm_atomic.LoadUint64(&m.afterCloseCounter) < 1 { return false } return true @@ -189,17 +226,17 @@ func (m *ConnMock) MinimockCloseDone() bool { // MinimockCloseInspect logs each unmet expectation func (m *ConnMock) MinimockCloseInspect() { for _, e := range m.CloseMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Error("Expected call to ConnMock.Close") } } // if default expectation was set then invocations count should be greater than zero - if m.CloseMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterCloseCounter) < 1 { + if m.CloseMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterCloseCounter) < 1 { m.t.Error("Expected call to ConnMock.Close") } // if func was set then invocations count should be greater than zero - if m.funcClose != nil && atomic.LoadUint64(&m.afterCloseCounter) < 1 { + if m.funcClose != nil && mm_atomic.LoadUint64(&m.afterCloseCounter) < 1 { m.t.Error("Expected call to ConnMock.Close") } } @@ -220,95 +257,110 @@ type ConnMockLocalAddrExpectation struct { // ConnMockLocalAddrResults contains results of the Conn.LocalAddr type ConnMockLocalAddrResults struct { - a1 net.Addr + a1 mm_net.Addr } // Expect sets up expected params for Conn.LocalAddr -func (m *mConnMockLocalAddr) Expect() *mConnMockLocalAddr { - if m.mock.funcLocalAddr != nil { - m.mock.t.Fatalf("ConnMock.LocalAddr mock is already set by Set") +func (mmLocalAddr *mConnMockLocalAddr) Expect() *mConnMockLocalAddr { + if mmLocalAddr.mock.funcLocalAddr != nil { + mmLocalAddr.mock.t.Fatalf("ConnMock.LocalAddr mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockLocalAddrExpectation{} + if mmLocalAddr.defaultExpectation == nil { + mmLocalAddr.defaultExpectation = &ConnMockLocalAddrExpectation{} } - return m + return mmLocalAddr +} + +// Inspect accepts an inspector function that has same arguments as the Conn.LocalAddr +func (mmLocalAddr *mConnMockLocalAddr) Inspect(f func()) *mConnMockLocalAddr { + if mmLocalAddr.mock.inspectFuncLocalAddr != nil { + mmLocalAddr.mock.t.Fatalf("Inspect function is already set for ConnMock.LocalAddr") + } + + mmLocalAddr.mock.inspectFuncLocalAddr = f + + return mmLocalAddr } // Return sets up results that will be returned by Conn.LocalAddr -func (m *mConnMockLocalAddr) Return(a1 net.Addr) *ConnMock { - if m.mock.funcLocalAddr != nil { - m.mock.t.Fatalf("ConnMock.LocalAddr mock is already set by Set") +func (mmLocalAddr *mConnMockLocalAddr) Return(a1 mm_net.Addr) *ConnMock { + if mmLocalAddr.mock.funcLocalAddr != nil { + mmLocalAddr.mock.t.Fatalf("ConnMock.LocalAddr mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockLocalAddrExpectation{mock: m.mock} + if mmLocalAddr.defaultExpectation == nil { + mmLocalAddr.defaultExpectation = &ConnMockLocalAddrExpectation{mock: mmLocalAddr.mock} } - m.defaultExpectation.results = &ConnMockLocalAddrResults{a1} - return m.mock + mmLocalAddr.defaultExpectation.results = &ConnMockLocalAddrResults{a1} + return mmLocalAddr.mock } //Set uses given function f to mock the Conn.LocalAddr method -func (m *mConnMockLocalAddr) Set(f func() (a1 net.Addr)) *ConnMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Conn.LocalAddr method") +func (mmLocalAddr *mConnMockLocalAddr) Set(f func() (a1 mm_net.Addr)) *ConnMock { + if mmLocalAddr.defaultExpectation != nil { + mmLocalAddr.mock.t.Fatalf("Default expectation is already set for the Conn.LocalAddr method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Conn.LocalAddr method") + if len(mmLocalAddr.expectations) > 0 { + mmLocalAddr.mock.t.Fatalf("Some expectations are already set for the Conn.LocalAddr method") } - m.mock.funcLocalAddr = f - return m.mock + mmLocalAddr.mock.funcLocalAddr = f + return mmLocalAddr.mock } // LocalAddr implements net.Conn -func (m *ConnMock) LocalAddr() (a1 net.Addr) { - atomic.AddUint64(&m.beforeLocalAddrCounter, 1) - defer atomic.AddUint64(&m.afterLocalAddrCounter, 1) +func (mmLocalAddr *ConnMock) LocalAddr() (a1 mm_net.Addr) { + mm_atomic.AddUint64(&mmLocalAddr.beforeLocalAddrCounter, 1) + defer mm_atomic.AddUint64(&mmLocalAddr.afterLocalAddrCounter, 1) + + if mmLocalAddr.inspectFuncLocalAddr != nil { + mmLocalAddr.inspectFuncLocalAddr() + } - if m.LocalAddrMock.defaultExpectation != nil { - atomic.AddUint64(&m.LocalAddrMock.defaultExpectation.Counter, 1) + if mmLocalAddr.LocalAddrMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmLocalAddr.LocalAddrMock.defaultExpectation.Counter, 1) - results := m.LocalAddrMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the ConnMock.LocalAddr") + mm_results := mmLocalAddr.LocalAddrMock.defaultExpectation.results + if mm_results == nil { + mmLocalAddr.t.Fatal("No results are set for the ConnMock.LocalAddr") } - return (*results).a1 + return (*mm_results).a1 } - if m.funcLocalAddr != nil { - return m.funcLocalAddr() + if mmLocalAddr.funcLocalAddr != nil { + return mmLocalAddr.funcLocalAddr() } - m.t.Fatalf("Unexpected call to ConnMock.LocalAddr.") + mmLocalAddr.t.Fatalf("Unexpected call to ConnMock.LocalAddr.") return } // LocalAddrAfterCounter returns a count of finished ConnMock.LocalAddr invocations -func (m *ConnMock) LocalAddrAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterLocalAddrCounter) +func (mmLocalAddr *ConnMock) LocalAddrAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmLocalAddr.afterLocalAddrCounter) } // LocalAddrBeforeCounter returns a count of ConnMock.LocalAddr invocations -func (m *ConnMock) LocalAddrBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeLocalAddrCounter) +func (mmLocalAddr *ConnMock) LocalAddrBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmLocalAddr.beforeLocalAddrCounter) } // MinimockLocalAddrDone returns true if the count of the LocalAddr invocations corresponds // the number of defined expectations func (m *ConnMock) MinimockLocalAddrDone() bool { for _, e := range m.LocalAddrMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.LocalAddrMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterLocalAddrCounter) < 1 { + if m.LocalAddrMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterLocalAddrCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcLocalAddr != nil && atomic.LoadUint64(&m.afterLocalAddrCounter) < 1 { + if m.funcLocalAddr != nil && mm_atomic.LoadUint64(&m.afterLocalAddrCounter) < 1 { return false } return true @@ -317,17 +369,17 @@ func (m *ConnMock) MinimockLocalAddrDone() bool { // MinimockLocalAddrInspect logs each unmet expectation func (m *ConnMock) MinimockLocalAddrInspect() { for _, e := range m.LocalAddrMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Error("Expected call to ConnMock.LocalAddr") } } // if default expectation was set then invocations count should be greater than zero - if m.LocalAddrMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterLocalAddrCounter) < 1 { + if m.LocalAddrMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterLocalAddrCounter) < 1 { m.t.Error("Expected call to ConnMock.LocalAddr") } // if func was set then invocations count should be greater than zero - if m.funcLocalAddr != nil && atomic.LoadUint64(&m.afterLocalAddrCounter) < 1 { + if m.funcLocalAddr != nil && mm_atomic.LoadUint64(&m.afterLocalAddrCounter) < 1 { m.t.Error("Expected call to ConnMock.LocalAddr") } } @@ -336,6 +388,9 @@ type mConnMockRead struct { mock *ConnMock defaultExpectation *ConnMockReadExpectation expectations []*ConnMockReadExpectation + + callArgs []*ConnMockReadParams + mutex sync.RWMutex } // ConnMockReadExpectation specifies expectation struct of the Conn.Read @@ -358,64 +413,75 @@ type ConnMockReadResults struct { } // Expect sets up expected params for Conn.Read -func (m *mConnMockRead) Expect(b []byte) *mConnMockRead { - if m.mock.funcRead != nil { - m.mock.t.Fatalf("ConnMock.Read mock is already set by Set") +func (mmRead *mConnMockRead) Expect(b []byte) *mConnMockRead { + if mmRead.mock.funcRead != nil { + mmRead.mock.t.Fatalf("ConnMock.Read mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockReadExpectation{} + if mmRead.defaultExpectation == nil { + mmRead.defaultExpectation = &ConnMockReadExpectation{} } - m.defaultExpectation.params = &ConnMockReadParams{b} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmRead.defaultExpectation.params = &ConnMockReadParams{b} + for _, e := range mmRead.expectations { + if minimock.Equal(e.params, mmRead.defaultExpectation.params) { + mmRead.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmRead.defaultExpectation.params) } } - return m + return mmRead +} + +// Inspect accepts an inspector function that has same arguments as the Conn.Read +func (mmRead *mConnMockRead) Inspect(f func(b []byte)) *mConnMockRead { + if mmRead.mock.inspectFuncRead != nil { + mmRead.mock.t.Fatalf("Inspect function is already set for ConnMock.Read") + } + + mmRead.mock.inspectFuncRead = f + + return mmRead } // Return sets up results that will be returned by Conn.Read -func (m *mConnMockRead) Return(n int, err error) *ConnMock { - if m.mock.funcRead != nil { - m.mock.t.Fatalf("ConnMock.Read mock is already set by Set") +func (mmRead *mConnMockRead) Return(n int, err error) *ConnMock { + if mmRead.mock.funcRead != nil { + mmRead.mock.t.Fatalf("ConnMock.Read mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockReadExpectation{mock: m.mock} + if mmRead.defaultExpectation == nil { + mmRead.defaultExpectation = &ConnMockReadExpectation{mock: mmRead.mock} } - m.defaultExpectation.results = &ConnMockReadResults{n, err} - return m.mock + mmRead.defaultExpectation.results = &ConnMockReadResults{n, err} + return mmRead.mock } //Set uses given function f to mock the Conn.Read method -func (m *mConnMockRead) Set(f func(b []byte) (n int, err error)) *ConnMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Conn.Read method") +func (mmRead *mConnMockRead) Set(f func(b []byte) (n int, err error)) *ConnMock { + if mmRead.defaultExpectation != nil { + mmRead.mock.t.Fatalf("Default expectation is already set for the Conn.Read method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Conn.Read method") + if len(mmRead.expectations) > 0 { + mmRead.mock.t.Fatalf("Some expectations are already set for the Conn.Read method") } - m.mock.funcRead = f - return m.mock + mmRead.mock.funcRead = f + return mmRead.mock } // When sets expectation for the Conn.Read which will trigger the result defined by the following // Then helper -func (m *mConnMockRead) When(b []byte) *ConnMockReadExpectation { - if m.mock.funcRead != nil { - m.mock.t.Fatalf("ConnMock.Read mock is already set by Set") +func (mmRead *mConnMockRead) When(b []byte) *ConnMockReadExpectation { + if mmRead.mock.funcRead != nil { + mmRead.mock.t.Fatalf("ConnMock.Read mock is already set by Set") } expectation := &ConnMockReadExpectation{ - mock: m.mock, + mock: mmRead.mock, params: &ConnMockReadParams{b}, } - m.expectations = append(m.expectations, expectation) + mmRead.expectations = append(mmRead.expectations, expectation) return expectation } @@ -426,63 +492,87 @@ func (e *ConnMockReadExpectation) Then(n int, err error) *ConnMock { } // Read implements net.Conn -func (m *ConnMock) Read(b []byte) (n int, err error) { - atomic.AddUint64(&m.beforeReadCounter, 1) - defer atomic.AddUint64(&m.afterReadCounter, 1) +func (mmRead *ConnMock) Read(b []byte) (n int, err error) { + mm_atomic.AddUint64(&mmRead.beforeReadCounter, 1) + defer mm_atomic.AddUint64(&mmRead.afterReadCounter, 1) - for _, e := range m.ReadMock.expectations { - if minimock.Equal(*e.params, ConnMockReadParams{b}) { - atomic.AddUint64(&e.Counter, 1) + if mmRead.inspectFuncRead != nil { + mmRead.inspectFuncRead(b) + } + + mm_params := &ConnMockReadParams{b} + + // Record call args + mmRead.ReadMock.mutex.Lock() + mmRead.ReadMock.callArgs = append(mmRead.ReadMock.callArgs, mm_params) + mmRead.ReadMock.mutex.Unlock() + + for _, e := range mmRead.ReadMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.n, e.results.err } } - if m.ReadMock.defaultExpectation != nil { - atomic.AddUint64(&m.ReadMock.defaultExpectation.Counter, 1) - want := m.ReadMock.defaultExpectation.params - got := ConnMockReadParams{b} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("ConnMock.Read got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmRead.ReadMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmRead.ReadMock.defaultExpectation.Counter, 1) + mm_want := mmRead.ReadMock.defaultExpectation.params + mm_got := ConnMockReadParams{b} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmRead.t.Errorf("ConnMock.Read got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.ReadMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the ConnMock.Read") + mm_results := mmRead.ReadMock.defaultExpectation.results + if mm_results == nil { + mmRead.t.Fatal("No results are set for the ConnMock.Read") } - return (*results).n, (*results).err + return (*mm_results).n, (*mm_results).err } - if m.funcRead != nil { - return m.funcRead(b) + if mmRead.funcRead != nil { + return mmRead.funcRead(b) } - m.t.Fatalf("Unexpected call to ConnMock.Read. %v", b) + mmRead.t.Fatalf("Unexpected call to ConnMock.Read. %v", b) return } // ReadAfterCounter returns a count of finished ConnMock.Read invocations -func (m *ConnMock) ReadAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterReadCounter) +func (mmRead *ConnMock) ReadAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmRead.afterReadCounter) } // ReadBeforeCounter returns a count of ConnMock.Read invocations -func (m *ConnMock) ReadBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeReadCounter) +func (mmRead *ConnMock) ReadBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmRead.beforeReadCounter) +} + +// Calls returns a list of arguments used in each call to ConnMock.Read. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmRead *mConnMockRead) Calls() []*ConnMockReadParams { + mmRead.mutex.RLock() + + argCopy := make([]*ConnMockReadParams, len(mmRead.callArgs)) + copy(argCopy, mmRead.callArgs) + + mmRead.mutex.RUnlock() + + return argCopy } // MinimockReadDone returns true if the count of the Read invocations corresponds // the number of defined expectations func (m *ConnMock) MinimockReadDone() bool { for _, e := range m.ReadMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.ReadMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterReadCounter) < 1 { + if m.ReadMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterReadCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcRead != nil && atomic.LoadUint64(&m.afterReadCounter) < 1 { + if m.funcRead != nil && mm_atomic.LoadUint64(&m.afterReadCounter) < 1 { return false } return true @@ -491,17 +581,21 @@ func (m *ConnMock) MinimockReadDone() bool { // MinimockReadInspect logs each unmet expectation func (m *ConnMock) MinimockReadInspect() { for _, e := range m.ReadMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to ConnMock.Read with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.ReadMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterReadCounter) < 1 { - m.t.Errorf("Expected call to ConnMock.Read with params: %#v", *m.ReadMock.defaultExpectation.params) + if m.ReadMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterReadCounter) < 1 { + if m.ReadMock.defaultExpectation.params == nil { + m.t.Error("Expected call to ConnMock.Read") + } else { + m.t.Errorf("Expected call to ConnMock.Read with params: %#v", *m.ReadMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcRead != nil && atomic.LoadUint64(&m.afterReadCounter) < 1 { + if m.funcRead != nil && mm_atomic.LoadUint64(&m.afterReadCounter) < 1 { m.t.Error("Expected call to ConnMock.Read") } } @@ -522,95 +616,110 @@ type ConnMockRemoteAddrExpectation struct { // ConnMockRemoteAddrResults contains results of the Conn.RemoteAddr type ConnMockRemoteAddrResults struct { - a1 net.Addr + a1 mm_net.Addr } // Expect sets up expected params for Conn.RemoteAddr -func (m *mConnMockRemoteAddr) Expect() *mConnMockRemoteAddr { - if m.mock.funcRemoteAddr != nil { - m.mock.t.Fatalf("ConnMock.RemoteAddr mock is already set by Set") +func (mmRemoteAddr *mConnMockRemoteAddr) Expect() *mConnMockRemoteAddr { + if mmRemoteAddr.mock.funcRemoteAddr != nil { + mmRemoteAddr.mock.t.Fatalf("ConnMock.RemoteAddr mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockRemoteAddrExpectation{} + if mmRemoteAddr.defaultExpectation == nil { + mmRemoteAddr.defaultExpectation = &ConnMockRemoteAddrExpectation{} } - return m + return mmRemoteAddr +} + +// Inspect accepts an inspector function that has same arguments as the Conn.RemoteAddr +func (mmRemoteAddr *mConnMockRemoteAddr) Inspect(f func()) *mConnMockRemoteAddr { + if mmRemoteAddr.mock.inspectFuncRemoteAddr != nil { + mmRemoteAddr.mock.t.Fatalf("Inspect function is already set for ConnMock.RemoteAddr") + } + + mmRemoteAddr.mock.inspectFuncRemoteAddr = f + + return mmRemoteAddr } // Return sets up results that will be returned by Conn.RemoteAddr -func (m *mConnMockRemoteAddr) Return(a1 net.Addr) *ConnMock { - if m.mock.funcRemoteAddr != nil { - m.mock.t.Fatalf("ConnMock.RemoteAddr mock is already set by Set") +func (mmRemoteAddr *mConnMockRemoteAddr) Return(a1 mm_net.Addr) *ConnMock { + if mmRemoteAddr.mock.funcRemoteAddr != nil { + mmRemoteAddr.mock.t.Fatalf("ConnMock.RemoteAddr mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockRemoteAddrExpectation{mock: m.mock} + if mmRemoteAddr.defaultExpectation == nil { + mmRemoteAddr.defaultExpectation = &ConnMockRemoteAddrExpectation{mock: mmRemoteAddr.mock} } - m.defaultExpectation.results = &ConnMockRemoteAddrResults{a1} - return m.mock + mmRemoteAddr.defaultExpectation.results = &ConnMockRemoteAddrResults{a1} + return mmRemoteAddr.mock } //Set uses given function f to mock the Conn.RemoteAddr method -func (m *mConnMockRemoteAddr) Set(f func() (a1 net.Addr)) *ConnMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Conn.RemoteAddr method") +func (mmRemoteAddr *mConnMockRemoteAddr) Set(f func() (a1 mm_net.Addr)) *ConnMock { + if mmRemoteAddr.defaultExpectation != nil { + mmRemoteAddr.mock.t.Fatalf("Default expectation is already set for the Conn.RemoteAddr method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Conn.RemoteAddr method") + if len(mmRemoteAddr.expectations) > 0 { + mmRemoteAddr.mock.t.Fatalf("Some expectations are already set for the Conn.RemoteAddr method") } - m.mock.funcRemoteAddr = f - return m.mock + mmRemoteAddr.mock.funcRemoteAddr = f + return mmRemoteAddr.mock } // RemoteAddr implements net.Conn -func (m *ConnMock) RemoteAddr() (a1 net.Addr) { - atomic.AddUint64(&m.beforeRemoteAddrCounter, 1) - defer atomic.AddUint64(&m.afterRemoteAddrCounter, 1) +func (mmRemoteAddr *ConnMock) RemoteAddr() (a1 mm_net.Addr) { + mm_atomic.AddUint64(&mmRemoteAddr.beforeRemoteAddrCounter, 1) + defer mm_atomic.AddUint64(&mmRemoteAddr.afterRemoteAddrCounter, 1) + + if mmRemoteAddr.inspectFuncRemoteAddr != nil { + mmRemoteAddr.inspectFuncRemoteAddr() + } - if m.RemoteAddrMock.defaultExpectation != nil { - atomic.AddUint64(&m.RemoteAddrMock.defaultExpectation.Counter, 1) + if mmRemoteAddr.RemoteAddrMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmRemoteAddr.RemoteAddrMock.defaultExpectation.Counter, 1) - results := m.RemoteAddrMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the ConnMock.RemoteAddr") + mm_results := mmRemoteAddr.RemoteAddrMock.defaultExpectation.results + if mm_results == nil { + mmRemoteAddr.t.Fatal("No results are set for the ConnMock.RemoteAddr") } - return (*results).a1 + return (*mm_results).a1 } - if m.funcRemoteAddr != nil { - return m.funcRemoteAddr() + if mmRemoteAddr.funcRemoteAddr != nil { + return mmRemoteAddr.funcRemoteAddr() } - m.t.Fatalf("Unexpected call to ConnMock.RemoteAddr.") + mmRemoteAddr.t.Fatalf("Unexpected call to ConnMock.RemoteAddr.") return } // RemoteAddrAfterCounter returns a count of finished ConnMock.RemoteAddr invocations -func (m *ConnMock) RemoteAddrAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterRemoteAddrCounter) +func (mmRemoteAddr *ConnMock) RemoteAddrAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmRemoteAddr.afterRemoteAddrCounter) } // RemoteAddrBeforeCounter returns a count of ConnMock.RemoteAddr invocations -func (m *ConnMock) RemoteAddrBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeRemoteAddrCounter) +func (mmRemoteAddr *ConnMock) RemoteAddrBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmRemoteAddr.beforeRemoteAddrCounter) } // MinimockRemoteAddrDone returns true if the count of the RemoteAddr invocations corresponds // the number of defined expectations func (m *ConnMock) MinimockRemoteAddrDone() bool { for _, e := range m.RemoteAddrMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.RemoteAddrMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterRemoteAddrCounter) < 1 { + if m.RemoteAddrMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterRemoteAddrCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcRemoteAddr != nil && atomic.LoadUint64(&m.afterRemoteAddrCounter) < 1 { + if m.funcRemoteAddr != nil && mm_atomic.LoadUint64(&m.afterRemoteAddrCounter) < 1 { return false } return true @@ -619,17 +728,17 @@ func (m *ConnMock) MinimockRemoteAddrDone() bool { // MinimockRemoteAddrInspect logs each unmet expectation func (m *ConnMock) MinimockRemoteAddrInspect() { for _, e := range m.RemoteAddrMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Error("Expected call to ConnMock.RemoteAddr") } } // if default expectation was set then invocations count should be greater than zero - if m.RemoteAddrMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterRemoteAddrCounter) < 1 { + if m.RemoteAddrMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterRemoteAddrCounter) < 1 { m.t.Error("Expected call to ConnMock.RemoteAddr") } // if func was set then invocations count should be greater than zero - if m.funcRemoteAddr != nil && atomic.LoadUint64(&m.afterRemoteAddrCounter) < 1 { + if m.funcRemoteAddr != nil && mm_atomic.LoadUint64(&m.afterRemoteAddrCounter) < 1 { m.t.Error("Expected call to ConnMock.RemoteAddr") } } @@ -638,6 +747,9 @@ type mConnMockSetDeadline struct { mock *ConnMock defaultExpectation *ConnMockSetDeadlineExpectation expectations []*ConnMockSetDeadlineExpectation + + callArgs []*ConnMockSetDeadlineParams + mutex sync.RWMutex } // ConnMockSetDeadlineExpectation specifies expectation struct of the Conn.SetDeadline @@ -659,64 +771,75 @@ type ConnMockSetDeadlineResults struct { } // Expect sets up expected params for Conn.SetDeadline -func (m *mConnMockSetDeadline) Expect(t time.Time) *mConnMockSetDeadline { - if m.mock.funcSetDeadline != nil { - m.mock.t.Fatalf("ConnMock.SetDeadline mock is already set by Set") +func (mmSetDeadline *mConnMockSetDeadline) Expect(t time.Time) *mConnMockSetDeadline { + if mmSetDeadline.mock.funcSetDeadline != nil { + mmSetDeadline.mock.t.Fatalf("ConnMock.SetDeadline mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockSetDeadlineExpectation{} + if mmSetDeadline.defaultExpectation == nil { + mmSetDeadline.defaultExpectation = &ConnMockSetDeadlineExpectation{} } - m.defaultExpectation.params = &ConnMockSetDeadlineParams{t} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmSetDeadline.defaultExpectation.params = &ConnMockSetDeadlineParams{t} + for _, e := range mmSetDeadline.expectations { + if minimock.Equal(e.params, mmSetDeadline.defaultExpectation.params) { + mmSetDeadline.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmSetDeadline.defaultExpectation.params) } } - return m + return mmSetDeadline +} + +// Inspect accepts an inspector function that has same arguments as the Conn.SetDeadline +func (mmSetDeadline *mConnMockSetDeadline) Inspect(f func(t time.Time)) *mConnMockSetDeadline { + if mmSetDeadline.mock.inspectFuncSetDeadline != nil { + mmSetDeadline.mock.t.Fatalf("Inspect function is already set for ConnMock.SetDeadline") + } + + mmSetDeadline.mock.inspectFuncSetDeadline = f + + return mmSetDeadline } // Return sets up results that will be returned by Conn.SetDeadline -func (m *mConnMockSetDeadline) Return(err error) *ConnMock { - if m.mock.funcSetDeadline != nil { - m.mock.t.Fatalf("ConnMock.SetDeadline mock is already set by Set") +func (mmSetDeadline *mConnMockSetDeadline) Return(err error) *ConnMock { + if mmSetDeadline.mock.funcSetDeadline != nil { + mmSetDeadline.mock.t.Fatalf("ConnMock.SetDeadline mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockSetDeadlineExpectation{mock: m.mock} + if mmSetDeadline.defaultExpectation == nil { + mmSetDeadline.defaultExpectation = &ConnMockSetDeadlineExpectation{mock: mmSetDeadline.mock} } - m.defaultExpectation.results = &ConnMockSetDeadlineResults{err} - return m.mock + mmSetDeadline.defaultExpectation.results = &ConnMockSetDeadlineResults{err} + return mmSetDeadline.mock } //Set uses given function f to mock the Conn.SetDeadline method -func (m *mConnMockSetDeadline) Set(f func(t time.Time) (err error)) *ConnMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Conn.SetDeadline method") +func (mmSetDeadline *mConnMockSetDeadline) Set(f func(t time.Time) (err error)) *ConnMock { + if mmSetDeadline.defaultExpectation != nil { + mmSetDeadline.mock.t.Fatalf("Default expectation is already set for the Conn.SetDeadline method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Conn.SetDeadline method") + if len(mmSetDeadline.expectations) > 0 { + mmSetDeadline.mock.t.Fatalf("Some expectations are already set for the Conn.SetDeadline method") } - m.mock.funcSetDeadline = f - return m.mock + mmSetDeadline.mock.funcSetDeadline = f + return mmSetDeadline.mock } // When sets expectation for the Conn.SetDeadline which will trigger the result defined by the following // Then helper -func (m *mConnMockSetDeadline) When(t time.Time) *ConnMockSetDeadlineExpectation { - if m.mock.funcSetDeadline != nil { - m.mock.t.Fatalf("ConnMock.SetDeadline mock is already set by Set") +func (mmSetDeadline *mConnMockSetDeadline) When(t time.Time) *ConnMockSetDeadlineExpectation { + if mmSetDeadline.mock.funcSetDeadline != nil { + mmSetDeadline.mock.t.Fatalf("ConnMock.SetDeadline mock is already set by Set") } expectation := &ConnMockSetDeadlineExpectation{ - mock: m.mock, + mock: mmSetDeadline.mock, params: &ConnMockSetDeadlineParams{t}, } - m.expectations = append(m.expectations, expectation) + mmSetDeadline.expectations = append(mmSetDeadline.expectations, expectation) return expectation } @@ -727,63 +850,87 @@ func (e *ConnMockSetDeadlineExpectation) Then(err error) *ConnMock { } // SetDeadline implements net.Conn -func (m *ConnMock) SetDeadline(t time.Time) (err error) { - atomic.AddUint64(&m.beforeSetDeadlineCounter, 1) - defer atomic.AddUint64(&m.afterSetDeadlineCounter, 1) +func (mmSetDeadline *ConnMock) SetDeadline(t time.Time) (err error) { + mm_atomic.AddUint64(&mmSetDeadline.beforeSetDeadlineCounter, 1) + defer mm_atomic.AddUint64(&mmSetDeadline.afterSetDeadlineCounter, 1) - for _, e := range m.SetDeadlineMock.expectations { - if minimock.Equal(*e.params, ConnMockSetDeadlineParams{t}) { - atomic.AddUint64(&e.Counter, 1) + if mmSetDeadline.inspectFuncSetDeadline != nil { + mmSetDeadline.inspectFuncSetDeadline(t) + } + + mm_params := &ConnMockSetDeadlineParams{t} + + // Record call args + mmSetDeadline.SetDeadlineMock.mutex.Lock() + mmSetDeadline.SetDeadlineMock.callArgs = append(mmSetDeadline.SetDeadlineMock.callArgs, mm_params) + mmSetDeadline.SetDeadlineMock.mutex.Unlock() + + for _, e := range mmSetDeadline.SetDeadlineMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.err } } - if m.SetDeadlineMock.defaultExpectation != nil { - atomic.AddUint64(&m.SetDeadlineMock.defaultExpectation.Counter, 1) - want := m.SetDeadlineMock.defaultExpectation.params - got := ConnMockSetDeadlineParams{t} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("ConnMock.SetDeadline got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmSetDeadline.SetDeadlineMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmSetDeadline.SetDeadlineMock.defaultExpectation.Counter, 1) + mm_want := mmSetDeadline.SetDeadlineMock.defaultExpectation.params + mm_got := ConnMockSetDeadlineParams{t} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmSetDeadline.t.Errorf("ConnMock.SetDeadline got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.SetDeadlineMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the ConnMock.SetDeadline") + mm_results := mmSetDeadline.SetDeadlineMock.defaultExpectation.results + if mm_results == nil { + mmSetDeadline.t.Fatal("No results are set for the ConnMock.SetDeadline") } - return (*results).err + return (*mm_results).err } - if m.funcSetDeadline != nil { - return m.funcSetDeadline(t) + if mmSetDeadline.funcSetDeadline != nil { + return mmSetDeadline.funcSetDeadline(t) } - m.t.Fatalf("Unexpected call to ConnMock.SetDeadline. %v", t) + mmSetDeadline.t.Fatalf("Unexpected call to ConnMock.SetDeadline. %v", t) return } // SetDeadlineAfterCounter returns a count of finished ConnMock.SetDeadline invocations -func (m *ConnMock) SetDeadlineAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterSetDeadlineCounter) +func (mmSetDeadline *ConnMock) SetDeadlineAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmSetDeadline.afterSetDeadlineCounter) } // SetDeadlineBeforeCounter returns a count of ConnMock.SetDeadline invocations -func (m *ConnMock) SetDeadlineBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeSetDeadlineCounter) +func (mmSetDeadline *ConnMock) SetDeadlineBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmSetDeadline.beforeSetDeadlineCounter) +} + +// Calls returns a list of arguments used in each call to ConnMock.SetDeadline. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmSetDeadline *mConnMockSetDeadline) Calls() []*ConnMockSetDeadlineParams { + mmSetDeadline.mutex.RLock() + + argCopy := make([]*ConnMockSetDeadlineParams, len(mmSetDeadline.callArgs)) + copy(argCopy, mmSetDeadline.callArgs) + + mmSetDeadline.mutex.RUnlock() + + return argCopy } // MinimockSetDeadlineDone returns true if the count of the SetDeadline invocations corresponds // the number of defined expectations func (m *ConnMock) MinimockSetDeadlineDone() bool { for _, e := range m.SetDeadlineMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.SetDeadlineMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterSetDeadlineCounter) < 1 { + if m.SetDeadlineMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSetDeadlineCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcSetDeadline != nil && atomic.LoadUint64(&m.afterSetDeadlineCounter) < 1 { + if m.funcSetDeadline != nil && mm_atomic.LoadUint64(&m.afterSetDeadlineCounter) < 1 { return false } return true @@ -792,17 +939,21 @@ func (m *ConnMock) MinimockSetDeadlineDone() bool { // MinimockSetDeadlineInspect logs each unmet expectation func (m *ConnMock) MinimockSetDeadlineInspect() { for _, e := range m.SetDeadlineMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to ConnMock.SetDeadline with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.SetDeadlineMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterSetDeadlineCounter) < 1 { - m.t.Errorf("Expected call to ConnMock.SetDeadline with params: %#v", *m.SetDeadlineMock.defaultExpectation.params) + if m.SetDeadlineMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSetDeadlineCounter) < 1 { + if m.SetDeadlineMock.defaultExpectation.params == nil { + m.t.Error("Expected call to ConnMock.SetDeadline") + } else { + m.t.Errorf("Expected call to ConnMock.SetDeadline with params: %#v", *m.SetDeadlineMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcSetDeadline != nil && atomic.LoadUint64(&m.afterSetDeadlineCounter) < 1 { + if m.funcSetDeadline != nil && mm_atomic.LoadUint64(&m.afterSetDeadlineCounter) < 1 { m.t.Error("Expected call to ConnMock.SetDeadline") } } @@ -811,6 +962,9 @@ type mConnMockSetReadDeadline struct { mock *ConnMock defaultExpectation *ConnMockSetReadDeadlineExpectation expectations []*ConnMockSetReadDeadlineExpectation + + callArgs []*ConnMockSetReadDeadlineParams + mutex sync.RWMutex } // ConnMockSetReadDeadlineExpectation specifies expectation struct of the Conn.SetReadDeadline @@ -832,64 +986,75 @@ type ConnMockSetReadDeadlineResults struct { } // Expect sets up expected params for Conn.SetReadDeadline -func (m *mConnMockSetReadDeadline) Expect(t time.Time) *mConnMockSetReadDeadline { - if m.mock.funcSetReadDeadline != nil { - m.mock.t.Fatalf("ConnMock.SetReadDeadline mock is already set by Set") +func (mmSetReadDeadline *mConnMockSetReadDeadline) Expect(t time.Time) *mConnMockSetReadDeadline { + if mmSetReadDeadline.mock.funcSetReadDeadline != nil { + mmSetReadDeadline.mock.t.Fatalf("ConnMock.SetReadDeadline mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockSetReadDeadlineExpectation{} + if mmSetReadDeadline.defaultExpectation == nil { + mmSetReadDeadline.defaultExpectation = &ConnMockSetReadDeadlineExpectation{} } - m.defaultExpectation.params = &ConnMockSetReadDeadlineParams{t} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmSetReadDeadline.defaultExpectation.params = &ConnMockSetReadDeadlineParams{t} + for _, e := range mmSetReadDeadline.expectations { + if minimock.Equal(e.params, mmSetReadDeadline.defaultExpectation.params) { + mmSetReadDeadline.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmSetReadDeadline.defaultExpectation.params) } } - return m + return mmSetReadDeadline +} + +// Inspect accepts an inspector function that has same arguments as the Conn.SetReadDeadline +func (mmSetReadDeadline *mConnMockSetReadDeadline) Inspect(f func(t time.Time)) *mConnMockSetReadDeadline { + if mmSetReadDeadline.mock.inspectFuncSetReadDeadline != nil { + mmSetReadDeadline.mock.t.Fatalf("Inspect function is already set for ConnMock.SetReadDeadline") + } + + mmSetReadDeadline.mock.inspectFuncSetReadDeadline = f + + return mmSetReadDeadline } // Return sets up results that will be returned by Conn.SetReadDeadline -func (m *mConnMockSetReadDeadline) Return(err error) *ConnMock { - if m.mock.funcSetReadDeadline != nil { - m.mock.t.Fatalf("ConnMock.SetReadDeadline mock is already set by Set") +func (mmSetReadDeadline *mConnMockSetReadDeadline) Return(err error) *ConnMock { + if mmSetReadDeadline.mock.funcSetReadDeadline != nil { + mmSetReadDeadline.mock.t.Fatalf("ConnMock.SetReadDeadline mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockSetReadDeadlineExpectation{mock: m.mock} + if mmSetReadDeadline.defaultExpectation == nil { + mmSetReadDeadline.defaultExpectation = &ConnMockSetReadDeadlineExpectation{mock: mmSetReadDeadline.mock} } - m.defaultExpectation.results = &ConnMockSetReadDeadlineResults{err} - return m.mock + mmSetReadDeadline.defaultExpectation.results = &ConnMockSetReadDeadlineResults{err} + return mmSetReadDeadline.mock } //Set uses given function f to mock the Conn.SetReadDeadline method -func (m *mConnMockSetReadDeadline) Set(f func(t time.Time) (err error)) *ConnMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Conn.SetReadDeadline method") +func (mmSetReadDeadline *mConnMockSetReadDeadline) Set(f func(t time.Time) (err error)) *ConnMock { + if mmSetReadDeadline.defaultExpectation != nil { + mmSetReadDeadline.mock.t.Fatalf("Default expectation is already set for the Conn.SetReadDeadline method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Conn.SetReadDeadline method") + if len(mmSetReadDeadline.expectations) > 0 { + mmSetReadDeadline.mock.t.Fatalf("Some expectations are already set for the Conn.SetReadDeadline method") } - m.mock.funcSetReadDeadline = f - return m.mock + mmSetReadDeadline.mock.funcSetReadDeadline = f + return mmSetReadDeadline.mock } // When sets expectation for the Conn.SetReadDeadline which will trigger the result defined by the following // Then helper -func (m *mConnMockSetReadDeadline) When(t time.Time) *ConnMockSetReadDeadlineExpectation { - if m.mock.funcSetReadDeadline != nil { - m.mock.t.Fatalf("ConnMock.SetReadDeadline mock is already set by Set") +func (mmSetReadDeadline *mConnMockSetReadDeadline) When(t time.Time) *ConnMockSetReadDeadlineExpectation { + if mmSetReadDeadline.mock.funcSetReadDeadline != nil { + mmSetReadDeadline.mock.t.Fatalf("ConnMock.SetReadDeadline mock is already set by Set") } expectation := &ConnMockSetReadDeadlineExpectation{ - mock: m.mock, + mock: mmSetReadDeadline.mock, params: &ConnMockSetReadDeadlineParams{t}, } - m.expectations = append(m.expectations, expectation) + mmSetReadDeadline.expectations = append(mmSetReadDeadline.expectations, expectation) return expectation } @@ -900,63 +1065,87 @@ func (e *ConnMockSetReadDeadlineExpectation) Then(err error) *ConnMock { } // SetReadDeadline implements net.Conn -func (m *ConnMock) SetReadDeadline(t time.Time) (err error) { - atomic.AddUint64(&m.beforeSetReadDeadlineCounter, 1) - defer atomic.AddUint64(&m.afterSetReadDeadlineCounter, 1) +func (mmSetReadDeadline *ConnMock) SetReadDeadline(t time.Time) (err error) { + mm_atomic.AddUint64(&mmSetReadDeadline.beforeSetReadDeadlineCounter, 1) + defer mm_atomic.AddUint64(&mmSetReadDeadline.afterSetReadDeadlineCounter, 1) - for _, e := range m.SetReadDeadlineMock.expectations { - if minimock.Equal(*e.params, ConnMockSetReadDeadlineParams{t}) { - atomic.AddUint64(&e.Counter, 1) + if mmSetReadDeadline.inspectFuncSetReadDeadline != nil { + mmSetReadDeadline.inspectFuncSetReadDeadline(t) + } + + mm_params := &ConnMockSetReadDeadlineParams{t} + + // Record call args + mmSetReadDeadline.SetReadDeadlineMock.mutex.Lock() + mmSetReadDeadline.SetReadDeadlineMock.callArgs = append(mmSetReadDeadline.SetReadDeadlineMock.callArgs, mm_params) + mmSetReadDeadline.SetReadDeadlineMock.mutex.Unlock() + + for _, e := range mmSetReadDeadline.SetReadDeadlineMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.err } } - if m.SetReadDeadlineMock.defaultExpectation != nil { - atomic.AddUint64(&m.SetReadDeadlineMock.defaultExpectation.Counter, 1) - want := m.SetReadDeadlineMock.defaultExpectation.params - got := ConnMockSetReadDeadlineParams{t} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("ConnMock.SetReadDeadline got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmSetReadDeadline.SetReadDeadlineMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmSetReadDeadline.SetReadDeadlineMock.defaultExpectation.Counter, 1) + mm_want := mmSetReadDeadline.SetReadDeadlineMock.defaultExpectation.params + mm_got := ConnMockSetReadDeadlineParams{t} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmSetReadDeadline.t.Errorf("ConnMock.SetReadDeadline got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.SetReadDeadlineMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the ConnMock.SetReadDeadline") + mm_results := mmSetReadDeadline.SetReadDeadlineMock.defaultExpectation.results + if mm_results == nil { + mmSetReadDeadline.t.Fatal("No results are set for the ConnMock.SetReadDeadline") } - return (*results).err + return (*mm_results).err } - if m.funcSetReadDeadline != nil { - return m.funcSetReadDeadline(t) + if mmSetReadDeadline.funcSetReadDeadline != nil { + return mmSetReadDeadline.funcSetReadDeadline(t) } - m.t.Fatalf("Unexpected call to ConnMock.SetReadDeadline. %v", t) + mmSetReadDeadline.t.Fatalf("Unexpected call to ConnMock.SetReadDeadline. %v", t) return } // SetReadDeadlineAfterCounter returns a count of finished ConnMock.SetReadDeadline invocations -func (m *ConnMock) SetReadDeadlineAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterSetReadDeadlineCounter) +func (mmSetReadDeadline *ConnMock) SetReadDeadlineAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmSetReadDeadline.afterSetReadDeadlineCounter) } // SetReadDeadlineBeforeCounter returns a count of ConnMock.SetReadDeadline invocations -func (m *ConnMock) SetReadDeadlineBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeSetReadDeadlineCounter) +func (mmSetReadDeadline *ConnMock) SetReadDeadlineBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmSetReadDeadline.beforeSetReadDeadlineCounter) +} + +// Calls returns a list of arguments used in each call to ConnMock.SetReadDeadline. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmSetReadDeadline *mConnMockSetReadDeadline) Calls() []*ConnMockSetReadDeadlineParams { + mmSetReadDeadline.mutex.RLock() + + argCopy := make([]*ConnMockSetReadDeadlineParams, len(mmSetReadDeadline.callArgs)) + copy(argCopy, mmSetReadDeadline.callArgs) + + mmSetReadDeadline.mutex.RUnlock() + + return argCopy } // MinimockSetReadDeadlineDone returns true if the count of the SetReadDeadline invocations corresponds // the number of defined expectations func (m *ConnMock) MinimockSetReadDeadlineDone() bool { for _, e := range m.SetReadDeadlineMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.SetReadDeadlineMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterSetReadDeadlineCounter) < 1 { + if m.SetReadDeadlineMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSetReadDeadlineCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcSetReadDeadline != nil && atomic.LoadUint64(&m.afterSetReadDeadlineCounter) < 1 { + if m.funcSetReadDeadline != nil && mm_atomic.LoadUint64(&m.afterSetReadDeadlineCounter) < 1 { return false } return true @@ -965,17 +1154,21 @@ func (m *ConnMock) MinimockSetReadDeadlineDone() bool { // MinimockSetReadDeadlineInspect logs each unmet expectation func (m *ConnMock) MinimockSetReadDeadlineInspect() { for _, e := range m.SetReadDeadlineMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to ConnMock.SetReadDeadline with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.SetReadDeadlineMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterSetReadDeadlineCounter) < 1 { - m.t.Errorf("Expected call to ConnMock.SetReadDeadline with params: %#v", *m.SetReadDeadlineMock.defaultExpectation.params) + if m.SetReadDeadlineMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSetReadDeadlineCounter) < 1 { + if m.SetReadDeadlineMock.defaultExpectation.params == nil { + m.t.Error("Expected call to ConnMock.SetReadDeadline") + } else { + m.t.Errorf("Expected call to ConnMock.SetReadDeadline with params: %#v", *m.SetReadDeadlineMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcSetReadDeadline != nil && atomic.LoadUint64(&m.afterSetReadDeadlineCounter) < 1 { + if m.funcSetReadDeadline != nil && mm_atomic.LoadUint64(&m.afterSetReadDeadlineCounter) < 1 { m.t.Error("Expected call to ConnMock.SetReadDeadline") } } @@ -984,6 +1177,9 @@ type mConnMockSetWriteDeadline struct { mock *ConnMock defaultExpectation *ConnMockSetWriteDeadlineExpectation expectations []*ConnMockSetWriteDeadlineExpectation + + callArgs []*ConnMockSetWriteDeadlineParams + mutex sync.RWMutex } // ConnMockSetWriteDeadlineExpectation specifies expectation struct of the Conn.SetWriteDeadline @@ -1005,64 +1201,75 @@ type ConnMockSetWriteDeadlineResults struct { } // Expect sets up expected params for Conn.SetWriteDeadline -func (m *mConnMockSetWriteDeadline) Expect(t time.Time) *mConnMockSetWriteDeadline { - if m.mock.funcSetWriteDeadline != nil { - m.mock.t.Fatalf("ConnMock.SetWriteDeadline mock is already set by Set") +func (mmSetWriteDeadline *mConnMockSetWriteDeadline) Expect(t time.Time) *mConnMockSetWriteDeadline { + if mmSetWriteDeadline.mock.funcSetWriteDeadline != nil { + mmSetWriteDeadline.mock.t.Fatalf("ConnMock.SetWriteDeadline mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockSetWriteDeadlineExpectation{} + if mmSetWriteDeadline.defaultExpectation == nil { + mmSetWriteDeadline.defaultExpectation = &ConnMockSetWriteDeadlineExpectation{} } - m.defaultExpectation.params = &ConnMockSetWriteDeadlineParams{t} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmSetWriteDeadline.defaultExpectation.params = &ConnMockSetWriteDeadlineParams{t} + for _, e := range mmSetWriteDeadline.expectations { + if minimock.Equal(e.params, mmSetWriteDeadline.defaultExpectation.params) { + mmSetWriteDeadline.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmSetWriteDeadline.defaultExpectation.params) } } - return m + return mmSetWriteDeadline +} + +// Inspect accepts an inspector function that has same arguments as the Conn.SetWriteDeadline +func (mmSetWriteDeadline *mConnMockSetWriteDeadline) Inspect(f func(t time.Time)) *mConnMockSetWriteDeadline { + if mmSetWriteDeadline.mock.inspectFuncSetWriteDeadline != nil { + mmSetWriteDeadline.mock.t.Fatalf("Inspect function is already set for ConnMock.SetWriteDeadline") + } + + mmSetWriteDeadline.mock.inspectFuncSetWriteDeadline = f + + return mmSetWriteDeadline } // Return sets up results that will be returned by Conn.SetWriteDeadline -func (m *mConnMockSetWriteDeadline) Return(err error) *ConnMock { - if m.mock.funcSetWriteDeadline != nil { - m.mock.t.Fatalf("ConnMock.SetWriteDeadline mock is already set by Set") +func (mmSetWriteDeadline *mConnMockSetWriteDeadline) Return(err error) *ConnMock { + if mmSetWriteDeadline.mock.funcSetWriteDeadline != nil { + mmSetWriteDeadline.mock.t.Fatalf("ConnMock.SetWriteDeadline mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockSetWriteDeadlineExpectation{mock: m.mock} + if mmSetWriteDeadline.defaultExpectation == nil { + mmSetWriteDeadline.defaultExpectation = &ConnMockSetWriteDeadlineExpectation{mock: mmSetWriteDeadline.mock} } - m.defaultExpectation.results = &ConnMockSetWriteDeadlineResults{err} - return m.mock + mmSetWriteDeadline.defaultExpectation.results = &ConnMockSetWriteDeadlineResults{err} + return mmSetWriteDeadline.mock } //Set uses given function f to mock the Conn.SetWriteDeadline method -func (m *mConnMockSetWriteDeadline) Set(f func(t time.Time) (err error)) *ConnMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Conn.SetWriteDeadline method") +func (mmSetWriteDeadline *mConnMockSetWriteDeadline) Set(f func(t time.Time) (err error)) *ConnMock { + if mmSetWriteDeadline.defaultExpectation != nil { + mmSetWriteDeadline.mock.t.Fatalf("Default expectation is already set for the Conn.SetWriteDeadline method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Conn.SetWriteDeadline method") + if len(mmSetWriteDeadline.expectations) > 0 { + mmSetWriteDeadline.mock.t.Fatalf("Some expectations are already set for the Conn.SetWriteDeadline method") } - m.mock.funcSetWriteDeadline = f - return m.mock + mmSetWriteDeadline.mock.funcSetWriteDeadline = f + return mmSetWriteDeadline.mock } // When sets expectation for the Conn.SetWriteDeadline which will trigger the result defined by the following // Then helper -func (m *mConnMockSetWriteDeadline) When(t time.Time) *ConnMockSetWriteDeadlineExpectation { - if m.mock.funcSetWriteDeadline != nil { - m.mock.t.Fatalf("ConnMock.SetWriteDeadline mock is already set by Set") +func (mmSetWriteDeadline *mConnMockSetWriteDeadline) When(t time.Time) *ConnMockSetWriteDeadlineExpectation { + if mmSetWriteDeadline.mock.funcSetWriteDeadline != nil { + mmSetWriteDeadline.mock.t.Fatalf("ConnMock.SetWriteDeadline mock is already set by Set") } expectation := &ConnMockSetWriteDeadlineExpectation{ - mock: m.mock, + mock: mmSetWriteDeadline.mock, params: &ConnMockSetWriteDeadlineParams{t}, } - m.expectations = append(m.expectations, expectation) + mmSetWriteDeadline.expectations = append(mmSetWriteDeadline.expectations, expectation) return expectation } @@ -1073,63 +1280,87 @@ func (e *ConnMockSetWriteDeadlineExpectation) Then(err error) *ConnMock { } // SetWriteDeadline implements net.Conn -func (m *ConnMock) SetWriteDeadline(t time.Time) (err error) { - atomic.AddUint64(&m.beforeSetWriteDeadlineCounter, 1) - defer atomic.AddUint64(&m.afterSetWriteDeadlineCounter, 1) +func (mmSetWriteDeadline *ConnMock) SetWriteDeadline(t time.Time) (err error) { + mm_atomic.AddUint64(&mmSetWriteDeadline.beforeSetWriteDeadlineCounter, 1) + defer mm_atomic.AddUint64(&mmSetWriteDeadline.afterSetWriteDeadlineCounter, 1) - for _, e := range m.SetWriteDeadlineMock.expectations { - if minimock.Equal(*e.params, ConnMockSetWriteDeadlineParams{t}) { - atomic.AddUint64(&e.Counter, 1) + if mmSetWriteDeadline.inspectFuncSetWriteDeadline != nil { + mmSetWriteDeadline.inspectFuncSetWriteDeadline(t) + } + + mm_params := &ConnMockSetWriteDeadlineParams{t} + + // Record call args + mmSetWriteDeadline.SetWriteDeadlineMock.mutex.Lock() + mmSetWriteDeadline.SetWriteDeadlineMock.callArgs = append(mmSetWriteDeadline.SetWriteDeadlineMock.callArgs, mm_params) + mmSetWriteDeadline.SetWriteDeadlineMock.mutex.Unlock() + + for _, e := range mmSetWriteDeadline.SetWriteDeadlineMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.err } } - if m.SetWriteDeadlineMock.defaultExpectation != nil { - atomic.AddUint64(&m.SetWriteDeadlineMock.defaultExpectation.Counter, 1) - want := m.SetWriteDeadlineMock.defaultExpectation.params - got := ConnMockSetWriteDeadlineParams{t} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("ConnMock.SetWriteDeadline got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmSetWriteDeadline.SetWriteDeadlineMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmSetWriteDeadline.SetWriteDeadlineMock.defaultExpectation.Counter, 1) + mm_want := mmSetWriteDeadline.SetWriteDeadlineMock.defaultExpectation.params + mm_got := ConnMockSetWriteDeadlineParams{t} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmSetWriteDeadline.t.Errorf("ConnMock.SetWriteDeadline got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.SetWriteDeadlineMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the ConnMock.SetWriteDeadline") + mm_results := mmSetWriteDeadline.SetWriteDeadlineMock.defaultExpectation.results + if mm_results == nil { + mmSetWriteDeadline.t.Fatal("No results are set for the ConnMock.SetWriteDeadline") } - return (*results).err + return (*mm_results).err } - if m.funcSetWriteDeadline != nil { - return m.funcSetWriteDeadline(t) + if mmSetWriteDeadline.funcSetWriteDeadline != nil { + return mmSetWriteDeadline.funcSetWriteDeadline(t) } - m.t.Fatalf("Unexpected call to ConnMock.SetWriteDeadline. %v", t) + mmSetWriteDeadline.t.Fatalf("Unexpected call to ConnMock.SetWriteDeadline. %v", t) return } // SetWriteDeadlineAfterCounter returns a count of finished ConnMock.SetWriteDeadline invocations -func (m *ConnMock) SetWriteDeadlineAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterSetWriteDeadlineCounter) +func (mmSetWriteDeadline *ConnMock) SetWriteDeadlineAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmSetWriteDeadline.afterSetWriteDeadlineCounter) } // SetWriteDeadlineBeforeCounter returns a count of ConnMock.SetWriteDeadline invocations -func (m *ConnMock) SetWriteDeadlineBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeSetWriteDeadlineCounter) +func (mmSetWriteDeadline *ConnMock) SetWriteDeadlineBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmSetWriteDeadline.beforeSetWriteDeadlineCounter) +} + +// Calls returns a list of arguments used in each call to ConnMock.SetWriteDeadline. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmSetWriteDeadline *mConnMockSetWriteDeadline) Calls() []*ConnMockSetWriteDeadlineParams { + mmSetWriteDeadline.mutex.RLock() + + argCopy := make([]*ConnMockSetWriteDeadlineParams, len(mmSetWriteDeadline.callArgs)) + copy(argCopy, mmSetWriteDeadline.callArgs) + + mmSetWriteDeadline.mutex.RUnlock() + + return argCopy } // MinimockSetWriteDeadlineDone returns true if the count of the SetWriteDeadline invocations corresponds // the number of defined expectations func (m *ConnMock) MinimockSetWriteDeadlineDone() bool { for _, e := range m.SetWriteDeadlineMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.SetWriteDeadlineMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterSetWriteDeadlineCounter) < 1 { + if m.SetWriteDeadlineMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSetWriteDeadlineCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcSetWriteDeadline != nil && atomic.LoadUint64(&m.afterSetWriteDeadlineCounter) < 1 { + if m.funcSetWriteDeadline != nil && mm_atomic.LoadUint64(&m.afterSetWriteDeadlineCounter) < 1 { return false } return true @@ -1138,17 +1369,21 @@ func (m *ConnMock) MinimockSetWriteDeadlineDone() bool { // MinimockSetWriteDeadlineInspect logs each unmet expectation func (m *ConnMock) MinimockSetWriteDeadlineInspect() { for _, e := range m.SetWriteDeadlineMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to ConnMock.SetWriteDeadline with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.SetWriteDeadlineMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterSetWriteDeadlineCounter) < 1 { - m.t.Errorf("Expected call to ConnMock.SetWriteDeadline with params: %#v", *m.SetWriteDeadlineMock.defaultExpectation.params) + if m.SetWriteDeadlineMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSetWriteDeadlineCounter) < 1 { + if m.SetWriteDeadlineMock.defaultExpectation.params == nil { + m.t.Error("Expected call to ConnMock.SetWriteDeadline") + } else { + m.t.Errorf("Expected call to ConnMock.SetWriteDeadline with params: %#v", *m.SetWriteDeadlineMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcSetWriteDeadline != nil && atomic.LoadUint64(&m.afterSetWriteDeadlineCounter) < 1 { + if m.funcSetWriteDeadline != nil && mm_atomic.LoadUint64(&m.afterSetWriteDeadlineCounter) < 1 { m.t.Error("Expected call to ConnMock.SetWriteDeadline") } } @@ -1157,6 +1392,9 @@ type mConnMockWrite struct { mock *ConnMock defaultExpectation *ConnMockWriteExpectation expectations []*ConnMockWriteExpectation + + callArgs []*ConnMockWriteParams + mutex sync.RWMutex } // ConnMockWriteExpectation specifies expectation struct of the Conn.Write @@ -1179,64 +1417,75 @@ type ConnMockWriteResults struct { } // Expect sets up expected params for Conn.Write -func (m *mConnMockWrite) Expect(b []byte) *mConnMockWrite { - if m.mock.funcWrite != nil { - m.mock.t.Fatalf("ConnMock.Write mock is already set by Set") +func (mmWrite *mConnMockWrite) Expect(b []byte) *mConnMockWrite { + if mmWrite.mock.funcWrite != nil { + mmWrite.mock.t.Fatalf("ConnMock.Write mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockWriteExpectation{} + if mmWrite.defaultExpectation == nil { + mmWrite.defaultExpectation = &ConnMockWriteExpectation{} } - m.defaultExpectation.params = &ConnMockWriteParams{b} - for _, e := range m.expectations { - if minimock.Equal(e.params, m.defaultExpectation.params) { - m.mock.t.Fatalf("Expectation set by When has same params: %#v", *m.defaultExpectation.params) + mmWrite.defaultExpectation.params = &ConnMockWriteParams{b} + for _, e := range mmWrite.expectations { + if minimock.Equal(e.params, mmWrite.defaultExpectation.params) { + mmWrite.mock.t.Fatalf("Expectation set by When has same params: %#v", *mmWrite.defaultExpectation.params) } } - return m + return mmWrite +} + +// Inspect accepts an inspector function that has same arguments as the Conn.Write +func (mmWrite *mConnMockWrite) Inspect(f func(b []byte)) *mConnMockWrite { + if mmWrite.mock.inspectFuncWrite != nil { + mmWrite.mock.t.Fatalf("Inspect function is already set for ConnMock.Write") + } + + mmWrite.mock.inspectFuncWrite = f + + return mmWrite } // Return sets up results that will be returned by Conn.Write -func (m *mConnMockWrite) Return(n int, err error) *ConnMock { - if m.mock.funcWrite != nil { - m.mock.t.Fatalf("ConnMock.Write mock is already set by Set") +func (mmWrite *mConnMockWrite) Return(n int, err error) *ConnMock { + if mmWrite.mock.funcWrite != nil { + mmWrite.mock.t.Fatalf("ConnMock.Write mock is already set by Set") } - if m.defaultExpectation == nil { - m.defaultExpectation = &ConnMockWriteExpectation{mock: m.mock} + if mmWrite.defaultExpectation == nil { + mmWrite.defaultExpectation = &ConnMockWriteExpectation{mock: mmWrite.mock} } - m.defaultExpectation.results = &ConnMockWriteResults{n, err} - return m.mock + mmWrite.defaultExpectation.results = &ConnMockWriteResults{n, err} + return mmWrite.mock } //Set uses given function f to mock the Conn.Write method -func (m *mConnMockWrite) Set(f func(b []byte) (n int, err error)) *ConnMock { - if m.defaultExpectation != nil { - m.mock.t.Fatalf("Default expectation is already set for the Conn.Write method") +func (mmWrite *mConnMockWrite) Set(f func(b []byte) (n int, err error)) *ConnMock { + if mmWrite.defaultExpectation != nil { + mmWrite.mock.t.Fatalf("Default expectation is already set for the Conn.Write method") } - if len(m.expectations) > 0 { - m.mock.t.Fatalf("Some expectations are already set for the Conn.Write method") + if len(mmWrite.expectations) > 0 { + mmWrite.mock.t.Fatalf("Some expectations are already set for the Conn.Write method") } - m.mock.funcWrite = f - return m.mock + mmWrite.mock.funcWrite = f + return mmWrite.mock } // When sets expectation for the Conn.Write which will trigger the result defined by the following // Then helper -func (m *mConnMockWrite) When(b []byte) *ConnMockWriteExpectation { - if m.mock.funcWrite != nil { - m.mock.t.Fatalf("ConnMock.Write mock is already set by Set") +func (mmWrite *mConnMockWrite) When(b []byte) *ConnMockWriteExpectation { + if mmWrite.mock.funcWrite != nil { + mmWrite.mock.t.Fatalf("ConnMock.Write mock is already set by Set") } expectation := &ConnMockWriteExpectation{ - mock: m.mock, + mock: mmWrite.mock, params: &ConnMockWriteParams{b}, } - m.expectations = append(m.expectations, expectation) + mmWrite.expectations = append(mmWrite.expectations, expectation) return expectation } @@ -1247,63 +1496,87 @@ func (e *ConnMockWriteExpectation) Then(n int, err error) *ConnMock { } // Write implements net.Conn -func (m *ConnMock) Write(b []byte) (n int, err error) { - atomic.AddUint64(&m.beforeWriteCounter, 1) - defer atomic.AddUint64(&m.afterWriteCounter, 1) +func (mmWrite *ConnMock) Write(b []byte) (n int, err error) { + mm_atomic.AddUint64(&mmWrite.beforeWriteCounter, 1) + defer mm_atomic.AddUint64(&mmWrite.afterWriteCounter, 1) - for _, e := range m.WriteMock.expectations { - if minimock.Equal(*e.params, ConnMockWriteParams{b}) { - atomic.AddUint64(&e.Counter, 1) + if mmWrite.inspectFuncWrite != nil { + mmWrite.inspectFuncWrite(b) + } + + mm_params := &ConnMockWriteParams{b} + + // Record call args + mmWrite.WriteMock.mutex.Lock() + mmWrite.WriteMock.callArgs = append(mmWrite.WriteMock.callArgs, mm_params) + mmWrite.WriteMock.mutex.Unlock() + + for _, e := range mmWrite.WriteMock.expectations { + if minimock.Equal(e.params, mm_params) { + mm_atomic.AddUint64(&e.Counter, 1) return e.results.n, e.results.err } } - if m.WriteMock.defaultExpectation != nil { - atomic.AddUint64(&m.WriteMock.defaultExpectation.Counter, 1) - want := m.WriteMock.defaultExpectation.params - got := ConnMockWriteParams{b} - if want != nil && !minimock.Equal(*want, got) { - m.t.Errorf("ConnMock.Write got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got)) + if mmWrite.WriteMock.defaultExpectation != nil { + mm_atomic.AddUint64(&mmWrite.WriteMock.defaultExpectation.Counter, 1) + mm_want := mmWrite.WriteMock.defaultExpectation.params + mm_got := ConnMockWriteParams{b} + if mm_want != nil && !minimock.Equal(*mm_want, mm_got) { + mmWrite.t.Errorf("ConnMock.Write got unexpected parameters, want: %#v, got: %#v%s\n", *mm_want, mm_got, minimock.Diff(*mm_want, mm_got)) } - results := m.WriteMock.defaultExpectation.results - if results == nil { - m.t.Fatal("No results are set for the ConnMock.Write") + mm_results := mmWrite.WriteMock.defaultExpectation.results + if mm_results == nil { + mmWrite.t.Fatal("No results are set for the ConnMock.Write") } - return (*results).n, (*results).err + return (*mm_results).n, (*mm_results).err } - if m.funcWrite != nil { - return m.funcWrite(b) + if mmWrite.funcWrite != nil { + return mmWrite.funcWrite(b) } - m.t.Fatalf("Unexpected call to ConnMock.Write. %v", b) + mmWrite.t.Fatalf("Unexpected call to ConnMock.Write. %v", b) return } // WriteAfterCounter returns a count of finished ConnMock.Write invocations -func (m *ConnMock) WriteAfterCounter() uint64 { - return atomic.LoadUint64(&m.afterWriteCounter) +func (mmWrite *ConnMock) WriteAfterCounter() uint64 { + return mm_atomic.LoadUint64(&mmWrite.afterWriteCounter) } // WriteBeforeCounter returns a count of ConnMock.Write invocations -func (m *ConnMock) WriteBeforeCounter() uint64 { - return atomic.LoadUint64(&m.beforeWriteCounter) +func (mmWrite *ConnMock) WriteBeforeCounter() uint64 { + return mm_atomic.LoadUint64(&mmWrite.beforeWriteCounter) +} + +// Calls returns a list of arguments used in each call to ConnMock.Write. +// The list is in the same order as the calls were made (i.e. recent calls have a higher index) +func (mmWrite *mConnMockWrite) Calls() []*ConnMockWriteParams { + mmWrite.mutex.RLock() + + argCopy := make([]*ConnMockWriteParams, len(mmWrite.callArgs)) + copy(argCopy, mmWrite.callArgs) + + mmWrite.mutex.RUnlock() + + return argCopy } // MinimockWriteDone returns true if the count of the Write invocations corresponds // the number of defined expectations func (m *ConnMock) MinimockWriteDone() bool { for _, e := range m.WriteMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { return false } } // if default expectation was set then invocations count should be greater than zero - if m.WriteMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterWriteCounter) < 1 { + if m.WriteMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterWriteCounter) < 1 { return false } // if func was set then invocations count should be greater than zero - if m.funcWrite != nil && atomic.LoadUint64(&m.afterWriteCounter) < 1 { + if m.funcWrite != nil && mm_atomic.LoadUint64(&m.afterWriteCounter) < 1 { return false } return true @@ -1312,17 +1585,21 @@ func (m *ConnMock) MinimockWriteDone() bool { // MinimockWriteInspect logs each unmet expectation func (m *ConnMock) MinimockWriteInspect() { for _, e := range m.WriteMock.expectations { - if atomic.LoadUint64(&e.Counter) < 1 { + if mm_atomic.LoadUint64(&e.Counter) < 1 { m.t.Errorf("Expected call to ConnMock.Write with params: %#v", *e.params) } } // if default expectation was set then invocations count should be greater than zero - if m.WriteMock.defaultExpectation != nil && atomic.LoadUint64(&m.afterWriteCounter) < 1 { - m.t.Errorf("Expected call to ConnMock.Write with params: %#v", *m.WriteMock.defaultExpectation.params) + if m.WriteMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterWriteCounter) < 1 { + if m.WriteMock.defaultExpectation.params == nil { + m.t.Error("Expected call to ConnMock.Write") + } else { + m.t.Errorf("Expected call to ConnMock.Write with params: %#v", *m.WriteMock.defaultExpectation.params) + } } // if func was set then invocations count should be greater than zero - if m.funcWrite != nil && atomic.LoadUint64(&m.afterWriteCounter) < 1 { + if m.funcWrite != nil && mm_atomic.LoadUint64(&m.afterWriteCounter) < 1 { m.t.Error("Expected call to ConnMock.Write") } } @@ -1350,8 +1627,8 @@ func (m *ConnMock) MinimockFinish() { } // MinimockWait waits for all mocked methods to be called the expected number of times -func (m *ConnMock) MinimockWait(timeout time.Duration) { - timeoutCh := time.After(timeout) +func (m *ConnMock) MinimockWait(timeout mm_time.Duration) { + timeoutCh := mm_time.After(timeout) for { if m.minimockDone() { return @@ -1360,7 +1637,7 @@ func (m *ConnMock) MinimockWait(timeout time.Duration) { case <-timeoutCh: m.MinimockFinish() return - case <-time.After(10 * time.Millisecond): + case <-mm_time.After(10 * mm_time.Millisecond): } } } From 2cfbd31f588f105dda5adcb6ea9cc1b7af091134 Mon Sep 17 00:00:00 2001 From: rekby Date: Sun, 24 Nov 2019 14:48:03 +0300 Subject: [PATCH 09/10] style --- internal/profiler/profiler_test.go | 5 +---- internal/profiler/secret_handler_test.go | 3 +++ 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/internal/profiler/profiler_test.go b/internal/profiler/profiler_test.go index 3ad8356c..4df89d10 100644 --- a/internal/profiler/profiler_test.go +++ b/internal/profiler/profiler_test.go @@ -11,8 +11,6 @@ import ( ) func TestNew(t *testing.T) { - const argName = "pass" - const pass = "qwe" td := testdeep.NewT(t) profiler := New(zap.NewNop(), Config{AllowedNetworks: []string{"127.0.0.1/32", "::1/128"}}) td.Len(profiler.secretHandler.AllowedNetworks, 2) @@ -21,8 +19,6 @@ func TestNew(t *testing.T) { } func TestProfiler_ServeHTTP(t *testing.T) { - const argName = "pass" - const pass = "qwe" td := testdeep.NewT(t) profiler := New(zap.NewNop(), Config{AllowedNetworks: []string{"127.0.0.1/32", "::1/128"}}) @@ -34,4 +30,5 @@ func TestProfiler_ServeHTTP(t *testing.T) { resp := respWriter.Result() td.Cmp(resp.StatusCode, http.StatusOK) td.True(strings.Contains(resp.Header.Get("content-type"), "text/html")) + _ = resp.Body.Close() } diff --git a/internal/profiler/secret_handler_test.go b/internal/profiler/secret_handler_test.go index f098a41a..5ab9b528 100644 --- a/internal/profiler/secret_handler_test.go +++ b/internal/profiler/secret_handler_test.go @@ -45,6 +45,7 @@ func TestSecretHandler_ServeHTTP(t *testing.T) { resp := respWriter.Result() td.Cmp(resp.StatusCode, http.StatusOK) td.True(nextCalled) + _ = resp.Body.Close() nextCalled = false respWriter = httptest.NewRecorder() @@ -56,6 +57,7 @@ func TestSecretHandler_ServeHTTP(t *testing.T) { td.Cmp(resp.StatusCode, http.StatusForbidden) td.False(nextCalled) nextCalled = false + _ = resp.Body.Close() nextCalled = false respWriter = httptest.NewRecorder() @@ -67,4 +69,5 @@ func TestSecretHandler_ServeHTTP(t *testing.T) { td.Cmp(resp.StatusCode, http.StatusInternalServerError) td.False(nextCalled) nextCalled = false + _ = resp.Body.Close() } From a81d0f1dcfaae8dc81fffbe2df6c174f1190cecc Mon Sep 17 00:00:00 2001 From: rekby Date: Sun, 24 Nov 2019 14:55:50 +0300 Subject: [PATCH 10/10] update vendor --- .../miekg/dns/duplicate_generate.go | 144 --- vendor/github.com/miekg/dns/msg_generate.go | 328 ------ vendor/github.com/miekg/dns/types_generate.go | 285 ----- vendor/golang.org/x/net/internal/iana/gen.go | 383 ------- .../x/net/internal/socket/defs_aix.go | 38 - .../x/net/internal/socket/defs_darwin.go | 36 - .../x/net/internal/socket/defs_dragonfly.go | 36 - .../x/net/internal/socket/defs_freebsd.go | 36 - .../x/net/internal/socket/defs_linux.go | 40 - .../x/net/internal/socket/defs_netbsd.go | 38 - .../x/net/internal/socket/defs_openbsd.go | 36 - .../x/net/internal/socket/defs_solaris.go | 36 - vendor/golang.org/x/net/ipv4/defs_aix.go | 39 - vendor/golang.org/x/net/ipv4/defs_darwin.go | 77 -- .../golang.org/x/net/ipv4/defs_dragonfly.go | 38 - vendor/golang.org/x/net/ipv4/defs_freebsd.go | 75 -- vendor/golang.org/x/net/ipv4/defs_linux.go | 122 --- vendor/golang.org/x/net/ipv4/defs_netbsd.go | 37 - vendor/golang.org/x/net/ipv4/defs_openbsd.go | 37 - vendor/golang.org/x/net/ipv4/defs_solaris.go | 84 -- vendor/golang.org/x/net/ipv4/gen.go | 199 ---- vendor/golang.org/x/net/ipv6/defs_aix.go | 82 -- vendor/golang.org/x/net/ipv6/defs_darwin.go | 112 -- .../golang.org/x/net/ipv6/defs_dragonfly.go | 82 -- vendor/golang.org/x/net/ipv6/defs_freebsd.go | 105 -- vendor/golang.org/x/net/ipv6/defs_linux.go | 147 --- vendor/golang.org/x/net/ipv6/defs_netbsd.go | 80 -- vendor/golang.org/x/net/ipv6/defs_openbsd.go | 89 -- vendor/golang.org/x/net/ipv6/defs_solaris.go | 114 -- vendor/golang.org/x/net/ipv6/gen.go | 199 ---- vendor/golang.org/x/sys/unix/mkasm_darwin.go | 61 -- vendor/golang.org/x/sys/unix/mkpost.go | 122 --- vendor/golang.org/x/sys/unix/mksyscall.go | 407 -------- .../x/sys/unix/mksyscall_aix_ppc.go | 415 -------- .../x/sys/unix/mksyscall_aix_ppc64.go | 614 ----------- .../x/sys/unix/mksyscall_solaris.go | 335 ------ .../golang.org/x/sys/unix/mksysctl_openbsd.go | 355 ------- vendor/golang.org/x/sys/unix/mksysnum.go | 190 ---- vendor/golang.org/x/sys/unix/types_aix.go | 237 ----- vendor/golang.org/x/sys/unix/types_darwin.go | 283 ----- .../golang.org/x/sys/unix/types_dragonfly.go | 263 ----- vendor/golang.org/x/sys/unix/types_freebsd.go | 400 ------- vendor/golang.org/x/sys/unix/types_netbsd.go | 290 ------ vendor/golang.org/x/sys/unix/types_openbsd.go | 283 ----- vendor/golang.org/x/sys/unix/types_solaris.go | 266 ----- vendor/golang.org/x/text/unicode/bidi/gen.go | 133 --- .../x/text/unicode/bidi/gen_ranges.go | 57 - .../x/text/unicode/bidi/gen_trieval.go | 64 -- .../x/text/unicode/norm/maketables.go | 986 ------------------ .../golang.org/x/text/unicode/norm/triegen.go | 117 --- vendor/modules.txt | 14 +- 51 files changed, 7 insertions(+), 9039 deletions(-) delete mode 100644 vendor/github.com/miekg/dns/duplicate_generate.go delete mode 100644 vendor/github.com/miekg/dns/msg_generate.go delete mode 100644 vendor/github.com/miekg/dns/types_generate.go delete mode 100644 vendor/golang.org/x/net/internal/iana/gen.go delete mode 100644 vendor/golang.org/x/net/internal/socket/defs_aix.go delete mode 100644 vendor/golang.org/x/net/internal/socket/defs_darwin.go delete mode 100644 vendor/golang.org/x/net/internal/socket/defs_dragonfly.go delete mode 100644 vendor/golang.org/x/net/internal/socket/defs_freebsd.go delete mode 100644 vendor/golang.org/x/net/internal/socket/defs_linux.go delete mode 100644 vendor/golang.org/x/net/internal/socket/defs_netbsd.go delete mode 100644 vendor/golang.org/x/net/internal/socket/defs_openbsd.go delete mode 100644 vendor/golang.org/x/net/internal/socket/defs_solaris.go delete mode 100644 vendor/golang.org/x/net/ipv4/defs_aix.go delete mode 100644 vendor/golang.org/x/net/ipv4/defs_darwin.go delete mode 100644 vendor/golang.org/x/net/ipv4/defs_dragonfly.go delete mode 100644 vendor/golang.org/x/net/ipv4/defs_freebsd.go delete mode 100644 vendor/golang.org/x/net/ipv4/defs_linux.go delete mode 100644 vendor/golang.org/x/net/ipv4/defs_netbsd.go delete mode 100644 vendor/golang.org/x/net/ipv4/defs_openbsd.go delete mode 100644 vendor/golang.org/x/net/ipv4/defs_solaris.go delete mode 100644 vendor/golang.org/x/net/ipv4/gen.go delete mode 100644 vendor/golang.org/x/net/ipv6/defs_aix.go delete mode 100644 vendor/golang.org/x/net/ipv6/defs_darwin.go delete mode 100644 vendor/golang.org/x/net/ipv6/defs_dragonfly.go delete mode 100644 vendor/golang.org/x/net/ipv6/defs_freebsd.go delete mode 100644 vendor/golang.org/x/net/ipv6/defs_linux.go delete mode 100644 vendor/golang.org/x/net/ipv6/defs_netbsd.go delete mode 100644 vendor/golang.org/x/net/ipv6/defs_openbsd.go delete mode 100644 vendor/golang.org/x/net/ipv6/defs_solaris.go delete mode 100644 vendor/golang.org/x/net/ipv6/gen.go delete mode 100644 vendor/golang.org/x/sys/unix/mkasm_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/mkpost.go delete mode 100644 vendor/golang.org/x/sys/unix/mksyscall.go delete mode 100644 vendor/golang.org/x/sys/unix/mksyscall_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/mksyscall_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/mksyscall_solaris.go delete mode 100644 vendor/golang.org/x/sys/unix/mksysctl_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/mksysnum.go delete mode 100644 vendor/golang.org/x/sys/unix/types_aix.go delete mode 100644 vendor/golang.org/x/sys/unix/types_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/types_dragonfly.go delete mode 100644 vendor/golang.org/x/sys/unix/types_freebsd.go delete mode 100644 vendor/golang.org/x/sys/unix/types_netbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/types_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/types_solaris.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/gen.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/gen_ranges.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/gen_trieval.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/maketables.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/triegen.go diff --git a/vendor/github.com/miekg/dns/duplicate_generate.go b/vendor/github.com/miekg/dns/duplicate_generate.go deleted file mode 100644 index 9b7a71b1..00000000 --- a/vendor/github.com/miekg/dns/duplicate_generate.go +++ /dev/null @@ -1,144 +0,0 @@ -//+build ignore - -// types_generate.go is meant to run with go generate. It will use -// go/{importer,types} to track down all the RR struct types. Then for each type -// it will generate conversion tables (TypeToRR and TypeToString) and banal -// methods (len, Header, copy) based on the struct tags. The generated source is -// written to ztypes.go, and is meant to be checked into git. -package main - -import ( - "bytes" - "fmt" - "go/format" - "go/importer" - "go/types" - "log" - "os" -) - -var packageHdr = ` -// Code generated by "go run duplicate_generate.go"; DO NOT EDIT. - -package dns - -` - -func getTypeStruct(t types.Type, scope *types.Scope) (*types.Struct, bool) { - st, ok := t.Underlying().(*types.Struct) - if !ok { - return nil, false - } - if st.Field(0).Type() == scope.Lookup("RR_Header").Type() { - return st, false - } - if st.Field(0).Anonymous() { - st, _ := getTypeStruct(st.Field(0).Type(), scope) - return st, true - } - return nil, false -} - -func main() { - // Import and type-check the package - pkg, err := importer.Default().Import("github.com/miekg/dns") - fatalIfErr(err) - scope := pkg.Scope() - - // Collect actual types (*X) - var namedTypes []string - for _, name := range scope.Names() { - o := scope.Lookup(name) - if o == nil || !o.Exported() { - continue - } - - if st, _ := getTypeStruct(o.Type(), scope); st == nil { - continue - } - - if name == "PrivateRR" || name == "OPT" { - continue - } - - namedTypes = append(namedTypes, o.Name()) - } - - b := &bytes.Buffer{} - b.WriteString(packageHdr) - - // Generate the duplicate check for each type. - fmt.Fprint(b, "// isDuplicate() functions\n\n") - for _, name := range namedTypes { - - o := scope.Lookup(name) - st, isEmbedded := getTypeStruct(o.Type(), scope) - if isEmbedded { - continue - } - fmt.Fprintf(b, "func (r1 *%s) isDuplicate(_r2 RR) bool {\n", name) - fmt.Fprintf(b, "r2, ok := _r2.(*%s)\n", name) - fmt.Fprint(b, "if !ok { return false }\n") - fmt.Fprint(b, "_ = r2\n") - for i := 1; i < st.NumFields(); i++ { - field := st.Field(i).Name() - o2 := func(s string) { fmt.Fprintf(b, s+"\n", field, field) } - o3 := func(s string) { fmt.Fprintf(b, s+"\n", field, field, field) } - - // For some reason, a and aaaa don't pop up as *types.Slice here (mostly like because the are - // *indirectly* defined as a slice in the net package). - if _, ok := st.Field(i).Type().(*types.Slice); ok { - o2("if len(r1.%s) != len(r2.%s) {\nreturn false\n}") - - if st.Tag(i) == `dns:"cdomain-name"` || st.Tag(i) == `dns:"domain-name"` { - o3(`for i := 0; i < len(r1.%s); i++ { - if !isDuplicateName(r1.%s[i], r2.%s[i]) { - return false - } - }`) - - continue - } - - o3(`for i := 0; i < len(r1.%s); i++ { - if r1.%s[i] != r2.%s[i] { - return false - } - }`) - - continue - } - - switch st.Tag(i) { - case `dns:"-"`: - // ignored - case `dns:"a"`, `dns:"aaaa"`: - o2("if !r1.%s.Equal(r2.%s) {\nreturn false\n}") - case `dns:"cdomain-name"`, `dns:"domain-name"`: - o2("if !isDuplicateName(r1.%s, r2.%s) {\nreturn false\n}") - default: - o2("if r1.%s != r2.%s {\nreturn false\n}") - } - } - fmt.Fprintf(b, "return true\n}\n\n") - } - - // gofmt - res, err := format.Source(b.Bytes()) - if err != nil { - b.WriteTo(os.Stderr) - log.Fatal(err) - } - - // write result - f, err := os.Create("zduplicate.go") - fatalIfErr(err) - defer f.Close() - f.Write(res) -} - -func fatalIfErr(err error) { - if err != nil { - log.Fatal(err) - } -} diff --git a/vendor/github.com/miekg/dns/msg_generate.go b/vendor/github.com/miekg/dns/msg_generate.go deleted file mode 100644 index 721a0fce..00000000 --- a/vendor/github.com/miekg/dns/msg_generate.go +++ /dev/null @@ -1,328 +0,0 @@ -//+build ignore - -// msg_generate.go is meant to run with go generate. It will use -// go/{importer,types} to track down all the RR struct types. Then for each type -// it will generate pack/unpack methods based on the struct tags. The generated source is -// written to zmsg.go, and is meant to be checked into git. -package main - -import ( - "bytes" - "fmt" - "go/format" - "go/importer" - "go/types" - "log" - "os" - "strings" -) - -var packageHdr = ` -// Code generated by "go run msg_generate.go"; DO NOT EDIT. - -package dns - -` - -// getTypeStruct will take a type and the package scope, and return the -// (innermost) struct if the type is considered a RR type (currently defined as -// those structs beginning with a RR_Header, could be redefined as implementing -// the RR interface). The bool return value indicates if embedded structs were -// resolved. -func getTypeStruct(t types.Type, scope *types.Scope) (*types.Struct, bool) { - st, ok := t.Underlying().(*types.Struct) - if !ok { - return nil, false - } - if st.Field(0).Type() == scope.Lookup("RR_Header").Type() { - return st, false - } - if st.Field(0).Anonymous() { - st, _ := getTypeStruct(st.Field(0).Type(), scope) - return st, true - } - return nil, false -} - -func main() { - // Import and type-check the package - pkg, err := importer.Default().Import("github.com/miekg/dns") - fatalIfErr(err) - scope := pkg.Scope() - - // Collect actual types (*X) - var namedTypes []string - for _, name := range scope.Names() { - o := scope.Lookup(name) - if o == nil || !o.Exported() { - continue - } - if st, _ := getTypeStruct(o.Type(), scope); st == nil { - continue - } - if name == "PrivateRR" { - continue - } - - // Check if corresponding TypeX exists - if scope.Lookup("Type"+o.Name()) == nil && o.Name() != "RFC3597" { - log.Fatalf("Constant Type%s does not exist.", o.Name()) - } - - namedTypes = append(namedTypes, o.Name()) - } - - b := &bytes.Buffer{} - b.WriteString(packageHdr) - - fmt.Fprint(b, "// pack*() functions\n\n") - for _, name := range namedTypes { - o := scope.Lookup(name) - st, _ := getTypeStruct(o.Type(), scope) - - fmt.Fprintf(b, "func (rr *%s) pack(msg []byte, off int, compression compressionMap, compress bool) (off1 int, err error) {\n", name) - for i := 1; i < st.NumFields(); i++ { - o := func(s string) { - fmt.Fprintf(b, s, st.Field(i).Name()) - fmt.Fprint(b, `if err != nil { -return off, err -} -`) - } - - if _, ok := st.Field(i).Type().(*types.Slice); ok { - switch st.Tag(i) { - case `dns:"-"`: // ignored - case `dns:"txt"`: - o("off, err = packStringTxt(rr.%s, msg, off)\n") - case `dns:"opt"`: - o("off, err = packDataOpt(rr.%s, msg, off)\n") - case `dns:"nsec"`: - o("off, err = packDataNsec(rr.%s, msg, off)\n") - case `dns:"domain-name"`: - o("off, err = packDataDomainNames(rr.%s, msg, off, compression, false)\n") - default: - log.Fatalln(name, st.Field(i).Name(), st.Tag(i)) - } - continue - } - - switch { - case st.Tag(i) == `dns:"-"`: // ignored - case st.Tag(i) == `dns:"cdomain-name"`: - o("off, err = packDomainName(rr.%s, msg, off, compression, compress)\n") - case st.Tag(i) == `dns:"domain-name"`: - o("off, err = packDomainName(rr.%s, msg, off, compression, false)\n") - case st.Tag(i) == `dns:"a"`: - o("off, err = packDataA(rr.%s, msg, off)\n") - case st.Tag(i) == `dns:"aaaa"`: - o("off, err = packDataAAAA(rr.%s, msg, off)\n") - case st.Tag(i) == `dns:"uint48"`: - o("off, err = packUint48(rr.%s, msg, off)\n") - case st.Tag(i) == `dns:"txt"`: - o("off, err = packString(rr.%s, msg, off)\n") - - case strings.HasPrefix(st.Tag(i), `dns:"size-base32`): // size-base32 can be packed just like base32 - fallthrough - case st.Tag(i) == `dns:"base32"`: - o("off, err = packStringBase32(rr.%s, msg, off)\n") - - case strings.HasPrefix(st.Tag(i), `dns:"size-base64`): // size-base64 can be packed just like base64 - fallthrough - case st.Tag(i) == `dns:"base64"`: - o("off, err = packStringBase64(rr.%s, msg, off)\n") - - case strings.HasPrefix(st.Tag(i), `dns:"size-hex:SaltLength`): - // directly write instead of using o() so we get the error check in the correct place - field := st.Field(i).Name() - fmt.Fprintf(b, `// Only pack salt if value is not "-", i.e. empty -if rr.%s != "-" { - off, err = packStringHex(rr.%s, msg, off) - if err != nil { - return off, err - } -} -`, field, field) - continue - case strings.HasPrefix(st.Tag(i), `dns:"size-hex`): // size-hex can be packed just like hex - fallthrough - case st.Tag(i) == `dns:"hex"`: - o("off, err = packStringHex(rr.%s, msg, off)\n") - case st.Tag(i) == `dns:"any"`: - o("off, err = packStringAny(rr.%s, msg, off)\n") - case st.Tag(i) == `dns:"octet"`: - o("off, err = packStringOctet(rr.%s, msg, off)\n") - case st.Tag(i) == "": - switch st.Field(i).Type().(*types.Basic).Kind() { - case types.Uint8: - o("off, err = packUint8(rr.%s, msg, off)\n") - case types.Uint16: - o("off, err = packUint16(rr.%s, msg, off)\n") - case types.Uint32: - o("off, err = packUint32(rr.%s, msg, off)\n") - case types.Uint64: - o("off, err = packUint64(rr.%s, msg, off)\n") - case types.String: - o("off, err = packString(rr.%s, msg, off)\n") - default: - log.Fatalln(name, st.Field(i).Name()) - } - default: - log.Fatalln(name, st.Field(i).Name(), st.Tag(i)) - } - } - fmt.Fprintln(b, "return off, nil }\n") - } - - fmt.Fprint(b, "// unpack*() functions\n\n") - for _, name := range namedTypes { - o := scope.Lookup(name) - st, _ := getTypeStruct(o.Type(), scope) - - fmt.Fprintf(b, "func (rr *%s) unpack(msg []byte, off int) (off1 int, err error) {\n", name) - fmt.Fprint(b, `rdStart := off -_ = rdStart - -`) - for i := 1; i < st.NumFields(); i++ { - o := func(s string) { - fmt.Fprintf(b, s, st.Field(i).Name()) - fmt.Fprint(b, `if err != nil { -return off, err -} -`) - } - - // size-* are special, because they reference a struct member we should use for the length. - if strings.HasPrefix(st.Tag(i), `dns:"size-`) { - structMember := structMember(st.Tag(i)) - structTag := structTag(st.Tag(i)) - switch structTag { - case "hex": - fmt.Fprintf(b, "rr.%s, off, err = unpackStringHex(msg, off, off + int(rr.%s))\n", st.Field(i).Name(), structMember) - case "base32": - fmt.Fprintf(b, "rr.%s, off, err = unpackStringBase32(msg, off, off + int(rr.%s))\n", st.Field(i).Name(), structMember) - case "base64": - fmt.Fprintf(b, "rr.%s, off, err = unpackStringBase64(msg, off, off + int(rr.%s))\n", st.Field(i).Name(), structMember) - default: - log.Fatalln(name, st.Field(i).Name(), st.Tag(i)) - } - fmt.Fprint(b, `if err != nil { -return off, err -} -`) - continue - } - - if _, ok := st.Field(i).Type().(*types.Slice); ok { - switch st.Tag(i) { - case `dns:"-"`: // ignored - case `dns:"txt"`: - o("rr.%s, off, err = unpackStringTxt(msg, off)\n") - case `dns:"opt"`: - o("rr.%s, off, err = unpackDataOpt(msg, off)\n") - case `dns:"nsec"`: - o("rr.%s, off, err = unpackDataNsec(msg, off)\n") - case `dns:"domain-name"`: - o("rr.%s, off, err = unpackDataDomainNames(msg, off, rdStart + int(rr.Hdr.Rdlength))\n") - default: - log.Fatalln(name, st.Field(i).Name(), st.Tag(i)) - } - continue - } - - switch st.Tag(i) { - case `dns:"-"`: // ignored - case `dns:"cdomain-name"`: - fallthrough - case `dns:"domain-name"`: - o("rr.%s, off, err = UnpackDomainName(msg, off)\n") - case `dns:"a"`: - o("rr.%s, off, err = unpackDataA(msg, off)\n") - case `dns:"aaaa"`: - o("rr.%s, off, err = unpackDataAAAA(msg, off)\n") - case `dns:"uint48"`: - o("rr.%s, off, err = unpackUint48(msg, off)\n") - case `dns:"txt"`: - o("rr.%s, off, err = unpackString(msg, off)\n") - case `dns:"base32"`: - o("rr.%s, off, err = unpackStringBase32(msg, off, rdStart + int(rr.Hdr.Rdlength))\n") - case `dns:"base64"`: - o("rr.%s, off, err = unpackStringBase64(msg, off, rdStart + int(rr.Hdr.Rdlength))\n") - case `dns:"hex"`: - o("rr.%s, off, err = unpackStringHex(msg, off, rdStart + int(rr.Hdr.Rdlength))\n") - case `dns:"any"`: - o("rr.%s, off, err = unpackStringAny(msg, off, rdStart + int(rr.Hdr.Rdlength))\n") - case `dns:"octet"`: - o("rr.%s, off, err = unpackStringOctet(msg, off)\n") - case "": - switch st.Field(i).Type().(*types.Basic).Kind() { - case types.Uint8: - o("rr.%s, off, err = unpackUint8(msg, off)\n") - case types.Uint16: - o("rr.%s, off, err = unpackUint16(msg, off)\n") - case types.Uint32: - o("rr.%s, off, err = unpackUint32(msg, off)\n") - case types.Uint64: - o("rr.%s, off, err = unpackUint64(msg, off)\n") - case types.String: - o("rr.%s, off, err = unpackString(msg, off)\n") - default: - log.Fatalln(name, st.Field(i).Name()) - } - default: - log.Fatalln(name, st.Field(i).Name(), st.Tag(i)) - } - // If we've hit len(msg) we return without error. - if i < st.NumFields()-1 { - fmt.Fprintf(b, `if off == len(msg) { -return off, nil - } -`) - } - } - fmt.Fprintf(b, "return off, nil }\n\n") - } - - // gofmt - res, err := format.Source(b.Bytes()) - if err != nil { - b.WriteTo(os.Stderr) - log.Fatal(err) - } - - // write result - f, err := os.Create("zmsg.go") - fatalIfErr(err) - defer f.Close() - f.Write(res) -} - -// structMember will take a tag like dns:"size-base32:SaltLength" and return the last part of this string. -func structMember(s string) string { - fields := strings.Split(s, ":") - if len(fields) == 0 { - return "" - } - f := fields[len(fields)-1] - // f should have a closing " - if len(f) > 1 { - return f[:len(f)-1] - } - return f -} - -// structTag will take a tag like dns:"size-base32:SaltLength" and return base32. -func structTag(s string) string { - fields := strings.Split(s, ":") - if len(fields) < 2 { - return "" - } - return fields[1][len("\"size-"):] -} - -func fatalIfErr(err error) { - if err != nil { - log.Fatal(err) - } -} diff --git a/vendor/github.com/miekg/dns/types_generate.go b/vendor/github.com/miekg/dns/types_generate.go deleted file mode 100644 index 8cda2a74..00000000 --- a/vendor/github.com/miekg/dns/types_generate.go +++ /dev/null @@ -1,285 +0,0 @@ -//+build ignore - -// types_generate.go is meant to run with go generate. It will use -// go/{importer,types} to track down all the RR struct types. Then for each type -// it will generate conversion tables (TypeToRR and TypeToString) and banal -// methods (len, Header, copy) based on the struct tags. The generated source is -// written to ztypes.go, and is meant to be checked into git. -package main - -import ( - "bytes" - "fmt" - "go/format" - "go/importer" - "go/types" - "log" - "os" - "strings" - "text/template" -) - -var skipLen = map[string]struct{}{ - "NSEC": {}, - "NSEC3": {}, - "OPT": {}, - "CSYNC": {}, -} - -var packageHdr = ` -// Code generated by "go run types_generate.go"; DO NOT EDIT. - -package dns - -import ( - "encoding/base64" - "net" -) - -` - -var TypeToRR = template.Must(template.New("TypeToRR").Parse(` -// TypeToRR is a map of constructors for each RR type. -var TypeToRR = map[uint16]func() RR{ -{{range .}}{{if ne . "RFC3597"}} Type{{.}}: func() RR { return new({{.}}) }, -{{end}}{{end}} } - -`)) - -var typeToString = template.Must(template.New("typeToString").Parse(` -// TypeToString is a map of strings for each RR type. -var TypeToString = map[uint16]string{ -{{range .}}{{if ne . "NSAPPTR"}} Type{{.}}: "{{.}}", -{{end}}{{end}} TypeNSAPPTR: "NSAP-PTR", -} - -`)) - -var headerFunc = template.Must(template.New("headerFunc").Parse(` -{{range .}} func (rr *{{.}}) Header() *RR_Header { return &rr.Hdr } -{{end}} - -`)) - -// getTypeStruct will take a type and the package scope, and return the -// (innermost) struct if the type is considered a RR type (currently defined as -// those structs beginning with a RR_Header, could be redefined as implementing -// the RR interface). The bool return value indicates if embedded structs were -// resolved. -func getTypeStruct(t types.Type, scope *types.Scope) (*types.Struct, bool) { - st, ok := t.Underlying().(*types.Struct) - if !ok { - return nil, false - } - if st.Field(0).Type() == scope.Lookup("RR_Header").Type() { - return st, false - } - if st.Field(0).Anonymous() { - st, _ := getTypeStruct(st.Field(0).Type(), scope) - return st, true - } - return nil, false -} - -func main() { - // Import and type-check the package - pkg, err := importer.Default().Import("github.com/miekg/dns") - fatalIfErr(err) - scope := pkg.Scope() - - // Collect constants like TypeX - var numberedTypes []string - for _, name := range scope.Names() { - o := scope.Lookup(name) - if o == nil || !o.Exported() { - continue - } - b, ok := o.Type().(*types.Basic) - if !ok || b.Kind() != types.Uint16 { - continue - } - if !strings.HasPrefix(o.Name(), "Type") { - continue - } - name := strings.TrimPrefix(o.Name(), "Type") - if name == "PrivateRR" { - continue - } - numberedTypes = append(numberedTypes, name) - } - - // Collect actual types (*X) - var namedTypes []string - for _, name := range scope.Names() { - o := scope.Lookup(name) - if o == nil || !o.Exported() { - continue - } - if st, _ := getTypeStruct(o.Type(), scope); st == nil { - continue - } - if name == "PrivateRR" { - continue - } - - // Check if corresponding TypeX exists - if scope.Lookup("Type"+o.Name()) == nil && o.Name() != "RFC3597" { - log.Fatalf("Constant Type%s does not exist.", o.Name()) - } - - namedTypes = append(namedTypes, o.Name()) - } - - b := &bytes.Buffer{} - b.WriteString(packageHdr) - - // Generate TypeToRR - fatalIfErr(TypeToRR.Execute(b, namedTypes)) - - // Generate typeToString - fatalIfErr(typeToString.Execute(b, numberedTypes)) - - // Generate headerFunc - fatalIfErr(headerFunc.Execute(b, namedTypes)) - - // Generate len() - fmt.Fprint(b, "// len() functions\n") - for _, name := range namedTypes { - if _, ok := skipLen[name]; ok { - continue - } - o := scope.Lookup(name) - st, isEmbedded := getTypeStruct(o.Type(), scope) - if isEmbedded { - continue - } - fmt.Fprintf(b, "func (rr *%s) len(off int, compression map[string]struct{}) int {\n", name) - fmt.Fprintf(b, "l := rr.Hdr.len(off, compression)\n") - for i := 1; i < st.NumFields(); i++ { - o := func(s string) { fmt.Fprintf(b, s, st.Field(i).Name()) } - - if _, ok := st.Field(i).Type().(*types.Slice); ok { - switch st.Tag(i) { - case `dns:"-"`: - // ignored - case `dns:"cdomain-name"`: - o("for _, x := range rr.%s { l += domainNameLen(x, off+l, compression, true) }\n") - case `dns:"domain-name"`: - o("for _, x := range rr.%s { l += domainNameLen(x, off+l, compression, false) }\n") - case `dns:"txt"`: - o("for _, x := range rr.%s { l += len(x) + 1 }\n") - default: - log.Fatalln(name, st.Field(i).Name(), st.Tag(i)) - } - continue - } - - switch { - case st.Tag(i) == `dns:"-"`: - // ignored - case st.Tag(i) == `dns:"cdomain-name"`: - o("l += domainNameLen(rr.%s, off+l, compression, true)\n") - case st.Tag(i) == `dns:"domain-name"`: - o("l += domainNameLen(rr.%s, off+l, compression, false)\n") - case st.Tag(i) == `dns:"octet"`: - o("l += len(rr.%s)\n") - case strings.HasPrefix(st.Tag(i), `dns:"size-base64`): - fallthrough - case st.Tag(i) == `dns:"base64"`: - o("l += base64.StdEncoding.DecodedLen(len(rr.%s))\n") - case strings.HasPrefix(st.Tag(i), `dns:"size-hex:`): // this has an extra field where the length is stored - o("l += len(rr.%s)/2\n") - case st.Tag(i) == `dns:"hex"`: - o("l += len(rr.%s)/2\n") - case st.Tag(i) == `dns:"any"`: - o("l += len(rr.%s)\n") - case st.Tag(i) == `dns:"a"`: - o("if len(rr.%s) != 0 { l += net.IPv4len }\n") - case st.Tag(i) == `dns:"aaaa"`: - o("if len(rr.%s) != 0 { l += net.IPv6len }\n") - case st.Tag(i) == `dns:"txt"`: - o("for _, t := range rr.%s { l += len(t) + 1 }\n") - case st.Tag(i) == `dns:"uint48"`: - o("l += 6 // %s\n") - case st.Tag(i) == "": - switch st.Field(i).Type().(*types.Basic).Kind() { - case types.Uint8: - o("l++ // %s\n") - case types.Uint16: - o("l += 2 // %s\n") - case types.Uint32: - o("l += 4 // %s\n") - case types.Uint64: - o("l += 8 // %s\n") - case types.String: - o("l += len(rr.%s) + 1\n") - default: - log.Fatalln(name, st.Field(i).Name()) - } - default: - log.Fatalln(name, st.Field(i).Name(), st.Tag(i)) - } - } - fmt.Fprintf(b, "return l }\n") - } - - // Generate copy() - fmt.Fprint(b, "// copy() functions\n") - for _, name := range namedTypes { - o := scope.Lookup(name) - st, isEmbedded := getTypeStruct(o.Type(), scope) - if isEmbedded { - continue - } - fmt.Fprintf(b, "func (rr *%s) copy() RR {\n", name) - fields := []string{"rr.Hdr"} - for i := 1; i < st.NumFields(); i++ { - f := st.Field(i).Name() - if sl, ok := st.Field(i).Type().(*types.Slice); ok { - t := sl.Underlying().String() - t = strings.TrimPrefix(t, "[]") - if strings.Contains(t, ".") { - splits := strings.Split(t, ".") - t = splits[len(splits)-1] - } - // For the EDNS0 interface (used in the OPT RR), we need to call the copy method on each element. - if t == "EDNS0" { - fmt.Fprintf(b, "%s := make([]%s, len(rr.%s));\nfor i,e := range rr.%s {\n %s[i] = e.copy()\n}\n", - f, t, f, f, f) - fields = append(fields, f) - continue - } - fmt.Fprintf(b, "%s := make([]%s, len(rr.%s)); copy(%s, rr.%s)\n", - f, t, f, f, f) - fields = append(fields, f) - continue - } - if st.Field(i).Type().String() == "net.IP" { - fields = append(fields, "copyIP(rr."+f+")") - continue - } - fields = append(fields, "rr."+f) - } - fmt.Fprintf(b, "return &%s{%s}\n", name, strings.Join(fields, ",")) - fmt.Fprintf(b, "}\n") - } - - // gofmt - res, err := format.Source(b.Bytes()) - if err != nil { - b.WriteTo(os.Stderr) - log.Fatal(err) - } - - // write result - f, err := os.Create("ztypes.go") - fatalIfErr(err) - defer f.Close() - f.Write(res) -} - -func fatalIfErr(err error) { - if err != nil { - log.Fatal(err) - } -} diff --git a/vendor/golang.org/x/net/internal/iana/gen.go b/vendor/golang.org/x/net/internal/iana/gen.go deleted file mode 100644 index 2a7661c2..00000000 --- a/vendor/golang.org/x/net/internal/iana/gen.go +++ /dev/null @@ -1,383 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -//go:generate go run gen.go - -// This program generates internet protocol constants and tables by -// reading IANA protocol registries. -package main - -import ( - "bytes" - "encoding/xml" - "fmt" - "go/format" - "io" - "io/ioutil" - "net/http" - "os" - "strconv" - "strings" -) - -var registries = []struct { - url string - parse func(io.Writer, io.Reader) error -}{ - { - "https://www.iana.org/assignments/dscp-registry/dscp-registry.xml", - parseDSCPRegistry, - }, - { - "https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xml", - parseProtocolNumbers, - }, - { - "https://www.iana.org/assignments/address-family-numbers/address-family-numbers.xml", - parseAddrFamilyNumbers, - }, -} - -func main() { - var bb bytes.Buffer - fmt.Fprintf(&bb, "// go generate gen.go\n") - fmt.Fprintf(&bb, "// Code generated by the command above; DO NOT EDIT.\n\n") - fmt.Fprintf(&bb, "// Package iana provides protocol number resources managed by the Internet Assigned Numbers Authority (IANA).\n") - fmt.Fprintf(&bb, `package iana // import "golang.org/x/net/internal/iana"`+"\n\n") - for _, r := range registries { - resp, err := http.Get(r.url) - if err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - fmt.Fprintf(os.Stderr, "got HTTP status code %v for %v\n", resp.StatusCode, r.url) - os.Exit(1) - } - if err := r.parse(&bb, resp.Body); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } - fmt.Fprintf(&bb, "\n") - } - b, err := format.Source(bb.Bytes()) - if err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } - if err := ioutil.WriteFile("const.go", b, 0644); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } -} - -func parseDSCPRegistry(w io.Writer, r io.Reader) error { - dec := xml.NewDecoder(r) - var dr dscpRegistry - if err := dec.Decode(&dr); err != nil { - return err - } - fmt.Fprintf(w, "// %s, Updated: %s\n", dr.Title, dr.Updated) - fmt.Fprintf(w, "const (\n") - for _, dr := range dr.escapeDSCP() { - fmt.Fprintf(w, "DiffServ%s = %#02x", dr.Name, dr.Value) - fmt.Fprintf(w, "// %s\n", dr.OrigName) - } - for _, er := range dr.escapeECN() { - fmt.Fprintf(w, "%s = %#02x", er.Descr, er.Value) - fmt.Fprintf(w, "// %s\n", er.OrigDescr) - } - fmt.Fprintf(w, ")\n") - return nil -} - -type dscpRegistry struct { - XMLName xml.Name `xml:"registry"` - Title string `xml:"title"` - Updated string `xml:"updated"` - Note string `xml:"note"` - Registries []struct { - Title string `xml:"title"` - Registries []struct { - Title string `xml:"title"` - Records []struct { - Name string `xml:"name"` - Space string `xml:"space"` - } `xml:"record"` - } `xml:"registry"` - Records []struct { - Value string `xml:"value"` - Descr string `xml:"description"` - } `xml:"record"` - } `xml:"registry"` -} - -type canonDSCPRecord struct { - OrigName string - Name string - Value int -} - -func (drr *dscpRegistry) escapeDSCP() []canonDSCPRecord { - var drs []canonDSCPRecord - for _, preg := range drr.Registries { - if !strings.Contains(preg.Title, "Differentiated Services Field Codepoints") { - continue - } - for _, reg := range preg.Registries { - if !strings.Contains(reg.Title, "Pool 1 Codepoints") { - continue - } - drs = make([]canonDSCPRecord, len(reg.Records)) - sr := strings.NewReplacer( - "+", "", - "-", "", - "/", "", - ".", "", - " ", "", - ) - for i, dr := range reg.Records { - s := strings.TrimSpace(dr.Name) - drs[i].OrigName = s - drs[i].Name = sr.Replace(s) - n, err := strconv.ParseUint(dr.Space, 2, 8) - if err != nil { - continue - } - drs[i].Value = int(n) << 2 - } - } - } - return drs -} - -type canonECNRecord struct { - OrigDescr string - Descr string - Value int -} - -func (drr *dscpRegistry) escapeECN() []canonECNRecord { - var ers []canonECNRecord - for _, reg := range drr.Registries { - if !strings.Contains(reg.Title, "ECN Field") { - continue - } - ers = make([]canonECNRecord, len(reg.Records)) - sr := strings.NewReplacer( - "Capable", "", - "Not-ECT", "", - "ECT(1)", "", - "ECT(0)", "", - "CE", "", - "(", "", - ")", "", - "+", "", - "-", "", - "/", "", - ".", "", - " ", "", - ) - for i, er := range reg.Records { - s := strings.TrimSpace(er.Descr) - ers[i].OrigDescr = s - ss := strings.Split(s, " ") - if len(ss) > 1 { - ers[i].Descr = strings.Join(ss[1:], " ") - } else { - ers[i].Descr = ss[0] - } - ers[i].Descr = sr.Replace(er.Descr) - n, err := strconv.ParseUint(er.Value, 2, 8) - if err != nil { - continue - } - ers[i].Value = int(n) - } - } - return ers -} - -func parseProtocolNumbers(w io.Writer, r io.Reader) error { - dec := xml.NewDecoder(r) - var pn protocolNumbers - if err := dec.Decode(&pn); err != nil { - return err - } - prs := pn.escape() - prs = append([]canonProtocolRecord{{ - Name: "IP", - Descr: "IPv4 encapsulation, pseudo protocol number", - Value: 0, - }}, prs...) - fmt.Fprintf(w, "// %s, Updated: %s\n", pn.Title, pn.Updated) - fmt.Fprintf(w, "const (\n") - for _, pr := range prs { - if pr.Name == "" { - continue - } - fmt.Fprintf(w, "Protocol%s = %d", pr.Name, pr.Value) - s := pr.Descr - if s == "" { - s = pr.OrigName - } - fmt.Fprintf(w, "// %s\n", s) - } - fmt.Fprintf(w, ")\n") - return nil -} - -type protocolNumbers struct { - XMLName xml.Name `xml:"registry"` - Title string `xml:"title"` - Updated string `xml:"updated"` - RegTitle string `xml:"registry>title"` - Note string `xml:"registry>note"` - Records []struct { - Value string `xml:"value"` - Name string `xml:"name"` - Descr string `xml:"description"` - } `xml:"registry>record"` -} - -type canonProtocolRecord struct { - OrigName string - Name string - Descr string - Value int -} - -func (pn *protocolNumbers) escape() []canonProtocolRecord { - prs := make([]canonProtocolRecord, len(pn.Records)) - sr := strings.NewReplacer( - "-in-", "in", - "-within-", "within", - "-over-", "over", - "+", "P", - "-", "", - "/", "", - ".", "", - " ", "", - ) - for i, pr := range pn.Records { - if strings.Contains(pr.Name, "Deprecated") || - strings.Contains(pr.Name, "deprecated") { - continue - } - prs[i].OrigName = pr.Name - s := strings.TrimSpace(pr.Name) - switch pr.Name { - case "ISIS over IPv4": - prs[i].Name = "ISIS" - case "manet": - prs[i].Name = "MANET" - default: - prs[i].Name = sr.Replace(s) - } - ss := strings.Split(pr.Descr, "\n") - for i := range ss { - ss[i] = strings.TrimSpace(ss[i]) - } - if len(ss) > 1 { - prs[i].Descr = strings.Join(ss, " ") - } else { - prs[i].Descr = ss[0] - } - prs[i].Value, _ = strconv.Atoi(pr.Value) - } - return prs -} - -func parseAddrFamilyNumbers(w io.Writer, r io.Reader) error { - dec := xml.NewDecoder(r) - var afn addrFamilylNumbers - if err := dec.Decode(&afn); err != nil { - return err - } - afrs := afn.escape() - fmt.Fprintf(w, "// %s, Updated: %s\n", afn.Title, afn.Updated) - fmt.Fprintf(w, "const (\n") - for _, afr := range afrs { - if afr.Name == "" { - continue - } - fmt.Fprintf(w, "AddrFamily%s = %d", afr.Name, afr.Value) - fmt.Fprintf(w, "// %s\n", afr.Descr) - } - fmt.Fprintf(w, ")\n") - return nil -} - -type addrFamilylNumbers struct { - XMLName xml.Name `xml:"registry"` - Title string `xml:"title"` - Updated string `xml:"updated"` - RegTitle string `xml:"registry>title"` - Note string `xml:"registry>note"` - Records []struct { - Value string `xml:"value"` - Descr string `xml:"description"` - } `xml:"registry>record"` -} - -type canonAddrFamilyRecord struct { - Name string - Descr string - Value int -} - -func (afn *addrFamilylNumbers) escape() []canonAddrFamilyRecord { - afrs := make([]canonAddrFamilyRecord, len(afn.Records)) - sr := strings.NewReplacer( - "IP version 4", "IPv4", - "IP version 6", "IPv6", - "Identifier", "ID", - "-", "", - "-", "", - "/", "", - ".", "", - " ", "", - ) - for i, afr := range afn.Records { - if strings.Contains(afr.Descr, "Unassigned") || - strings.Contains(afr.Descr, "Reserved") { - continue - } - afrs[i].Descr = afr.Descr - s := strings.TrimSpace(afr.Descr) - switch s { - case "IP (IP version 4)": - afrs[i].Name = "IPv4" - case "IP6 (IP version 6)": - afrs[i].Name = "IPv6" - case "AFI for L2VPN information": - afrs[i].Name = "L2VPN" - case "E.164 with NSAP format subaddress": - afrs[i].Name = "E164withSubaddress" - case "MT IP: Multi-Topology IP version 4": - afrs[i].Name = "MTIPv4" - case "MAC/24": - afrs[i].Name = "MACFinal24bits" - case "MAC/40": - afrs[i].Name = "MACFinal40bits" - case "IPv6/64": - afrs[i].Name = "IPv6Initial64bits" - default: - n := strings.Index(s, "(") - if n > 0 { - s = s[:n] - } - n = strings.Index(s, ":") - if n > 0 { - s = s[:n] - } - afrs[i].Name = sr.Replace(s) - } - afrs[i].Value, _ = strconv.Atoi(afr.Value) - } - return afrs -} diff --git a/vendor/golang.org/x/net/internal/socket/defs_aix.go b/vendor/golang.org/x/net/internal/socket/defs_aix.go deleted file mode 100644 index ae1b21c5..00000000 --- a/vendor/golang.org/x/net/internal/socket/defs_aix.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package socket - -/* -#include - -#include -*/ -import "C" - -type iovec C.struct_iovec - -type msghdr C.struct_msghdr - -type mmsghdr C.struct_mmsghdr - -type cmsghdr C.struct_cmsghdr - -type sockaddrInet C.struct_sockaddr_in - -type sockaddrInet6 C.struct_sockaddr_in6 - -const ( - sizeofIovec = C.sizeof_struct_iovec - sizeofMsghdr = C.sizeof_struct_msghdr - sizeofCmsghdr = C.sizeof_struct_cmsghdr - - sizeofSockaddrInet = C.sizeof_struct_sockaddr_in - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 -) diff --git a/vendor/golang.org/x/net/internal/socket/defs_darwin.go b/vendor/golang.org/x/net/internal/socket/defs_darwin.go deleted file mode 100644 index b780bc67..00000000 --- a/vendor/golang.org/x/net/internal/socket/defs_darwin.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package socket - -/* -#include - -#include -*/ -import "C" - -type iovec C.struct_iovec - -type msghdr C.struct_msghdr - -type cmsghdr C.struct_cmsghdr - -type sockaddrInet C.struct_sockaddr_in - -type sockaddrInet6 C.struct_sockaddr_in6 - -const ( - sizeofIovec = C.sizeof_struct_iovec - sizeofMsghdr = C.sizeof_struct_msghdr - sizeofCmsghdr = C.sizeof_struct_cmsghdr - - sizeofSockaddrInet = C.sizeof_struct_sockaddr_in - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 -) diff --git a/vendor/golang.org/x/net/internal/socket/defs_dragonfly.go b/vendor/golang.org/x/net/internal/socket/defs_dragonfly.go deleted file mode 100644 index b780bc67..00000000 --- a/vendor/golang.org/x/net/internal/socket/defs_dragonfly.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package socket - -/* -#include - -#include -*/ -import "C" - -type iovec C.struct_iovec - -type msghdr C.struct_msghdr - -type cmsghdr C.struct_cmsghdr - -type sockaddrInet C.struct_sockaddr_in - -type sockaddrInet6 C.struct_sockaddr_in6 - -const ( - sizeofIovec = C.sizeof_struct_iovec - sizeofMsghdr = C.sizeof_struct_msghdr - sizeofCmsghdr = C.sizeof_struct_cmsghdr - - sizeofSockaddrInet = C.sizeof_struct_sockaddr_in - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 -) diff --git a/vendor/golang.org/x/net/internal/socket/defs_freebsd.go b/vendor/golang.org/x/net/internal/socket/defs_freebsd.go deleted file mode 100644 index b780bc67..00000000 --- a/vendor/golang.org/x/net/internal/socket/defs_freebsd.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package socket - -/* -#include - -#include -*/ -import "C" - -type iovec C.struct_iovec - -type msghdr C.struct_msghdr - -type cmsghdr C.struct_cmsghdr - -type sockaddrInet C.struct_sockaddr_in - -type sockaddrInet6 C.struct_sockaddr_in6 - -const ( - sizeofIovec = C.sizeof_struct_iovec - sizeofMsghdr = C.sizeof_struct_msghdr - sizeofCmsghdr = C.sizeof_struct_cmsghdr - - sizeofSockaddrInet = C.sizeof_struct_sockaddr_in - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 -) diff --git a/vendor/golang.org/x/net/internal/socket/defs_linux.go b/vendor/golang.org/x/net/internal/socket/defs_linux.go deleted file mode 100644 index 85bb7450..00000000 --- a/vendor/golang.org/x/net/internal/socket/defs_linux.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package socket - -/* -#include -#include - -#define _GNU_SOURCE -#include -*/ -import "C" - -type iovec C.struct_iovec - -type msghdr C.struct_msghdr - -type mmsghdr C.struct_mmsghdr - -type cmsghdr C.struct_cmsghdr - -type sockaddrInet C.struct_sockaddr_in - -type sockaddrInet6 C.struct_sockaddr_in6 - -const ( - sizeofIovec = C.sizeof_struct_iovec - sizeofMsghdr = C.sizeof_struct_msghdr - sizeofCmsghdr = C.sizeof_struct_cmsghdr - - sizeofSockaddrInet = C.sizeof_struct_sockaddr_in - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 -) diff --git a/vendor/golang.org/x/net/internal/socket/defs_netbsd.go b/vendor/golang.org/x/net/internal/socket/defs_netbsd.go deleted file mode 100644 index 5bfdd467..00000000 --- a/vendor/golang.org/x/net/internal/socket/defs_netbsd.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package socket - -/* -#include - -#include -*/ -import "C" - -type iovec C.struct_iovec - -type msghdr C.struct_msghdr - -type mmsghdr C.struct_mmsghdr - -type cmsghdr C.struct_cmsghdr - -type sockaddrInet C.struct_sockaddr_in - -type sockaddrInet6 C.struct_sockaddr_in6 - -const ( - sizeofIovec = C.sizeof_struct_iovec - sizeofMsghdr = C.sizeof_struct_msghdr - sizeofCmsghdr = C.sizeof_struct_cmsghdr - - sizeofSockaddrInet = C.sizeof_struct_sockaddr_in - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 -) diff --git a/vendor/golang.org/x/net/internal/socket/defs_openbsd.go b/vendor/golang.org/x/net/internal/socket/defs_openbsd.go deleted file mode 100644 index b780bc67..00000000 --- a/vendor/golang.org/x/net/internal/socket/defs_openbsd.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package socket - -/* -#include - -#include -*/ -import "C" - -type iovec C.struct_iovec - -type msghdr C.struct_msghdr - -type cmsghdr C.struct_cmsghdr - -type sockaddrInet C.struct_sockaddr_in - -type sockaddrInet6 C.struct_sockaddr_in6 - -const ( - sizeofIovec = C.sizeof_struct_iovec - sizeofMsghdr = C.sizeof_struct_msghdr - sizeofCmsghdr = C.sizeof_struct_cmsghdr - - sizeofSockaddrInet = C.sizeof_struct_sockaddr_in - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 -) diff --git a/vendor/golang.org/x/net/internal/socket/defs_solaris.go b/vendor/golang.org/x/net/internal/socket/defs_solaris.go deleted file mode 100644 index b780bc67..00000000 --- a/vendor/golang.org/x/net/internal/socket/defs_solaris.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package socket - -/* -#include - -#include -*/ -import "C" - -type iovec C.struct_iovec - -type msghdr C.struct_msghdr - -type cmsghdr C.struct_cmsghdr - -type sockaddrInet C.struct_sockaddr_in - -type sockaddrInet6 C.struct_sockaddr_in6 - -const ( - sizeofIovec = C.sizeof_struct_iovec - sizeofMsghdr = C.sizeof_struct_msghdr - sizeofCmsghdr = C.sizeof_struct_cmsghdr - - sizeofSockaddrInet = C.sizeof_struct_sockaddr_in - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 -) diff --git a/vendor/golang.org/x/net/ipv4/defs_aix.go b/vendor/golang.org/x/net/ipv4/defs_aix.go deleted file mode 100644 index 0f37211c..00000000 --- a/vendor/golang.org/x/net/ipv4/defs_aix.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ - -package ipv4 - -/* -#include -*/ -import "C" - -const ( - sysIP_OPTIONS = C.IP_OPTIONS - sysIP_HDRINCL = C.IP_HDRINCL - sysIP_TOS = C.IP_TOS - sysIP_TTL = C.IP_TTL - sysIP_RECVOPTS = C.IP_RECVOPTS - sysIP_RECVRETOPTS = C.IP_RECVRETOPTS - sysIP_RECVDSTADDR = C.IP_RECVDSTADDR - sysIP_RETOPTS = C.IP_RETOPTS - // IP_RECVIF is defined on AIX but doesn't work. - // IP_RECVINTERFACE must be used instead. - sysIP_RECVIF = C.IP_RECVINTERFACE - sysIP_RECVTTL = C.IP_RECVTTL - - sysIP_MULTICAST_IF = C.IP_MULTICAST_IF - sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL - sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP - sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP - sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP - - sizeofIPMreq = C.sizeof_struct_ip_mreq -) - -type ipMreq C.struct_ip_mreq diff --git a/vendor/golang.org/x/net/ipv4/defs_darwin.go b/vendor/golang.org/x/net/ipv4/defs_darwin.go deleted file mode 100644 index c8f2e05b..00000000 --- a/vendor/golang.org/x/net/ipv4/defs_darwin.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ - -package ipv4 - -/* -#include - -#include -*/ -import "C" - -const ( - sysIP_OPTIONS = C.IP_OPTIONS - sysIP_HDRINCL = C.IP_HDRINCL - sysIP_TOS = C.IP_TOS - sysIP_TTL = C.IP_TTL - sysIP_RECVOPTS = C.IP_RECVOPTS - sysIP_RECVRETOPTS = C.IP_RECVRETOPTS - sysIP_RECVDSTADDR = C.IP_RECVDSTADDR - sysIP_RETOPTS = C.IP_RETOPTS - sysIP_RECVIF = C.IP_RECVIF - sysIP_STRIPHDR = C.IP_STRIPHDR - sysIP_RECVTTL = C.IP_RECVTTL - sysIP_BOUND_IF = C.IP_BOUND_IF - sysIP_PKTINFO = C.IP_PKTINFO - sysIP_RECVPKTINFO = C.IP_RECVPKTINFO - - sysIP_MULTICAST_IF = C.IP_MULTICAST_IF - sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL - sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP - sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP - sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP - sysIP_MULTICAST_VIF = C.IP_MULTICAST_VIF - sysIP_MULTICAST_IFINDEX = C.IP_MULTICAST_IFINDEX - sysIP_ADD_SOURCE_MEMBERSHIP = C.IP_ADD_SOURCE_MEMBERSHIP - sysIP_DROP_SOURCE_MEMBERSHIP = C.IP_DROP_SOURCE_MEMBERSHIP - sysIP_BLOCK_SOURCE = C.IP_BLOCK_SOURCE - sysIP_UNBLOCK_SOURCE = C.IP_UNBLOCK_SOURCE - sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP - sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP - sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP - sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP - sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE - sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE - - sizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage - sizeofSockaddrInet = C.sizeof_struct_sockaddr_in - sizeofInetPktinfo = C.sizeof_struct_in_pktinfo - - sizeofIPMreq = C.sizeof_struct_ip_mreq - sizeofIPMreqn = C.sizeof_struct_ip_mreqn - sizeofIPMreqSource = C.sizeof_struct_ip_mreq_source - sizeofGroupReq = C.sizeof_struct_group_req - sizeofGroupSourceReq = C.sizeof_struct_group_source_req -) - -type sockaddrStorage C.struct_sockaddr_storage - -type sockaddrInet C.struct_sockaddr_in - -type inetPktinfo C.struct_in_pktinfo - -type ipMreq C.struct_ip_mreq - -type ipMreqn C.struct_ip_mreqn - -type ipMreqSource C.struct_ip_mreq_source - -type groupReq C.struct_group_req - -type groupSourceReq C.struct_group_source_req diff --git a/vendor/golang.org/x/net/ipv4/defs_dragonfly.go b/vendor/golang.org/x/net/ipv4/defs_dragonfly.go deleted file mode 100644 index f30544ea..00000000 --- a/vendor/golang.org/x/net/ipv4/defs_dragonfly.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ - -package ipv4 - -/* -#include -*/ -import "C" - -const ( - sysIP_OPTIONS = C.IP_OPTIONS - sysIP_HDRINCL = C.IP_HDRINCL - sysIP_TOS = C.IP_TOS - sysIP_TTL = C.IP_TTL - sysIP_RECVOPTS = C.IP_RECVOPTS - sysIP_RECVRETOPTS = C.IP_RECVRETOPTS - sysIP_RECVDSTADDR = C.IP_RECVDSTADDR - sysIP_RETOPTS = C.IP_RETOPTS - sysIP_RECVIF = C.IP_RECVIF - sysIP_RECVTTL = C.IP_RECVTTL - - sysIP_MULTICAST_IF = C.IP_MULTICAST_IF - sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL - sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP - sysIP_MULTICAST_VIF = C.IP_MULTICAST_VIF - sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP - sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP - - sizeofIPMreq = C.sizeof_struct_ip_mreq -) - -type ipMreq C.struct_ip_mreq diff --git a/vendor/golang.org/x/net/ipv4/defs_freebsd.go b/vendor/golang.org/x/net/ipv4/defs_freebsd.go deleted file mode 100644 index 4dd57d86..00000000 --- a/vendor/golang.org/x/net/ipv4/defs_freebsd.go +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ - -package ipv4 - -/* -#include - -#include -*/ -import "C" - -const ( - sysIP_OPTIONS = C.IP_OPTIONS - sysIP_HDRINCL = C.IP_HDRINCL - sysIP_TOS = C.IP_TOS - sysIP_TTL = C.IP_TTL - sysIP_RECVOPTS = C.IP_RECVOPTS - sysIP_RECVRETOPTS = C.IP_RECVRETOPTS - sysIP_RECVDSTADDR = C.IP_RECVDSTADDR - sysIP_SENDSRCADDR = C.IP_SENDSRCADDR - sysIP_RETOPTS = C.IP_RETOPTS - sysIP_RECVIF = C.IP_RECVIF - sysIP_ONESBCAST = C.IP_ONESBCAST - sysIP_BINDANY = C.IP_BINDANY - sysIP_RECVTTL = C.IP_RECVTTL - sysIP_MINTTL = C.IP_MINTTL - sysIP_DONTFRAG = C.IP_DONTFRAG - sysIP_RECVTOS = C.IP_RECVTOS - - sysIP_MULTICAST_IF = C.IP_MULTICAST_IF - sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL - sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP - sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP - sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP - sysIP_MULTICAST_VIF = C.IP_MULTICAST_VIF - sysIP_ADD_SOURCE_MEMBERSHIP = C.IP_ADD_SOURCE_MEMBERSHIP - sysIP_DROP_SOURCE_MEMBERSHIP = C.IP_DROP_SOURCE_MEMBERSHIP - sysIP_BLOCK_SOURCE = C.IP_BLOCK_SOURCE - sysIP_UNBLOCK_SOURCE = C.IP_UNBLOCK_SOURCE - sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP - sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP - sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP - sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP - sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE - sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE - - sizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage - sizeofSockaddrInet = C.sizeof_struct_sockaddr_in - - sizeofIPMreq = C.sizeof_struct_ip_mreq - sizeofIPMreqn = C.sizeof_struct_ip_mreqn - sizeofIPMreqSource = C.sizeof_struct_ip_mreq_source - sizeofGroupReq = C.sizeof_struct_group_req - sizeofGroupSourceReq = C.sizeof_struct_group_source_req -) - -type sockaddrStorage C.struct_sockaddr_storage - -type sockaddrInet C.struct_sockaddr_in - -type ipMreq C.struct_ip_mreq - -type ipMreqn C.struct_ip_mreqn - -type ipMreqSource C.struct_ip_mreq_source - -type groupReq C.struct_group_req - -type groupSourceReq C.struct_group_source_req diff --git a/vendor/golang.org/x/net/ipv4/defs_linux.go b/vendor/golang.org/x/net/ipv4/defs_linux.go deleted file mode 100644 index beb11071..00000000 --- a/vendor/golang.org/x/net/ipv4/defs_linux.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ - -package ipv4 - -/* -#include - -#include -#include -#include -#include -#include -*/ -import "C" - -const ( - sysIP_TOS = C.IP_TOS - sysIP_TTL = C.IP_TTL - sysIP_HDRINCL = C.IP_HDRINCL - sysIP_OPTIONS = C.IP_OPTIONS - sysIP_ROUTER_ALERT = C.IP_ROUTER_ALERT - sysIP_RECVOPTS = C.IP_RECVOPTS - sysIP_RETOPTS = C.IP_RETOPTS - sysIP_PKTINFO = C.IP_PKTINFO - sysIP_PKTOPTIONS = C.IP_PKTOPTIONS - sysIP_MTU_DISCOVER = C.IP_MTU_DISCOVER - sysIP_RECVERR = C.IP_RECVERR - sysIP_RECVTTL = C.IP_RECVTTL - sysIP_RECVTOS = C.IP_RECVTOS - sysIP_MTU = C.IP_MTU - sysIP_FREEBIND = C.IP_FREEBIND - sysIP_TRANSPARENT = C.IP_TRANSPARENT - sysIP_RECVRETOPTS = C.IP_RECVRETOPTS - sysIP_ORIGDSTADDR = C.IP_ORIGDSTADDR - sysIP_RECVORIGDSTADDR = C.IP_RECVORIGDSTADDR - sysIP_MINTTL = C.IP_MINTTL - sysIP_NODEFRAG = C.IP_NODEFRAG - sysIP_UNICAST_IF = C.IP_UNICAST_IF - - sysIP_MULTICAST_IF = C.IP_MULTICAST_IF - sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL - sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP - sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP - sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP - sysIP_UNBLOCK_SOURCE = C.IP_UNBLOCK_SOURCE - sysIP_BLOCK_SOURCE = C.IP_BLOCK_SOURCE - sysIP_ADD_SOURCE_MEMBERSHIP = C.IP_ADD_SOURCE_MEMBERSHIP - sysIP_DROP_SOURCE_MEMBERSHIP = C.IP_DROP_SOURCE_MEMBERSHIP - sysIP_MSFILTER = C.IP_MSFILTER - sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP - sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP - sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP - sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP - sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE - sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE - sysMCAST_MSFILTER = C.MCAST_MSFILTER - sysIP_MULTICAST_ALL = C.IP_MULTICAST_ALL - - //sysIP_PMTUDISC_DONT = C.IP_PMTUDISC_DONT - //sysIP_PMTUDISC_WANT = C.IP_PMTUDISC_WANT - //sysIP_PMTUDISC_DO = C.IP_PMTUDISC_DO - //sysIP_PMTUDISC_PROBE = C.IP_PMTUDISC_PROBE - //sysIP_PMTUDISC_INTERFACE = C.IP_PMTUDISC_INTERFACE - //sysIP_PMTUDISC_OMIT = C.IP_PMTUDISC_OMIT - - sysICMP_FILTER = C.ICMP_FILTER - - sysSO_EE_ORIGIN_NONE = C.SO_EE_ORIGIN_NONE - sysSO_EE_ORIGIN_LOCAL = C.SO_EE_ORIGIN_LOCAL - sysSO_EE_ORIGIN_ICMP = C.SO_EE_ORIGIN_ICMP - sysSO_EE_ORIGIN_ICMP6 = C.SO_EE_ORIGIN_ICMP6 - sysSO_EE_ORIGIN_TXSTATUS = C.SO_EE_ORIGIN_TXSTATUS - sysSO_EE_ORIGIN_TIMESTAMPING = C.SO_EE_ORIGIN_TIMESTAMPING - - sysSOL_SOCKET = C.SOL_SOCKET - sysSO_ATTACH_FILTER = C.SO_ATTACH_FILTER - - sizeofKernelSockaddrStorage = C.sizeof_struct___kernel_sockaddr_storage - sizeofSockaddrInet = C.sizeof_struct_sockaddr_in - sizeofInetPktinfo = C.sizeof_struct_in_pktinfo - sizeofSockExtendedErr = C.sizeof_struct_sock_extended_err - - sizeofIPMreq = C.sizeof_struct_ip_mreq - sizeofIPMreqn = C.sizeof_struct_ip_mreqn - sizeofIPMreqSource = C.sizeof_struct_ip_mreq_source - sizeofGroupReq = C.sizeof_struct_group_req - sizeofGroupSourceReq = C.sizeof_struct_group_source_req - - sizeofICMPFilter = C.sizeof_struct_icmp_filter - - sizeofSockFprog = C.sizeof_struct_sock_fprog -) - -type kernelSockaddrStorage C.struct___kernel_sockaddr_storage - -type sockaddrInet C.struct_sockaddr_in - -type inetPktinfo C.struct_in_pktinfo - -type sockExtendedErr C.struct_sock_extended_err - -type ipMreq C.struct_ip_mreq - -type ipMreqn C.struct_ip_mreqn - -type ipMreqSource C.struct_ip_mreq_source - -type groupReq C.struct_group_req - -type groupSourceReq C.struct_group_source_req - -type icmpFilter C.struct_icmp_filter - -type sockFProg C.struct_sock_fprog - -type sockFilter C.struct_sock_filter diff --git a/vendor/golang.org/x/net/ipv4/defs_netbsd.go b/vendor/golang.org/x/net/ipv4/defs_netbsd.go deleted file mode 100644 index 8f8af1b8..00000000 --- a/vendor/golang.org/x/net/ipv4/defs_netbsd.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ - -package ipv4 - -/* -#include -*/ -import "C" - -const ( - sysIP_OPTIONS = C.IP_OPTIONS - sysIP_HDRINCL = C.IP_HDRINCL - sysIP_TOS = C.IP_TOS - sysIP_TTL = C.IP_TTL - sysIP_RECVOPTS = C.IP_RECVOPTS - sysIP_RECVRETOPTS = C.IP_RECVRETOPTS - sysIP_RECVDSTADDR = C.IP_RECVDSTADDR - sysIP_RETOPTS = C.IP_RETOPTS - sysIP_RECVIF = C.IP_RECVIF - sysIP_RECVTTL = C.IP_RECVTTL - - sysIP_MULTICAST_IF = C.IP_MULTICAST_IF - sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL - sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP - sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP - sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP - - sizeofIPMreq = C.sizeof_struct_ip_mreq -) - -type ipMreq C.struct_ip_mreq diff --git a/vendor/golang.org/x/net/ipv4/defs_openbsd.go b/vendor/golang.org/x/net/ipv4/defs_openbsd.go deleted file mode 100644 index 8f8af1b8..00000000 --- a/vendor/golang.org/x/net/ipv4/defs_openbsd.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ - -package ipv4 - -/* -#include -*/ -import "C" - -const ( - sysIP_OPTIONS = C.IP_OPTIONS - sysIP_HDRINCL = C.IP_HDRINCL - sysIP_TOS = C.IP_TOS - sysIP_TTL = C.IP_TTL - sysIP_RECVOPTS = C.IP_RECVOPTS - sysIP_RECVRETOPTS = C.IP_RECVRETOPTS - sysIP_RECVDSTADDR = C.IP_RECVDSTADDR - sysIP_RETOPTS = C.IP_RETOPTS - sysIP_RECVIF = C.IP_RECVIF - sysIP_RECVTTL = C.IP_RECVTTL - - sysIP_MULTICAST_IF = C.IP_MULTICAST_IF - sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL - sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP - sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP - sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP - - sizeofIPMreq = C.sizeof_struct_ip_mreq -) - -type ipMreq C.struct_ip_mreq diff --git a/vendor/golang.org/x/net/ipv4/defs_solaris.go b/vendor/golang.org/x/net/ipv4/defs_solaris.go deleted file mode 100644 index aeb33e9c..00000000 --- a/vendor/golang.org/x/net/ipv4/defs_solaris.go +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ - -package ipv4 - -/* -#include - -#include -*/ -import "C" - -const ( - sysIP_OPTIONS = C.IP_OPTIONS - sysIP_HDRINCL = C.IP_HDRINCL - sysIP_TOS = C.IP_TOS - sysIP_TTL = C.IP_TTL - sysIP_RECVOPTS = C.IP_RECVOPTS - sysIP_RECVRETOPTS = C.IP_RECVRETOPTS - sysIP_RECVDSTADDR = C.IP_RECVDSTADDR - sysIP_RETOPTS = C.IP_RETOPTS - sysIP_RECVIF = C.IP_RECVIF - sysIP_RECVSLLA = C.IP_RECVSLLA - sysIP_RECVTTL = C.IP_RECVTTL - - sysIP_MULTICAST_IF = C.IP_MULTICAST_IF - sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL - sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP - sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP - sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP - sysIP_BLOCK_SOURCE = C.IP_BLOCK_SOURCE - sysIP_UNBLOCK_SOURCE = C.IP_UNBLOCK_SOURCE - sysIP_ADD_SOURCE_MEMBERSHIP = C.IP_ADD_SOURCE_MEMBERSHIP - sysIP_DROP_SOURCE_MEMBERSHIP = C.IP_DROP_SOURCE_MEMBERSHIP - sysIP_NEXTHOP = C.IP_NEXTHOP - - sysIP_PKTINFO = C.IP_PKTINFO - sysIP_RECVPKTINFO = C.IP_RECVPKTINFO - sysIP_DONTFRAG = C.IP_DONTFRAG - - sysIP_BOUND_IF = C.IP_BOUND_IF - sysIP_UNSPEC_SRC = C.IP_UNSPEC_SRC - sysIP_BROADCAST_TTL = C.IP_BROADCAST_TTL - sysIP_DHCPINIT_IF = C.IP_DHCPINIT_IF - - sysIP_REUSEADDR = C.IP_REUSEADDR - sysIP_DONTROUTE = C.IP_DONTROUTE - sysIP_BROADCAST = C.IP_BROADCAST - - sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP - sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP - sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE - sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE - sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP - sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP - - sizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage - sizeofSockaddrInet = C.sizeof_struct_sockaddr_in - sizeofInetPktinfo = C.sizeof_struct_in_pktinfo - - sizeofIPMreq = C.sizeof_struct_ip_mreq - sizeofIPMreqSource = C.sizeof_struct_ip_mreq_source - sizeofGroupReq = C.sizeof_struct_group_req - sizeofGroupSourceReq = C.sizeof_struct_group_source_req -) - -type sockaddrStorage C.struct_sockaddr_storage - -type sockaddrInet C.struct_sockaddr_in - -type inetPktinfo C.struct_in_pktinfo - -type ipMreq C.struct_ip_mreq - -type ipMreqSource C.struct_ip_mreq_source - -type groupReq C.struct_group_req - -type groupSourceReq C.struct_group_source_req diff --git a/vendor/golang.org/x/net/ipv4/gen.go b/vendor/golang.org/x/net/ipv4/gen.go deleted file mode 100644 index 1bb1737f..00000000 --- a/vendor/golang.org/x/net/ipv4/gen.go +++ /dev/null @@ -1,199 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -//go:generate go run gen.go - -// This program generates system adaptation constants and types, -// internet protocol constants and tables by reading template files -// and IANA protocol registries. -package main - -import ( - "bytes" - "encoding/xml" - "fmt" - "go/format" - "io" - "io/ioutil" - "net/http" - "os" - "os/exec" - "runtime" - "strconv" - "strings" -) - -func main() { - if err := genzsys(); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } - if err := geniana(); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } -} - -func genzsys() error { - defs := "defs_" + runtime.GOOS + ".go" - f, err := os.Open(defs) - if err != nil { - if os.IsNotExist(err) { - return nil - } - return err - } - f.Close() - cmd := exec.Command("go", "tool", "cgo", "-godefs", defs) - b, err := cmd.Output() - if err != nil { - return err - } - b, err = format.Source(b) - if err != nil { - return err - } - zsys := "zsys_" + runtime.GOOS + ".go" - switch runtime.GOOS { - case "freebsd", "linux": - zsys = "zsys_" + runtime.GOOS + "_" + runtime.GOARCH + ".go" - } - if err := ioutil.WriteFile(zsys, b, 0644); err != nil { - return err - } - return nil -} - -var registries = []struct { - url string - parse func(io.Writer, io.Reader) error -}{ - { - "https://www.iana.org/assignments/icmp-parameters/icmp-parameters.xml", - parseICMPv4Parameters, - }, -} - -func geniana() error { - var bb bytes.Buffer - fmt.Fprintf(&bb, "// go generate gen.go\n") - fmt.Fprintf(&bb, "// Code generated by the command above; DO NOT EDIT.\n\n") - fmt.Fprintf(&bb, "package ipv4\n\n") - for _, r := range registries { - resp, err := http.Get(r.url) - if err != nil { - return err - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("got HTTP status code %v for %v\n", resp.StatusCode, r.url) - } - if err := r.parse(&bb, resp.Body); err != nil { - return err - } - fmt.Fprintf(&bb, "\n") - } - b, err := format.Source(bb.Bytes()) - if err != nil { - return err - } - if err := ioutil.WriteFile("iana.go", b, 0644); err != nil { - return err - } - return nil -} - -func parseICMPv4Parameters(w io.Writer, r io.Reader) error { - dec := xml.NewDecoder(r) - var icp icmpv4Parameters - if err := dec.Decode(&icp); err != nil { - return err - } - prs := icp.escape() - fmt.Fprintf(w, "// %s, Updated: %s\n", icp.Title, icp.Updated) - fmt.Fprintf(w, "const (\n") - for _, pr := range prs { - if pr.Descr == "" { - continue - } - fmt.Fprintf(w, "ICMPType%s ICMPType = %d", pr.Descr, pr.Value) - fmt.Fprintf(w, "// %s\n", pr.OrigDescr) - } - fmt.Fprintf(w, ")\n\n") - fmt.Fprintf(w, "// %s, Updated: %s\n", icp.Title, icp.Updated) - fmt.Fprintf(w, "var icmpTypes = map[ICMPType]string{\n") - for _, pr := range prs { - if pr.Descr == "" { - continue - } - fmt.Fprintf(w, "%d: %q,\n", pr.Value, strings.ToLower(pr.OrigDescr)) - } - fmt.Fprintf(w, "}\n") - return nil -} - -type icmpv4Parameters struct { - XMLName xml.Name `xml:"registry"` - Title string `xml:"title"` - Updated string `xml:"updated"` - Registries []struct { - Title string `xml:"title"` - Records []struct { - Value string `xml:"value"` - Descr string `xml:"description"` - } `xml:"record"` - } `xml:"registry"` -} - -type canonICMPv4ParamRecord struct { - OrigDescr string - Descr string - Value int -} - -func (icp *icmpv4Parameters) escape() []canonICMPv4ParamRecord { - id := -1 - for i, r := range icp.Registries { - if strings.Contains(r.Title, "Type") || strings.Contains(r.Title, "type") { - id = i - break - } - } - if id < 0 { - return nil - } - prs := make([]canonICMPv4ParamRecord, len(icp.Registries[id].Records)) - sr := strings.NewReplacer( - "Messages", "", - "Message", "", - "ICMP", "", - "+", "P", - "-", "", - "/", "", - ".", "", - " ", "", - ) - for i, pr := range icp.Registries[id].Records { - if strings.Contains(pr.Descr, "Reserved") || - strings.Contains(pr.Descr, "Unassigned") || - strings.Contains(pr.Descr, "Deprecated") || - strings.Contains(pr.Descr, "Experiment") || - strings.Contains(pr.Descr, "experiment") { - continue - } - ss := strings.Split(pr.Descr, "\n") - if len(ss) > 1 { - prs[i].Descr = strings.Join(ss, " ") - } else { - prs[i].Descr = ss[0] - } - s := strings.TrimSpace(prs[i].Descr) - prs[i].OrigDescr = s - prs[i].Descr = sr.Replace(s) - prs[i].Value, _ = strconv.Atoi(pr.Value) - } - return prs -} diff --git a/vendor/golang.org/x/net/ipv6/defs_aix.go b/vendor/golang.org/x/net/ipv6/defs_aix.go deleted file mode 100644 index ea396a3c..00000000 --- a/vendor/golang.org/x/net/ipv6/defs_aix.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package ipv6 - -/* -#include -#include - -#include -#include -*/ -import "C" - -const ( - sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS - sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF - sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS - sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP - sysIPV6_JOIN_GROUP = C.IPV6_JOIN_GROUP - sysIPV6_LEAVE_GROUP = C.IPV6_LEAVE_GROUP - sysICMP6_FILTER = C.ICMP6_FILTER - - sysIPV6_CHECKSUM = C.IPV6_CHECKSUM - sysIPV6_V6ONLY = C.IPV6_V6ONLY - - sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS - - sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO - sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT - sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR - sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS - sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS - - sysIPV6_USE_MIN_MTU = C.IPV6_USE_MIN_MTU - sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU - sysIPV6_PATHMTU = C.IPV6_PATHMTU - - sysIPV6_PKTINFO = C.IPV6_PKTINFO - sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT - sysIPV6_NEXTHOP = C.IPV6_NEXTHOP - sysIPV6_HOPOPTS = C.IPV6_HOPOPTS - sysIPV6_DSTOPTS = C.IPV6_DSTOPTS - sysIPV6_RTHDR = C.IPV6_RTHDR - - sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS - - sysIPV6_TCLASS = C.IPV6_TCLASS - sysIPV6_DONTFRAG = C.IPV6_DONTFRAG - - sizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - sizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - sizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo - - sizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - sizeofGroupReq = C.sizeof_struct_group_req - sizeofGroupSourceReq = C.sizeof_struct_group_source_req - - sizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -type sockaddrStorage C.struct_sockaddr_storage - -type sockaddrInet6 C.struct_sockaddr_in6 - -type inet6Pktinfo C.struct_in6_pktinfo - -type ipv6Mtuinfo C.struct_ip6_mtuinfo - -type ipv6Mreq C.struct_ipv6_mreq - -type icmpv6Filter C.struct_icmp6_filter - -type groupReq C.struct_group_req - -type groupSourceReq C.struct_group_source_req diff --git a/vendor/golang.org/x/net/ipv6/defs_darwin.go b/vendor/golang.org/x/net/ipv6/defs_darwin.go deleted file mode 100644 index 55ddc116..00000000 --- a/vendor/golang.org/x/net/ipv6/defs_darwin.go +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package ipv6 - -/* -#define __APPLE_USE_RFC_3542 -#include -#include -*/ -import "C" - -const ( - sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS - sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF - sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS - sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP - sysIPV6_JOIN_GROUP = C.IPV6_JOIN_GROUP - sysIPV6_LEAVE_GROUP = C.IPV6_LEAVE_GROUP - - sysIPV6_PORTRANGE = C.IPV6_PORTRANGE - sysICMP6_FILTER = C.ICMP6_FILTER - sysIPV6_2292PKTINFO = C.IPV6_2292PKTINFO - sysIPV6_2292HOPLIMIT = C.IPV6_2292HOPLIMIT - sysIPV6_2292NEXTHOP = C.IPV6_2292NEXTHOP - sysIPV6_2292HOPOPTS = C.IPV6_2292HOPOPTS - sysIPV6_2292DSTOPTS = C.IPV6_2292DSTOPTS - sysIPV6_2292RTHDR = C.IPV6_2292RTHDR - - sysIPV6_2292PKTOPTIONS = C.IPV6_2292PKTOPTIONS - - sysIPV6_CHECKSUM = C.IPV6_CHECKSUM - sysIPV6_V6ONLY = C.IPV6_V6ONLY - - sysIPV6_IPSEC_POLICY = C.IPV6_IPSEC_POLICY - - sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS - sysIPV6_TCLASS = C.IPV6_TCLASS - - sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS - - sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO - - sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT - sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR - sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS - sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS - - sysIPV6_USE_MIN_MTU = C.IPV6_USE_MIN_MTU - sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU - - sysIPV6_PATHMTU = C.IPV6_PATHMTU - - sysIPV6_PKTINFO = C.IPV6_PKTINFO - sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT - sysIPV6_NEXTHOP = C.IPV6_NEXTHOP - sysIPV6_HOPOPTS = C.IPV6_HOPOPTS - sysIPV6_DSTOPTS = C.IPV6_DSTOPTS - sysIPV6_RTHDR = C.IPV6_RTHDR - - sysIPV6_AUTOFLOWLABEL = C.IPV6_AUTOFLOWLABEL - - sysIPV6_DONTFRAG = C.IPV6_DONTFRAG - - sysIPV6_PREFER_TEMPADDR = C.IPV6_PREFER_TEMPADDR - - sysIPV6_MSFILTER = C.IPV6_MSFILTER - sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP - sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP - sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP - sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP - sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE - sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE - - sysIPV6_BOUND_IF = C.IPV6_BOUND_IF - - sysIPV6_PORTRANGE_DEFAULT = C.IPV6_PORTRANGE_DEFAULT - sysIPV6_PORTRANGE_HIGH = C.IPV6_PORTRANGE_HIGH - sysIPV6_PORTRANGE_LOW = C.IPV6_PORTRANGE_LOW - - sizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - sizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - sizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo - - sizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - sizeofGroupReq = C.sizeof_struct_group_req - sizeofGroupSourceReq = C.sizeof_struct_group_source_req - - sizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -type sockaddrStorage C.struct_sockaddr_storage - -type sockaddrInet6 C.struct_sockaddr_in6 - -type inet6Pktinfo C.struct_in6_pktinfo - -type ipv6Mtuinfo C.struct_ip6_mtuinfo - -type ipv6Mreq C.struct_ipv6_mreq - -type icmpv6Filter C.struct_icmp6_filter - -type groupReq C.struct_group_req - -type groupSourceReq C.struct_group_source_req diff --git a/vendor/golang.org/x/net/ipv6/defs_dragonfly.go b/vendor/golang.org/x/net/ipv6/defs_dragonfly.go deleted file mode 100644 index 27a1d1d6..00000000 --- a/vendor/golang.org/x/net/ipv6/defs_dragonfly.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package ipv6 - -/* -#include -#include - -#include -#include -*/ -import "C" - -const ( - sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS - sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF - sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS - sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP - sysIPV6_JOIN_GROUP = C.IPV6_JOIN_GROUP - sysIPV6_LEAVE_GROUP = C.IPV6_LEAVE_GROUP - sysIPV6_PORTRANGE = C.IPV6_PORTRANGE - sysICMP6_FILTER = C.ICMP6_FILTER - - sysIPV6_CHECKSUM = C.IPV6_CHECKSUM - sysIPV6_V6ONLY = C.IPV6_V6ONLY - - sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS - sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO - sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT - sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR - sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS - sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS - - sysIPV6_USE_MIN_MTU = C.IPV6_USE_MIN_MTU - sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU - - sysIPV6_PATHMTU = C.IPV6_PATHMTU - - sysIPV6_PKTINFO = C.IPV6_PKTINFO - sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT - sysIPV6_NEXTHOP = C.IPV6_NEXTHOP - sysIPV6_HOPOPTS = C.IPV6_HOPOPTS - sysIPV6_DSTOPTS = C.IPV6_DSTOPTS - sysIPV6_RTHDR = C.IPV6_RTHDR - - sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS - - sysIPV6_AUTOFLOWLABEL = C.IPV6_AUTOFLOWLABEL - - sysIPV6_TCLASS = C.IPV6_TCLASS - sysIPV6_DONTFRAG = C.IPV6_DONTFRAG - - sysIPV6_PREFER_TEMPADDR = C.IPV6_PREFER_TEMPADDR - - sysIPV6_PORTRANGE_DEFAULT = C.IPV6_PORTRANGE_DEFAULT - sysIPV6_PORTRANGE_HIGH = C.IPV6_PORTRANGE_HIGH - sysIPV6_PORTRANGE_LOW = C.IPV6_PORTRANGE_LOW - - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - sizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - sizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo - - sizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - - sizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -type sockaddrInet6 C.struct_sockaddr_in6 - -type inet6Pktinfo C.struct_in6_pktinfo - -type ipv6Mtuinfo C.struct_ip6_mtuinfo - -type ipv6Mreq C.struct_ipv6_mreq - -type icmpv6Filter C.struct_icmp6_filter diff --git a/vendor/golang.org/x/net/ipv6/defs_freebsd.go b/vendor/golang.org/x/net/ipv6/defs_freebsd.go deleted file mode 100644 index 53e62538..00000000 --- a/vendor/golang.org/x/net/ipv6/defs_freebsd.go +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package ipv6 - -/* -#include -#include - -#include -#include -*/ -import "C" - -const ( - sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS - sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF - sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS - sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP - sysIPV6_JOIN_GROUP = C.IPV6_JOIN_GROUP - sysIPV6_LEAVE_GROUP = C.IPV6_LEAVE_GROUP - sysIPV6_PORTRANGE = C.IPV6_PORTRANGE - sysICMP6_FILTER = C.ICMP6_FILTER - - sysIPV6_CHECKSUM = C.IPV6_CHECKSUM - sysIPV6_V6ONLY = C.IPV6_V6ONLY - - sysIPV6_IPSEC_POLICY = C.IPV6_IPSEC_POLICY - - sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS - - sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO - sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT - sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR - sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS - sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS - - sysIPV6_USE_MIN_MTU = C.IPV6_USE_MIN_MTU - sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU - - sysIPV6_PATHMTU = C.IPV6_PATHMTU - - sysIPV6_PKTINFO = C.IPV6_PKTINFO - sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT - sysIPV6_NEXTHOP = C.IPV6_NEXTHOP - sysIPV6_HOPOPTS = C.IPV6_HOPOPTS - sysIPV6_DSTOPTS = C.IPV6_DSTOPTS - sysIPV6_RTHDR = C.IPV6_RTHDR - - sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS - - sysIPV6_AUTOFLOWLABEL = C.IPV6_AUTOFLOWLABEL - - sysIPV6_TCLASS = C.IPV6_TCLASS - sysIPV6_DONTFRAG = C.IPV6_DONTFRAG - - sysIPV6_PREFER_TEMPADDR = C.IPV6_PREFER_TEMPADDR - - sysIPV6_BINDANY = C.IPV6_BINDANY - - sysIPV6_MSFILTER = C.IPV6_MSFILTER - - sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP - sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP - sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP - sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP - sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE - sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE - - sysIPV6_PORTRANGE_DEFAULT = C.IPV6_PORTRANGE_DEFAULT - sysIPV6_PORTRANGE_HIGH = C.IPV6_PORTRANGE_HIGH - sysIPV6_PORTRANGE_LOW = C.IPV6_PORTRANGE_LOW - - sizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - sizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - sizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo - - sizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - sizeofGroupReq = C.sizeof_struct_group_req - sizeofGroupSourceReq = C.sizeof_struct_group_source_req - - sizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -type sockaddrStorage C.struct_sockaddr_storage - -type sockaddrInet6 C.struct_sockaddr_in6 - -type inet6Pktinfo C.struct_in6_pktinfo - -type ipv6Mtuinfo C.struct_ip6_mtuinfo - -type ipv6Mreq C.struct_ipv6_mreq - -type groupReq C.struct_group_req - -type groupSourceReq C.struct_group_source_req - -type icmpv6Filter C.struct_icmp6_filter diff --git a/vendor/golang.org/x/net/ipv6/defs_linux.go b/vendor/golang.org/x/net/ipv6/defs_linux.go deleted file mode 100644 index 3308cb2c..00000000 --- a/vendor/golang.org/x/net/ipv6/defs_linux.go +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package ipv6 - -/* -#include -#include -#include -#include -#include -#include -*/ -import "C" - -const ( - sysIPV6_ADDRFORM = C.IPV6_ADDRFORM - sysIPV6_2292PKTINFO = C.IPV6_2292PKTINFO - sysIPV6_2292HOPOPTS = C.IPV6_2292HOPOPTS - sysIPV6_2292DSTOPTS = C.IPV6_2292DSTOPTS - sysIPV6_2292RTHDR = C.IPV6_2292RTHDR - sysIPV6_2292PKTOPTIONS = C.IPV6_2292PKTOPTIONS - sysIPV6_CHECKSUM = C.IPV6_CHECKSUM - sysIPV6_2292HOPLIMIT = C.IPV6_2292HOPLIMIT - sysIPV6_NEXTHOP = C.IPV6_NEXTHOP - sysIPV6_FLOWINFO = C.IPV6_FLOWINFO - - sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS - sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF - sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS - sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP - sysIPV6_ADD_MEMBERSHIP = C.IPV6_ADD_MEMBERSHIP - sysIPV6_DROP_MEMBERSHIP = C.IPV6_DROP_MEMBERSHIP - sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP - sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP - sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP - sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP - sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE - sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE - sysMCAST_MSFILTER = C.MCAST_MSFILTER - sysIPV6_ROUTER_ALERT = C.IPV6_ROUTER_ALERT - sysIPV6_MTU_DISCOVER = C.IPV6_MTU_DISCOVER - sysIPV6_MTU = C.IPV6_MTU - sysIPV6_RECVERR = C.IPV6_RECVERR - sysIPV6_V6ONLY = C.IPV6_V6ONLY - sysIPV6_JOIN_ANYCAST = C.IPV6_JOIN_ANYCAST - sysIPV6_LEAVE_ANYCAST = C.IPV6_LEAVE_ANYCAST - - //sysIPV6_PMTUDISC_DONT = C.IPV6_PMTUDISC_DONT - //sysIPV6_PMTUDISC_WANT = C.IPV6_PMTUDISC_WANT - //sysIPV6_PMTUDISC_DO = C.IPV6_PMTUDISC_DO - //sysIPV6_PMTUDISC_PROBE = C.IPV6_PMTUDISC_PROBE - //sysIPV6_PMTUDISC_INTERFACE = C.IPV6_PMTUDISC_INTERFACE - //sysIPV6_PMTUDISC_OMIT = C.IPV6_PMTUDISC_OMIT - - sysIPV6_FLOWLABEL_MGR = C.IPV6_FLOWLABEL_MGR - sysIPV6_FLOWINFO_SEND = C.IPV6_FLOWINFO_SEND - - sysIPV6_IPSEC_POLICY = C.IPV6_IPSEC_POLICY - sysIPV6_XFRM_POLICY = C.IPV6_XFRM_POLICY - - sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO - sysIPV6_PKTINFO = C.IPV6_PKTINFO - sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT - sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT - sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS - sysIPV6_HOPOPTS = C.IPV6_HOPOPTS - sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS - sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR - sysIPV6_RTHDR = C.IPV6_RTHDR - sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS - sysIPV6_DSTOPTS = C.IPV6_DSTOPTS - sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU - sysIPV6_PATHMTU = C.IPV6_PATHMTU - sysIPV6_DONTFRAG = C.IPV6_DONTFRAG - - sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS - sysIPV6_TCLASS = C.IPV6_TCLASS - - sysIPV6_ADDR_PREFERENCES = C.IPV6_ADDR_PREFERENCES - - sysIPV6_PREFER_SRC_TMP = C.IPV6_PREFER_SRC_TMP - sysIPV6_PREFER_SRC_PUBLIC = C.IPV6_PREFER_SRC_PUBLIC - sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = C.IPV6_PREFER_SRC_PUBTMP_DEFAULT - sysIPV6_PREFER_SRC_COA = C.IPV6_PREFER_SRC_COA - sysIPV6_PREFER_SRC_HOME = C.IPV6_PREFER_SRC_HOME - sysIPV6_PREFER_SRC_CGA = C.IPV6_PREFER_SRC_CGA - sysIPV6_PREFER_SRC_NONCGA = C.IPV6_PREFER_SRC_NONCGA - - sysIPV6_MINHOPCOUNT = C.IPV6_MINHOPCOUNT - - sysIPV6_ORIGDSTADDR = C.IPV6_ORIGDSTADDR - sysIPV6_RECVORIGDSTADDR = C.IPV6_RECVORIGDSTADDR - sysIPV6_TRANSPARENT = C.IPV6_TRANSPARENT - sysIPV6_UNICAST_IF = C.IPV6_UNICAST_IF - - sysICMPV6_FILTER = C.ICMPV6_FILTER - - sysICMPV6_FILTER_BLOCK = C.ICMPV6_FILTER_BLOCK - sysICMPV6_FILTER_PASS = C.ICMPV6_FILTER_PASS - sysICMPV6_FILTER_BLOCKOTHERS = C.ICMPV6_FILTER_BLOCKOTHERS - sysICMPV6_FILTER_PASSONLY = C.ICMPV6_FILTER_PASSONLY - - sysSOL_SOCKET = C.SOL_SOCKET - sysSO_ATTACH_FILTER = C.SO_ATTACH_FILTER - - sizeofKernelSockaddrStorage = C.sizeof_struct___kernel_sockaddr_storage - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - sizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - sizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo - sizeofIPv6FlowlabelReq = C.sizeof_struct_in6_flowlabel_req - - sizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - sizeofGroupReq = C.sizeof_struct_group_req - sizeofGroupSourceReq = C.sizeof_struct_group_source_req - - sizeofICMPv6Filter = C.sizeof_struct_icmp6_filter - - sizeofSockFprog = C.sizeof_struct_sock_fprog -) - -type kernelSockaddrStorage C.struct___kernel_sockaddr_storage - -type sockaddrInet6 C.struct_sockaddr_in6 - -type inet6Pktinfo C.struct_in6_pktinfo - -type ipv6Mtuinfo C.struct_ip6_mtuinfo - -type ipv6FlowlabelReq C.struct_in6_flowlabel_req - -type ipv6Mreq C.struct_ipv6_mreq - -type groupReq C.struct_group_req - -type groupSourceReq C.struct_group_source_req - -type icmpv6Filter C.struct_icmp6_filter - -type sockFProg C.struct_sock_fprog - -type sockFilter C.struct_sock_filter diff --git a/vendor/golang.org/x/net/ipv6/defs_netbsd.go b/vendor/golang.org/x/net/ipv6/defs_netbsd.go deleted file mode 100644 index be9ceb9c..00000000 --- a/vendor/golang.org/x/net/ipv6/defs_netbsd.go +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package ipv6 - -/* -#include -#include - -#include -#include -*/ -import "C" - -const ( - sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS - sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF - sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS - sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP - sysIPV6_JOIN_GROUP = C.IPV6_JOIN_GROUP - sysIPV6_LEAVE_GROUP = C.IPV6_LEAVE_GROUP - sysIPV6_PORTRANGE = C.IPV6_PORTRANGE - sysICMP6_FILTER = C.ICMP6_FILTER - - sysIPV6_CHECKSUM = C.IPV6_CHECKSUM - sysIPV6_V6ONLY = C.IPV6_V6ONLY - - sysIPV6_IPSEC_POLICY = C.IPV6_IPSEC_POLICY - - sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS - - sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO - sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT - sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR - sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS - sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS - - sysIPV6_USE_MIN_MTU = C.IPV6_USE_MIN_MTU - sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU - sysIPV6_PATHMTU = C.IPV6_PATHMTU - - sysIPV6_PKTINFO = C.IPV6_PKTINFO - sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT - sysIPV6_NEXTHOP = C.IPV6_NEXTHOP - sysIPV6_HOPOPTS = C.IPV6_HOPOPTS - sysIPV6_DSTOPTS = C.IPV6_DSTOPTS - sysIPV6_RTHDR = C.IPV6_RTHDR - - sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS - - sysIPV6_TCLASS = C.IPV6_TCLASS - sysIPV6_DONTFRAG = C.IPV6_DONTFRAG - - sysIPV6_PORTRANGE_DEFAULT = C.IPV6_PORTRANGE_DEFAULT - sysIPV6_PORTRANGE_HIGH = C.IPV6_PORTRANGE_HIGH - sysIPV6_PORTRANGE_LOW = C.IPV6_PORTRANGE_LOW - - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - sizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - sizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo - - sizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - - sizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -type sockaddrInet6 C.struct_sockaddr_in6 - -type inet6Pktinfo C.struct_in6_pktinfo - -type ipv6Mtuinfo C.struct_ip6_mtuinfo - -type ipv6Mreq C.struct_ipv6_mreq - -type icmpv6Filter C.struct_icmp6_filter diff --git a/vendor/golang.org/x/net/ipv6/defs_openbsd.go b/vendor/golang.org/x/net/ipv6/defs_openbsd.go deleted file mode 100644 index 177ddf87..00000000 --- a/vendor/golang.org/x/net/ipv6/defs_openbsd.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package ipv6 - -/* -#include -#include - -#include -#include -*/ -import "C" - -const ( - sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS - sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF - sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS - sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP - sysIPV6_JOIN_GROUP = C.IPV6_JOIN_GROUP - sysIPV6_LEAVE_GROUP = C.IPV6_LEAVE_GROUP - sysIPV6_PORTRANGE = C.IPV6_PORTRANGE - sysICMP6_FILTER = C.ICMP6_FILTER - - sysIPV6_CHECKSUM = C.IPV6_CHECKSUM - sysIPV6_V6ONLY = C.IPV6_V6ONLY - - sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS - - sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO - sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT - sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR - sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS - sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS - - sysIPV6_USE_MIN_MTU = C.IPV6_USE_MIN_MTU - sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU - - sysIPV6_PATHMTU = C.IPV6_PATHMTU - - sysIPV6_PKTINFO = C.IPV6_PKTINFO - sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT - sysIPV6_NEXTHOP = C.IPV6_NEXTHOP - sysIPV6_HOPOPTS = C.IPV6_HOPOPTS - sysIPV6_DSTOPTS = C.IPV6_DSTOPTS - sysIPV6_RTHDR = C.IPV6_RTHDR - - sysIPV6_AUTH_LEVEL = C.IPV6_AUTH_LEVEL - sysIPV6_ESP_TRANS_LEVEL = C.IPV6_ESP_TRANS_LEVEL - sysIPV6_ESP_NETWORK_LEVEL = C.IPV6_ESP_NETWORK_LEVEL - sysIPSEC6_OUTSA = C.IPSEC6_OUTSA - sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS - - sysIPV6_AUTOFLOWLABEL = C.IPV6_AUTOFLOWLABEL - sysIPV6_IPCOMP_LEVEL = C.IPV6_IPCOMP_LEVEL - - sysIPV6_TCLASS = C.IPV6_TCLASS - sysIPV6_DONTFRAG = C.IPV6_DONTFRAG - sysIPV6_PIPEX = C.IPV6_PIPEX - - sysIPV6_RTABLE = C.IPV6_RTABLE - - sysIPV6_PORTRANGE_DEFAULT = C.IPV6_PORTRANGE_DEFAULT - sysIPV6_PORTRANGE_HIGH = C.IPV6_PORTRANGE_HIGH - sysIPV6_PORTRANGE_LOW = C.IPV6_PORTRANGE_LOW - - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - sizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - sizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo - - sizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - - sizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -type sockaddrInet6 C.struct_sockaddr_in6 - -type inet6Pktinfo C.struct_in6_pktinfo - -type ipv6Mtuinfo C.struct_ip6_mtuinfo - -type ipv6Mreq C.struct_ipv6_mreq - -type icmpv6Filter C.struct_icmp6_filter diff --git a/vendor/golang.org/x/net/ipv6/defs_solaris.go b/vendor/golang.org/x/net/ipv6/defs_solaris.go deleted file mode 100644 index 0f8ce2b4..00000000 --- a/vendor/golang.org/x/net/ipv6/defs_solaris.go +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package ipv6 - -/* -#include - -#include -#include -*/ -import "C" - -const ( - sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS - sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF - sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS - sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP - sysIPV6_JOIN_GROUP = C.IPV6_JOIN_GROUP - sysIPV6_LEAVE_GROUP = C.IPV6_LEAVE_GROUP - - sysIPV6_PKTINFO = C.IPV6_PKTINFO - - sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT - sysIPV6_NEXTHOP = C.IPV6_NEXTHOP - sysIPV6_HOPOPTS = C.IPV6_HOPOPTS - sysIPV6_DSTOPTS = C.IPV6_DSTOPTS - - sysIPV6_RTHDR = C.IPV6_RTHDR - sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS - - sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO - sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT - sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS - - sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR - - sysIPV6_RECVRTHDRDSTOPTS = C.IPV6_RECVRTHDRDSTOPTS - - sysIPV6_CHECKSUM = C.IPV6_CHECKSUM - sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS - sysIPV6_USE_MIN_MTU = C.IPV6_USE_MIN_MTU - sysIPV6_DONTFRAG = C.IPV6_DONTFRAG - sysIPV6_SEC_OPT = C.IPV6_SEC_OPT - sysIPV6_SRC_PREFERENCES = C.IPV6_SRC_PREFERENCES - sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU - sysIPV6_PATHMTU = C.IPV6_PATHMTU - sysIPV6_TCLASS = C.IPV6_TCLASS - sysIPV6_V6ONLY = C.IPV6_V6ONLY - - sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS - - sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP - sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP - sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE - sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE - sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP - sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP - - sysIPV6_PREFER_SRC_HOME = C.IPV6_PREFER_SRC_HOME - sysIPV6_PREFER_SRC_COA = C.IPV6_PREFER_SRC_COA - sysIPV6_PREFER_SRC_PUBLIC = C.IPV6_PREFER_SRC_PUBLIC - sysIPV6_PREFER_SRC_TMP = C.IPV6_PREFER_SRC_TMP - sysIPV6_PREFER_SRC_NONCGA = C.IPV6_PREFER_SRC_NONCGA - sysIPV6_PREFER_SRC_CGA = C.IPV6_PREFER_SRC_CGA - - sysIPV6_PREFER_SRC_MIPMASK = C.IPV6_PREFER_SRC_MIPMASK - sysIPV6_PREFER_SRC_MIPDEFAULT = C.IPV6_PREFER_SRC_MIPDEFAULT - sysIPV6_PREFER_SRC_TMPMASK = C.IPV6_PREFER_SRC_TMPMASK - sysIPV6_PREFER_SRC_TMPDEFAULT = C.IPV6_PREFER_SRC_TMPDEFAULT - sysIPV6_PREFER_SRC_CGAMASK = C.IPV6_PREFER_SRC_CGAMASK - sysIPV6_PREFER_SRC_CGADEFAULT = C.IPV6_PREFER_SRC_CGADEFAULT - - sysIPV6_PREFER_SRC_MASK = C.IPV6_PREFER_SRC_MASK - - sysIPV6_PREFER_SRC_DEFAULT = C.IPV6_PREFER_SRC_DEFAULT - - sysIPV6_BOUND_IF = C.IPV6_BOUND_IF - sysIPV6_UNSPEC_SRC = C.IPV6_UNSPEC_SRC - - sysICMP6_FILTER = C.ICMP6_FILTER - - sizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - sizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - sizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo - - sizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - sizeofGroupReq = C.sizeof_struct_group_req - sizeofGroupSourceReq = C.sizeof_struct_group_source_req - - sizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -type sockaddrStorage C.struct_sockaddr_storage - -type sockaddrInet6 C.struct_sockaddr_in6 - -type inet6Pktinfo C.struct_in6_pktinfo - -type ipv6Mtuinfo C.struct_ip6_mtuinfo - -type ipv6Mreq C.struct_ipv6_mreq - -type groupReq C.struct_group_req - -type groupSourceReq C.struct_group_source_req - -type icmpv6Filter C.struct_icmp6_filter diff --git a/vendor/golang.org/x/net/ipv6/gen.go b/vendor/golang.org/x/net/ipv6/gen.go deleted file mode 100644 index 5885664f..00000000 --- a/vendor/golang.org/x/net/ipv6/gen.go +++ /dev/null @@ -1,199 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -//go:generate go run gen.go - -// This program generates system adaptation constants and types, -// internet protocol constants and tables by reading template files -// and IANA protocol registries. -package main - -import ( - "bytes" - "encoding/xml" - "fmt" - "go/format" - "io" - "io/ioutil" - "net/http" - "os" - "os/exec" - "runtime" - "strconv" - "strings" -) - -func main() { - if err := genzsys(); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } - if err := geniana(); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } -} - -func genzsys() error { - defs := "defs_" + runtime.GOOS + ".go" - f, err := os.Open(defs) - if err != nil { - if os.IsNotExist(err) { - return nil - } - return err - } - f.Close() - cmd := exec.Command("go", "tool", "cgo", "-godefs", defs) - b, err := cmd.Output() - if err != nil { - return err - } - b, err = format.Source(b) - if err != nil { - return err - } - zsys := "zsys_" + runtime.GOOS + ".go" - switch runtime.GOOS { - case "freebsd", "linux": - zsys = "zsys_" + runtime.GOOS + "_" + runtime.GOARCH + ".go" - } - if err := ioutil.WriteFile(zsys, b, 0644); err != nil { - return err - } - return nil -} - -var registries = []struct { - url string - parse func(io.Writer, io.Reader) error -}{ - { - "https://www.iana.org/assignments/icmpv6-parameters/icmpv6-parameters.xml", - parseICMPv6Parameters, - }, -} - -func geniana() error { - var bb bytes.Buffer - fmt.Fprintf(&bb, "// go generate gen.go\n") - fmt.Fprintf(&bb, "// Code generated by the command above; DO NOT EDIT.\n\n") - fmt.Fprintf(&bb, "package ipv6\n\n") - for _, r := range registries { - resp, err := http.Get(r.url) - if err != nil { - return err - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("got HTTP status code %v for %v\n", resp.StatusCode, r.url) - } - if err := r.parse(&bb, resp.Body); err != nil { - return err - } - fmt.Fprintf(&bb, "\n") - } - b, err := format.Source(bb.Bytes()) - if err != nil { - return err - } - if err := ioutil.WriteFile("iana.go", b, 0644); err != nil { - return err - } - return nil -} - -func parseICMPv6Parameters(w io.Writer, r io.Reader) error { - dec := xml.NewDecoder(r) - var icp icmpv6Parameters - if err := dec.Decode(&icp); err != nil { - return err - } - prs := icp.escape() - fmt.Fprintf(w, "// %s, Updated: %s\n", icp.Title, icp.Updated) - fmt.Fprintf(w, "const (\n") - for _, pr := range prs { - if pr.Name == "" { - continue - } - fmt.Fprintf(w, "ICMPType%s ICMPType = %d", pr.Name, pr.Value) - fmt.Fprintf(w, "// %s\n", pr.OrigName) - } - fmt.Fprintf(w, ")\n\n") - fmt.Fprintf(w, "// %s, Updated: %s\n", icp.Title, icp.Updated) - fmt.Fprintf(w, "var icmpTypes = map[ICMPType]string{\n") - for _, pr := range prs { - if pr.Name == "" { - continue - } - fmt.Fprintf(w, "%d: %q,\n", pr.Value, strings.ToLower(pr.OrigName)) - } - fmt.Fprintf(w, "}\n") - return nil -} - -type icmpv6Parameters struct { - XMLName xml.Name `xml:"registry"` - Title string `xml:"title"` - Updated string `xml:"updated"` - Registries []struct { - Title string `xml:"title"` - Records []struct { - Value string `xml:"value"` - Name string `xml:"name"` - } `xml:"record"` - } `xml:"registry"` -} - -type canonICMPv6ParamRecord struct { - OrigName string - Name string - Value int -} - -func (icp *icmpv6Parameters) escape() []canonICMPv6ParamRecord { - id := -1 - for i, r := range icp.Registries { - if strings.Contains(r.Title, "Type") || strings.Contains(r.Title, "type") { - id = i - break - } - } - if id < 0 { - return nil - } - prs := make([]canonICMPv6ParamRecord, len(icp.Registries[id].Records)) - sr := strings.NewReplacer( - "Messages", "", - "Message", "", - "ICMP", "", - "+", "P", - "-", "", - "/", "", - ".", "", - " ", "", - ) - for i, pr := range icp.Registries[id].Records { - if strings.Contains(pr.Name, "Reserved") || - strings.Contains(pr.Name, "Unassigned") || - strings.Contains(pr.Name, "Deprecated") || - strings.Contains(pr.Name, "Experiment") || - strings.Contains(pr.Name, "experiment") { - continue - } - ss := strings.Split(pr.Name, "\n") - if len(ss) > 1 { - prs[i].Name = strings.Join(ss, " ") - } else { - prs[i].Name = ss[0] - } - s := strings.TrimSpace(prs[i].Name) - prs[i].OrigName = s - prs[i].Name = sr.Replace(s) - prs[i].Value, _ = strconv.Atoi(pr.Value) - } - return prs -} diff --git a/vendor/golang.org/x/sys/unix/mkasm_darwin.go b/vendor/golang.org/x/sys/unix/mkasm_darwin.go deleted file mode 100644 index 4548b993..00000000 --- a/vendor/golang.org/x/sys/unix/mkasm_darwin.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// mkasm_darwin.go generates assembly trampolines to call libSystem routines from Go. -//This program must be run after mksyscall.go. -package main - -import ( - "bytes" - "fmt" - "io/ioutil" - "log" - "os" - "strings" -) - -func main() { - in1, err := ioutil.ReadFile("syscall_darwin.go") - if err != nil { - log.Fatalf("can't open syscall_darwin.go: %s", err) - } - arch := os.Args[1] - in2, err := ioutil.ReadFile(fmt.Sprintf("syscall_darwin_%s.go", arch)) - if err != nil { - log.Fatalf("can't open syscall_darwin_%s.go: %s", arch, err) - } - in3, err := ioutil.ReadFile(fmt.Sprintf("zsyscall_darwin_%s.go", arch)) - if err != nil { - log.Fatalf("can't open zsyscall_darwin_%s.go: %s", arch, err) - } - in := string(in1) + string(in2) + string(in3) - - trampolines := map[string]bool{} - - var out bytes.Buffer - - fmt.Fprintf(&out, "// go run mkasm_darwin.go %s\n", strings.Join(os.Args[1:], " ")) - fmt.Fprintf(&out, "// Code generated by the command above; DO NOT EDIT.\n") - fmt.Fprintf(&out, "\n") - fmt.Fprintf(&out, "// +build go1.12\n") - fmt.Fprintf(&out, "\n") - fmt.Fprintf(&out, "#include \"textflag.h\"\n") - for _, line := range strings.Split(in, "\n") { - if !strings.HasPrefix(line, "func ") || !strings.HasSuffix(line, "_trampoline()") { - continue - } - fn := line[5 : len(line)-13] - if !trampolines[fn] { - trampolines[fn] = true - fmt.Fprintf(&out, "TEXT ·%s_trampoline(SB),NOSPLIT,$0-0\n", fn) - fmt.Fprintf(&out, "\tJMP\t%s(SB)\n", fn) - } - } - err = ioutil.WriteFile(fmt.Sprintf("zsyscall_darwin_%s.s", arch), out.Bytes(), 0644) - if err != nil { - log.Fatalf("can't write zsyscall_darwin_%s.s: %s", arch, err) - } -} diff --git a/vendor/golang.org/x/sys/unix/mkpost.go b/vendor/golang.org/x/sys/unix/mkpost.go deleted file mode 100644 index eb433205..00000000 --- a/vendor/golang.org/x/sys/unix/mkpost.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// mkpost processes the output of cgo -godefs to -// modify the generated types. It is used to clean up -// the sys API in an architecture specific manner. -// -// mkpost is run after cgo -godefs; see README.md. -package main - -import ( - "bytes" - "fmt" - "go/format" - "io/ioutil" - "log" - "os" - "regexp" -) - -func main() { - // Get the OS and architecture (using GOARCH_TARGET if it exists) - goos := os.Getenv("GOOS") - goarch := os.Getenv("GOARCH_TARGET") - if goarch == "" { - goarch = os.Getenv("GOARCH") - } - // Check that we are using the Docker-based build system if we should be. - if goos == "linux" { - if os.Getenv("GOLANG_SYS_BUILD") != "docker" { - os.Stderr.WriteString("In the Docker-based build system, mkpost should not be called directly.\n") - os.Stderr.WriteString("See README.md\n") - os.Exit(1) - } - } - - b, err := ioutil.ReadAll(os.Stdin) - if err != nil { - log.Fatal(err) - } - - if goos == "aix" { - // Replace type of Atim, Mtim and Ctim by Timespec in Stat_t - // to avoid having both StTimespec and Timespec. - sttimespec := regexp.MustCompile(`_Ctype_struct_st_timespec`) - b = sttimespec.ReplaceAll(b, []byte("Timespec")) - } - - // Intentionally export __val fields in Fsid and Sigset_t - valRegex := regexp.MustCompile(`type (Fsid|Sigset_t) struct {(\s+)X__(bits|val)(\s+\S+\s+)}`) - b = valRegex.ReplaceAll(b, []byte("type $1 struct {${2}Val$4}")) - - // Intentionally export __fds_bits field in FdSet - fdSetRegex := regexp.MustCompile(`type (FdSet) struct {(\s+)X__fds_bits(\s+\S+\s+)}`) - b = fdSetRegex.ReplaceAll(b, []byte("type $1 struct {${2}Bits$3}")) - - // If we have empty Ptrace structs, we should delete them. Only s390x emits - // nonempty Ptrace structs. - ptraceRexexp := regexp.MustCompile(`type Ptrace((Psw|Fpregs|Per) struct {\s*})`) - b = ptraceRexexp.ReplaceAll(b, nil) - - // Replace the control_regs union with a blank identifier for now. - controlRegsRegex := regexp.MustCompile(`(Control_regs)\s+\[0\]uint64`) - b = controlRegsRegex.ReplaceAll(b, []byte("_ [0]uint64")) - - // Remove fields that are added by glibc - // Note that this is unstable as the identifers are private. - removeFieldsRegex := regexp.MustCompile(`X__glibc\S*`) - b = removeFieldsRegex.ReplaceAll(b, []byte("_")) - - // Convert [65]int8 to [65]byte in Utsname members to simplify - // conversion to string; see golang.org/issue/20753 - convertUtsnameRegex := regexp.MustCompile(`((Sys|Node|Domain)name|Release|Version|Machine)(\s+)\[(\d+)\]u?int8`) - b = convertUtsnameRegex.ReplaceAll(b, []byte("$1$3[$4]byte")) - - // Convert [1024]int8 to [1024]byte in Ptmget members - convertPtmget := regexp.MustCompile(`([SC]n)(\s+)\[(\d+)\]u?int8`) - b = convertPtmget.ReplaceAll(b, []byte("$1[$3]byte")) - - // Remove spare fields (e.g. in Statx_t) - spareFieldsRegex := regexp.MustCompile(`X__spare\S*`) - b = spareFieldsRegex.ReplaceAll(b, []byte("_")) - - // Remove cgo padding fields - removePaddingFieldsRegex := regexp.MustCompile(`Pad_cgo_\d+`) - b = removePaddingFieldsRegex.ReplaceAll(b, []byte("_")) - - // Remove padding, hidden, or unused fields - removeFieldsRegex = regexp.MustCompile(`\b(X_\S+|Padding)`) - b = removeFieldsRegex.ReplaceAll(b, []byte("_")) - - // Remove the first line of warning from cgo - b = b[bytes.IndexByte(b, '\n')+1:] - // Modify the command in the header to include: - // mkpost, our own warning, and a build tag. - replacement := fmt.Sprintf(`$1 | go run mkpost.go -// Code generated by the command above; see README.md. DO NOT EDIT. - -// +build %s,%s`, goarch, goos) - cgoCommandRegex := regexp.MustCompile(`(cgo -godefs .*)`) - b = cgoCommandRegex.ReplaceAll(b, []byte(replacement)) - - // Rename Stat_t time fields - if goos == "freebsd" && goarch == "386" { - // Hide Stat_t.[AMCB]tim_ext fields - renameStatTimeExtFieldsRegex := regexp.MustCompile(`[AMCB]tim_ext`) - b = renameStatTimeExtFieldsRegex.ReplaceAll(b, []byte("_")) - } - renameStatTimeFieldsRegex := regexp.MustCompile(`([AMCB])(?:irth)?time?(?:spec)?\s+(Timespec|StTimespec)`) - b = renameStatTimeFieldsRegex.ReplaceAll(b, []byte("${1}tim ${2}")) - - // gofmt - b, err = format.Source(b) - if err != nil { - log.Fatal(err) - } - - os.Stdout.Write(b) -} diff --git a/vendor/golang.org/x/sys/unix/mksyscall.go b/vendor/golang.org/x/sys/unix/mksyscall.go deleted file mode 100644 index e4af9424..00000000 --- a/vendor/golang.org/x/sys/unix/mksyscall.go +++ /dev/null @@ -1,407 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -This program reads a file containing function prototypes -(like syscall_darwin.go) and generates system call bodies. -The prototypes are marked by lines beginning with "//sys" -and read like func declarations if //sys is replaced by func, but: - * The parameter lists must give a name for each argument. - This includes return parameters. - * The parameter lists must give a type for each argument: - the (x, y, z int) shorthand is not allowed. - * If the return parameter is an error number, it must be named errno. - -A line beginning with //sysnb is like //sys, except that the -goroutine will not be suspended during the execution of the system -call. This must only be used for system calls which can never -block, as otherwise the system call could cause all goroutines to -hang. -*/ -package main - -import ( - "bufio" - "flag" - "fmt" - "os" - "regexp" - "strings" -) - -var ( - b32 = flag.Bool("b32", false, "32bit big-endian") - l32 = flag.Bool("l32", false, "32bit little-endian") - plan9 = flag.Bool("plan9", false, "plan9") - openbsd = flag.Bool("openbsd", false, "openbsd") - netbsd = flag.Bool("netbsd", false, "netbsd") - dragonfly = flag.Bool("dragonfly", false, "dragonfly") - arm = flag.Bool("arm", false, "arm") // 64-bit value should use (even, odd)-pair - tags = flag.String("tags", "", "build tags") - filename = flag.String("output", "", "output file name (standard output if omitted)") -) - -// cmdLine returns this programs's commandline arguments -func cmdLine() string { - return "go run mksyscall.go " + strings.Join(os.Args[1:], " ") -} - -// buildTags returns build tags -func buildTags() string { - return *tags -} - -// Param is function parameter -type Param struct { - Name string - Type string -} - -// usage prints the program usage -func usage() { - fmt.Fprintf(os.Stderr, "usage: go run mksyscall.go [-b32 | -l32] [-tags x,y] [file ...]\n") - os.Exit(1) -} - -// parseParamList parses parameter list and returns a slice of parameters -func parseParamList(list string) []string { - list = strings.TrimSpace(list) - if list == "" { - return []string{} - } - return regexp.MustCompile(`\s*,\s*`).Split(list, -1) -} - -// parseParam splits a parameter into name and type -func parseParam(p string) Param { - ps := regexp.MustCompile(`^(\S*) (\S*)$`).FindStringSubmatch(p) - if ps == nil { - fmt.Fprintf(os.Stderr, "malformed parameter: %s\n", p) - os.Exit(1) - } - return Param{ps[1], ps[2]} -} - -func main() { - // Get the OS and architecture (using GOARCH_TARGET if it exists) - goos := os.Getenv("GOOS") - if goos == "" { - fmt.Fprintln(os.Stderr, "GOOS not defined in environment") - os.Exit(1) - } - goarch := os.Getenv("GOARCH_TARGET") - if goarch == "" { - goarch = os.Getenv("GOARCH") - } - - // Check that we are using the Docker-based build system if we should - if goos == "linux" { - if os.Getenv("GOLANG_SYS_BUILD") != "docker" { - fmt.Fprintf(os.Stderr, "In the Docker-based build system, mksyscall should not be called directly.\n") - fmt.Fprintf(os.Stderr, "See README.md\n") - os.Exit(1) - } - } - - flag.Usage = usage - flag.Parse() - if len(flag.Args()) <= 0 { - fmt.Fprintf(os.Stderr, "no files to parse provided\n") - usage() - } - - endianness := "" - if *b32 { - endianness = "big-endian" - } else if *l32 { - endianness = "little-endian" - } - - libc := false - if goos == "darwin" && strings.Contains(buildTags(), ",go1.12") { - libc = true - } - trampolines := map[string]bool{} - - text := "" - for _, path := range flag.Args() { - file, err := os.Open(path) - if err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - s := bufio.NewScanner(file) - for s.Scan() { - t := s.Text() - t = strings.TrimSpace(t) - t = regexp.MustCompile(`\s+`).ReplaceAllString(t, ` `) - nonblock := regexp.MustCompile(`^\/\/sysnb `).FindStringSubmatch(t) - if regexp.MustCompile(`^\/\/sys `).FindStringSubmatch(t) == nil && nonblock == nil { - continue - } - - // Line must be of the form - // func Open(path string, mode int, perm int) (fd int, errno error) - // Split into name, in params, out params. - f := regexp.MustCompile(`^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*((?i)SYS_[A-Z0-9_]+))?$`).FindStringSubmatch(t) - if f == nil { - fmt.Fprintf(os.Stderr, "%s:%s\nmalformed //sys declaration\n", path, t) - os.Exit(1) - } - funct, inps, outps, sysname := f[2], f[3], f[4], f[5] - - // ClockGettime doesn't have a syscall number on Darwin, only generate libc wrappers. - if goos == "darwin" && !libc && funct == "ClockGettime" { - continue - } - - // Split argument lists on comma. - in := parseParamList(inps) - out := parseParamList(outps) - - // Try in vain to keep people from editing this file. - // The theory is that they jump into the middle of the file - // without reading the header. - text += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n" - - // Go function header. - outDecl := "" - if len(out) > 0 { - outDecl = fmt.Sprintf(" (%s)", strings.Join(out, ", ")) - } - text += fmt.Sprintf("func %s(%s)%s {\n", funct, strings.Join(in, ", "), outDecl) - - // Check if err return available - errvar := "" - for _, param := range out { - p := parseParam(param) - if p.Type == "error" { - errvar = p.Name - break - } - } - - // Prepare arguments to Syscall. - var args []string - n := 0 - for _, param := range in { - p := parseParam(param) - if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil { - args = append(args, "uintptr(unsafe.Pointer("+p.Name+"))") - } else if p.Type == "string" && errvar != "" { - text += fmt.Sprintf("\tvar _p%d *byte\n", n) - text += fmt.Sprintf("\t_p%d, %s = BytePtrFromString(%s)\n", n, errvar, p.Name) - text += fmt.Sprintf("\tif %s != nil {\n\t\treturn\n\t}\n", errvar) - args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n)) - n++ - } else if p.Type == "string" { - fmt.Fprintf(os.Stderr, path+":"+funct+" uses string arguments, but has no error return\n") - text += fmt.Sprintf("\tvar _p%d *byte\n", n) - text += fmt.Sprintf("\t_p%d, _ = BytePtrFromString(%s)\n", n, p.Name) - args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n)) - n++ - } else if regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type) != nil { - // Convert slice into pointer, length. - // Have to be careful not to take address of &a[0] if len == 0: - // pass dummy pointer in that case. - // Used to pass nil, but some OSes or simulators reject write(fd, nil, 0). - text += fmt.Sprintf("\tvar _p%d unsafe.Pointer\n", n) - text += fmt.Sprintf("\tif len(%s) > 0 {\n\t\t_p%d = unsafe.Pointer(&%s[0])\n\t}", p.Name, n, p.Name) - text += fmt.Sprintf(" else {\n\t\t_p%d = unsafe.Pointer(&_zero)\n\t}\n", n) - args = append(args, fmt.Sprintf("uintptr(_p%d)", n), fmt.Sprintf("uintptr(len(%s))", p.Name)) - n++ - } else if p.Type == "int64" && (*openbsd || *netbsd) { - args = append(args, "0") - if endianness == "big-endian" { - args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name)) - } else if endianness == "little-endian" { - args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name)) - } else { - args = append(args, fmt.Sprintf("uintptr(%s)", p.Name)) - } - } else if p.Type == "int64" && *dragonfly { - if regexp.MustCompile(`^(?i)extp(read|write)`).FindStringSubmatch(funct) == nil { - args = append(args, "0") - } - if endianness == "big-endian" { - args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name)) - } else if endianness == "little-endian" { - args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name)) - } else { - args = append(args, fmt.Sprintf("uintptr(%s)", p.Name)) - } - } else if (p.Type == "int64" || p.Type == "uint64") && endianness != "" { - if len(args)%2 == 1 && *arm { - // arm abi specifies 64-bit argument uses - // (even, odd) pair - args = append(args, "0") - } - if endianness == "big-endian" { - args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name)) - } else { - args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name)) - } - } else { - args = append(args, fmt.Sprintf("uintptr(%s)", p.Name)) - } - } - - // Determine which form to use; pad args with zeros. - asm := "Syscall" - if nonblock != nil { - if errvar == "" && goos == "linux" { - asm = "RawSyscallNoError" - } else { - asm = "RawSyscall" - } - } else { - if errvar == "" && goos == "linux" { - asm = "SyscallNoError" - } - } - if len(args) <= 3 { - for len(args) < 3 { - args = append(args, "0") - } - } else if len(args) <= 6 { - asm += "6" - for len(args) < 6 { - args = append(args, "0") - } - } else if len(args) <= 9 { - asm += "9" - for len(args) < 9 { - args = append(args, "0") - } - } else { - fmt.Fprintf(os.Stderr, "%s:%s too many arguments to system call\n", path, funct) - } - - // System call number. - if sysname == "" { - sysname = "SYS_" + funct - sysname = regexp.MustCompile(`([a-z])([A-Z])`).ReplaceAllString(sysname, `${1}_$2`) - sysname = strings.ToUpper(sysname) - } - - var libcFn string - if libc { - asm = "syscall_" + strings.ToLower(asm[:1]) + asm[1:] // internal syscall call - sysname = strings.TrimPrefix(sysname, "SYS_") // remove SYS_ - sysname = strings.ToLower(sysname) // lowercase - if sysname == "getdirentries64" { - // Special case - libSystem name and - // raw syscall name don't match. - sysname = "__getdirentries64" - } - libcFn = sysname - sysname = "funcPC(libc_" + sysname + "_trampoline)" - } - - // Actual call. - arglist := strings.Join(args, ", ") - call := fmt.Sprintf("%s(%s, %s)", asm, sysname, arglist) - - // Assign return values. - body := "" - ret := []string{"_", "_", "_"} - doErrno := false - for i := 0; i < len(out); i++ { - p := parseParam(out[i]) - reg := "" - if p.Name == "err" && !*plan9 { - reg = "e1" - ret[2] = reg - doErrno = true - } else if p.Name == "err" && *plan9 { - ret[0] = "r0" - ret[2] = "e1" - break - } else { - reg = fmt.Sprintf("r%d", i) - ret[i] = reg - } - if p.Type == "bool" { - reg = fmt.Sprintf("%s != 0", reg) - } - if p.Type == "int64" && endianness != "" { - // 64-bit number in r1:r0 or r0:r1. - if i+2 > len(out) { - fmt.Fprintf(os.Stderr, "%s:%s not enough registers for int64 return\n", path, funct) - } - if endianness == "big-endian" { - reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i, i+1) - } else { - reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i+1, i) - } - ret[i] = fmt.Sprintf("r%d", i) - ret[i+1] = fmt.Sprintf("r%d", i+1) - } - if reg != "e1" || *plan9 { - body += fmt.Sprintf("\t%s = %s(%s)\n", p.Name, p.Type, reg) - } - } - if ret[0] == "_" && ret[1] == "_" && ret[2] == "_" { - text += fmt.Sprintf("\t%s\n", call) - } else { - if errvar == "" && goos == "linux" { - // raw syscall without error on Linux, see golang.org/issue/22924 - text += fmt.Sprintf("\t%s, %s := %s\n", ret[0], ret[1], call) - } else { - text += fmt.Sprintf("\t%s, %s, %s := %s\n", ret[0], ret[1], ret[2], call) - } - } - text += body - - if *plan9 && ret[2] == "e1" { - text += "\tif int32(r0) == -1 {\n" - text += "\t\terr = e1\n" - text += "\t}\n" - } else if doErrno { - text += "\tif e1 != 0 {\n" - text += "\t\terr = errnoErr(e1)\n" - text += "\t}\n" - } - text += "\treturn\n" - text += "}\n\n" - - if libc && !trampolines[libcFn] { - // some system calls share a trampoline, like read and readlen. - trampolines[libcFn] = true - // Declare assembly trampoline. - text += fmt.Sprintf("func libc_%s_trampoline()\n", libcFn) - // Assembly trampoline calls the libc_* function, which this magic - // redirects to use the function from libSystem. - text += fmt.Sprintf("//go:linkname libc_%s libc_%s\n", libcFn, libcFn) - text += fmt.Sprintf("//go:cgo_import_dynamic libc_%s %s \"/usr/lib/libSystem.B.dylib\"\n", libcFn, libcFn) - text += "\n" - } - } - if err := s.Err(); err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - file.Close() - } - fmt.Printf(srcTemplate, cmdLine(), buildTags(), text) -} - -const srcTemplate = `// %s -// Code generated by the command above; see README.md. DO NOT EDIT. - -// +build %s - -package unix - -import ( - "syscall" - "unsafe" -) - -var _ syscall.Errno - -%s -` diff --git a/vendor/golang.org/x/sys/unix/mksyscall_aix_ppc.go b/vendor/golang.org/x/sys/unix/mksyscall_aix_ppc.go deleted file mode 100644 index 3be3cdfc..00000000 --- a/vendor/golang.org/x/sys/unix/mksyscall_aix_ppc.go +++ /dev/null @@ -1,415 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -This program reads a file containing function prototypes -(like syscall_aix.go) and generates system call bodies. -The prototypes are marked by lines beginning with "//sys" -and read like func declarations if //sys is replaced by func, but: - * The parameter lists must give a name for each argument. - This includes return parameters. - * The parameter lists must give a type for each argument: - the (x, y, z int) shorthand is not allowed. - * If the return parameter is an error number, it must be named err. - * If go func name needs to be different than its libc name, - * or the function is not in libc, name could be specified - * at the end, after "=" sign, like - //sys getsockopt(s int, level int, name int, val uintptr, vallen *_Socklen) (err error) = libsocket.getsockopt -*/ -package main - -import ( - "bufio" - "flag" - "fmt" - "os" - "regexp" - "strings" -) - -var ( - b32 = flag.Bool("b32", false, "32bit big-endian") - l32 = flag.Bool("l32", false, "32bit little-endian") - aix = flag.Bool("aix", false, "aix") - tags = flag.String("tags", "", "build tags") -) - -// cmdLine returns this programs's commandline arguments -func cmdLine() string { - return "go run mksyscall_aix_ppc.go " + strings.Join(os.Args[1:], " ") -} - -// buildTags returns build tags -func buildTags() string { - return *tags -} - -// Param is function parameter -type Param struct { - Name string - Type string -} - -// usage prints the program usage -func usage() { - fmt.Fprintf(os.Stderr, "usage: go run mksyscall_aix_ppc.go [-b32 | -l32] [-tags x,y] [file ...]\n") - os.Exit(1) -} - -// parseParamList parses parameter list and returns a slice of parameters -func parseParamList(list string) []string { - list = strings.TrimSpace(list) - if list == "" { - return []string{} - } - return regexp.MustCompile(`\s*,\s*`).Split(list, -1) -} - -// parseParam splits a parameter into name and type -func parseParam(p string) Param { - ps := regexp.MustCompile(`^(\S*) (\S*)$`).FindStringSubmatch(p) - if ps == nil { - fmt.Fprintf(os.Stderr, "malformed parameter: %s\n", p) - os.Exit(1) - } - return Param{ps[1], ps[2]} -} - -func main() { - flag.Usage = usage - flag.Parse() - if len(flag.Args()) <= 0 { - fmt.Fprintf(os.Stderr, "no files to parse provided\n") - usage() - } - - endianness := "" - if *b32 { - endianness = "big-endian" - } else if *l32 { - endianness = "little-endian" - } - - pack := "" - text := "" - cExtern := "/*\n#include \n#include \n" - for _, path := range flag.Args() { - file, err := os.Open(path) - if err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - s := bufio.NewScanner(file) - for s.Scan() { - t := s.Text() - t = strings.TrimSpace(t) - t = regexp.MustCompile(`\s+`).ReplaceAllString(t, ` `) - if p := regexp.MustCompile(`^package (\S+)$`).FindStringSubmatch(t); p != nil && pack == "" { - pack = p[1] - } - nonblock := regexp.MustCompile(`^\/\/sysnb `).FindStringSubmatch(t) - if regexp.MustCompile(`^\/\/sys `).FindStringSubmatch(t) == nil && nonblock == nil { - continue - } - - // Line must be of the form - // func Open(path string, mode int, perm int) (fd int, err error) - // Split into name, in params, out params. - f := regexp.MustCompile(`^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*(?:(\w*)\.)?(\w*))?$`).FindStringSubmatch(t) - if f == nil { - fmt.Fprintf(os.Stderr, "%s:%s\nmalformed //sys declaration\n", path, t) - os.Exit(1) - } - funct, inps, outps, modname, sysname := f[2], f[3], f[4], f[5], f[6] - - // Split argument lists on comma. - in := parseParamList(inps) - out := parseParamList(outps) - - inps = strings.Join(in, ", ") - outps = strings.Join(out, ", ") - - // Try in vain to keep people from editing this file. - // The theory is that they jump into the middle of the file - // without reading the header. - text += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n" - - // Check if value return, err return available - errvar := "" - retvar := "" - rettype := "" - for _, param := range out { - p := parseParam(param) - if p.Type == "error" { - errvar = p.Name - } else { - retvar = p.Name - rettype = p.Type - } - } - - // System call name. - if sysname == "" { - sysname = funct - } - sysname = regexp.MustCompile(`([a-z])([A-Z])`).ReplaceAllString(sysname, `${1}_$2`) - sysname = strings.ToLower(sysname) // All libc functions are lowercase. - - cRettype := "" - if rettype == "unsafe.Pointer" { - cRettype = "uintptr_t" - } else if rettype == "uintptr" { - cRettype = "uintptr_t" - } else if regexp.MustCompile(`^_`).FindStringSubmatch(rettype) != nil { - cRettype = "uintptr_t" - } else if rettype == "int" { - cRettype = "int" - } else if rettype == "int32" { - cRettype = "int" - } else if rettype == "int64" { - cRettype = "long long" - } else if rettype == "uint32" { - cRettype = "unsigned int" - } else if rettype == "uint64" { - cRettype = "unsigned long long" - } else { - cRettype = "int" - } - if sysname == "exit" { - cRettype = "void" - } - - // Change p.Types to c - var cIn []string - for _, param := range in { - p := parseParam(param) - if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil { - cIn = append(cIn, "uintptr_t") - } else if p.Type == "string" { - cIn = append(cIn, "uintptr_t") - } else if regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type) != nil { - cIn = append(cIn, "uintptr_t", "size_t") - } else if p.Type == "unsafe.Pointer" { - cIn = append(cIn, "uintptr_t") - } else if p.Type == "uintptr" { - cIn = append(cIn, "uintptr_t") - } else if regexp.MustCompile(`^_`).FindStringSubmatch(p.Type) != nil { - cIn = append(cIn, "uintptr_t") - } else if p.Type == "int" { - cIn = append(cIn, "int") - } else if p.Type == "int32" { - cIn = append(cIn, "int") - } else if p.Type == "int64" { - cIn = append(cIn, "long long") - } else if p.Type == "uint32" { - cIn = append(cIn, "unsigned int") - } else if p.Type == "uint64" { - cIn = append(cIn, "unsigned long long") - } else { - cIn = append(cIn, "int") - } - } - - if funct != "fcntl" && funct != "FcntlInt" && funct != "readlen" && funct != "writelen" { - if sysname == "select" { - // select is a keyword of Go. Its name is - // changed to c_select. - cExtern += "#define c_select select\n" - } - // Imports of system calls from libc - cExtern += fmt.Sprintf("%s %s", cRettype, sysname) - cIn := strings.Join(cIn, ", ") - cExtern += fmt.Sprintf("(%s);\n", cIn) - } - - // So file name. - if *aix { - if modname == "" { - modname = "libc.a/shr_64.o" - } else { - fmt.Fprintf(os.Stderr, "%s: only syscall using libc are available\n", funct) - os.Exit(1) - } - } - - strconvfunc := "C.CString" - - // Go function header. - if outps != "" { - outps = fmt.Sprintf(" (%s)", outps) - } - if text != "" { - text += "\n" - } - - text += fmt.Sprintf("func %s(%s)%s {\n", funct, strings.Join(in, ", "), outps) - - // Prepare arguments to Syscall. - var args []string - n := 0 - argN := 0 - for _, param := range in { - p := parseParam(param) - if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil { - args = append(args, "C.uintptr_t(uintptr(unsafe.Pointer("+p.Name+")))") - } else if p.Type == "string" && errvar != "" { - text += fmt.Sprintf("\t_p%d := uintptr(unsafe.Pointer(%s(%s)))\n", n, strconvfunc, p.Name) - args = append(args, fmt.Sprintf("C.uintptr_t(_p%d)", n)) - n++ - } else if p.Type == "string" { - fmt.Fprintf(os.Stderr, path+":"+funct+" uses string arguments, but has no error return\n") - text += fmt.Sprintf("\t_p%d := uintptr(unsafe.Pointer(%s(%s)))\n", n, strconvfunc, p.Name) - args = append(args, fmt.Sprintf("C.uintptr_t(_p%d)", n)) - n++ - } else if m := regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type); m != nil { - // Convert slice into pointer, length. - // Have to be careful not to take address of &a[0] if len == 0: - // pass nil in that case. - text += fmt.Sprintf("\tvar _p%d *%s\n", n, m[1]) - text += fmt.Sprintf("\tif len(%s) > 0 {\n\t\t_p%d = &%s[0]\n\t}\n", p.Name, n, p.Name) - args = append(args, fmt.Sprintf("C.uintptr_t(uintptr(unsafe.Pointer(_p%d)))", n)) - n++ - text += fmt.Sprintf("\tvar _p%d int\n", n) - text += fmt.Sprintf("\t_p%d = len(%s)\n", n, p.Name) - args = append(args, fmt.Sprintf("C.size_t(_p%d)", n)) - n++ - } else if p.Type == "int64" && endianness != "" { - if endianness == "big-endian" { - args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name)) - } else { - args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name)) - } - n++ - } else if p.Type == "bool" { - text += fmt.Sprintf("\tvar _p%d uint32\n", n) - text += fmt.Sprintf("\tif %s {\n\t\t_p%d = 1\n\t} else {\n\t\t_p%d = 0\n\t}\n", p.Name, n, n) - args = append(args, fmt.Sprintf("_p%d", n)) - } else if regexp.MustCompile(`^_`).FindStringSubmatch(p.Type) != nil { - args = append(args, fmt.Sprintf("C.uintptr_t(uintptr(%s))", p.Name)) - } else if p.Type == "unsafe.Pointer" { - args = append(args, fmt.Sprintf("C.uintptr_t(uintptr(%s))", p.Name)) - } else if p.Type == "int" { - if (argN == 2) && ((funct == "readlen") || (funct == "writelen")) { - args = append(args, fmt.Sprintf("C.size_t(%s)", p.Name)) - } else if argN == 0 && funct == "fcntl" { - args = append(args, fmt.Sprintf("C.uintptr_t(%s)", p.Name)) - } else if (argN == 2) && ((funct == "fcntl") || (funct == "FcntlInt")) { - args = append(args, fmt.Sprintf("C.uintptr_t(%s)", p.Name)) - } else { - args = append(args, fmt.Sprintf("C.int(%s)", p.Name)) - } - } else if p.Type == "int32" { - args = append(args, fmt.Sprintf("C.int(%s)", p.Name)) - } else if p.Type == "int64" { - args = append(args, fmt.Sprintf("C.longlong(%s)", p.Name)) - } else if p.Type == "uint32" { - args = append(args, fmt.Sprintf("C.uint(%s)", p.Name)) - } else if p.Type == "uint64" { - args = append(args, fmt.Sprintf("C.ulonglong(%s)", p.Name)) - } else if p.Type == "uintptr" { - args = append(args, fmt.Sprintf("C.uintptr_t(%s)", p.Name)) - } else { - args = append(args, fmt.Sprintf("C.int(%s)", p.Name)) - } - argN++ - } - - // Actual call. - arglist := strings.Join(args, ", ") - call := "" - if sysname == "exit" { - if errvar != "" { - call += "er :=" - } else { - call += "" - } - } else if errvar != "" { - call += "r0,er :=" - } else if retvar != "" { - call += "r0,_ :=" - } else { - call += "" - } - if sysname == "select" { - // select is a keyword of Go. Its name is - // changed to c_select. - call += fmt.Sprintf("C.c_%s(%s)", sysname, arglist) - } else { - call += fmt.Sprintf("C.%s(%s)", sysname, arglist) - } - - // Assign return values. - body := "" - for i := 0; i < len(out); i++ { - p := parseParam(out[i]) - reg := "" - if p.Name == "err" { - reg = "e1" - } else { - reg = "r0" - } - if reg != "e1" { - body += fmt.Sprintf("\t%s = %s(%s)\n", p.Name, p.Type, reg) - } - } - - // verify return - if sysname != "exit" && errvar != "" { - if regexp.MustCompile(`^uintptr`).FindStringSubmatch(cRettype) != nil { - body += "\tif (uintptr(r0) ==^uintptr(0) && er != nil) {\n" - body += fmt.Sprintf("\t\t%s = er\n", errvar) - body += "\t}\n" - } else { - body += "\tif (r0 ==-1 && er != nil) {\n" - body += fmt.Sprintf("\t\t%s = er\n", errvar) - body += "\t}\n" - } - } else if errvar != "" { - body += "\tif (er != nil) {\n" - body += fmt.Sprintf("\t\t%s = er\n", errvar) - body += "\t}\n" - } - - text += fmt.Sprintf("\t%s\n", call) - text += body - - text += "\treturn\n" - text += "}\n" - } - if err := s.Err(); err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - file.Close() - } - imp := "" - if pack != "unix" { - imp = "import \"golang.org/x/sys/unix\"\n" - - } - fmt.Printf(srcTemplate, cmdLine(), buildTags(), pack, cExtern, imp, text) -} - -const srcTemplate = `// %s -// Code generated by the command above; see README.md. DO NOT EDIT. - -// +build %s - -package %s - - -%s -*/ -import "C" -import ( - "unsafe" -) - - -%s - -%s -` diff --git a/vendor/golang.org/x/sys/unix/mksyscall_aix_ppc64.go b/vendor/golang.org/x/sys/unix/mksyscall_aix_ppc64.go deleted file mode 100644 index c9600995..00000000 --- a/vendor/golang.org/x/sys/unix/mksyscall_aix_ppc64.go +++ /dev/null @@ -1,614 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -This program reads a file containing function prototypes -(like syscall_aix.go) and generates system call bodies. -The prototypes are marked by lines beginning with "//sys" -and read like func declarations if //sys is replaced by func, but: - * The parameter lists must give a name for each argument. - This includes return parameters. - * The parameter lists must give a type for each argument: - the (x, y, z int) shorthand is not allowed. - * If the return parameter is an error number, it must be named err. - * If go func name needs to be different than its libc name, - * or the function is not in libc, name could be specified - * at the end, after "=" sign, like - //sys getsockopt(s int, level int, name int, val uintptr, vallen *_Socklen) (err error) = libsocket.getsockopt - - -This program will generate three files and handle both gc and gccgo implementation: - - zsyscall_aix_ppc64.go: the common part of each implementation (error handler, pointer creation) - - zsyscall_aix_ppc64_gc.go: gc part with //go_cgo_import_dynamic and a call to syscall6 - - zsyscall_aix_ppc64_gccgo.go: gccgo part with C function and conversion to C type. - - The generated code looks like this - -zsyscall_aix_ppc64.go -func asyscall(...) (n int, err error) { - // Pointer Creation - r1, e1 := callasyscall(...) - // Type Conversion - // Error Handler - return -} - -zsyscall_aix_ppc64_gc.go -//go:cgo_import_dynamic libc_asyscall asyscall "libc.a/shr_64.o" -//go:linkname libc_asyscall libc_asyscall -var asyscall syscallFunc - -func callasyscall(...) (r1 uintptr, e1 Errno) { - r1, _, e1 = syscall6(uintptr(unsafe.Pointer(&libc_asyscall)), "nb_args", ... ) - return -} - -zsyscall_aix_ppc64_ggcgo.go - -// int asyscall(...) - -import "C" - -func callasyscall(...) (r1 uintptr, e1 Errno) { - r1 = uintptr(C.asyscall(...)) - e1 = syscall.GetErrno() - return -} -*/ - -package main - -import ( - "bufio" - "flag" - "fmt" - "io/ioutil" - "os" - "regexp" - "strings" -) - -var ( - b32 = flag.Bool("b32", false, "32bit big-endian") - l32 = flag.Bool("l32", false, "32bit little-endian") - aix = flag.Bool("aix", false, "aix") - tags = flag.String("tags", "", "build tags") -) - -// cmdLine returns this programs's commandline arguments -func cmdLine() string { - return "go run mksyscall_aix_ppc64.go " + strings.Join(os.Args[1:], " ") -} - -// buildTags returns build tags -func buildTags() string { - return *tags -} - -// Param is function parameter -type Param struct { - Name string - Type string -} - -// usage prints the program usage -func usage() { - fmt.Fprintf(os.Stderr, "usage: go run mksyscall_aix_ppc64.go [-b32 | -l32] [-tags x,y] [file ...]\n") - os.Exit(1) -} - -// parseParamList parses parameter list and returns a slice of parameters -func parseParamList(list string) []string { - list = strings.TrimSpace(list) - if list == "" { - return []string{} - } - return regexp.MustCompile(`\s*,\s*`).Split(list, -1) -} - -// parseParam splits a parameter into name and type -func parseParam(p string) Param { - ps := regexp.MustCompile(`^(\S*) (\S*)$`).FindStringSubmatch(p) - if ps == nil { - fmt.Fprintf(os.Stderr, "malformed parameter: %s\n", p) - os.Exit(1) - } - return Param{ps[1], ps[2]} -} - -func main() { - flag.Usage = usage - flag.Parse() - if len(flag.Args()) <= 0 { - fmt.Fprintf(os.Stderr, "no files to parse provided\n") - usage() - } - - endianness := "" - if *b32 { - endianness = "big-endian" - } else if *l32 { - endianness = "little-endian" - } - - pack := "" - // GCCGO - textgccgo := "" - cExtern := "/*\n#include \n" - // GC - textgc := "" - dynimports := "" - linknames := "" - var vars []string - // COMMON - textcommon := "" - for _, path := range flag.Args() { - file, err := os.Open(path) - if err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - s := bufio.NewScanner(file) - for s.Scan() { - t := s.Text() - t = strings.TrimSpace(t) - t = regexp.MustCompile(`\s+`).ReplaceAllString(t, ` `) - if p := regexp.MustCompile(`^package (\S+)$`).FindStringSubmatch(t); p != nil && pack == "" { - pack = p[1] - } - nonblock := regexp.MustCompile(`^\/\/sysnb `).FindStringSubmatch(t) - if regexp.MustCompile(`^\/\/sys `).FindStringSubmatch(t) == nil && nonblock == nil { - continue - } - - // Line must be of the form - // func Open(path string, mode int, perm int) (fd int, err error) - // Split into name, in params, out params. - f := regexp.MustCompile(`^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*(?:(\w*)\.)?(\w*))?$`).FindStringSubmatch(t) - if f == nil { - fmt.Fprintf(os.Stderr, "%s:%s\nmalformed //sys declaration\n", path, t) - os.Exit(1) - } - funct, inps, outps, modname, sysname := f[2], f[3], f[4], f[5], f[6] - - // Split argument lists on comma. - in := parseParamList(inps) - out := parseParamList(outps) - - inps = strings.Join(in, ", ") - outps = strings.Join(out, ", ") - - if sysname == "" { - sysname = funct - } - - onlyCommon := false - if funct == "readlen" || funct == "writelen" || funct == "FcntlInt" || funct == "FcntlFlock" { - // This function call another syscall which is already implemented. - // Therefore, the gc and gccgo part must not be generated. - onlyCommon = true - } - - // Try in vain to keep people from editing this file. - // The theory is that they jump into the middle of the file - // without reading the header. - - textcommon += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n" - if !onlyCommon { - textgccgo += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n" - textgc += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n" - } - - // Check if value return, err return available - errvar := "" - rettype := "" - for _, param := range out { - p := parseParam(param) - if p.Type == "error" { - errvar = p.Name - } else { - rettype = p.Type - } - } - - sysname = regexp.MustCompile(`([a-z])([A-Z])`).ReplaceAllString(sysname, `${1}_$2`) - sysname = strings.ToLower(sysname) // All libc functions are lowercase. - - // GCCGO Prototype return type - cRettype := "" - if rettype == "unsafe.Pointer" { - cRettype = "uintptr_t" - } else if rettype == "uintptr" { - cRettype = "uintptr_t" - } else if regexp.MustCompile(`^_`).FindStringSubmatch(rettype) != nil { - cRettype = "uintptr_t" - } else if rettype == "int" { - cRettype = "int" - } else if rettype == "int32" { - cRettype = "int" - } else if rettype == "int64" { - cRettype = "long long" - } else if rettype == "uint32" { - cRettype = "unsigned int" - } else if rettype == "uint64" { - cRettype = "unsigned long long" - } else { - cRettype = "int" - } - if sysname == "exit" { - cRettype = "void" - } - - // GCCGO Prototype arguments type - var cIn []string - for i, param := range in { - p := parseParam(param) - if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil { - cIn = append(cIn, "uintptr_t") - } else if p.Type == "string" { - cIn = append(cIn, "uintptr_t") - } else if regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type) != nil { - cIn = append(cIn, "uintptr_t", "size_t") - } else if p.Type == "unsafe.Pointer" { - cIn = append(cIn, "uintptr_t") - } else if p.Type == "uintptr" { - cIn = append(cIn, "uintptr_t") - } else if regexp.MustCompile(`^_`).FindStringSubmatch(p.Type) != nil { - cIn = append(cIn, "uintptr_t") - } else if p.Type == "int" { - if (i == 0 || i == 2) && funct == "fcntl" { - // These fcntl arguments needs to be uintptr to be able to call FcntlInt and FcntlFlock - cIn = append(cIn, "uintptr_t") - } else { - cIn = append(cIn, "int") - } - - } else if p.Type == "int32" { - cIn = append(cIn, "int") - } else if p.Type == "int64" { - cIn = append(cIn, "long long") - } else if p.Type == "uint32" { - cIn = append(cIn, "unsigned int") - } else if p.Type == "uint64" { - cIn = append(cIn, "unsigned long long") - } else { - cIn = append(cIn, "int") - } - } - - if !onlyCommon { - // GCCGO Prototype Generation - // Imports of system calls from libc - if sysname == "select" { - // select is a keyword of Go. Its name is - // changed to c_select. - cExtern += "#define c_select select\n" - } - cExtern += fmt.Sprintf("%s %s", cRettype, sysname) - cIn := strings.Join(cIn, ", ") - cExtern += fmt.Sprintf("(%s);\n", cIn) - } - // GC Library name - if modname == "" { - modname = "libc.a/shr_64.o" - } else { - fmt.Fprintf(os.Stderr, "%s: only syscall using libc are available\n", funct) - os.Exit(1) - } - sysvarname := fmt.Sprintf("libc_%s", sysname) - - if !onlyCommon { - // GC Runtime import of function to allow cross-platform builds. - dynimports += fmt.Sprintf("//go:cgo_import_dynamic %s %s \"%s\"\n", sysvarname, sysname, modname) - // GC Link symbol to proc address variable. - linknames += fmt.Sprintf("//go:linkname %s %s\n", sysvarname, sysvarname) - // GC Library proc address variable. - vars = append(vars, sysvarname) - } - - strconvfunc := "BytePtrFromString" - strconvtype := "*byte" - - // Go function header. - if outps != "" { - outps = fmt.Sprintf(" (%s)", outps) - } - if textcommon != "" { - textcommon += "\n" - } - - textcommon += fmt.Sprintf("func %s(%s)%s {\n", funct, strings.Join(in, ", "), outps) - - // Prepare arguments tocall. - var argscommon []string // Arguments in the common part - var argscall []string // Arguments for call prototype - var argsgc []string // Arguments for gc call (with syscall6) - var argsgccgo []string // Arguments for gccgo call (with C.name_of_syscall) - n := 0 - argN := 0 - for _, param := range in { - p := parseParam(param) - if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil { - argscommon = append(argscommon, fmt.Sprintf("uintptr(unsafe.Pointer(%s))", p.Name)) - argscall = append(argscall, fmt.Sprintf("%s uintptr", p.Name)) - argsgc = append(argsgc, p.Name) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.uintptr_t(%s)", p.Name)) - } else if p.Type == "string" && errvar != "" { - textcommon += fmt.Sprintf("\tvar _p%d %s\n", n, strconvtype) - textcommon += fmt.Sprintf("\t_p%d, %s = %s(%s)\n", n, errvar, strconvfunc, p.Name) - textcommon += fmt.Sprintf("\tif %s != nil {\n\t\treturn\n\t}\n", errvar) - - argscommon = append(argscommon, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n)) - argscall = append(argscall, fmt.Sprintf("_p%d uintptr ", n)) - argsgc = append(argsgc, fmt.Sprintf("_p%d", n)) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.uintptr_t(_p%d)", n)) - n++ - } else if p.Type == "string" { - fmt.Fprintf(os.Stderr, path+":"+funct+" uses string arguments, but has no error return\n") - textcommon += fmt.Sprintf("\tvar _p%d %s\n", n, strconvtype) - textcommon += fmt.Sprintf("\t_p%d, %s = %s(%s)\n", n, errvar, strconvfunc, p.Name) - textcommon += fmt.Sprintf("\tif %s != nil {\n\t\treturn\n\t}\n", errvar) - - argscommon = append(argscommon, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n)) - argscall = append(argscall, fmt.Sprintf("_p%d uintptr", n)) - argsgc = append(argsgc, fmt.Sprintf("_p%d", n)) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.uintptr_t(_p%d)", n)) - n++ - } else if m := regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type); m != nil { - // Convert slice into pointer, length. - // Have to be careful not to take address of &a[0] if len == 0: - // pass nil in that case. - textcommon += fmt.Sprintf("\tvar _p%d *%s\n", n, m[1]) - textcommon += fmt.Sprintf("\tif len(%s) > 0 {\n\t\t_p%d = &%s[0]\n\t}\n", p.Name, n, p.Name) - argscommon = append(argscommon, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n), fmt.Sprintf("len(%s)", p.Name)) - argscall = append(argscall, fmt.Sprintf("_p%d uintptr", n), fmt.Sprintf("_lenp%d int", n)) - argsgc = append(argsgc, fmt.Sprintf("_p%d", n), fmt.Sprintf("uintptr(_lenp%d)", n)) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.uintptr_t(_p%d)", n), fmt.Sprintf("C.size_t(_lenp%d)", n)) - n++ - } else if p.Type == "int64" && endianness != "" { - fmt.Fprintf(os.Stderr, path+":"+funct+" uses int64 with 32 bits mode. Case not yet implemented\n") - } else if p.Type == "bool" { - fmt.Fprintf(os.Stderr, path+":"+funct+" uses bool. Case not yet implemented\n") - } else if regexp.MustCompile(`^_`).FindStringSubmatch(p.Type) != nil || p.Type == "unsafe.Pointer" { - argscommon = append(argscommon, fmt.Sprintf("uintptr(%s)", p.Name)) - argscall = append(argscall, fmt.Sprintf("%s uintptr", p.Name)) - argsgc = append(argsgc, p.Name) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.uintptr_t(%s)", p.Name)) - } else if p.Type == "int" { - if (argN == 0 || argN == 2) && ((funct == "fcntl") || (funct == "FcntlInt") || (funct == "FcntlFlock")) { - // These fcntl arguments need to be uintptr to be able to call FcntlInt and FcntlFlock - argscommon = append(argscommon, fmt.Sprintf("uintptr(%s)", p.Name)) - argscall = append(argscall, fmt.Sprintf("%s uintptr", p.Name)) - argsgc = append(argsgc, p.Name) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.uintptr_t(%s)", p.Name)) - - } else { - argscommon = append(argscommon, p.Name) - argscall = append(argscall, fmt.Sprintf("%s int", p.Name)) - argsgc = append(argsgc, fmt.Sprintf("uintptr(%s)", p.Name)) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.int(%s)", p.Name)) - } - } else if p.Type == "int32" { - argscommon = append(argscommon, p.Name) - argscall = append(argscall, fmt.Sprintf("%s int32", p.Name)) - argsgc = append(argsgc, fmt.Sprintf("uintptr(%s)", p.Name)) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.int(%s)", p.Name)) - } else if p.Type == "int64" { - argscommon = append(argscommon, p.Name) - argscall = append(argscall, fmt.Sprintf("%s int64", p.Name)) - argsgc = append(argsgc, fmt.Sprintf("uintptr(%s)", p.Name)) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.longlong(%s)", p.Name)) - } else if p.Type == "uint32" { - argscommon = append(argscommon, p.Name) - argscall = append(argscall, fmt.Sprintf("%s uint32", p.Name)) - argsgc = append(argsgc, fmt.Sprintf("uintptr(%s)", p.Name)) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.uint(%s)", p.Name)) - } else if p.Type == "uint64" { - argscommon = append(argscommon, p.Name) - argscall = append(argscall, fmt.Sprintf("%s uint64", p.Name)) - argsgc = append(argsgc, fmt.Sprintf("uintptr(%s)", p.Name)) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.ulonglong(%s)", p.Name)) - } else if p.Type == "uintptr" { - argscommon = append(argscommon, p.Name) - argscall = append(argscall, fmt.Sprintf("%s uintptr", p.Name)) - argsgc = append(argsgc, p.Name) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.uintptr_t(%s)", p.Name)) - } else { - argscommon = append(argscommon, fmt.Sprintf("int(%s)", p.Name)) - argscall = append(argscall, fmt.Sprintf("%s int", p.Name)) - argsgc = append(argsgc, fmt.Sprintf("uintptr(%s)", p.Name)) - argsgccgo = append(argsgccgo, fmt.Sprintf("C.int(%s)", p.Name)) - } - argN++ - } - nargs := len(argsgc) - - // COMMON function generation - argscommonlist := strings.Join(argscommon, ", ") - callcommon := fmt.Sprintf("call%s(%s)", sysname, argscommonlist) - ret := []string{"_", "_"} - body := "" - doErrno := false - for i := 0; i < len(out); i++ { - p := parseParam(out[i]) - reg := "" - if p.Name == "err" { - reg = "e1" - ret[1] = reg - doErrno = true - } else { - reg = "r0" - ret[0] = reg - } - if p.Type == "bool" { - reg = fmt.Sprintf("%s != 0", reg) - } - if reg != "e1" { - body += fmt.Sprintf("\t%s = %s(%s)\n", p.Name, p.Type, reg) - } - } - if ret[0] == "_" && ret[1] == "_" { - textcommon += fmt.Sprintf("\t%s\n", callcommon) - } else { - textcommon += fmt.Sprintf("\t%s, %s := %s\n", ret[0], ret[1], callcommon) - } - textcommon += body - - if doErrno { - textcommon += "\tif e1 != 0 {\n" - textcommon += "\t\terr = errnoErr(e1)\n" - textcommon += "\t}\n" - } - textcommon += "\treturn\n" - textcommon += "}\n" - - if onlyCommon { - continue - } - - // CALL Prototype - callProto := fmt.Sprintf("func call%s(%s) (r1 uintptr, e1 Errno) {\n", sysname, strings.Join(argscall, ", ")) - - // GC function generation - asm := "syscall6" - if nonblock != nil { - asm = "rawSyscall6" - } - - if len(argsgc) <= 6 { - for len(argsgc) < 6 { - argsgc = append(argsgc, "0") - } - } else { - fmt.Fprintf(os.Stderr, "%s: too many arguments to system call", funct) - os.Exit(1) - } - argsgclist := strings.Join(argsgc, ", ") - callgc := fmt.Sprintf("%s(uintptr(unsafe.Pointer(&%s)), %d, %s)", asm, sysvarname, nargs, argsgclist) - - textgc += callProto - textgc += fmt.Sprintf("\tr1, _, e1 = %s\n", callgc) - textgc += "\treturn\n}\n" - - // GCCGO function generation - argsgccgolist := strings.Join(argsgccgo, ", ") - var callgccgo string - if sysname == "select" { - // select is a keyword of Go. Its name is - // changed to c_select. - callgccgo = fmt.Sprintf("C.c_%s(%s)", sysname, argsgccgolist) - } else { - callgccgo = fmt.Sprintf("C.%s(%s)", sysname, argsgccgolist) - } - textgccgo += callProto - textgccgo += fmt.Sprintf("\tr1 = uintptr(%s)\n", callgccgo) - textgccgo += "\te1 = syscall.GetErrno()\n" - textgccgo += "\treturn\n}\n" - } - if err := s.Err(); err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - file.Close() - } - imp := "" - if pack != "unix" { - imp = "import \"golang.org/x/sys/unix\"\n" - - } - - // Print zsyscall_aix_ppc64.go - err := ioutil.WriteFile("zsyscall_aix_ppc64.go", - []byte(fmt.Sprintf(srcTemplate1, cmdLine(), buildTags(), pack, imp, textcommon)), - 0644) - if err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - - // Print zsyscall_aix_ppc64_gc.go - vardecls := "\t" + strings.Join(vars, ",\n\t") - vardecls += " syscallFunc" - err = ioutil.WriteFile("zsyscall_aix_ppc64_gc.go", - []byte(fmt.Sprintf(srcTemplate2, cmdLine(), buildTags(), pack, imp, dynimports, linknames, vardecls, textgc)), - 0644) - if err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - - // Print zsyscall_aix_ppc64_gccgo.go - err = ioutil.WriteFile("zsyscall_aix_ppc64_gccgo.go", - []byte(fmt.Sprintf(srcTemplate3, cmdLine(), buildTags(), pack, cExtern, imp, textgccgo)), - 0644) - if err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } -} - -const srcTemplate1 = `// %s -// Code generated by the command above; see README.md. DO NOT EDIT. - -// +build %s - -package %s - -import ( - "unsafe" -) - - -%s - -%s -` -const srcTemplate2 = `// %s -// Code generated by the command above; see README.md. DO NOT EDIT. - -// +build %s -// +build !gccgo - -package %s - -import ( - "unsafe" -) -%s -%s -%s -type syscallFunc uintptr - -var ( -%s -) - -// Implemented in runtime/syscall_aix.go. -func rawSyscall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno) -func syscall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno) - -%s -` -const srcTemplate3 = `// %s -// Code generated by the command above; see README.md. DO NOT EDIT. - -// +build %s -// +build gccgo - -package %s - -%s -*/ -import "C" -import ( - "syscall" -) - - -%s - -%s -` diff --git a/vendor/golang.org/x/sys/unix/mksyscall_solaris.go b/vendor/golang.org/x/sys/unix/mksyscall_solaris.go deleted file mode 100644 index 3d864738..00000000 --- a/vendor/golang.org/x/sys/unix/mksyscall_solaris.go +++ /dev/null @@ -1,335 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* - This program reads a file containing function prototypes - (like syscall_solaris.go) and generates system call bodies. - The prototypes are marked by lines beginning with "//sys" - and read like func declarations if //sys is replaced by func, but: - * The parameter lists must give a name for each argument. - This includes return parameters. - * The parameter lists must give a type for each argument: - the (x, y, z int) shorthand is not allowed. - * If the return parameter is an error number, it must be named err. - * If go func name needs to be different than its libc name, - * or the function is not in libc, name could be specified - * at the end, after "=" sign, like - //sys getsockopt(s int, level int, name int, val uintptr, vallen *_Socklen) (err error) = libsocket.getsockopt -*/ - -package main - -import ( - "bufio" - "flag" - "fmt" - "os" - "regexp" - "strings" -) - -var ( - b32 = flag.Bool("b32", false, "32bit big-endian") - l32 = flag.Bool("l32", false, "32bit little-endian") - tags = flag.String("tags", "", "build tags") -) - -// cmdLine returns this programs's commandline arguments -func cmdLine() string { - return "go run mksyscall_solaris.go " + strings.Join(os.Args[1:], " ") -} - -// buildTags returns build tags -func buildTags() string { - return *tags -} - -// Param is function parameter -type Param struct { - Name string - Type string -} - -// usage prints the program usage -func usage() { - fmt.Fprintf(os.Stderr, "usage: go run mksyscall_solaris.go [-b32 | -l32] [-tags x,y] [file ...]\n") - os.Exit(1) -} - -// parseParamList parses parameter list and returns a slice of parameters -func parseParamList(list string) []string { - list = strings.TrimSpace(list) - if list == "" { - return []string{} - } - return regexp.MustCompile(`\s*,\s*`).Split(list, -1) -} - -// parseParam splits a parameter into name and type -func parseParam(p string) Param { - ps := regexp.MustCompile(`^(\S*) (\S*)$`).FindStringSubmatch(p) - if ps == nil { - fmt.Fprintf(os.Stderr, "malformed parameter: %s\n", p) - os.Exit(1) - } - return Param{ps[1], ps[2]} -} - -func main() { - flag.Usage = usage - flag.Parse() - if len(flag.Args()) <= 0 { - fmt.Fprintf(os.Stderr, "no files to parse provided\n") - usage() - } - - endianness := "" - if *b32 { - endianness = "big-endian" - } else if *l32 { - endianness = "little-endian" - } - - pack := "" - text := "" - dynimports := "" - linknames := "" - var vars []string - for _, path := range flag.Args() { - file, err := os.Open(path) - if err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - s := bufio.NewScanner(file) - for s.Scan() { - t := s.Text() - t = strings.TrimSpace(t) - t = regexp.MustCompile(`\s+`).ReplaceAllString(t, ` `) - if p := regexp.MustCompile(`^package (\S+)$`).FindStringSubmatch(t); p != nil && pack == "" { - pack = p[1] - } - nonblock := regexp.MustCompile(`^\/\/sysnb `).FindStringSubmatch(t) - if regexp.MustCompile(`^\/\/sys `).FindStringSubmatch(t) == nil && nonblock == nil { - continue - } - - // Line must be of the form - // func Open(path string, mode int, perm int) (fd int, err error) - // Split into name, in params, out params. - f := regexp.MustCompile(`^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*(?:(\w*)\.)?(\w*))?$`).FindStringSubmatch(t) - if f == nil { - fmt.Fprintf(os.Stderr, "%s:%s\nmalformed //sys declaration\n", path, t) - os.Exit(1) - } - funct, inps, outps, modname, sysname := f[2], f[3], f[4], f[5], f[6] - - // Split argument lists on comma. - in := parseParamList(inps) - out := parseParamList(outps) - - inps = strings.Join(in, ", ") - outps = strings.Join(out, ", ") - - // Try in vain to keep people from editing this file. - // The theory is that they jump into the middle of the file - // without reading the header. - text += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n" - - // So file name. - if modname == "" { - modname = "libc" - } - - // System call name. - if sysname == "" { - sysname = funct - } - - // System call pointer variable name. - sysvarname := fmt.Sprintf("proc%s", sysname) - - strconvfunc := "BytePtrFromString" - strconvtype := "*byte" - - sysname = strings.ToLower(sysname) // All libc functions are lowercase. - - // Runtime import of function to allow cross-platform builds. - dynimports += fmt.Sprintf("//go:cgo_import_dynamic libc_%s %s \"%s.so\"\n", sysname, sysname, modname) - // Link symbol to proc address variable. - linknames += fmt.Sprintf("//go:linkname %s libc_%s\n", sysvarname, sysname) - // Library proc address variable. - vars = append(vars, sysvarname) - - // Go function header. - outlist := strings.Join(out, ", ") - if outlist != "" { - outlist = fmt.Sprintf(" (%s)", outlist) - } - if text != "" { - text += "\n" - } - text += fmt.Sprintf("func %s(%s)%s {\n", funct, strings.Join(in, ", "), outlist) - - // Check if err return available - errvar := "" - for _, param := range out { - p := parseParam(param) - if p.Type == "error" { - errvar = p.Name - continue - } - } - - // Prepare arguments to Syscall. - var args []string - n := 0 - for _, param := range in { - p := parseParam(param) - if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil { - args = append(args, "uintptr(unsafe.Pointer("+p.Name+"))") - } else if p.Type == "string" && errvar != "" { - text += fmt.Sprintf("\tvar _p%d %s\n", n, strconvtype) - text += fmt.Sprintf("\t_p%d, %s = %s(%s)\n", n, errvar, strconvfunc, p.Name) - text += fmt.Sprintf("\tif %s != nil {\n\t\treturn\n\t}\n", errvar) - args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n)) - n++ - } else if p.Type == "string" { - fmt.Fprintf(os.Stderr, path+":"+funct+" uses string arguments, but has no error return\n") - text += fmt.Sprintf("\tvar _p%d %s\n", n, strconvtype) - text += fmt.Sprintf("\t_p%d, _ = %s(%s)\n", n, strconvfunc, p.Name) - args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n)) - n++ - } else if s := regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type); s != nil { - // Convert slice into pointer, length. - // Have to be careful not to take address of &a[0] if len == 0: - // pass nil in that case. - text += fmt.Sprintf("\tvar _p%d *%s\n", n, s[1]) - text += fmt.Sprintf("\tif len(%s) > 0 {\n\t\t_p%d = &%s[0]\n\t}\n", p.Name, n, p.Name) - args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n), fmt.Sprintf("uintptr(len(%s))", p.Name)) - n++ - } else if p.Type == "int64" && endianness != "" { - if endianness == "big-endian" { - args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name)) - } else { - args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name)) - } - } else if p.Type == "bool" { - text += fmt.Sprintf("\tvar _p%d uint32\n", n) - text += fmt.Sprintf("\tif %s {\n\t\t_p%d = 1\n\t} else {\n\t\t_p%d = 0\n\t}\n", p.Name, n, n) - args = append(args, fmt.Sprintf("uintptr(_p%d)", n)) - n++ - } else { - args = append(args, fmt.Sprintf("uintptr(%s)", p.Name)) - } - } - nargs := len(args) - - // Determine which form to use; pad args with zeros. - asm := "sysvicall6" - if nonblock != nil { - asm = "rawSysvicall6" - } - if len(args) <= 6 { - for len(args) < 6 { - args = append(args, "0") - } - } else { - fmt.Fprintf(os.Stderr, "%s: too many arguments to system call\n", path) - os.Exit(1) - } - - // Actual call. - arglist := strings.Join(args, ", ") - call := fmt.Sprintf("%s(uintptr(unsafe.Pointer(&%s)), %d, %s)", asm, sysvarname, nargs, arglist) - - // Assign return values. - body := "" - ret := []string{"_", "_", "_"} - doErrno := false - for i := 0; i < len(out); i++ { - p := parseParam(out[i]) - reg := "" - if p.Name == "err" { - reg = "e1" - ret[2] = reg - doErrno = true - } else { - reg = fmt.Sprintf("r%d", i) - ret[i] = reg - } - if p.Type == "bool" { - reg = fmt.Sprintf("%d != 0", reg) - } - if p.Type == "int64" && endianness != "" { - // 64-bit number in r1:r0 or r0:r1. - if i+2 > len(out) { - fmt.Fprintf(os.Stderr, "%s: not enough registers for int64 return\n", path) - os.Exit(1) - } - if endianness == "big-endian" { - reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i, i+1) - } else { - reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i+1, i) - } - ret[i] = fmt.Sprintf("r%d", i) - ret[i+1] = fmt.Sprintf("r%d", i+1) - } - if reg != "e1" { - body += fmt.Sprintf("\t%s = %s(%s)\n", p.Name, p.Type, reg) - } - } - if ret[0] == "_" && ret[1] == "_" && ret[2] == "_" { - text += fmt.Sprintf("\t%s\n", call) - } else { - text += fmt.Sprintf("\t%s, %s, %s := %s\n", ret[0], ret[1], ret[2], call) - } - text += body - - if doErrno { - text += "\tif e1 != 0 {\n" - text += "\t\terr = e1\n" - text += "\t}\n" - } - text += "\treturn\n" - text += "}\n" - } - if err := s.Err(); err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - file.Close() - } - imp := "" - if pack != "unix" { - imp = "import \"golang.org/x/sys/unix\"\n" - - } - vardecls := "\t" + strings.Join(vars, ",\n\t") - vardecls += " syscallFunc" - fmt.Printf(srcTemplate, cmdLine(), buildTags(), pack, imp, dynimports, linknames, vardecls, text) -} - -const srcTemplate = `// %s -// Code generated by the command above; see README.md. DO NOT EDIT. - -// +build %s - -package %s - -import ( - "syscall" - "unsafe" -) -%s -%s -%s -var ( -%s -) - -%s -` diff --git a/vendor/golang.org/x/sys/unix/mksysctl_openbsd.go b/vendor/golang.org/x/sys/unix/mksysctl_openbsd.go deleted file mode 100644 index b6b40990..00000000 --- a/vendor/golang.org/x/sys/unix/mksysctl_openbsd.go +++ /dev/null @@ -1,355 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// Parse the header files for OpenBSD and generate a Go usable sysctl MIB. -// -// Build a MIB with each entry being an array containing the level, type and -// a hash that will contain additional entries if the current entry is a node. -// We then walk this MIB and create a flattened sysctl name to OID hash. - -package main - -import ( - "bufio" - "fmt" - "os" - "path/filepath" - "regexp" - "sort" - "strings" -) - -var ( - goos, goarch string -) - -// cmdLine returns this programs's commandline arguments. -func cmdLine() string { - return "go run mksysctl_openbsd.go " + strings.Join(os.Args[1:], " ") -} - -// buildTags returns build tags. -func buildTags() string { - return fmt.Sprintf("%s,%s", goarch, goos) -} - -// reMatch performs regular expression match and stores the substring slice to value pointed by m. -func reMatch(re *regexp.Regexp, str string, m *[]string) bool { - *m = re.FindStringSubmatch(str) - if *m != nil { - return true - } - return false -} - -type nodeElement struct { - n int - t string - pE *map[string]nodeElement -} - -var ( - debugEnabled bool - mib map[string]nodeElement - node *map[string]nodeElement - nodeMap map[string]string - sysCtl []string -) - -var ( - ctlNames1RE = regexp.MustCompile(`^#define\s+(CTL_NAMES)\s+{`) - ctlNames2RE = regexp.MustCompile(`^#define\s+(CTL_(.*)_NAMES)\s+{`) - ctlNames3RE = regexp.MustCompile(`^#define\s+((.*)CTL_NAMES)\s+{`) - netInetRE = regexp.MustCompile(`^netinet/`) - netInet6RE = regexp.MustCompile(`^netinet6/`) - netRE = regexp.MustCompile(`^net/`) - bracesRE = regexp.MustCompile(`{.*}`) - ctlTypeRE = regexp.MustCompile(`{\s+"(\w+)",\s+(CTLTYPE_[A-Z]+)\s+}`) - fsNetKernRE = regexp.MustCompile(`^(fs|net|kern)_`) -) - -func debug(s string) { - if debugEnabled { - fmt.Fprintln(os.Stderr, s) - } -} - -// Walk the MIB and build a sysctl name to OID mapping. -func buildSysctl(pNode *map[string]nodeElement, name string, oid []int) { - lNode := pNode // local copy of pointer to node - var keys []string - for k := range *lNode { - keys = append(keys, k) - } - sort.Strings(keys) - - for _, key := range keys { - nodename := name - if name != "" { - nodename += "." - } - nodename += key - - nodeoid := append(oid, (*pNode)[key].n) - - if (*pNode)[key].t == `CTLTYPE_NODE` { - if _, ok := nodeMap[nodename]; ok { - lNode = &mib - ctlName := nodeMap[nodename] - for _, part := range strings.Split(ctlName, ".") { - lNode = ((*lNode)[part]).pE - } - } else { - lNode = (*pNode)[key].pE - } - buildSysctl(lNode, nodename, nodeoid) - } else if (*pNode)[key].t != "" { - oidStr := []string{} - for j := range nodeoid { - oidStr = append(oidStr, fmt.Sprintf("%d", nodeoid[j])) - } - text := "\t{ \"" + nodename + "\", []_C_int{ " + strings.Join(oidStr, ", ") + " } }, \n" - sysCtl = append(sysCtl, text) - } - } -} - -func main() { - // Get the OS (using GOOS_TARGET if it exist) - goos = os.Getenv("GOOS_TARGET") - if goos == "" { - goos = os.Getenv("GOOS") - } - // Get the architecture (using GOARCH_TARGET if it exists) - goarch = os.Getenv("GOARCH_TARGET") - if goarch == "" { - goarch = os.Getenv("GOARCH") - } - // Check if GOOS and GOARCH environment variables are defined - if goarch == "" || goos == "" { - fmt.Fprintf(os.Stderr, "GOARCH or GOOS not defined in environment\n") - os.Exit(1) - } - - mib = make(map[string]nodeElement) - headers := [...]string{ - `sys/sysctl.h`, - `sys/socket.h`, - `sys/tty.h`, - `sys/malloc.h`, - `sys/mount.h`, - `sys/namei.h`, - `sys/sem.h`, - `sys/shm.h`, - `sys/vmmeter.h`, - `uvm/uvmexp.h`, - `uvm/uvm_param.h`, - `uvm/uvm_swap_encrypt.h`, - `ddb/db_var.h`, - `net/if.h`, - `net/if_pfsync.h`, - `net/pipex.h`, - `netinet/in.h`, - `netinet/icmp_var.h`, - `netinet/igmp_var.h`, - `netinet/ip_ah.h`, - `netinet/ip_carp.h`, - `netinet/ip_divert.h`, - `netinet/ip_esp.h`, - `netinet/ip_ether.h`, - `netinet/ip_gre.h`, - `netinet/ip_ipcomp.h`, - `netinet/ip_ipip.h`, - `netinet/pim_var.h`, - `netinet/tcp_var.h`, - `netinet/udp_var.h`, - `netinet6/in6.h`, - `netinet6/ip6_divert.h`, - `netinet6/pim6_var.h`, - `netinet/icmp6.h`, - `netmpls/mpls.h`, - } - - ctls := [...]string{ - `kern`, - `vm`, - `fs`, - `net`, - //debug /* Special handling required */ - `hw`, - //machdep /* Arch specific */ - `user`, - `ddb`, - //vfs /* Special handling required */ - `fs.posix`, - `kern.forkstat`, - `kern.intrcnt`, - `kern.malloc`, - `kern.nchstats`, - `kern.seminfo`, - `kern.shminfo`, - `kern.timecounter`, - `kern.tty`, - `kern.watchdog`, - `net.bpf`, - `net.ifq`, - `net.inet`, - `net.inet.ah`, - `net.inet.carp`, - `net.inet.divert`, - `net.inet.esp`, - `net.inet.etherip`, - `net.inet.gre`, - `net.inet.icmp`, - `net.inet.igmp`, - `net.inet.ip`, - `net.inet.ip.ifq`, - `net.inet.ipcomp`, - `net.inet.ipip`, - `net.inet.mobileip`, - `net.inet.pfsync`, - `net.inet.pim`, - `net.inet.tcp`, - `net.inet.udp`, - `net.inet6`, - `net.inet6.divert`, - `net.inet6.ip6`, - `net.inet6.icmp6`, - `net.inet6.pim6`, - `net.inet6.tcp6`, - `net.inet6.udp6`, - `net.mpls`, - `net.mpls.ifq`, - `net.key`, - `net.pflow`, - `net.pfsync`, - `net.pipex`, - `net.rt`, - `vm.swapencrypt`, - //vfsgenctl /* Special handling required */ - } - - // Node name "fixups" - ctlMap := map[string]string{ - "ipproto": "net.inet", - "net.inet.ipproto": "net.inet", - "net.inet6.ipv6proto": "net.inet6", - "net.inet6.ipv6": "net.inet6.ip6", - "net.inet.icmpv6": "net.inet6.icmp6", - "net.inet6.divert6": "net.inet6.divert", - "net.inet6.tcp6": "net.inet.tcp", - "net.inet6.udp6": "net.inet.udp", - "mpls": "net.mpls", - "swpenc": "vm.swapencrypt", - } - - // Node mappings - nodeMap = map[string]string{ - "net.inet.ip.ifq": "net.ifq", - "net.inet.pfsync": "net.pfsync", - "net.mpls.ifq": "net.ifq", - } - - mCtls := make(map[string]bool) - for _, ctl := range ctls { - mCtls[ctl] = true - } - - for _, header := range headers { - debug("Processing " + header) - file, err := os.Open(filepath.Join("/usr/include", header)) - if err != nil { - fmt.Fprintf(os.Stderr, "%v\n", err) - os.Exit(1) - } - s := bufio.NewScanner(file) - for s.Scan() { - var sub []string - if reMatch(ctlNames1RE, s.Text(), &sub) || - reMatch(ctlNames2RE, s.Text(), &sub) || - reMatch(ctlNames3RE, s.Text(), &sub) { - if sub[1] == `CTL_NAMES` { - // Top level. - node = &mib - } else { - // Node. - nodename := strings.ToLower(sub[2]) - ctlName := "" - if reMatch(netInetRE, header, &sub) { - ctlName = "net.inet." + nodename - } else if reMatch(netInet6RE, header, &sub) { - ctlName = "net.inet6." + nodename - } else if reMatch(netRE, header, &sub) { - ctlName = "net." + nodename - } else { - ctlName = nodename - ctlName = fsNetKernRE.ReplaceAllString(ctlName, `$1.`) - } - - if val, ok := ctlMap[ctlName]; ok { - ctlName = val - } - if _, ok := mCtls[ctlName]; !ok { - debug("Ignoring " + ctlName + "...") - continue - } - - // Walk down from the top of the MIB. - node = &mib - for _, part := range strings.Split(ctlName, ".") { - if _, ok := (*node)[part]; !ok { - debug("Missing node " + part) - (*node)[part] = nodeElement{n: 0, t: "", pE: &map[string]nodeElement{}} - } - node = (*node)[part].pE - } - } - - // Populate current node with entries. - i := -1 - for !strings.HasPrefix(s.Text(), "}") { - s.Scan() - if reMatch(bracesRE, s.Text(), &sub) { - i++ - } - if !reMatch(ctlTypeRE, s.Text(), &sub) { - continue - } - (*node)[sub[1]] = nodeElement{n: i, t: sub[2], pE: &map[string]nodeElement{}} - } - } - } - err = s.Err() - if err != nil { - fmt.Fprintf(os.Stderr, "%v\n", err) - os.Exit(1) - } - file.Close() - } - buildSysctl(&mib, "", []int{}) - - sort.Strings(sysCtl) - text := strings.Join(sysCtl, "") - - fmt.Printf(srcTemplate, cmdLine(), buildTags(), text) -} - -const srcTemplate = `// %s -// Code generated by the command above; DO NOT EDIT. - -// +build %s - -package unix - -type mibentry struct { - ctlname string - ctloid []_C_int -} - -var sysctlMib = []mibentry { -%s -} -` diff --git a/vendor/golang.org/x/sys/unix/mksysnum.go b/vendor/golang.org/x/sys/unix/mksysnum.go deleted file mode 100644 index baa6ecd8..00000000 --- a/vendor/golang.org/x/sys/unix/mksysnum.go +++ /dev/null @@ -1,190 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// Generate system call table for DragonFly, NetBSD, -// FreeBSD, OpenBSD or Darwin from master list -// (for example, /usr/src/sys/kern/syscalls.master or -// sys/syscall.h). -package main - -import ( - "bufio" - "fmt" - "io" - "io/ioutil" - "net/http" - "os" - "regexp" - "strings" -) - -var ( - goos, goarch string -) - -// cmdLine returns this programs's commandline arguments -func cmdLine() string { - return "go run mksysnum.go " + strings.Join(os.Args[1:], " ") -} - -// buildTags returns build tags -func buildTags() string { - return fmt.Sprintf("%s,%s", goarch, goos) -} - -func checkErr(err error) { - if err != nil { - fmt.Fprintf(os.Stderr, "%v\n", err) - os.Exit(1) - } -} - -// source string and substring slice for regexp -type re struct { - str string // source string - sub []string // matched sub-string -} - -// Match performs regular expression match -func (r *re) Match(exp string) bool { - r.sub = regexp.MustCompile(exp).FindStringSubmatch(r.str) - if r.sub != nil { - return true - } - return false -} - -// fetchFile fetches a text file from URL -func fetchFile(URL string) io.Reader { - resp, err := http.Get(URL) - checkErr(err) - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - checkErr(err) - return strings.NewReader(string(body)) -} - -// readFile reads a text file from path -func readFile(path string) io.Reader { - file, err := os.Open(os.Args[1]) - checkErr(err) - return file -} - -func format(name, num, proto string) string { - name = strings.ToUpper(name) - // There are multiple entries for enosys and nosys, so comment them out. - nm := re{str: name} - if nm.Match(`^SYS_E?NOSYS$`) { - name = fmt.Sprintf("// %s", name) - } - if name == `SYS_SYS_EXIT` { - name = `SYS_EXIT` - } - return fmt.Sprintf(" %s = %s; // %s\n", name, num, proto) -} - -func main() { - // Get the OS (using GOOS_TARGET if it exist) - goos = os.Getenv("GOOS_TARGET") - if goos == "" { - goos = os.Getenv("GOOS") - } - // Get the architecture (using GOARCH_TARGET if it exists) - goarch = os.Getenv("GOARCH_TARGET") - if goarch == "" { - goarch = os.Getenv("GOARCH") - } - // Check if GOOS and GOARCH environment variables are defined - if goarch == "" || goos == "" { - fmt.Fprintf(os.Stderr, "GOARCH or GOOS not defined in environment\n") - os.Exit(1) - } - - file := strings.TrimSpace(os.Args[1]) - var syscalls io.Reader - if strings.HasPrefix(file, "https://") || strings.HasPrefix(file, "http://") { - // Download syscalls.master file - syscalls = fetchFile(file) - } else { - syscalls = readFile(file) - } - - var text, line string - s := bufio.NewScanner(syscalls) - for s.Scan() { - t := re{str: line} - if t.Match(`^(.*)\\$`) { - // Handle continuation - line = t.sub[1] - line += strings.TrimLeft(s.Text(), " \t") - } else { - // New line - line = s.Text() - } - t = re{str: line} - if t.Match(`\\$`) { - continue - } - t = re{str: line} - - switch goos { - case "dragonfly": - if t.Match(`^([0-9]+)\s+STD\s+({ \S+\s+(\w+).*)$`) { - num, proto := t.sub[1], t.sub[2] - name := fmt.Sprintf("SYS_%s", t.sub[3]) - text += format(name, num, proto) - } - case "freebsd": - if t.Match(`^([0-9]+)\s+\S+\s+(?:(?:NO)?STD|COMPAT10)\s+({ \S+\s+(\w+).*)$`) { - num, proto := t.sub[1], t.sub[2] - name := fmt.Sprintf("SYS_%s", t.sub[3]) - text += format(name, num, proto) - } - case "openbsd": - if t.Match(`^([0-9]+)\s+STD\s+(NOLOCK\s+)?({ \S+\s+\*?(\w+).*)$`) { - num, proto, name := t.sub[1], t.sub[3], t.sub[4] - text += format(name, num, proto) - } - case "netbsd": - if t.Match(`^([0-9]+)\s+((STD)|(NOERR))\s+(RUMP\s+)?({\s+\S+\s*\*?\s*\|(\S+)\|(\S*)\|(\w+).*\s+})(\s+(\S+))?$`) { - num, proto, compat := t.sub[1], t.sub[6], t.sub[8] - name := t.sub[7] + "_" + t.sub[9] - if t.sub[11] != "" { - name = t.sub[7] + "_" + t.sub[11] - } - name = strings.ToUpper(name) - if compat == "" || compat == "13" || compat == "30" || compat == "50" { - text += fmt.Sprintf(" %s = %s; // %s\n", name, num, proto) - } - } - case "darwin": - if t.Match(`^#define\s+SYS_(\w+)\s+([0-9]+)`) { - name, num := t.sub[1], t.sub[2] - name = strings.ToUpper(name) - text += fmt.Sprintf(" SYS_%s = %s;\n", name, num) - } - default: - fmt.Fprintf(os.Stderr, "unrecognized GOOS=%s\n", goos) - os.Exit(1) - - } - } - err := s.Err() - checkErr(err) - - fmt.Printf(template, cmdLine(), buildTags(), text) -} - -const template = `// %s -// Code generated by the command above; see README.md. DO NOT EDIT. - -// +build %s - -package unix - -const( -%s)` diff --git a/vendor/golang.org/x/sys/unix/types_aix.go b/vendor/golang.org/x/sys/unix/types_aix.go deleted file mode 100644 index 40d2beed..00000000 --- a/vendor/golang.org/x/sys/unix/types_aix.go +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore -// +build aix - -/* -Input to cgo -godefs. See also mkerrors.sh and mkall.sh -*/ - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package unix - -/* -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include - - -#include -#include - -enum { - sizeofPtr = sizeof(void*), -}; - -union sockaddr_all { - struct sockaddr s1; // this one gets used for fields - struct sockaddr_in s2; // these pad it out - struct sockaddr_in6 s3; - struct sockaddr_un s4; - struct sockaddr_dl s5; -}; - -struct sockaddr_any { - struct sockaddr addr; - char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; -}; - -*/ -import "C" - -// Machine characteristics - -const ( - SizeofPtr = C.sizeofPtr - SizeofShort = C.sizeof_short - SizeofInt = C.sizeof_int - SizeofLong = C.sizeof_long - SizeofLongLong = C.sizeof_longlong - PathMax = C.PATH_MAX -) - -// Basic types - -type ( - _C_short C.short - _C_int C.int - _C_long C.long - _C_long_long C.longlong -) - -type off64 C.off64_t -type off C.off_t -type Mode_t C.mode_t - -// Time - -type Timespec C.struct_timespec - -type Timeval C.struct_timeval - -type Timeval32 C.struct_timeval32 - -type Timex C.struct_timex - -type Time_t C.time_t - -type Tms C.struct_tms - -type Utimbuf C.struct_utimbuf - -type Timezone C.struct_timezone - -// Processes - -type Rusage C.struct_rusage - -type Rlimit C.struct_rlimit64 - -type Pid_t C.pid_t - -type _Gid_t C.gid_t - -type dev_t C.dev_t - -// Files - -type Stat_t C.struct_stat - -type StatxTimestamp C.struct_statx_timestamp - -type Statx_t C.struct_statx - -type Dirent C.struct_dirent - -// Sockets - -type RawSockaddrInet4 C.struct_sockaddr_in - -type RawSockaddrInet6 C.struct_sockaddr_in6 - -type RawSockaddrUnix C.struct_sockaddr_un - -type RawSockaddrDatalink C.struct_sockaddr_dl - -type RawSockaddr C.struct_sockaddr - -type RawSockaddrAny C.struct_sockaddr_any - -type _Socklen C.socklen_t - -type Cmsghdr C.struct_cmsghdr - -type ICMPv6Filter C.struct_icmp6_filter - -type Iovec C.struct_iovec - -type IPMreq C.struct_ip_mreq - -type IPv6Mreq C.struct_ipv6_mreq - -type IPv6MTUInfo C.struct_ip6_mtuinfo - -type Linger C.struct_linger - -type Msghdr C.struct_msghdr - -const ( - SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in - SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - SizeofSockaddrAny = C.sizeof_struct_sockaddr_any - SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un - SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl - SizeofLinger = C.sizeof_struct_linger - SizeofIPMreq = C.sizeof_struct_ip_mreq - SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo - SizeofMsghdr = C.sizeof_struct_msghdr - SizeofCmsghdr = C.sizeof_struct_cmsghdr - SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -// Routing and interface messages - -const ( - SizeofIfMsghdr = C.sizeof_struct_if_msghdr -) - -type IfMsgHdr C.struct_if_msghdr - -// Misc - -type FdSet C.fd_set - -type Utsname C.struct_utsname - -type Ustat_t C.struct_ustat - -type Sigset_t C.sigset_t - -const ( - AT_FDCWD = C.AT_FDCWD - AT_REMOVEDIR = C.AT_REMOVEDIR - AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW -) - -// Terminal handling - -type Termios C.struct_termios - -type Termio C.struct_termio - -type Winsize C.struct_winsize - -//poll - -type PollFd struct { - Fd int32 - Events uint16 - Revents uint16 -} - -const ( - POLLERR = C.POLLERR - POLLHUP = C.POLLHUP - POLLIN = C.POLLIN - POLLNVAL = C.POLLNVAL - POLLOUT = C.POLLOUT - POLLPRI = C.POLLPRI - POLLRDBAND = C.POLLRDBAND - POLLRDNORM = C.POLLRDNORM - POLLWRBAND = C.POLLWRBAND - POLLWRNORM = C.POLLWRNORM -) - -//flock_t - -type Flock_t C.struct_flock64 - -// Statfs - -type Fsid_t C.struct_fsid_t -type Fsid64_t C.struct_fsid64_t - -type Statfs_t C.struct_statfs - -const RNDGETENTCNT = 0x80045200 diff --git a/vendor/golang.org/x/sys/unix/types_darwin.go b/vendor/golang.org/x/sys/unix/types_darwin.go deleted file mode 100644 index 155c2e69..00000000 --- a/vendor/golang.org/x/sys/unix/types_darwin.go +++ /dev/null @@ -1,283 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -Input to cgo -godefs. See README.md -*/ - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package unix - -/* -#define __DARWIN_UNIX03 0 -#define KERNEL -#define _DARWIN_USE_64_BIT_INODE -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum { - sizeofPtr = sizeof(void*), -}; - -union sockaddr_all { - struct sockaddr s1; // this one gets used for fields - struct sockaddr_in s2; // these pad it out - struct sockaddr_in6 s3; - struct sockaddr_un s4; - struct sockaddr_dl s5; -}; - -struct sockaddr_any { - struct sockaddr addr; - char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; -}; - -*/ -import "C" - -// Machine characteristics - -const ( - SizeofPtr = C.sizeofPtr - SizeofShort = C.sizeof_short - SizeofInt = C.sizeof_int - SizeofLong = C.sizeof_long - SizeofLongLong = C.sizeof_longlong -) - -// Basic types - -type ( - _C_short C.short - _C_int C.int - _C_long C.long - _C_long_long C.longlong -) - -// Time - -type Timespec C.struct_timespec - -type Timeval C.struct_timeval - -type Timeval32 C.struct_timeval32 - -// Processes - -type Rusage C.struct_rusage - -type Rlimit C.struct_rlimit - -type _Gid_t C.gid_t - -// Files - -type Stat_t C.struct_stat64 - -type Statfs_t C.struct_statfs64 - -type Flock_t C.struct_flock - -type Fstore_t C.struct_fstore - -type Radvisory_t C.struct_radvisory - -type Fbootstraptransfer_t C.struct_fbootstraptransfer - -type Log2phys_t C.struct_log2phys - -type Fsid C.struct_fsid - -type Dirent C.struct_dirent - -// Sockets - -type RawSockaddrInet4 C.struct_sockaddr_in - -type RawSockaddrInet6 C.struct_sockaddr_in6 - -type RawSockaddrUnix C.struct_sockaddr_un - -type RawSockaddrDatalink C.struct_sockaddr_dl - -type RawSockaddr C.struct_sockaddr - -type RawSockaddrAny C.struct_sockaddr_any - -type _Socklen C.socklen_t - -type Linger C.struct_linger - -type Iovec C.struct_iovec - -type IPMreq C.struct_ip_mreq - -type IPv6Mreq C.struct_ipv6_mreq - -type Msghdr C.struct_msghdr - -type Cmsghdr C.struct_cmsghdr - -type Inet4Pktinfo C.struct_in_pktinfo - -type Inet6Pktinfo C.struct_in6_pktinfo - -type IPv6MTUInfo C.struct_ip6_mtuinfo - -type ICMPv6Filter C.struct_icmp6_filter - -const ( - SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in - SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - SizeofSockaddrAny = C.sizeof_struct_sockaddr_any - SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un - SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl - SizeofLinger = C.sizeof_struct_linger - SizeofIPMreq = C.sizeof_struct_ip_mreq - SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - SizeofMsghdr = C.sizeof_struct_msghdr - SizeofCmsghdr = C.sizeof_struct_cmsghdr - SizeofInet4Pktinfo = C.sizeof_struct_in_pktinfo - SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo - SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -// Ptrace requests - -const ( - PTRACE_TRACEME = C.PT_TRACE_ME - PTRACE_CONT = C.PT_CONTINUE - PTRACE_KILL = C.PT_KILL -) - -// Events (kqueue, kevent) - -type Kevent_t C.struct_kevent - -// Select - -type FdSet C.fd_set - -// Routing and interface messages - -const ( - SizeofIfMsghdr = C.sizeof_struct_if_msghdr - SizeofIfData = C.sizeof_struct_if_data - SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr - SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr - SizeofIfmaMsghdr2 = C.sizeof_struct_ifma_msghdr2 - SizeofRtMsghdr = C.sizeof_struct_rt_msghdr - SizeofRtMetrics = C.sizeof_struct_rt_metrics -) - -type IfMsghdr C.struct_if_msghdr - -type IfData C.struct_if_data - -type IfaMsghdr C.struct_ifa_msghdr - -type IfmaMsghdr C.struct_ifma_msghdr - -type IfmaMsghdr2 C.struct_ifma_msghdr2 - -type RtMsghdr C.struct_rt_msghdr - -type RtMetrics C.struct_rt_metrics - -// Berkeley packet filter - -const ( - SizeofBpfVersion = C.sizeof_struct_bpf_version - SizeofBpfStat = C.sizeof_struct_bpf_stat - SizeofBpfProgram = C.sizeof_struct_bpf_program - SizeofBpfInsn = C.sizeof_struct_bpf_insn - SizeofBpfHdr = C.sizeof_struct_bpf_hdr -) - -type BpfVersion C.struct_bpf_version - -type BpfStat C.struct_bpf_stat - -type BpfProgram C.struct_bpf_program - -type BpfInsn C.struct_bpf_insn - -type BpfHdr C.struct_bpf_hdr - -// Terminal handling - -type Termios C.struct_termios - -type Winsize C.struct_winsize - -// fchmodat-like syscalls. - -const ( - AT_FDCWD = C.AT_FDCWD - AT_REMOVEDIR = C.AT_REMOVEDIR - AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW - AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW -) - -// poll - -type PollFd C.struct_pollfd - -const ( - POLLERR = C.POLLERR - POLLHUP = C.POLLHUP - POLLIN = C.POLLIN - POLLNVAL = C.POLLNVAL - POLLOUT = C.POLLOUT - POLLPRI = C.POLLPRI - POLLRDBAND = C.POLLRDBAND - POLLRDNORM = C.POLLRDNORM - POLLWRBAND = C.POLLWRBAND - POLLWRNORM = C.POLLWRNORM -) - -// uname - -type Utsname C.struct_utsname - -// Clockinfo - -const SizeofClockinfo = C.sizeof_struct_clockinfo - -type Clockinfo C.struct_clockinfo diff --git a/vendor/golang.org/x/sys/unix/types_dragonfly.go b/vendor/golang.org/x/sys/unix/types_dragonfly.go deleted file mode 100644 index 3365dd79..00000000 --- a/vendor/golang.org/x/sys/unix/types_dragonfly.go +++ /dev/null @@ -1,263 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -Input to cgo -godefs. See README.md -*/ - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package unix - -/* -#define KERNEL -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum { - sizeofPtr = sizeof(void*), -}; - -union sockaddr_all { - struct sockaddr s1; // this one gets used for fields - struct sockaddr_in s2; // these pad it out - struct sockaddr_in6 s3; - struct sockaddr_un s4; - struct sockaddr_dl s5; -}; - -struct sockaddr_any { - struct sockaddr addr; - char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; -}; - -*/ -import "C" - -// Machine characteristics - -const ( - SizeofPtr = C.sizeofPtr - SizeofShort = C.sizeof_short - SizeofInt = C.sizeof_int - SizeofLong = C.sizeof_long - SizeofLongLong = C.sizeof_longlong -) - -// Basic types - -type ( - _C_short C.short - _C_int C.int - _C_long C.long - _C_long_long C.longlong -) - -// Time - -type Timespec C.struct_timespec - -type Timeval C.struct_timeval - -// Processes - -type Rusage C.struct_rusage - -type Rlimit C.struct_rlimit - -type _Gid_t C.gid_t - -// Files - -type Stat_t C.struct_stat - -type Statfs_t C.struct_statfs - -type Flock_t C.struct_flock - -type Dirent C.struct_dirent - -type Fsid C.struct_fsid - -// File system limits - -const ( - PathMax = C.PATH_MAX -) - -// Sockets - -type RawSockaddrInet4 C.struct_sockaddr_in - -type RawSockaddrInet6 C.struct_sockaddr_in6 - -type RawSockaddrUnix C.struct_sockaddr_un - -type RawSockaddrDatalink C.struct_sockaddr_dl - -type RawSockaddr C.struct_sockaddr - -type RawSockaddrAny C.struct_sockaddr_any - -type _Socklen C.socklen_t - -type Linger C.struct_linger - -type Iovec C.struct_iovec - -type IPMreq C.struct_ip_mreq - -type IPv6Mreq C.struct_ipv6_mreq - -type Msghdr C.struct_msghdr - -type Cmsghdr C.struct_cmsghdr - -type Inet6Pktinfo C.struct_in6_pktinfo - -type IPv6MTUInfo C.struct_ip6_mtuinfo - -type ICMPv6Filter C.struct_icmp6_filter - -const ( - SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in - SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - SizeofSockaddrAny = C.sizeof_struct_sockaddr_any - SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un - SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl - SizeofLinger = C.sizeof_struct_linger - SizeofIPMreq = C.sizeof_struct_ip_mreq - SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - SizeofMsghdr = C.sizeof_struct_msghdr - SizeofCmsghdr = C.sizeof_struct_cmsghdr - SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo - SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -// Ptrace requests - -const ( - PTRACE_TRACEME = C.PT_TRACE_ME - PTRACE_CONT = C.PT_CONTINUE - PTRACE_KILL = C.PT_KILL -) - -// Events (kqueue, kevent) - -type Kevent_t C.struct_kevent - -// Select - -type FdSet C.fd_set - -// Routing and interface messages - -const ( - SizeofIfMsghdr = C.sizeof_struct_if_msghdr - SizeofIfData = C.sizeof_struct_if_data - SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr - SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr - SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr - SizeofRtMsghdr = C.sizeof_struct_rt_msghdr - SizeofRtMetrics = C.sizeof_struct_rt_metrics -) - -type IfMsghdr C.struct_if_msghdr - -type IfData C.struct_if_data - -type IfaMsghdr C.struct_ifa_msghdr - -type IfmaMsghdr C.struct_ifma_msghdr - -type IfAnnounceMsghdr C.struct_if_announcemsghdr - -type RtMsghdr C.struct_rt_msghdr - -type RtMetrics C.struct_rt_metrics - -// Berkeley packet filter - -const ( - SizeofBpfVersion = C.sizeof_struct_bpf_version - SizeofBpfStat = C.sizeof_struct_bpf_stat - SizeofBpfProgram = C.sizeof_struct_bpf_program - SizeofBpfInsn = C.sizeof_struct_bpf_insn - SizeofBpfHdr = C.sizeof_struct_bpf_hdr -) - -type BpfVersion C.struct_bpf_version - -type BpfStat C.struct_bpf_stat - -type BpfProgram C.struct_bpf_program - -type BpfInsn C.struct_bpf_insn - -type BpfHdr C.struct_bpf_hdr - -// Terminal handling - -type Termios C.struct_termios - -type Winsize C.struct_winsize - -// fchmodat-like syscalls. - -const ( - AT_FDCWD = C.AT_FDCWD - AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW -) - -// poll - -type PollFd C.struct_pollfd - -const ( - POLLERR = C.POLLERR - POLLHUP = C.POLLHUP - POLLIN = C.POLLIN - POLLNVAL = C.POLLNVAL - POLLOUT = C.POLLOUT - POLLPRI = C.POLLPRI - POLLRDBAND = C.POLLRDBAND - POLLRDNORM = C.POLLRDNORM - POLLWRBAND = C.POLLWRBAND - POLLWRNORM = C.POLLWRNORM -) - -// Uname - -type Utsname C.struct_utsname diff --git a/vendor/golang.org/x/sys/unix/types_freebsd.go b/vendor/golang.org/x/sys/unix/types_freebsd.go deleted file mode 100644 index a121dc33..00000000 --- a/vendor/golang.org/x/sys/unix/types_freebsd.go +++ /dev/null @@ -1,400 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -Input to cgo -godefs. See README.md -*/ - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package unix - -/* -#define _WANT_FREEBSD11_STAT 1 -#define _WANT_FREEBSD11_STATFS 1 -#define _WANT_FREEBSD11_DIRENT 1 -#define _WANT_FREEBSD11_KEVENT 1 - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum { - sizeofPtr = sizeof(void*), -}; - -union sockaddr_all { - struct sockaddr s1; // this one gets used for fields - struct sockaddr_in s2; // these pad it out - struct sockaddr_in6 s3; - struct sockaddr_un s4; - struct sockaddr_dl s5; -}; - -struct sockaddr_any { - struct sockaddr addr; - char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; -}; - -// This structure is a duplicate of if_data on FreeBSD 8-STABLE. -// See /usr/include/net/if.h. -struct if_data8 { - u_char ifi_type; - u_char ifi_physical; - u_char ifi_addrlen; - u_char ifi_hdrlen; - u_char ifi_link_state; - u_char ifi_spare_char1; - u_char ifi_spare_char2; - u_char ifi_datalen; - u_long ifi_mtu; - u_long ifi_metric; - u_long ifi_baudrate; - u_long ifi_ipackets; - u_long ifi_ierrors; - u_long ifi_opackets; - u_long ifi_oerrors; - u_long ifi_collisions; - u_long ifi_ibytes; - u_long ifi_obytes; - u_long ifi_imcasts; - u_long ifi_omcasts; - u_long ifi_iqdrops; - u_long ifi_noproto; - u_long ifi_hwassist; -// FIXME: these are now unions, so maybe need to change definitions? -#undef ifi_epoch - time_t ifi_epoch; -#undef ifi_lastchange - struct timeval ifi_lastchange; -}; - -// This structure is a duplicate of if_msghdr on FreeBSD 8-STABLE. -// See /usr/include/net/if.h. -struct if_msghdr8 { - u_short ifm_msglen; - u_char ifm_version; - u_char ifm_type; - int ifm_addrs; - int ifm_flags; - u_short ifm_index; - struct if_data8 ifm_data; -}; -*/ -import "C" - -// Machine characteristics - -const ( - SizeofPtr = C.sizeofPtr - SizeofShort = C.sizeof_short - SizeofInt = C.sizeof_int - SizeofLong = C.sizeof_long - SizeofLongLong = C.sizeof_longlong -) - -// Basic types - -type ( - _C_short C.short - _C_int C.int - _C_long C.long - _C_long_long C.longlong -) - -// Time - -type Timespec C.struct_timespec - -type Timeval C.struct_timeval - -// Processes - -type Rusage C.struct_rusage - -type Rlimit C.struct_rlimit - -type _Gid_t C.gid_t - -// Files - -const ( - _statfsVersion = C.STATFS_VERSION - _dirblksiz = C.DIRBLKSIZ -) - -type Stat_t C.struct_stat - -type stat_freebsd11_t C.struct_freebsd11_stat - -type Statfs_t C.struct_statfs - -type statfs_freebsd11_t C.struct_freebsd11_statfs - -type Flock_t C.struct_flock - -type Dirent C.struct_dirent - -type dirent_freebsd11 C.struct_freebsd11_dirent - -type Fsid C.struct_fsid - -// File system limits - -const ( - PathMax = C.PATH_MAX -) - -// Advice to Fadvise - -const ( - FADV_NORMAL = C.POSIX_FADV_NORMAL - FADV_RANDOM = C.POSIX_FADV_RANDOM - FADV_SEQUENTIAL = C.POSIX_FADV_SEQUENTIAL - FADV_WILLNEED = C.POSIX_FADV_WILLNEED - FADV_DONTNEED = C.POSIX_FADV_DONTNEED - FADV_NOREUSE = C.POSIX_FADV_NOREUSE -) - -// Sockets - -type RawSockaddrInet4 C.struct_sockaddr_in - -type RawSockaddrInet6 C.struct_sockaddr_in6 - -type RawSockaddrUnix C.struct_sockaddr_un - -type RawSockaddrDatalink C.struct_sockaddr_dl - -type RawSockaddr C.struct_sockaddr - -type RawSockaddrAny C.struct_sockaddr_any - -type _Socklen C.socklen_t - -type Linger C.struct_linger - -type Iovec C.struct_iovec - -type IPMreq C.struct_ip_mreq - -type IPMreqn C.struct_ip_mreqn - -type IPv6Mreq C.struct_ipv6_mreq - -type Msghdr C.struct_msghdr - -type Cmsghdr C.struct_cmsghdr - -type Inet6Pktinfo C.struct_in6_pktinfo - -type IPv6MTUInfo C.struct_ip6_mtuinfo - -type ICMPv6Filter C.struct_icmp6_filter - -const ( - SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in - SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - SizeofSockaddrAny = C.sizeof_struct_sockaddr_any - SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un - SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl - SizeofLinger = C.sizeof_struct_linger - SizeofIPMreq = C.sizeof_struct_ip_mreq - SizeofIPMreqn = C.sizeof_struct_ip_mreqn - SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - SizeofMsghdr = C.sizeof_struct_msghdr - SizeofCmsghdr = C.sizeof_struct_cmsghdr - SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo - SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -// Ptrace requests - -const ( - PTRACE_ATTACH = C.PT_ATTACH - PTRACE_CONT = C.PT_CONTINUE - PTRACE_DETACH = C.PT_DETACH - PTRACE_GETFPREGS = C.PT_GETFPREGS - PTRACE_GETFSBASE = C.PT_GETFSBASE - PTRACE_GETLWPLIST = C.PT_GETLWPLIST - PTRACE_GETNUMLWPS = C.PT_GETNUMLWPS - PTRACE_GETREGS = C.PT_GETREGS - PTRACE_GETXSTATE = C.PT_GETXSTATE - PTRACE_IO = C.PT_IO - PTRACE_KILL = C.PT_KILL - PTRACE_LWPEVENTS = C.PT_LWP_EVENTS - PTRACE_LWPINFO = C.PT_LWPINFO - PTRACE_SETFPREGS = C.PT_SETFPREGS - PTRACE_SETREGS = C.PT_SETREGS - PTRACE_SINGLESTEP = C.PT_STEP - PTRACE_TRACEME = C.PT_TRACE_ME -) - -const ( - PIOD_READ_D = C.PIOD_READ_D - PIOD_WRITE_D = C.PIOD_WRITE_D - PIOD_READ_I = C.PIOD_READ_I - PIOD_WRITE_I = C.PIOD_WRITE_I -) - -const ( - PL_FLAG_BORN = C.PL_FLAG_BORN - PL_FLAG_EXITED = C.PL_FLAG_EXITED - PL_FLAG_SI = C.PL_FLAG_SI -) - -const ( - TRAP_BRKPT = C.TRAP_BRKPT - TRAP_TRACE = C.TRAP_TRACE -) - -type PtraceLwpInfoStruct C.struct_ptrace_lwpinfo - -type __Siginfo C.struct___siginfo - -type Sigset_t C.sigset_t - -type Reg C.struct_reg - -type FpReg C.struct_fpreg - -type PtraceIoDesc C.struct_ptrace_io_desc - -// Events (kqueue, kevent) - -type Kevent_t C.struct_kevent_freebsd11 - -// Select - -type FdSet C.fd_set - -// Routing and interface messages - -const ( - sizeofIfMsghdr = C.sizeof_struct_if_msghdr - SizeofIfMsghdr = C.sizeof_struct_if_msghdr8 - sizeofIfData = C.sizeof_struct_if_data - SizeofIfData = C.sizeof_struct_if_data8 - SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr - SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr - SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr - SizeofRtMsghdr = C.sizeof_struct_rt_msghdr - SizeofRtMetrics = C.sizeof_struct_rt_metrics -) - -type ifMsghdr C.struct_if_msghdr - -type IfMsghdr C.struct_if_msghdr8 - -type ifData C.struct_if_data - -type IfData C.struct_if_data8 - -type IfaMsghdr C.struct_ifa_msghdr - -type IfmaMsghdr C.struct_ifma_msghdr - -type IfAnnounceMsghdr C.struct_if_announcemsghdr - -type RtMsghdr C.struct_rt_msghdr - -type RtMetrics C.struct_rt_metrics - -// Berkeley packet filter - -const ( - SizeofBpfVersion = C.sizeof_struct_bpf_version - SizeofBpfStat = C.sizeof_struct_bpf_stat - SizeofBpfZbuf = C.sizeof_struct_bpf_zbuf - SizeofBpfProgram = C.sizeof_struct_bpf_program - SizeofBpfInsn = C.sizeof_struct_bpf_insn - SizeofBpfHdr = C.sizeof_struct_bpf_hdr - SizeofBpfZbufHeader = C.sizeof_struct_bpf_zbuf_header -) - -type BpfVersion C.struct_bpf_version - -type BpfStat C.struct_bpf_stat - -type BpfZbuf C.struct_bpf_zbuf - -type BpfProgram C.struct_bpf_program - -type BpfInsn C.struct_bpf_insn - -type BpfHdr C.struct_bpf_hdr - -type BpfZbufHeader C.struct_bpf_zbuf_header - -// Terminal handling - -type Termios C.struct_termios - -type Winsize C.struct_winsize - -// fchmodat-like syscalls. - -const ( - AT_FDCWD = C.AT_FDCWD - AT_REMOVEDIR = C.AT_REMOVEDIR - AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW - AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW -) - -// poll - -type PollFd C.struct_pollfd - -const ( - POLLERR = C.POLLERR - POLLHUP = C.POLLHUP - POLLIN = C.POLLIN - POLLINIGNEOF = C.POLLINIGNEOF - POLLNVAL = C.POLLNVAL - POLLOUT = C.POLLOUT - POLLPRI = C.POLLPRI - POLLRDBAND = C.POLLRDBAND - POLLRDNORM = C.POLLRDNORM - POLLWRBAND = C.POLLWRBAND - POLLWRNORM = C.POLLWRNORM -) - -// Capabilities - -type CapRights C.struct_cap_rights - -// Uname - -type Utsname C.struct_utsname diff --git a/vendor/golang.org/x/sys/unix/types_netbsd.go b/vendor/golang.org/x/sys/unix/types_netbsd.go deleted file mode 100644 index 4a96d72c..00000000 --- a/vendor/golang.org/x/sys/unix/types_netbsd.go +++ /dev/null @@ -1,290 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -Input to cgo -godefs. See README.md -*/ - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package unix - -/* -#define KERNEL -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum { - sizeofPtr = sizeof(void*), -}; - -union sockaddr_all { - struct sockaddr s1; // this one gets used for fields - struct sockaddr_in s2; // these pad it out - struct sockaddr_in6 s3; - struct sockaddr_un s4; - struct sockaddr_dl s5; -}; - -struct sockaddr_any { - struct sockaddr addr; - char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; -}; - -*/ -import "C" - -// Machine characteristics - -const ( - SizeofPtr = C.sizeofPtr - SizeofShort = C.sizeof_short - SizeofInt = C.sizeof_int - SizeofLong = C.sizeof_long - SizeofLongLong = C.sizeof_longlong -) - -// Basic types - -type ( - _C_short C.short - _C_int C.int - _C_long C.long - _C_long_long C.longlong -) - -// Time - -type Timespec C.struct_timespec - -type Timeval C.struct_timeval - -// Processes - -type Rusage C.struct_rusage - -type Rlimit C.struct_rlimit - -type _Gid_t C.gid_t - -// Files - -type Stat_t C.struct_stat - -type Statfs_t C.struct_statfs - -type Flock_t C.struct_flock - -type Dirent C.struct_dirent - -type Fsid C.fsid_t - -// File system limits - -const ( - PathMax = C.PATH_MAX -) - -// Advice to Fadvise - -const ( - FADV_NORMAL = C.POSIX_FADV_NORMAL - FADV_RANDOM = C.POSIX_FADV_RANDOM - FADV_SEQUENTIAL = C.POSIX_FADV_SEQUENTIAL - FADV_WILLNEED = C.POSIX_FADV_WILLNEED - FADV_DONTNEED = C.POSIX_FADV_DONTNEED - FADV_NOREUSE = C.POSIX_FADV_NOREUSE -) - -// Sockets - -type RawSockaddrInet4 C.struct_sockaddr_in - -type RawSockaddrInet6 C.struct_sockaddr_in6 - -type RawSockaddrUnix C.struct_sockaddr_un - -type RawSockaddrDatalink C.struct_sockaddr_dl - -type RawSockaddr C.struct_sockaddr - -type RawSockaddrAny C.struct_sockaddr_any - -type _Socklen C.socklen_t - -type Linger C.struct_linger - -type Iovec C.struct_iovec - -type IPMreq C.struct_ip_mreq - -type IPv6Mreq C.struct_ipv6_mreq - -type Msghdr C.struct_msghdr - -type Cmsghdr C.struct_cmsghdr - -type Inet6Pktinfo C.struct_in6_pktinfo - -type IPv6MTUInfo C.struct_ip6_mtuinfo - -type ICMPv6Filter C.struct_icmp6_filter - -const ( - SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in - SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - SizeofSockaddrAny = C.sizeof_struct_sockaddr_any - SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un - SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl - SizeofLinger = C.sizeof_struct_linger - SizeofIPMreq = C.sizeof_struct_ip_mreq - SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - SizeofMsghdr = C.sizeof_struct_msghdr - SizeofCmsghdr = C.sizeof_struct_cmsghdr - SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo - SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -// Ptrace requests - -const ( - PTRACE_TRACEME = C.PT_TRACE_ME - PTRACE_CONT = C.PT_CONTINUE - PTRACE_KILL = C.PT_KILL -) - -// Events (kqueue, kevent) - -type Kevent_t C.struct_kevent - -// Select - -type FdSet C.fd_set - -// Routing and interface messages - -const ( - SizeofIfMsghdr = C.sizeof_struct_if_msghdr - SizeofIfData = C.sizeof_struct_if_data - SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr - SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr - SizeofRtMsghdr = C.sizeof_struct_rt_msghdr - SizeofRtMetrics = C.sizeof_struct_rt_metrics -) - -type IfMsghdr C.struct_if_msghdr - -type IfData C.struct_if_data - -type IfaMsghdr C.struct_ifa_msghdr - -type IfAnnounceMsghdr C.struct_if_announcemsghdr - -type RtMsghdr C.struct_rt_msghdr - -type RtMetrics C.struct_rt_metrics - -type Mclpool C.struct_mclpool - -// Berkeley packet filter - -const ( - SizeofBpfVersion = C.sizeof_struct_bpf_version - SizeofBpfStat = C.sizeof_struct_bpf_stat - SizeofBpfProgram = C.sizeof_struct_bpf_program - SizeofBpfInsn = C.sizeof_struct_bpf_insn - SizeofBpfHdr = C.sizeof_struct_bpf_hdr -) - -type BpfVersion C.struct_bpf_version - -type BpfStat C.struct_bpf_stat - -type BpfProgram C.struct_bpf_program - -type BpfInsn C.struct_bpf_insn - -type BpfHdr C.struct_bpf_hdr - -type BpfTimeval C.struct_bpf_timeval - -// Terminal handling - -type Termios C.struct_termios - -type Winsize C.struct_winsize - -type Ptmget C.struct_ptmget - -// fchmodat-like syscalls. - -const ( - AT_FDCWD = C.AT_FDCWD - AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW - AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW -) - -// poll - -type PollFd C.struct_pollfd - -const ( - POLLERR = C.POLLERR - POLLHUP = C.POLLHUP - POLLIN = C.POLLIN - POLLNVAL = C.POLLNVAL - POLLOUT = C.POLLOUT - POLLPRI = C.POLLPRI - POLLRDBAND = C.POLLRDBAND - POLLRDNORM = C.POLLRDNORM - POLLWRBAND = C.POLLWRBAND - POLLWRNORM = C.POLLWRNORM -) - -// Sysctl - -type Sysctlnode C.struct_sysctlnode - -// Uname - -type Utsname C.struct_utsname - -// Clockinfo - -const SizeofClockinfo = C.sizeof_struct_clockinfo - -type Clockinfo C.struct_clockinfo diff --git a/vendor/golang.org/x/sys/unix/types_openbsd.go b/vendor/golang.org/x/sys/unix/types_openbsd.go deleted file mode 100644 index 775cb57d..00000000 --- a/vendor/golang.org/x/sys/unix/types_openbsd.go +++ /dev/null @@ -1,283 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -Input to cgo -godefs. See README.md -*/ - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package unix - -/* -#define KERNEL -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum { - sizeofPtr = sizeof(void*), -}; - -union sockaddr_all { - struct sockaddr s1; // this one gets used for fields - struct sockaddr_in s2; // these pad it out - struct sockaddr_in6 s3; - struct sockaddr_un s4; - struct sockaddr_dl s5; -}; - -struct sockaddr_any { - struct sockaddr addr; - char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; -}; - -*/ -import "C" - -// Machine characteristics - -const ( - SizeofPtr = C.sizeofPtr - SizeofShort = C.sizeof_short - SizeofInt = C.sizeof_int - SizeofLong = C.sizeof_long - SizeofLongLong = C.sizeof_longlong -) - -// Basic types - -type ( - _C_short C.short - _C_int C.int - _C_long C.long - _C_long_long C.longlong -) - -// Time - -type Timespec C.struct_timespec - -type Timeval C.struct_timeval - -// Processes - -type Rusage C.struct_rusage - -type Rlimit C.struct_rlimit - -type _Gid_t C.gid_t - -// Files - -type Stat_t C.struct_stat - -type Statfs_t C.struct_statfs - -type Flock_t C.struct_flock - -type Dirent C.struct_dirent - -type Fsid C.fsid_t - -// File system limits - -const ( - PathMax = C.PATH_MAX -) - -// Sockets - -type RawSockaddrInet4 C.struct_sockaddr_in - -type RawSockaddrInet6 C.struct_sockaddr_in6 - -type RawSockaddrUnix C.struct_sockaddr_un - -type RawSockaddrDatalink C.struct_sockaddr_dl - -type RawSockaddr C.struct_sockaddr - -type RawSockaddrAny C.struct_sockaddr_any - -type _Socklen C.socklen_t - -type Linger C.struct_linger - -type Iovec C.struct_iovec - -type IPMreq C.struct_ip_mreq - -type IPv6Mreq C.struct_ipv6_mreq - -type Msghdr C.struct_msghdr - -type Cmsghdr C.struct_cmsghdr - -type Inet6Pktinfo C.struct_in6_pktinfo - -type IPv6MTUInfo C.struct_ip6_mtuinfo - -type ICMPv6Filter C.struct_icmp6_filter - -const ( - SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in - SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - SizeofSockaddrAny = C.sizeof_struct_sockaddr_any - SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un - SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl - SizeofLinger = C.sizeof_struct_linger - SizeofIPMreq = C.sizeof_struct_ip_mreq - SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - SizeofMsghdr = C.sizeof_struct_msghdr - SizeofCmsghdr = C.sizeof_struct_cmsghdr - SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo - SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -// Ptrace requests - -const ( - PTRACE_TRACEME = C.PT_TRACE_ME - PTRACE_CONT = C.PT_CONTINUE - PTRACE_KILL = C.PT_KILL -) - -// Events (kqueue, kevent) - -type Kevent_t C.struct_kevent - -// Select - -type FdSet C.fd_set - -// Routing and interface messages - -const ( - SizeofIfMsghdr = C.sizeof_struct_if_msghdr - SizeofIfData = C.sizeof_struct_if_data - SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr - SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr - SizeofRtMsghdr = C.sizeof_struct_rt_msghdr - SizeofRtMetrics = C.sizeof_struct_rt_metrics -) - -type IfMsghdr C.struct_if_msghdr - -type IfData C.struct_if_data - -type IfaMsghdr C.struct_ifa_msghdr - -type IfAnnounceMsghdr C.struct_if_announcemsghdr - -type RtMsghdr C.struct_rt_msghdr - -type RtMetrics C.struct_rt_metrics - -type Mclpool C.struct_mclpool - -// Berkeley packet filter - -const ( - SizeofBpfVersion = C.sizeof_struct_bpf_version - SizeofBpfStat = C.sizeof_struct_bpf_stat - SizeofBpfProgram = C.sizeof_struct_bpf_program - SizeofBpfInsn = C.sizeof_struct_bpf_insn - SizeofBpfHdr = C.sizeof_struct_bpf_hdr -) - -type BpfVersion C.struct_bpf_version - -type BpfStat C.struct_bpf_stat - -type BpfProgram C.struct_bpf_program - -type BpfInsn C.struct_bpf_insn - -type BpfHdr C.struct_bpf_hdr - -type BpfTimeval C.struct_bpf_timeval - -// Terminal handling - -type Termios C.struct_termios - -type Winsize C.struct_winsize - -// fchmodat-like syscalls. - -const ( - AT_FDCWD = C.AT_FDCWD - AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW - AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW -) - -// poll - -type PollFd C.struct_pollfd - -const ( - POLLERR = C.POLLERR - POLLHUP = C.POLLHUP - POLLIN = C.POLLIN - POLLNVAL = C.POLLNVAL - POLLOUT = C.POLLOUT - POLLPRI = C.POLLPRI - POLLRDBAND = C.POLLRDBAND - POLLRDNORM = C.POLLRDNORM - POLLWRBAND = C.POLLWRBAND - POLLWRNORM = C.POLLWRNORM -) - -// Signal Sets - -type Sigset_t C.sigset_t - -// Uname - -type Utsname C.struct_utsname - -// Uvmexp - -const SizeofUvmexp = C.sizeof_struct_uvmexp - -type Uvmexp C.struct_uvmexp - -// Clockinfo - -const SizeofClockinfo = C.sizeof_struct_clockinfo - -type Clockinfo C.struct_clockinfo diff --git a/vendor/golang.org/x/sys/unix/types_solaris.go b/vendor/golang.org/x/sys/unix/types_solaris.go deleted file mode 100644 index 2b716f93..00000000 --- a/vendor/golang.org/x/sys/unix/types_solaris.go +++ /dev/null @@ -1,266 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -/* -Input to cgo -godefs. See README.md -*/ - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package unix - -/* -#define KERNEL -// These defines ensure that builds done on newer versions of Solaris are -// backwards-compatible with older versions of Solaris and -// OpenSolaris-based derivatives. -#define __USE_SUNOS_SOCKETS__ // msghdr -#define __USE_LEGACY_PROTOTYPES__ // iovec -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum { - sizeofPtr = sizeof(void*), -}; - -union sockaddr_all { - struct sockaddr s1; // this one gets used for fields - struct sockaddr_in s2; // these pad it out - struct sockaddr_in6 s3; - struct sockaddr_un s4; - struct sockaddr_dl s5; -}; - -struct sockaddr_any { - struct sockaddr addr; - char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; -}; - -*/ -import "C" - -// Machine characteristics - -const ( - SizeofPtr = C.sizeofPtr - SizeofShort = C.sizeof_short - SizeofInt = C.sizeof_int - SizeofLong = C.sizeof_long - SizeofLongLong = C.sizeof_longlong - PathMax = C.PATH_MAX - MaxHostNameLen = C.MAXHOSTNAMELEN -) - -// Basic types - -type ( - _C_short C.short - _C_int C.int - _C_long C.long - _C_long_long C.longlong -) - -// Time - -type Timespec C.struct_timespec - -type Timeval C.struct_timeval - -type Timeval32 C.struct_timeval32 - -type Tms C.struct_tms - -type Utimbuf C.struct_utimbuf - -// Processes - -type Rusage C.struct_rusage - -type Rlimit C.struct_rlimit - -type _Gid_t C.gid_t - -// Files - -type Stat_t C.struct_stat - -type Flock_t C.struct_flock - -type Dirent C.struct_dirent - -// Filesystems - -type _Fsblkcnt_t C.fsblkcnt_t - -type Statvfs_t C.struct_statvfs - -// Sockets - -type RawSockaddrInet4 C.struct_sockaddr_in - -type RawSockaddrInet6 C.struct_sockaddr_in6 - -type RawSockaddrUnix C.struct_sockaddr_un - -type RawSockaddrDatalink C.struct_sockaddr_dl - -type RawSockaddr C.struct_sockaddr - -type RawSockaddrAny C.struct_sockaddr_any - -type _Socklen C.socklen_t - -type Linger C.struct_linger - -type Iovec C.struct_iovec - -type IPMreq C.struct_ip_mreq - -type IPv6Mreq C.struct_ipv6_mreq - -type Msghdr C.struct_msghdr - -type Cmsghdr C.struct_cmsghdr - -type Inet6Pktinfo C.struct_in6_pktinfo - -type IPv6MTUInfo C.struct_ip6_mtuinfo - -type ICMPv6Filter C.struct_icmp6_filter - -const ( - SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in - SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 - SizeofSockaddrAny = C.sizeof_struct_sockaddr_any - SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un - SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl - SizeofLinger = C.sizeof_struct_linger - SizeofIPMreq = C.sizeof_struct_ip_mreq - SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq - SizeofMsghdr = C.sizeof_struct_msghdr - SizeofCmsghdr = C.sizeof_struct_cmsghdr - SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo - SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo - SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter -) - -// Select - -type FdSet C.fd_set - -// Misc - -type Utsname C.struct_utsname - -type Ustat_t C.struct_ustat - -const ( - AT_FDCWD = C.AT_FDCWD - AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW - AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW - AT_REMOVEDIR = C.AT_REMOVEDIR - AT_EACCESS = C.AT_EACCESS -) - -// Routing and interface messages - -const ( - SizeofIfMsghdr = C.sizeof_struct_if_msghdr - SizeofIfData = C.sizeof_struct_if_data - SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr - SizeofRtMsghdr = C.sizeof_struct_rt_msghdr - SizeofRtMetrics = C.sizeof_struct_rt_metrics -) - -type IfMsghdr C.struct_if_msghdr - -type IfData C.struct_if_data - -type IfaMsghdr C.struct_ifa_msghdr - -type RtMsghdr C.struct_rt_msghdr - -type RtMetrics C.struct_rt_metrics - -// Berkeley packet filter - -const ( - SizeofBpfVersion = C.sizeof_struct_bpf_version - SizeofBpfStat = C.sizeof_struct_bpf_stat - SizeofBpfProgram = C.sizeof_struct_bpf_program - SizeofBpfInsn = C.sizeof_struct_bpf_insn - SizeofBpfHdr = C.sizeof_struct_bpf_hdr -) - -type BpfVersion C.struct_bpf_version - -type BpfStat C.struct_bpf_stat - -type BpfProgram C.struct_bpf_program - -type BpfInsn C.struct_bpf_insn - -type BpfTimeval C.struct_bpf_timeval - -type BpfHdr C.struct_bpf_hdr - -// Terminal handling - -type Termios C.struct_termios - -type Termio C.struct_termio - -type Winsize C.struct_winsize - -// poll - -type PollFd C.struct_pollfd - -const ( - POLLERR = C.POLLERR - POLLHUP = C.POLLHUP - POLLIN = C.POLLIN - POLLNVAL = C.POLLNVAL - POLLOUT = C.POLLOUT - POLLPRI = C.POLLPRI - POLLRDBAND = C.POLLRDBAND - POLLRDNORM = C.POLLRDNORM - POLLWRBAND = C.POLLWRBAND - POLLWRNORM = C.POLLWRNORM -) diff --git a/vendor/golang.org/x/text/unicode/bidi/gen.go b/vendor/golang.org/x/text/unicode/bidi/gen.go deleted file mode 100644 index 987fc169..00000000 --- a/vendor/golang.org/x/text/unicode/bidi/gen.go +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -package main - -import ( - "flag" - "log" - - "golang.org/x/text/internal/gen" - "golang.org/x/text/internal/triegen" - "golang.org/x/text/internal/ucd" -) - -var outputFile = flag.String("out", "tables.go", "output file") - -func main() { - gen.Init() - gen.Repackage("gen_trieval.go", "trieval.go", "bidi") - gen.Repackage("gen_ranges.go", "ranges_test.go", "bidi") - - genTables() -} - -// bidiClass names and codes taken from class "bc" in -// https://www.unicode.org/Public/8.0.0/ucd/PropertyValueAliases.txt -var bidiClass = map[string]Class{ - "AL": AL, // ArabicLetter - "AN": AN, // ArabicNumber - "B": B, // ParagraphSeparator - "BN": BN, // BoundaryNeutral - "CS": CS, // CommonSeparator - "EN": EN, // EuropeanNumber - "ES": ES, // EuropeanSeparator - "ET": ET, // EuropeanTerminator - "L": L, // LeftToRight - "NSM": NSM, // NonspacingMark - "ON": ON, // OtherNeutral - "R": R, // RightToLeft - "S": S, // SegmentSeparator - "WS": WS, // WhiteSpace - - "FSI": Control, - "PDF": Control, - "PDI": Control, - "LRE": Control, - "LRI": Control, - "LRO": Control, - "RLE": Control, - "RLI": Control, - "RLO": Control, -} - -func genTables() { - if numClass > 0x0F { - log.Fatalf("Too many Class constants (%#x > 0x0F).", numClass) - } - w := gen.NewCodeWriter() - defer w.WriteVersionedGoFile(*outputFile, "bidi") - - gen.WriteUnicodeVersion(w) - - t := triegen.NewTrie("bidi") - - // Build data about bracket mapping. These bits need to be or-ed with - // any other bits. - orMask := map[rune]uint64{} - - xorMap := map[rune]int{} - xorMasks := []rune{0} // First value is no-op. - - ucd.Parse(gen.OpenUCDFile("BidiBrackets.txt"), func(p *ucd.Parser) { - r1 := p.Rune(0) - r2 := p.Rune(1) - xor := r1 ^ r2 - if _, ok := xorMap[xor]; !ok { - xorMap[xor] = len(xorMasks) - xorMasks = append(xorMasks, xor) - } - entry := uint64(xorMap[xor]) << xorMaskShift - switch p.String(2) { - case "o": - entry |= openMask - case "c", "n": - default: - log.Fatalf("Unknown bracket class %q.", p.String(2)) - } - orMask[r1] = entry - }) - - w.WriteComment(` - xorMasks contains masks to be xor-ed with brackets to get the reverse - version.`) - w.WriteVar("xorMasks", xorMasks) - - done := map[rune]bool{} - - insert := func(r rune, c Class) { - if !done[r] { - t.Insert(r, orMask[r]|uint64(c)) - done[r] = true - } - } - - // Insert the derived BiDi properties. - ucd.Parse(gen.OpenUCDFile("extracted/DerivedBidiClass.txt"), func(p *ucd.Parser) { - r := p.Rune(0) - class, ok := bidiClass[p.String(1)] - if !ok { - log.Fatalf("%U: Unknown BiDi class %q", r, p.String(1)) - } - insert(r, class) - }) - visitDefaults(insert) - - // TODO: use sparse blocks. This would reduce table size considerably - // from the looks of it. - - sz, err := t.Gen(w) - if err != nil { - log.Fatal(err) - } - w.Size += sz -} - -// dummy values to make methods in gen_common compile. The real versions -// will be generated by this file to tables.go. -var ( - xorMasks []rune -) diff --git a/vendor/golang.org/x/text/unicode/bidi/gen_ranges.go b/vendor/golang.org/x/text/unicode/bidi/gen_ranges.go deleted file mode 100644 index 02c3b505..00000000 --- a/vendor/golang.org/x/text/unicode/bidi/gen_ranges.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -package main - -import ( - "unicode" - - "golang.org/x/text/internal/gen" - "golang.org/x/text/internal/ucd" - "golang.org/x/text/unicode/rangetable" -) - -// These tables are hand-extracted from: -// https://www.unicode.org/Public/8.0.0/ucd/extracted/DerivedBidiClass.txt -func visitDefaults(fn func(r rune, c Class)) { - // first write default values for ranges listed above. - visitRunes(fn, AL, []rune{ - 0x0600, 0x07BF, // Arabic - 0x08A0, 0x08FF, // Arabic Extended-A - 0xFB50, 0xFDCF, // Arabic Presentation Forms - 0xFDF0, 0xFDFF, - 0xFE70, 0xFEFF, - 0x0001EE00, 0x0001EEFF, // Arabic Mathematical Alpha Symbols - }) - visitRunes(fn, R, []rune{ - 0x0590, 0x05FF, // Hebrew - 0x07C0, 0x089F, // Nko et al. - 0xFB1D, 0xFB4F, - 0x00010800, 0x00010FFF, // Cypriot Syllabary et. al. - 0x0001E800, 0x0001EDFF, - 0x0001EF00, 0x0001EFFF, - }) - visitRunes(fn, ET, []rune{ // European Terminator - 0x20A0, 0x20Cf, // Currency symbols - }) - rangetable.Visit(unicode.Noncharacter_Code_Point, func(r rune) { - fn(r, BN) // Boundary Neutral - }) - ucd.Parse(gen.OpenUCDFile("DerivedCoreProperties.txt"), func(p *ucd.Parser) { - if p.String(1) == "Default_Ignorable_Code_Point" { - fn(p.Rune(0), BN) // Boundary Neutral - } - }) -} - -func visitRunes(fn func(r rune, c Class), c Class, runes []rune) { - for i := 0; i < len(runes); i += 2 { - lo, hi := runes[i], runes[i+1] - for j := lo; j <= hi; j++ { - fn(j, c) - } - } -} diff --git a/vendor/golang.org/x/text/unicode/bidi/gen_trieval.go b/vendor/golang.org/x/text/unicode/bidi/gen_trieval.go deleted file mode 100644 index 9cb99428..00000000 --- a/vendor/golang.org/x/text/unicode/bidi/gen_trieval.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -package main - -// Class is the Unicode BiDi class. Each rune has a single class. -type Class uint - -const ( - L Class = iota // LeftToRight - R // RightToLeft - EN // EuropeanNumber - ES // EuropeanSeparator - ET // EuropeanTerminator - AN // ArabicNumber - CS // CommonSeparator - B // ParagraphSeparator - S // SegmentSeparator - WS // WhiteSpace - ON // OtherNeutral - BN // BoundaryNeutral - NSM // NonspacingMark - AL // ArabicLetter - Control // Control LRO - PDI - - numClass - - LRO // LeftToRightOverride - RLO // RightToLeftOverride - LRE // LeftToRightEmbedding - RLE // RightToLeftEmbedding - PDF // PopDirectionalFormat - LRI // LeftToRightIsolate - RLI // RightToLeftIsolate - FSI // FirstStrongIsolate - PDI // PopDirectionalIsolate - - unknownClass = ^Class(0) -) - -var controlToClass = map[rune]Class{ - 0x202D: LRO, // LeftToRightOverride, - 0x202E: RLO, // RightToLeftOverride, - 0x202A: LRE, // LeftToRightEmbedding, - 0x202B: RLE, // RightToLeftEmbedding, - 0x202C: PDF, // PopDirectionalFormat, - 0x2066: LRI, // LeftToRightIsolate, - 0x2067: RLI, // RightToLeftIsolate, - 0x2068: FSI, // FirstStrongIsolate, - 0x2069: PDI, // PopDirectionalIsolate, -} - -// A trie entry has the following bits: -// 7..5 XOR mask for brackets -// 4 1: Bracket open, 0: Bracket close -// 3..0 Class type - -const ( - openMask = 0x10 - xorMaskShift = 5 -) diff --git a/vendor/golang.org/x/text/unicode/norm/maketables.go b/vendor/golang.org/x/text/unicode/norm/maketables.go deleted file mode 100644 index 30a3aa93..00000000 --- a/vendor/golang.org/x/text/unicode/norm/maketables.go +++ /dev/null @@ -1,986 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// Normalization table generator. -// Data read from the web. -// See forminfo.go for a description of the trie values associated with each rune. - -package main - -import ( - "bytes" - "encoding/binary" - "flag" - "fmt" - "io" - "log" - "sort" - "strconv" - "strings" - - "golang.org/x/text/internal/gen" - "golang.org/x/text/internal/triegen" - "golang.org/x/text/internal/ucd" -) - -func main() { - gen.Init() - loadUnicodeData() - compactCCC() - loadCompositionExclusions() - completeCharFields(FCanonical) - completeCharFields(FCompatibility) - computeNonStarterCounts() - verifyComputed() - printChars() - testDerived() - printTestdata() - makeTables() -} - -var ( - tablelist = flag.String("tables", - "all", - "comma-separated list of which tables to generate; "+ - "can be 'decomp', 'recomp', 'info' and 'all'") - test = flag.Bool("test", - false, - "test existing tables against DerivedNormalizationProps and generate test data for regression testing") - verbose = flag.Bool("verbose", - false, - "write data to stdout as it is parsed") -) - -const MaxChar = 0x10FFFF // anything above this shouldn't exist - -// Quick Check properties of runes allow us to quickly -// determine whether a rune may occur in a normal form. -// For a given normal form, a rune may be guaranteed to occur -// verbatim (QC=Yes), may or may not combine with another -// rune (QC=Maybe), or may not occur (QC=No). -type QCResult int - -const ( - QCUnknown QCResult = iota - QCYes - QCNo - QCMaybe -) - -func (r QCResult) String() string { - switch r { - case QCYes: - return "Yes" - case QCNo: - return "No" - case QCMaybe: - return "Maybe" - } - return "***UNKNOWN***" -} - -const ( - FCanonical = iota // NFC or NFD - FCompatibility // NFKC or NFKD - FNumberOfFormTypes -) - -const ( - MComposed = iota // NFC or NFKC - MDecomposed // NFD or NFKD - MNumberOfModes -) - -// This contains only the properties we're interested in. -type Char struct { - name string - codePoint rune // if zero, this index is not a valid code point. - ccc uint8 // canonical combining class - origCCC uint8 - excludeInComp bool // from CompositionExclusions.txt - compatDecomp bool // it has a compatibility expansion - - nTrailingNonStarters uint8 - nLeadingNonStarters uint8 // must be equal to trailing if non-zero - - forms [FNumberOfFormTypes]FormInfo // For FCanonical and FCompatibility - - state State -} - -var chars = make([]Char, MaxChar+1) -var cccMap = make(map[uint8]uint8) - -func (c Char) String() string { - buf := new(bytes.Buffer) - - fmt.Fprintf(buf, "%U [%s]:\n", c.codePoint, c.name) - fmt.Fprintf(buf, " ccc: %v\n", c.ccc) - fmt.Fprintf(buf, " excludeInComp: %v\n", c.excludeInComp) - fmt.Fprintf(buf, " compatDecomp: %v\n", c.compatDecomp) - fmt.Fprintf(buf, " state: %v\n", c.state) - fmt.Fprintf(buf, " NFC:\n") - fmt.Fprint(buf, c.forms[FCanonical]) - fmt.Fprintf(buf, " NFKC:\n") - fmt.Fprint(buf, c.forms[FCompatibility]) - - return buf.String() -} - -// In UnicodeData.txt, some ranges are marked like this: -// 3400;;Lo;0;L;;;;;N;;;;; -// 4DB5;;Lo;0;L;;;;;N;;;;; -// parseCharacter keeps a state variable indicating the weirdness. -type State int - -const ( - SNormal State = iota // known to be zero for the type - SFirst - SLast - SMissing -) - -var lastChar = rune('\u0000') - -func (c Char) isValid() bool { - return c.codePoint != 0 && c.state != SMissing -} - -type FormInfo struct { - quickCheck [MNumberOfModes]QCResult // index: MComposed or MDecomposed - verified [MNumberOfModes]bool // index: MComposed or MDecomposed - - combinesForward bool // May combine with rune on the right - combinesBackward bool // May combine with rune on the left - isOneWay bool // Never appears in result - inDecomp bool // Some decompositions result in this char. - decomp Decomposition - expandedDecomp Decomposition -} - -func (f FormInfo) String() string { - buf := bytes.NewBuffer(make([]byte, 0)) - - fmt.Fprintf(buf, " quickCheck[C]: %v\n", f.quickCheck[MComposed]) - fmt.Fprintf(buf, " quickCheck[D]: %v\n", f.quickCheck[MDecomposed]) - fmt.Fprintf(buf, " cmbForward: %v\n", f.combinesForward) - fmt.Fprintf(buf, " cmbBackward: %v\n", f.combinesBackward) - fmt.Fprintf(buf, " isOneWay: %v\n", f.isOneWay) - fmt.Fprintf(buf, " inDecomp: %v\n", f.inDecomp) - fmt.Fprintf(buf, " decomposition: %X\n", f.decomp) - fmt.Fprintf(buf, " expandedDecomp: %X\n", f.expandedDecomp) - - return buf.String() -} - -type Decomposition []rune - -func parseDecomposition(s string, skipfirst bool) (a []rune, err error) { - decomp := strings.Split(s, " ") - if len(decomp) > 0 && skipfirst { - decomp = decomp[1:] - } - for _, d := range decomp { - point, err := strconv.ParseUint(d, 16, 64) - if err != nil { - return a, err - } - a = append(a, rune(point)) - } - return a, nil -} - -func loadUnicodeData() { - f := gen.OpenUCDFile("UnicodeData.txt") - defer f.Close() - p := ucd.New(f) - for p.Next() { - r := p.Rune(ucd.CodePoint) - char := &chars[r] - - char.ccc = uint8(p.Uint(ucd.CanonicalCombiningClass)) - decmap := p.String(ucd.DecompMapping) - - exp, err := parseDecomposition(decmap, false) - isCompat := false - if err != nil { - if len(decmap) > 0 { - exp, err = parseDecomposition(decmap, true) - if err != nil { - log.Fatalf(`%U: bad decomp |%v|: "%s"`, r, decmap, err) - } - isCompat = true - } - } - - char.name = p.String(ucd.Name) - char.codePoint = r - char.forms[FCompatibility].decomp = exp - if !isCompat { - char.forms[FCanonical].decomp = exp - } else { - char.compatDecomp = true - } - if len(decmap) > 0 { - char.forms[FCompatibility].decomp = exp - } - } - if err := p.Err(); err != nil { - log.Fatal(err) - } -} - -// compactCCC converts the sparse set of CCC values to a continguous one, -// reducing the number of bits needed from 8 to 6. -func compactCCC() { - m := make(map[uint8]uint8) - for i := range chars { - c := &chars[i] - m[c.ccc] = 0 - } - cccs := []int{} - for v, _ := range m { - cccs = append(cccs, int(v)) - } - sort.Ints(cccs) - for i, c := range cccs { - cccMap[uint8(i)] = uint8(c) - m[uint8(c)] = uint8(i) - } - for i := range chars { - c := &chars[i] - c.origCCC = c.ccc - c.ccc = m[c.ccc] - } - if len(m) >= 1<<6 { - log.Fatalf("too many difference CCC values: %d >= 64", len(m)) - } -} - -// CompositionExclusions.txt has form: -// 0958 # ... -// See https://unicode.org/reports/tr44/ for full explanation -func loadCompositionExclusions() { - f := gen.OpenUCDFile("CompositionExclusions.txt") - defer f.Close() - p := ucd.New(f) - for p.Next() { - c := &chars[p.Rune(0)] - if c.excludeInComp { - log.Fatalf("%U: Duplicate entry in exclusions.", c.codePoint) - } - c.excludeInComp = true - } - if e := p.Err(); e != nil { - log.Fatal(e) - } -} - -// hasCompatDecomp returns true if any of the recursive -// decompositions contains a compatibility expansion. -// In this case, the character may not occur in NFK*. -func hasCompatDecomp(r rune) bool { - c := &chars[r] - if c.compatDecomp { - return true - } - for _, d := range c.forms[FCompatibility].decomp { - if hasCompatDecomp(d) { - return true - } - } - return false -} - -// Hangul related constants. -const ( - HangulBase = 0xAC00 - HangulEnd = 0xD7A4 // hangulBase + Jamo combinations (19 * 21 * 28) - - JamoLBase = 0x1100 - JamoLEnd = 0x1113 - JamoVBase = 0x1161 - JamoVEnd = 0x1176 - JamoTBase = 0x11A8 - JamoTEnd = 0x11C3 - - JamoLVTCount = 19 * 21 * 28 - JamoTCount = 28 -) - -func isHangul(r rune) bool { - return HangulBase <= r && r < HangulEnd -} - -func isHangulWithoutJamoT(r rune) bool { - if !isHangul(r) { - return false - } - r -= HangulBase - return r < JamoLVTCount && r%JamoTCount == 0 -} - -func ccc(r rune) uint8 { - return chars[r].ccc -} - -// Insert a rune in a buffer, ordered by Canonical Combining Class. -func insertOrdered(b Decomposition, r rune) Decomposition { - n := len(b) - b = append(b, 0) - cc := ccc(r) - if cc > 0 { - // Use bubble sort. - for ; n > 0; n-- { - if ccc(b[n-1]) <= cc { - break - } - b[n] = b[n-1] - } - } - b[n] = r - return b -} - -// Recursively decompose. -func decomposeRecursive(form int, r rune, d Decomposition) Decomposition { - dcomp := chars[r].forms[form].decomp - if len(dcomp) == 0 { - return insertOrdered(d, r) - } - for _, c := range dcomp { - d = decomposeRecursive(form, c, d) - } - return d -} - -func completeCharFields(form int) { - // Phase 0: pre-expand decomposition. - for i := range chars { - f := &chars[i].forms[form] - if len(f.decomp) == 0 { - continue - } - exp := make(Decomposition, 0) - for _, c := range f.decomp { - exp = decomposeRecursive(form, c, exp) - } - f.expandedDecomp = exp - } - - // Phase 1: composition exclusion, mark decomposition. - for i := range chars { - c := &chars[i] - f := &c.forms[form] - - // Marks script-specific exclusions and version restricted. - f.isOneWay = c.excludeInComp - - // Singletons - f.isOneWay = f.isOneWay || len(f.decomp) == 1 - - // Non-starter decompositions - if len(f.decomp) > 1 { - chk := c.ccc != 0 || chars[f.decomp[0]].ccc != 0 - f.isOneWay = f.isOneWay || chk - } - - // Runes that decompose into more than two runes. - f.isOneWay = f.isOneWay || len(f.decomp) > 2 - - if form == FCompatibility { - f.isOneWay = f.isOneWay || hasCompatDecomp(c.codePoint) - } - - for _, r := range f.decomp { - chars[r].forms[form].inDecomp = true - } - } - - // Phase 2: forward and backward combining. - for i := range chars { - c := &chars[i] - f := &c.forms[form] - - if !f.isOneWay && len(f.decomp) == 2 { - f0 := &chars[f.decomp[0]].forms[form] - f1 := &chars[f.decomp[1]].forms[form] - if !f0.isOneWay { - f0.combinesForward = true - } - if !f1.isOneWay { - f1.combinesBackward = true - } - } - if isHangulWithoutJamoT(rune(i)) { - f.combinesForward = true - } - } - - // Phase 3: quick check values. - for i := range chars { - c := &chars[i] - f := &c.forms[form] - - switch { - case len(f.decomp) > 0: - f.quickCheck[MDecomposed] = QCNo - case isHangul(rune(i)): - f.quickCheck[MDecomposed] = QCNo - default: - f.quickCheck[MDecomposed] = QCYes - } - switch { - case f.isOneWay: - f.quickCheck[MComposed] = QCNo - case (i & 0xffff00) == JamoLBase: - f.quickCheck[MComposed] = QCYes - if JamoLBase <= i && i < JamoLEnd { - f.combinesForward = true - } - if JamoVBase <= i && i < JamoVEnd { - f.quickCheck[MComposed] = QCMaybe - f.combinesBackward = true - f.combinesForward = true - } - if JamoTBase <= i && i < JamoTEnd { - f.quickCheck[MComposed] = QCMaybe - f.combinesBackward = true - } - case !f.combinesBackward: - f.quickCheck[MComposed] = QCYes - default: - f.quickCheck[MComposed] = QCMaybe - } - } -} - -func computeNonStarterCounts() { - // Phase 4: leading and trailing non-starter count - for i := range chars { - c := &chars[i] - - runes := []rune{rune(i)} - // We always use FCompatibility so that the CGJ insertion points do not - // change for repeated normalizations with different forms. - if exp := c.forms[FCompatibility].expandedDecomp; len(exp) > 0 { - runes = exp - } - // We consider runes that combine backwards to be non-starters for the - // purpose of Stream-Safe Text Processing. - for _, r := range runes { - if cr := &chars[r]; cr.ccc == 0 && !cr.forms[FCompatibility].combinesBackward { - break - } - c.nLeadingNonStarters++ - } - for i := len(runes) - 1; i >= 0; i-- { - if cr := &chars[runes[i]]; cr.ccc == 0 && !cr.forms[FCompatibility].combinesBackward { - break - } - c.nTrailingNonStarters++ - } - if c.nTrailingNonStarters > 3 { - log.Fatalf("%U: Decomposition with more than 3 (%d) trailing modifiers (%U)", i, c.nTrailingNonStarters, runes) - } - - if isHangul(rune(i)) { - c.nTrailingNonStarters = 2 - if isHangulWithoutJamoT(rune(i)) { - c.nTrailingNonStarters = 1 - } - } - - if l, t := c.nLeadingNonStarters, c.nTrailingNonStarters; l > 0 && l != t { - log.Fatalf("%U: number of leading and trailing non-starters should be equal (%d vs %d)", i, l, t) - } - if t := c.nTrailingNonStarters; t > 3 { - log.Fatalf("%U: number of trailing non-starters is %d > 3", t) - } - } -} - -func printBytes(w io.Writer, b []byte, name string) { - fmt.Fprintf(w, "// %s: %d bytes\n", name, len(b)) - fmt.Fprintf(w, "var %s = [...]byte {", name) - for i, c := range b { - switch { - case i%64 == 0: - fmt.Fprintf(w, "\n// Bytes %x - %x\n", i, i+63) - case i%8 == 0: - fmt.Fprintf(w, "\n") - } - fmt.Fprintf(w, "0x%.2X, ", c) - } - fmt.Fprint(w, "\n}\n\n") -} - -// See forminfo.go for format. -func makeEntry(f *FormInfo, c *Char) uint16 { - e := uint16(0) - if r := c.codePoint; HangulBase <= r && r < HangulEnd { - e |= 0x40 - } - if f.combinesForward { - e |= 0x20 - } - if f.quickCheck[MDecomposed] == QCNo { - e |= 0x4 - } - switch f.quickCheck[MComposed] { - case QCYes: - case QCNo: - e |= 0x10 - case QCMaybe: - e |= 0x18 - default: - log.Fatalf("Illegal quickcheck value %v.", f.quickCheck[MComposed]) - } - e |= uint16(c.nTrailingNonStarters) - return e -} - -// decompSet keeps track of unique decompositions, grouped by whether -// the decomposition is followed by a trailing and/or leading CCC. -type decompSet [7]map[string]bool - -const ( - normalDecomp = iota - firstMulti - firstCCC - endMulti - firstLeadingCCC - firstCCCZeroExcept - firstStarterWithNLead - lastDecomp -) - -var cname = []string{"firstMulti", "firstCCC", "endMulti", "firstLeadingCCC", "firstCCCZeroExcept", "firstStarterWithNLead", "lastDecomp"} - -func makeDecompSet() decompSet { - m := decompSet{} - for i := range m { - m[i] = make(map[string]bool) - } - return m -} -func (m *decompSet) insert(key int, s string) { - m[key][s] = true -} - -func printCharInfoTables(w io.Writer) int { - mkstr := func(r rune, f *FormInfo) (int, string) { - d := f.expandedDecomp - s := string([]rune(d)) - if max := 1 << 6; len(s) >= max { - const msg = "%U: too many bytes in decomposition: %d >= %d" - log.Fatalf(msg, r, len(s), max) - } - head := uint8(len(s)) - if f.quickCheck[MComposed] != QCYes { - head |= 0x40 - } - if f.combinesForward { - head |= 0x80 - } - s = string([]byte{head}) + s - - lccc := ccc(d[0]) - tccc := ccc(d[len(d)-1]) - cc := ccc(r) - if cc != 0 && lccc == 0 && tccc == 0 { - log.Fatalf("%U: trailing and leading ccc are 0 for non-zero ccc %d", r, cc) - } - if tccc < lccc && lccc != 0 { - const msg = "%U: lccc (%d) must be <= tcc (%d)" - log.Fatalf(msg, r, lccc, tccc) - } - index := normalDecomp - nTrail := chars[r].nTrailingNonStarters - nLead := chars[r].nLeadingNonStarters - if tccc > 0 || lccc > 0 || nTrail > 0 { - tccc <<= 2 - tccc |= nTrail - s += string([]byte{tccc}) - index = endMulti - for _, r := range d[1:] { - if ccc(r) == 0 { - index = firstCCC - } - } - if lccc > 0 || nLead > 0 { - s += string([]byte{lccc}) - if index == firstCCC { - log.Fatalf("%U: multi-segment decomposition not supported for decompositions with leading CCC != 0", r) - } - index = firstLeadingCCC - } - if cc != lccc { - if cc != 0 { - log.Fatalf("%U: for lccc != ccc, expected ccc to be 0; was %d", r, cc) - } - index = firstCCCZeroExcept - } - } else if len(d) > 1 { - index = firstMulti - } - return index, s - } - - decompSet := makeDecompSet() - const nLeadStr = "\x00\x01" // 0-byte length and tccc with nTrail. - decompSet.insert(firstStarterWithNLead, nLeadStr) - - // Store the uniqued decompositions in a byte buffer, - // preceded by their byte length. - for _, c := range chars { - for _, f := range c.forms { - if len(f.expandedDecomp) == 0 { - continue - } - if f.combinesBackward { - log.Fatalf("%U: combinesBackward and decompose", c.codePoint) - } - index, s := mkstr(c.codePoint, &f) - decompSet.insert(index, s) - } - } - - decompositions := bytes.NewBuffer(make([]byte, 0, 10000)) - size := 0 - positionMap := make(map[string]uint16) - decompositions.WriteString("\000") - fmt.Fprintln(w, "const (") - for i, m := range decompSet { - sa := []string{} - for s := range m { - sa = append(sa, s) - } - sort.Strings(sa) - for _, s := range sa { - p := decompositions.Len() - decompositions.WriteString(s) - positionMap[s] = uint16(p) - } - if cname[i] != "" { - fmt.Fprintf(w, "%s = 0x%X\n", cname[i], decompositions.Len()) - } - } - fmt.Fprintln(w, "maxDecomp = 0x8000") - fmt.Fprintln(w, ")") - b := decompositions.Bytes() - printBytes(w, b, "decomps") - size += len(b) - - varnames := []string{"nfc", "nfkc"} - for i := 0; i < FNumberOfFormTypes; i++ { - trie := triegen.NewTrie(varnames[i]) - - for r, c := range chars { - f := c.forms[i] - d := f.expandedDecomp - if len(d) != 0 { - _, key := mkstr(c.codePoint, &f) - trie.Insert(rune(r), uint64(positionMap[key])) - if c.ccc != ccc(d[0]) { - // We assume the lead ccc of a decomposition !=0 in this case. - if ccc(d[0]) == 0 { - log.Fatalf("Expected leading CCC to be non-zero; ccc is %d", c.ccc) - } - } - } else if c.nLeadingNonStarters > 0 && len(f.expandedDecomp) == 0 && c.ccc == 0 && !f.combinesBackward { - // Handle cases where it can't be detected that the nLead should be equal - // to nTrail. - trie.Insert(c.codePoint, uint64(positionMap[nLeadStr])) - } else if v := makeEntry(&f, &c)<<8 | uint16(c.ccc); v != 0 { - trie.Insert(c.codePoint, uint64(0x8000|v)) - } - } - sz, err := trie.Gen(w, triegen.Compact(&normCompacter{name: varnames[i]})) - if err != nil { - log.Fatal(err) - } - size += sz - } - return size -} - -func contains(sa []string, s string) bool { - for _, a := range sa { - if a == s { - return true - } - } - return false -} - -func makeTables() { - w := &bytes.Buffer{} - - size := 0 - if *tablelist == "" { - return - } - list := strings.Split(*tablelist, ",") - if *tablelist == "all" { - list = []string{"recomp", "info"} - } - - // Compute maximum decomposition size. - max := 0 - for _, c := range chars { - if n := len(string(c.forms[FCompatibility].expandedDecomp)); n > max { - max = n - } - } - fmt.Fprintln(w, `import "sync"`) - fmt.Fprintln(w) - - fmt.Fprintln(w, "const (") - fmt.Fprintln(w, "\t// Version is the Unicode edition from which the tables are derived.") - fmt.Fprintf(w, "\tVersion = %q\n", gen.UnicodeVersion()) - fmt.Fprintln(w) - fmt.Fprintln(w, "\t// MaxTransformChunkSize indicates the maximum number of bytes that Transform") - fmt.Fprintln(w, "\t// may need to write atomically for any Form. Making a destination buffer at") - fmt.Fprintln(w, "\t// least this size ensures that Transform can always make progress and that") - fmt.Fprintln(w, "\t// the user does not need to grow the buffer on an ErrShortDst.") - fmt.Fprintf(w, "\tMaxTransformChunkSize = %d+maxNonStarters*4\n", len(string(0x034F))+max) - fmt.Fprintln(w, ")\n") - - // Print the CCC remap table. - size += len(cccMap) - fmt.Fprintf(w, "var ccc = [%d]uint8{", len(cccMap)) - for i := 0; i < len(cccMap); i++ { - if i%8 == 0 { - fmt.Fprintln(w) - } - fmt.Fprintf(w, "%3d, ", cccMap[uint8(i)]) - } - fmt.Fprintln(w, "\n}\n") - - if contains(list, "info") { - size += printCharInfoTables(w) - } - - if contains(list, "recomp") { - // Note that we use 32 bit keys, instead of 64 bit. - // This clips the bits of three entries, but we know - // this won't cause a collision. The compiler will catch - // any changes made to UnicodeData.txt that introduces - // a collision. - // Note that the recomposition map for NFC and NFKC - // are identical. - - // Recomposition map - nrentries := 0 - for _, c := range chars { - f := c.forms[FCanonical] - if !f.isOneWay && len(f.decomp) > 0 { - nrentries++ - } - } - sz := nrentries * 8 - size += sz - fmt.Fprintf(w, "// recompMap: %d bytes (entries only)\n", sz) - fmt.Fprintln(w, "var recompMap map[uint32]rune") - fmt.Fprintln(w, "var recompMapOnce sync.Once\n") - fmt.Fprintln(w, `const recompMapPacked = "" +`) - var buf [8]byte - for i, c := range chars { - f := c.forms[FCanonical] - d := f.decomp - if !f.isOneWay && len(d) > 0 { - key := uint32(uint16(d[0]))<<16 + uint32(uint16(d[1])) - binary.BigEndian.PutUint32(buf[:4], key) - binary.BigEndian.PutUint32(buf[4:], uint32(i)) - fmt.Fprintf(w, "\t\t%q + // 0x%.8X: 0x%.8X\n", string(buf[:]), key, uint32(i)) - } - } - // hack so we don't have to special case the trailing plus sign - fmt.Fprintf(w, ` ""`) - fmt.Fprintln(w) - } - - fmt.Fprintf(w, "// Total size of tables: %dKB (%d bytes)\n", (size+512)/1024, size) - gen.WriteVersionedGoFile("tables.go", "norm", w.Bytes()) -} - -func printChars() { - if *verbose { - for _, c := range chars { - if !c.isValid() || c.state == SMissing { - continue - } - fmt.Println(c) - } - } -} - -// verifyComputed does various consistency tests. -func verifyComputed() { - for i, c := range chars { - for _, f := range c.forms { - isNo := (f.quickCheck[MDecomposed] == QCNo) - if (len(f.decomp) > 0) != isNo && !isHangul(rune(i)) { - log.Fatalf("%U: NF*D QC must be No if rune decomposes", i) - } - - isMaybe := f.quickCheck[MComposed] == QCMaybe - if f.combinesBackward != isMaybe { - log.Fatalf("%U: NF*C QC must be Maybe if combinesBackward", i) - } - if len(f.decomp) > 0 && f.combinesForward && isMaybe { - log.Fatalf("%U: NF*C QC must be Yes or No if combinesForward and decomposes", i) - } - - if len(f.expandedDecomp) != 0 { - continue - } - if a, b := c.nLeadingNonStarters > 0, (c.ccc > 0 || f.combinesBackward); a != b { - // We accept these runes to be treated differently (it only affects - // segment breaking in iteration, most likely on improper use), but - // reconsider if more characters are added. - // U+FF9E HALFWIDTH KATAKANA VOICED SOUND MARK;Lm;0;L; 3099;;;;N;;;;; - // U+FF9F HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK;Lm;0;L; 309A;;;;N;;;;; - // U+3133 HANGUL LETTER KIYEOK-SIOS;Lo;0;L; 11AA;;;;N;HANGUL LETTER GIYEOG SIOS;;;; - // U+318E HANGUL LETTER ARAEAE;Lo;0;L; 11A1;;;;N;HANGUL LETTER ALAE AE;;;; - // U+FFA3 HALFWIDTH HANGUL LETTER KIYEOK-SIOS;Lo;0;L; 3133;;;;N;HALFWIDTH HANGUL LETTER GIYEOG SIOS;;;; - // U+FFDC HALFWIDTH HANGUL LETTER I;Lo;0;L; 3163;;;;N;;;;; - if i != 0xFF9E && i != 0xFF9F && !(0x3133 <= i && i <= 0x318E) && !(0xFFA3 <= i && i <= 0xFFDC) { - log.Fatalf("%U: nLead was %v; want %v", i, a, b) - } - } - } - nfc := c.forms[FCanonical] - nfkc := c.forms[FCompatibility] - if nfc.combinesBackward != nfkc.combinesBackward { - log.Fatalf("%U: Cannot combine combinesBackward\n", c.codePoint) - } - } -} - -// Use values in DerivedNormalizationProps.txt to compare against the -// values we computed. -// DerivedNormalizationProps.txt has form: -// 00C0..00C5 ; NFD_QC; N # ... -// 0374 ; NFD_QC; N # ... -// See https://unicode.org/reports/tr44/ for full explanation -func testDerived() { - f := gen.OpenUCDFile("DerivedNormalizationProps.txt") - defer f.Close() - p := ucd.New(f) - for p.Next() { - r := p.Rune(0) - c := &chars[r] - - var ftype, mode int - qt := p.String(1) - switch qt { - case "NFC_QC": - ftype, mode = FCanonical, MComposed - case "NFD_QC": - ftype, mode = FCanonical, MDecomposed - case "NFKC_QC": - ftype, mode = FCompatibility, MComposed - case "NFKD_QC": - ftype, mode = FCompatibility, MDecomposed - default: - continue - } - var qr QCResult - switch p.String(2) { - case "Y": - qr = QCYes - case "N": - qr = QCNo - case "M": - qr = QCMaybe - default: - log.Fatalf(`Unexpected quick check value "%s"`, p.String(2)) - } - if got := c.forms[ftype].quickCheck[mode]; got != qr { - log.Printf("%U: FAILED %s (was %v need %v)\n", r, qt, got, qr) - } - c.forms[ftype].verified[mode] = true - } - if err := p.Err(); err != nil { - log.Fatal(err) - } - // Any unspecified value must be QCYes. Verify this. - for i, c := range chars { - for j, fd := range c.forms { - for k, qr := range fd.quickCheck { - if !fd.verified[k] && qr != QCYes { - m := "%U: FAIL F:%d M:%d (was %v need Yes) %s\n" - log.Printf(m, i, j, k, qr, c.name) - } - } - } - } -} - -var testHeader = `const ( - Yes = iota - No - Maybe -) - -type formData struct { - qc uint8 - combinesForward bool - decomposition string -} - -type runeData struct { - r rune - ccc uint8 - nLead uint8 - nTrail uint8 - f [2]formData // 0: canonical; 1: compatibility -} - -func f(qc uint8, cf bool, dec string) [2]formData { - return [2]formData{{qc, cf, dec}, {qc, cf, dec}} -} - -func g(qc, qck uint8, cf, cfk bool, d, dk string) [2]formData { - return [2]formData{{qc, cf, d}, {qck, cfk, dk}} -} - -var testData = []runeData{ -` - -func printTestdata() { - type lastInfo struct { - ccc uint8 - nLead uint8 - nTrail uint8 - f string - } - - last := lastInfo{} - w := &bytes.Buffer{} - fmt.Fprintf(w, testHeader) - for r, c := range chars { - f := c.forms[FCanonical] - qc, cf, d := f.quickCheck[MComposed], f.combinesForward, string(f.expandedDecomp) - f = c.forms[FCompatibility] - qck, cfk, dk := f.quickCheck[MComposed], f.combinesForward, string(f.expandedDecomp) - s := "" - if d == dk && qc == qck && cf == cfk { - s = fmt.Sprintf("f(%s, %v, %q)", qc, cf, d) - } else { - s = fmt.Sprintf("g(%s, %s, %v, %v, %q, %q)", qc, qck, cf, cfk, d, dk) - } - current := lastInfo{c.ccc, c.nLeadingNonStarters, c.nTrailingNonStarters, s} - if last != current { - fmt.Fprintf(w, "\t{0x%x, %d, %d, %d, %s},\n", r, c.origCCC, c.nLeadingNonStarters, c.nTrailingNonStarters, s) - last = current - } - } - fmt.Fprintln(w, "}") - gen.WriteVersionedGoFile("data_test.go", "norm", w.Bytes()) -} diff --git a/vendor/golang.org/x/text/unicode/norm/triegen.go b/vendor/golang.org/x/text/unicode/norm/triegen.go deleted file mode 100644 index 45d71190..00000000 --- a/vendor/golang.org/x/text/unicode/norm/triegen.go +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// Trie table generator. -// Used by make*tables tools to generate a go file with trie data structures -// for mapping UTF-8 to a 16-bit value. All but the last byte in a UTF-8 byte -// sequence are used to lookup offsets in the index table to be used for the -// next byte. The last byte is used to index into a table with 16-bit values. - -package main - -import ( - "fmt" - "io" -) - -const maxSparseEntries = 16 - -type normCompacter struct { - sparseBlocks [][]uint64 - sparseOffset []uint16 - sparseCount int - name string -} - -func mostFrequentStride(a []uint64) int { - counts := make(map[int]int) - var v int - for _, x := range a { - if stride := int(x) - v; v != 0 && stride >= 0 { - counts[stride]++ - } - v = int(x) - } - var maxs, maxc int - for stride, cnt := range counts { - if cnt > maxc || (cnt == maxc && stride < maxs) { - maxs, maxc = stride, cnt - } - } - return maxs -} - -func countSparseEntries(a []uint64) int { - stride := mostFrequentStride(a) - var v, count int - for _, tv := range a { - if int(tv)-v != stride { - if tv != 0 { - count++ - } - } - v = int(tv) - } - return count -} - -func (c *normCompacter) Size(v []uint64) (sz int, ok bool) { - if n := countSparseEntries(v); n <= maxSparseEntries { - return (n+1)*4 + 2, true - } - return 0, false -} - -func (c *normCompacter) Store(v []uint64) uint32 { - h := uint32(len(c.sparseOffset)) - c.sparseBlocks = append(c.sparseBlocks, v) - c.sparseOffset = append(c.sparseOffset, uint16(c.sparseCount)) - c.sparseCount += countSparseEntries(v) + 1 - return h -} - -func (c *normCompacter) Handler() string { - return c.name + "Sparse.lookup" -} - -func (c *normCompacter) Print(w io.Writer) (retErr error) { - p := func(f string, x ...interface{}) { - if _, err := fmt.Fprintf(w, f, x...); retErr == nil && err != nil { - retErr = err - } - } - - ls := len(c.sparseBlocks) - p("// %sSparseOffset: %d entries, %d bytes\n", c.name, ls, ls*2) - p("var %sSparseOffset = %#v\n\n", c.name, c.sparseOffset) - - ns := c.sparseCount - p("// %sSparseValues: %d entries, %d bytes\n", c.name, ns, ns*4) - p("var %sSparseValues = [%d]valueRange {", c.name, ns) - for i, b := range c.sparseBlocks { - p("\n// Block %#x, offset %#x", i, c.sparseOffset[i]) - var v int - stride := mostFrequentStride(b) - n := countSparseEntries(b) - p("\n{value:%#04x,lo:%#02x},", stride, uint8(n)) - for i, nv := range b { - if int(nv)-v != stride { - if v != 0 { - p(",hi:%#02x},", 0x80+i-1) - } - if nv != 0 { - p("\n{value:%#04x,lo:%#02x", nv, 0x80+i) - } - } - v = int(nv) - } - if v != 0 { - p(",hi:%#02x},", 0x80+len(b)-1) - } - } - p("\n}\n\n") - return -} diff --git a/vendor/modules.txt b/vendor/modules.txt index c73566a7..6153c078 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -44,30 +44,30 @@ go.uber.org/atomic go.uber.org/multierr # go.uber.org/zap v1.11.0 go.uber.org/zap -go.uber.org/zap/zapcore -go.uber.org/zap/internal/bufferpool go.uber.org/zap/buffer +go.uber.org/zap/internal/bufferpool go.uber.org/zap/internal/color go.uber.org/zap/internal/exit +go.uber.org/zap/zapcore # golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 golang.org/x/crypto/acme golang.org/x/crypto/ed25519 golang.org/x/crypto/ed25519/internal/edwards25519 # golang.org/x/net v0.0.0-20191027093000-83d349e8ac1a -golang.org/x/net/idna -golang.org/x/net/ipv4 -golang.org/x/net/ipv6 golang.org/x/net/bpf +golang.org/x/net/idna golang.org/x/net/internal/iana golang.org/x/net/internal/socket +golang.org/x/net/ipv4 +golang.org/x/net/ipv6 # golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe -golang.org/x/sys/windows/svc golang.org/x/sys/unix golang.org/x/sys/windows +golang.org/x/sys/windows/svc # golang.org/x/text v0.3.2 golang.org/x/text/secure/bidirule +golang.org/x/text/transform golang.org/x/text/unicode/bidi golang.org/x/text/unicode/norm -golang.org/x/text/transform # gopkg.in/natefinch/lumberjack.v2 v2.0.0 gopkg.in/natefinch/lumberjack.v2