diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index 68fabb17313..804f7f5348c 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -7,43 +7,43 @@ "Deps": [ { "ImportPath": "github.com/elastic/libbeat/beat", - "Comment": "v1.0.0-beta4-35-g3989f8f", - "Rev": "3989f8f01bb335d756bad200f8b3b1fa0ae941db" + "Comment": "v1.0.0-beta4-42-g00f00f9", + "Rev": "00f00f9e991b32db10ce2a10f825525b35e38a52" }, { "ImportPath": "github.com/elastic/libbeat/cfgfile", - "Comment": "v1.0.0-beta4-35-g3989f8f", - "Rev": "3989f8f01bb335d756bad200f8b3b1fa0ae941db" + "Comment": "v1.0.0-beta4-42-g00f00f9", + "Rev": "00f00f9e991b32db10ce2a10f825525b35e38a52" }, { "ImportPath": "github.com/elastic/libbeat/common", - "Comment": "v1.0.0-beta4-35-g3989f8f", - "Rev": "3989f8f01bb335d756bad200f8b3b1fa0ae941db" + "Comment": "v1.0.0-beta4-42-g00f00f9", + "Rev": "00f00f9e991b32db10ce2a10f825525b35e38a52" }, { "ImportPath": "github.com/elastic/libbeat/filters", - "Comment": "v1.0.0-beta4-35-g3989f8f", - "Rev": "3989f8f01bb335d756bad200f8b3b1fa0ae941db" + "Comment": "v1.0.0-beta4-42-g00f00f9", + "Rev": "00f00f9e991b32db10ce2a10f825525b35e38a52" }, { "ImportPath": "github.com/elastic/libbeat/logp", - "Comment": "v1.0.0-beta4-35-g3989f8f", - "Rev": "3989f8f01bb335d756bad200f8b3b1fa0ae941db" + "Comment": "v1.0.0-beta4-42-g00f00f9", + "Rev": "00f00f9e991b32db10ce2a10f825525b35e38a52" }, { "ImportPath": "github.com/elastic/libbeat/outputs", - "Comment": "v1.0.0-beta4-35-g3989f8f", - "Rev": "3989f8f01bb335d756bad200f8b3b1fa0ae941db" + "Comment": "v1.0.0-beta4-42-g00f00f9", + "Rev": "00f00f9e991b32db10ce2a10f825525b35e38a52" }, { "ImportPath": "github.com/elastic/libbeat/publisher", - "Comment": "v1.0.0-beta4-35-g3989f8f", - "Rev": "3989f8f01bb335d756bad200f8b3b1fa0ae941db" + "Comment": "v1.0.0-beta4-42-g00f00f9", + "Rev": "00f00f9e991b32db10ce2a10f825525b35e38a52" }, { "ImportPath": "github.com/elastic/libbeat/service", - "Comment": "v1.0.0-beta4-35-g3989f8f", - "Rev": "3989f8f01bb335d756bad200f8b3b1fa0ae941db" + "Comment": "v1.0.0-beta4-42-g00f00f9", + "Rev": "00f00f9e991b32db10ce2a10f825525b35e38a52" }, { "ImportPath": "github.com/garyburd/redigo/internal", diff --git a/Godeps/_workspace/src/github.com/elastic/libbeat/logp/log.go b/Godeps/_workspace/src/github.com/elastic/libbeat/logp/log.go index 3839518fa44..ea7f8522f8c 100644 --- a/Godeps/_workspace/src/github.com/elastic/libbeat/logp/log.go +++ b/Godeps/_workspace/src/github.com/elastic/libbeat/logp/log.go @@ -68,7 +68,7 @@ func MakeDebug(selector string) func(string, ...interface{}) { } func IsDebug(selector string) bool { - return _log.selectors[selector] + return _log.debug_all_selectors || _log.selectors[selector] } func msg(level Priority, prefix string, format string, v ...interface{}) { diff --git a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/console/console.go b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/console/console.go index 9c8365c8ce4..2470043bfb5 100644 --- a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/console/console.go +++ b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/console/console.go @@ -75,7 +75,6 @@ func (c *console) PublishEvent( outputs.SignalCompleted(s) return nil fail: - logp.Err("Fail to write event: %s", err) - outputs.SignalFailed(s) + outputs.SignalFailed(s, err) return err } diff --git a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/elasticsearch/client.go b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/elasticsearch/client.go index 0c645e49324..06e59fb0c31 100644 --- a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/elasticsearch/client.go +++ b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/elasticsearch/client.go @@ -78,7 +78,7 @@ func (client *Client) PublishEvents( } for _, event := range events { - ts := time.Time(event["timestamp"].(common.Time)) + ts := time.Time(event["@timestamp"].(common.Time)) index := fmt.Sprintf("%s-%d.%02d.%02d", client.index, ts.Year(), ts.Month(), ts.Day()) meta := bulkMeta{ @@ -109,7 +109,7 @@ func (client *Client) PublishEvent(event common.MapStr) error { return ErrNotConnected } - ts := time.Time(event["timestamp"].(common.Time)) + ts := time.Time(event["@timestamp"].(common.Time)) index := fmt.Sprintf("%s-%d.%02d.%02d", client.index, ts.Year(), ts.Month(), ts.Day()) logp.Debug("output_elasticsearch", "Publish event: %s", event) diff --git a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/elasticsearch/output.go b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/elasticsearch/output.go index 7eca183d42a..51d0f8c3892 100644 --- a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/elasticsearch/output.go +++ b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/elasticsearch/output.go @@ -1,8 +1,8 @@ package elasticsearch import ( + "crypto/tls" "errors" - "fmt" "time" "github.com/elastic/libbeat/common" @@ -14,9 +14,6 @@ import ( var debug = logp.MakeDebug("elasticsearch") var ( - // ErrNoHostsConfigured indicates missing host or hosts configuration - ErrNoHostsConfigured = errors.New("no host configuration found") - // ErrNotConnected indicates failure due to client having no valid connection ErrNotConnected = errors.New("not connected") @@ -64,7 +61,12 @@ func (out *elasticsearchOutput) init( config outputs.MothershipConfig, topologyExpire int, ) error { - clients, err := makeClients(beat, config) + tlsConfig, err := outputs.LoadTLSConfig(config.TLS) + if err != nil { + return err + } + + clients, err := mode.MakeClients(config, makeClientFactory(beat, tlsConfig, config)) if err != nil { return err } @@ -130,43 +132,26 @@ func (out *elasticsearchOutput) init( return nil } -func makeClients( +func makeClientFactory( beat string, + tls *tls.Config, config outputs.MothershipConfig, -) ([]mode.ProtocolClient, error) { - var urls []string - if len(config.Hosts) > 0 { - // use hosts setting - for _, host := range config.Hosts { - url, err := getURL(config.Protocol, config.Path, host) - if err != nil { - logp.Err("Invalid host param set: %s, Error: %v", host, err) - } - - urls = append(urls, url) +) func(string) (mode.ProtocolClient, error) { + return func(host string) (mode.ProtocolClient, error) { + url, err := getURL(config.Protocol, config.Path, host) + if err != nil { + logp.Err("Invalid host param set: %s, Error: %v", host, err) + return nil, err } - } else { - // usage of host and port is deprecated as it is replaced by hosts - url := fmt.Sprintf("%s://%s:%d%s", config.Protocol, config.Host, config.Port, config.Path) - urls = append(urls, url) - } - index := beat - if config.Index != "" { - index = config.Index - } - - tlsConfig, err := outputs.LoadTLSConfig(config.TLS) - if err != nil { - return nil, err - } + index := beat + if config.Index != "" { + index = config.Index + } - var clients []mode.ProtocolClient - for _, url := range urls { - client := NewClient(url, index, tlsConfig, config.Username, config.Password) - clients = append(clients, client) + client := NewClient(url, index, tls, config.Username, config.Password) + return client, nil } - return clients, nil } func (out *elasticsearchOutput) PublishEvent( diff --git a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/logstash/logstash.go b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/logstash/logstash.go index 49db6695b0e..5faec62ed9a 100644 --- a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/logstash/logstash.go +++ b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/logstash/logstash.go @@ -5,7 +5,6 @@ package logstash import ( "crypto/tls" - "errors" "fmt" "time" @@ -48,9 +47,6 @@ const ( defaultSendRetries = 3 ) -// ErrNoHostsConfigured indicates missing host or hosts configuration -var ErrNoHostsConfigured = errors.New("no host configuration found") - var waitRetry = time.Duration(1) * time.Second func (lj *logstash) init( @@ -82,15 +78,15 @@ func (lj *logstash) init( return err } - clients, err = makeClients(config, timeout, + clients, err = mode.MakeClients(config, makeClientFactory(timeout, func(host string) (TransportClient, error) { return newTLSClient(host, defaultPort, tlsConfig) - }) + })) } else { - clients, err = makeClients(config, timeout, + clients, err = mode.MakeClients(config, makeClientFactory(timeout, func(host string) (TransportClient, error) { return newTCPClient(host, defaultPort) - }) + })) } if err != nil { return err @@ -126,34 +122,16 @@ func (lj *logstash) init( return nil } -func makeClients( - config outputs.MothershipConfig, +func makeClientFactory( timeout time.Duration, - newTransp func(string) (TransportClient, error), -) ([]mode.ProtocolClient, error) { - switch { - case len(config.Hosts) > 0: - var clients []mode.ProtocolClient - for _, host := range config.Hosts { - transp, err := newTransp(host) - if err != nil { - for _, client := range clients { - _ = client.Close() // ignore error - } - return nil, err - } - client := newLumberjackClient(transp, timeout) - clients = append(clients, client) - } - return clients, nil - case config.Host != "": - transp, err := newTransp(config.Host) + makeTransp func(string) (TransportClient, error), +) func(string) (mode.ProtocolClient, error) { + return func(host string) (mode.ProtocolClient, error) { + transp, err := makeTransp(host) if err != nil { return nil, err } - return []mode.ProtocolClient{newLumberjackClient(transp, timeout)}, nil - default: - return nil, ErrNoHostsConfigured + return newLumberjackClient(transp, timeout), nil } } diff --git a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/mode/balance.go b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/mode/balance.go index e3b7bd6629d..72c4c96af29 100644 --- a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/mode/balance.go +++ b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/mode/balance.go @@ -5,6 +5,7 @@ import ( "time" "github.com/elastic/libbeat/common" + "github.com/elastic/libbeat/logp" "github.com/elastic/libbeat/outputs" ) @@ -114,7 +115,7 @@ func (m *LoadBalancerMode) PublishEvent( func (m *LoadBalancerMode) publishEventsMessage(msg eventsMessage) error { if ok := m.forwardEvent(m.work, msg); !ok { - outputs.SignalFailed(msg.signaler) + outputs.SignalFailed(msg.signaler, nil) } return nil } @@ -167,7 +168,7 @@ func (m *LoadBalancerMode) start(clients []ProtocolClient) { func (m *LoadBalancerMode) onMessage(client ProtocolClient, msg eventsMessage) { if msg.event != nil { if err := client.PublishEvent(msg.event); err != nil { - m.onFail(msg) + m.onFail(msg, err) return } } else { @@ -184,7 +185,7 @@ func (m *LoadBalancerMode) onMessage(client ProtocolClient, msg eventsMessage) { if send > 0 { msg.attemptsLeft = m.maxAttempts + 1 } - m.onFail(msg) + m.onFail(msg, err) return } published += n @@ -194,9 +195,12 @@ func (m *LoadBalancerMode) onMessage(client ProtocolClient, msg eventsMessage) { outputs.SignalCompleted(msg.signaler) } -func (m *LoadBalancerMode) onFail(msg eventsMessage) { +func (m *LoadBalancerMode) onFail(msg eventsMessage, err error) { + + logp.Info("Error publishing events (retrying): %s", err) + if ok := m.forwardEvent(m.retries, msg); !ok { - outputs.SignalFailed(msg.signaler) + outputs.SignalFailed(msg.signaler, err) } } diff --git a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/mode/failover.go b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/mode/failover.go index 840c3082082..d4597935e05 100644 --- a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/mode/failover.go +++ b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/mode/failover.go @@ -6,6 +6,7 @@ import ( "time" "github.com/elastic/libbeat/common" + "github.com/elastic/libbeat/logp" "github.com/elastic/libbeat/outputs" ) @@ -109,8 +110,11 @@ func (f *FailOverConnectionMode) PublishEvents( ) error { published := 0 fails := 0 + var err error + for !f.closed && (f.maxAttempts == 0 || fails < f.maxAttempts) { - if err := f.connect(f.active); err != nil { + if err = f.connect(f.active); err != nil { + logp.Info("Connecting error publishing events (retrying): %s", err) fails++ time.Sleep(f.waitRetry) continue @@ -121,6 +125,7 @@ func (f *FailOverConnectionMode) PublishEvents( conn := f.conns[f.active] n, err := conn.PublishEvents(events[published:]) if err != nil { + logp.Info("Error publishing events (retrying): %s", err) break } published += n @@ -140,7 +145,7 @@ func (f *FailOverConnectionMode) PublishEvents( fails++ } - outputs.SignalFailed(trans) + outputs.SignalFailed(trans, err) return nil } @@ -150,14 +155,17 @@ func (f *FailOverConnectionMode) PublishEvent( event common.MapStr, ) error { fails := 0 + var err error for !f.closed && (f.maxAttempts == 0 || fails < f.maxAttempts) { if err := f.connect(f.active); err != nil { + logp.Info("Connecting error publishing events (retrying): %s", err) fails++ time.Sleep(f.waitRetry) continue } if err := f.conns[f.active].PublishEvent(event); err != nil { + logp.Info("Error publishing events (retrying): %s", err) fails++ continue } @@ -166,6 +174,6 @@ func (f *FailOverConnectionMode) PublishEvent( return nil } - outputs.SignalFailed(signaler) + outputs.SignalFailed(signaler, err) return nil } diff --git a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/mode/mode.go b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/mode/mode.go index 14a55dd9068..673faf24fb9 100644 --- a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/mode/mode.go +++ b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/mode/mode.go @@ -3,12 +3,16 @@ package mode import ( + "errors" "time" "github.com/elastic/libbeat/common" "github.com/elastic/libbeat/outputs" ) +// ErrNoHostsConfigured indicates missing host or hosts configuration +var ErrNoHostsConfigured = errors.New("no host configuration found") + // ConnectionMode takes care of connecting to hosts // and potentially doing load balancing and/or failover type ConnectionMode interface { @@ -56,3 +60,54 @@ type ProtocolClient interface { // returned. PublishEvent(event common.MapStr) error } + +// MakeClients will create a list from of ProtocolClient instances from +// outputer configuration host list and client factory function. +func MakeClients( + config outputs.MothershipConfig, + newClient func(string) (ProtocolClient, error), +) ([]ProtocolClient, error) { + hosts := readHostList(config) + if len(hosts) == 0 { + return nil, ErrNoHostsConfigured + } + + clients := make([]ProtocolClient, 0, len(hosts)) + for _, host := range hosts { + client, err := newClient(host) + if err != nil { + // on error destroy all client instance created + for _, client := range clients { + _ = client.Close() // ignore error + } + return nil, err + } + clients = append(clients, client) + } + return clients, nil +} + +func readHostList(config outputs.MothershipConfig) []string { + var lst []string + + // TODO: remove config.Host + if len(config.Hosts) > 0 { + lst = config.Hosts + } else if config.Host != "" { + lst = []string{config.Host} + } + + if len(lst) == 0 || config.Worker <= 1 { + return lst + } + + // duplicate entries config.Workers times + hosts := make([]string, 0, len(lst)*config.Worker) + for _, entry := range lst { + for i := 0; i < config.Worker; i++ { + hosts = append(hosts, entry) + } + } + + return hosts +} diff --git a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/mode/single.go b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/mode/single.go index 2a296201678..ca5236d5853 100644 --- a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/mode/single.go +++ b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/mode/single.go @@ -4,6 +4,7 @@ import ( "time" "github.com/elastic/libbeat/common" + "github.com/elastic/libbeat/logp" "github.com/elastic/libbeat/outputs" ) @@ -61,8 +62,12 @@ func (s *SingleConnectionMode) PublishEvents( ) error { published := 0 fails := 0 + var err error + for !s.closed && (s.maxAttempts == 0 || fails < s.maxAttempts) { if err := s.connect(); err != nil { + logp.Info("Connecting error publishing events (retrying): %s", err) + fails++ time.Sleep(s.waitRetry) continue @@ -71,6 +76,7 @@ func (s *SingleConnectionMode) PublishEvents( for published < len(events) { n, err := s.conn.PublishEvents(events[published:]) if err != nil { + logp.Info("Error publishing events (retrying): %s", err) break } @@ -87,7 +93,7 @@ func (s *SingleConnectionMode) PublishEvents( fails++ } - outputs.SignalFailed(signaler) + outputs.SignalFailed(signaler, err) return nil } @@ -97,13 +103,20 @@ func (s *SingleConnectionMode) PublishEvent( event common.MapStr, ) error { fails := 0 + + var err error + for !s.closed && (s.maxAttempts == 0 || fails < s.maxAttempts) { - if err := s.connect(); err != nil { + if err = s.connect(); err != nil { + logp.Info("Connecting error publishing event (retrying): %s", err) + fails++ time.Sleep(s.waitRetry) continue } if err := s.conn.PublishEvent(event); err != nil { + logp.Info("Error publishing event (retrying): %s", err) + fails++ continue } @@ -112,6 +125,6 @@ func (s *SingleConnectionMode) PublishEvent( return nil } - outputs.SignalFailed(signaler) + outputs.SignalFailed(signaler, err) return nil } diff --git a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/outputs.go b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/outputs.go index 9c8804d59e5..85af56c4a29 100644 --- a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/outputs.go +++ b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/outputs.go @@ -32,6 +32,7 @@ type MothershipConfig struct { Max_retries *int Pretty *bool TLS *TLSConfig + Worker int } type Outputer interface { diff --git a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/redis/redis.go b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/redis/redis.go index 33c1b142b91..7cb0c8a036b 100644 --- a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/redis/redis.go +++ b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/redis/redis.go @@ -300,7 +300,7 @@ func (out *redisOutput) BulkPublish( } err = out.Conn.Send(command, out.Index, string(jsonEvent)) if err != nil { - outputs.SignalFailed(signal) + outputs.SignalFailed(signal, err) out.onFail(err) return err } diff --git a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/signal.go b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/signal.go index 1cb3642c15f..973d409226e 100644 --- a/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/signal.go +++ b/Godeps/_workspace/src/github.com/elastic/libbeat/outputs/signal.go @@ -1,6 +1,7 @@ package outputs import ( + "github.com/elastic/libbeat/logp" "sync/atomic" ) @@ -140,7 +141,12 @@ func SignalCompleted(s Signaler) { } // SignalFailed sends the Failed event to s if s is not nil -func SignalFailed(s Signaler) { +func SignalFailed(s Signaler, err error) { + + if err != nil { + logp.Err("Error sending/writing event: %s", err) + } + if s != nil { s.Failed() } @@ -149,6 +155,11 @@ func SignalFailed(s Signaler) { // Signal will send the Completed or Failed event to s depending // on err being set if s is not nil. func Signal(s Signaler, err error) { + + if err != nil { + logp.Info("Failed to send event %s", err) + } + if s != nil { if err == nil { s.Completed() diff --git a/Godeps/_workspace/src/github.com/elastic/libbeat/publisher/output.go b/Godeps/_workspace/src/github.com/elastic/libbeat/publisher/output.go index 21fd6103acb..3c5b5bd23f4 100644 --- a/Godeps/_workspace/src/github.com/elastic/libbeat/publisher/output.go +++ b/Godeps/_workspace/src/github.com/elastic/libbeat/publisher/output.go @@ -4,6 +4,7 @@ import ( "time" "github.com/elastic/libbeat/common" + "github.com/elastic/libbeat/logp" "github.com/elastic/libbeat/outputs" ) @@ -30,7 +31,7 @@ func (o *outputWorker) onMessage(m message) { if m.event != nil { debug("output worker: publish single event") - ts := time.Time(m.event["timestamp"].(common.Time)).UTC() + ts := time.Time(m.event["@timestamp"].(common.Time)).UTC() _ = o.out.PublishEvent(m.signal, ts, m.event) } else { if len(m.events) == 0 { @@ -40,7 +41,11 @@ func (o *outputWorker) onMessage(m message) { } debug("output worker: publish %v events", len(m.events)) - ts := time.Time(m.events[0]["timestamp"].(common.Time)).UTC() - _ = o.out.BulkPublish(m.signal, ts, m.events) + ts := time.Time(m.events[0]["@timestamp"].(common.Time)).UTC() + err := o.out.BulkPublish(m.signal, ts, m.events) + + if err != nil { + logp.Info("Error bulk publishing events: %s", err) + } } } diff --git a/Godeps/_workspace/src/github.com/elastic/libbeat/publisher/preprocess.go b/Godeps/_workspace/src/github.com/elastic/libbeat/publisher/preprocess.go index adf17669941..54ed5c46a25 100644 --- a/Godeps/_workspace/src/github.com/elastic/libbeat/publisher/preprocess.go +++ b/Godeps/_workspace/src/github.com/elastic/libbeat/publisher/preprocess.go @@ -99,14 +99,14 @@ func (p *preprocessor) onMessage(m message) { // filterEvent validates an event for common required fields with types. // If event is to be filtered out the reason is returned as error. func filterEvent(event common.MapStr) error { - ts, ok := event["timestamp"] + ts, ok := event["@timestamp"] if !ok { - return errors.New("Missing 'timestamp' field from event") + return errors.New("Missing '@timestamp' field from event") } _, ok = ts.(common.Time) if !ok { - return errors.New("Invalid 'timestamp' field from event.") + return errors.New("Invalid '@timestamp' field from event.") } err := event.EnsureCountField() diff --git a/Godeps/_workspace/src/github.com/elastic/libbeat/publisher/worker.go b/Godeps/_workspace/src/github.com/elastic/libbeat/publisher/worker.go index 512bb9517f1..2ff3324423a 100644 --- a/Godeps/_workspace/src/github.com/elastic/libbeat/publisher/worker.go +++ b/Godeps/_workspace/src/github.com/elastic/libbeat/publisher/worker.go @@ -87,6 +87,6 @@ func (ws *workerSignal) Init() { func stopQueue(qu chan message) { close(qu) for msg := range qu { // clear queue and send fail signal - outputs.SignalFailed(msg.signal) + outputs.SignalFailed(msg.signal, nil) } } diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/internal/commandinfo_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/internal/commandinfo_test.go deleted file mode 100644 index 118e94b6731..00000000000 --- a/Godeps/_workspace/src/github.com/garyburd/redigo/internal/commandinfo_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package internal - -import "testing" - -func TestLookupCommandInfo(t *testing.T) { - for _, n := range []string{"watch", "WATCH", "wAtch"} { - if LookupCommandInfo(n) == (CommandInfo{}) { - t.Errorf("LookupCommandInfo(%q) = CommandInfo{}, expected non-zero value", n) - } - } -} - -func benchmarkLookupCommandInfo(b *testing.B, names ...string) { - for i := 0; i < b.N; i++ { - for _, c := range names { - LookupCommandInfo(c) - } - } -} - -func BenchmarkLookupCommandInfoCorrectCase(b *testing.B) { - benchmarkLookupCommandInfo(b, "watch", "WATCH", "monitor", "MONITOR") -} - -func BenchmarkLookupCommandInfoMixedCase(b *testing.B) { - benchmarkLookupCommandInfo(b, "wAtch", "WeTCH", "monItor", "MONiTOR") -} diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/conn_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/conn_test.go deleted file mode 100644 index 24887cf0337..00000000000 --- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/conn_test.go +++ /dev/null @@ -1,659 +0,0 @@ -// Copyright 2012 Gary Burd -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package redis_test - -import ( - "bytes" - "io" - "math" - "net" - "os" - "reflect" - "strings" - "testing" - "time" - - "github.com/garyburd/redigo/redis" -) - -type testConn struct { - io.Reader - io.Writer -} - -func (*testConn) Close() error { return nil } -func (*testConn) LocalAddr() net.Addr { return nil } -func (*testConn) RemoteAddr() net.Addr { return nil } -func (*testConn) SetDeadline(t time.Time) error { return nil } -func (*testConn) SetReadDeadline(t time.Time) error { return nil } -func (*testConn) SetWriteDeadline(t time.Time) error { return nil } - -func dialTestConn(r io.Reader, w io.Writer) redis.DialOption { - return redis.DialNetDial(func(net, addr string) (net.Conn, error) { - return &testConn{Reader: r, Writer: w}, nil - }) -} - -var writeTests = []struct { - args []interface{} - expected string -}{ - { - []interface{}{"SET", "key", "value"}, - "*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$5\r\nvalue\r\n", - }, - { - []interface{}{"SET", "key", "value"}, - "*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$5\r\nvalue\r\n", - }, - { - []interface{}{"SET", "key", byte(100)}, - "*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$3\r\n100\r\n", - }, - { - []interface{}{"SET", "key", 100}, - "*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$3\r\n100\r\n", - }, - { - []interface{}{"SET", "key", int64(math.MinInt64)}, - "*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$20\r\n-9223372036854775808\r\n", - }, - { - []interface{}{"SET", "key", float64(1349673917.939762)}, - "*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$21\r\n1.349673917939762e+09\r\n", - }, - { - []interface{}{"SET", "key", ""}, - "*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$0\r\n\r\n", - }, - { - []interface{}{"SET", "key", nil}, - "*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$0\r\n\r\n", - }, - { - []interface{}{"ECHO", true, false}, - "*3\r\n$4\r\nECHO\r\n$1\r\n1\r\n$1\r\n0\r\n", - }, -} - -func TestWrite(t *testing.T) { - for _, tt := range writeTests { - var buf bytes.Buffer - c, _ := redis.Dial("", "", dialTestConn(nil, &buf)) - err := c.Send(tt.args[0].(string), tt.args[1:]...) - if err != nil { - t.Errorf("Send(%v) returned error %v", tt.args, err) - continue - } - c.Flush() - actual := buf.String() - if actual != tt.expected { - t.Errorf("Send(%v) = %q, want %q", tt.args, actual, tt.expected) - } - } -} - -var errorSentinel = &struct{}{} - -var readTests = []struct { - reply string - expected interface{} -}{ - { - "+OK\r\n", - "OK", - }, - { - "+PONG\r\n", - "PONG", - }, - { - "@OK\r\n", - errorSentinel, - }, - { - "$6\r\nfoobar\r\n", - []byte("foobar"), - }, - { - "$-1\r\n", - nil, - }, - { - ":1\r\n", - int64(1), - }, - { - ":-2\r\n", - int64(-2), - }, - { - "*0\r\n", - []interface{}{}, - }, - { - "*-1\r\n", - nil, - }, - { - "*4\r\n$3\r\nfoo\r\n$3\r\nbar\r\n$5\r\nHello\r\n$5\r\nWorld\r\n", - []interface{}{[]byte("foo"), []byte("bar"), []byte("Hello"), []byte("World")}, - }, - { - "*3\r\n$3\r\nfoo\r\n$-1\r\n$3\r\nbar\r\n", - []interface{}{[]byte("foo"), nil, []byte("bar")}, - }, - - { - // "x" is not a valid length - "$x\r\nfoobar\r\n", - errorSentinel, - }, - { - // -2 is not a valid length - "$-2\r\n", - errorSentinel, - }, - { - // "x" is not a valid integer - ":x\r\n", - errorSentinel, - }, - { - // missing \r\n following value - "$6\r\nfoobar", - errorSentinel, - }, - { - // short value - "$6\r\nxx", - errorSentinel, - }, - { - // long value - "$6\r\nfoobarx\r\n", - errorSentinel, - }, -} - -func TestRead(t *testing.T) { - for _, tt := range readTests { - c, _ := redis.Dial("", "", dialTestConn(strings.NewReader(tt.reply), nil)) - actual, err := c.Receive() - if tt.expected == errorSentinel { - if err == nil { - t.Errorf("Receive(%q) did not return expected error", tt.reply) - } - } else { - if err != nil { - t.Errorf("Receive(%q) returned error %v", tt.reply, err) - continue - } - if !reflect.DeepEqual(actual, tt.expected) { - t.Errorf("Receive(%q) = %v, want %v", tt.reply, actual, tt.expected) - } - } - } -} - -var testCommands = []struct { - args []interface{} - expected interface{} -}{ - { - []interface{}{"PING"}, - "PONG", - }, - { - []interface{}{"SET", "foo", "bar"}, - "OK", - }, - { - []interface{}{"GET", "foo"}, - []byte("bar"), - }, - { - []interface{}{"GET", "nokey"}, - nil, - }, - { - []interface{}{"MGET", "nokey", "foo"}, - []interface{}{nil, []byte("bar")}, - }, - { - []interface{}{"INCR", "mycounter"}, - int64(1), - }, - { - []interface{}{"LPUSH", "mylist", "foo"}, - int64(1), - }, - { - []interface{}{"LPUSH", "mylist", "bar"}, - int64(2), - }, - { - []interface{}{"LRANGE", "mylist", 0, -1}, - []interface{}{[]byte("bar"), []byte("foo")}, - }, - { - []interface{}{"MULTI"}, - "OK", - }, - { - []interface{}{"LRANGE", "mylist", 0, -1}, - "QUEUED", - }, - { - []interface{}{"PING"}, - "QUEUED", - }, - { - []interface{}{"EXEC"}, - []interface{}{ - []interface{}{[]byte("bar"), []byte("foo")}, - "PONG", - }, - }, -} - -func TestDoCommands(t *testing.T) { - c, err := redis.DialDefaultServer() - if err != nil { - t.Fatalf("error connection to database, %v", err) - } - defer c.Close() - - for _, cmd := range testCommands { - actual, err := c.Do(cmd.args[0].(string), cmd.args[1:]...) - if err != nil { - t.Errorf("Do(%v) returned error %v", cmd.args, err) - continue - } - if !reflect.DeepEqual(actual, cmd.expected) { - t.Errorf("Do(%v) = %v, want %v", cmd.args, actual, cmd.expected) - } - } -} - -func TestPipelineCommands(t *testing.T) { - c, err := redis.DialDefaultServer() - if err != nil { - t.Fatalf("error connection to database, %v", err) - } - defer c.Close() - - for _, cmd := range testCommands { - if err := c.Send(cmd.args[0].(string), cmd.args[1:]...); err != nil { - t.Fatalf("Send(%v) returned error %v", cmd.args, err) - } - } - if err := c.Flush(); err != nil { - t.Errorf("Flush() returned error %v", err) - } - for _, cmd := range testCommands { - actual, err := c.Receive() - if err != nil { - t.Fatalf("Receive(%v) returned error %v", cmd.args, err) - } - if !reflect.DeepEqual(actual, cmd.expected) { - t.Errorf("Receive(%v) = %v, want %v", cmd.args, actual, cmd.expected) - } - } -} - -func TestBlankCommmand(t *testing.T) { - c, err := redis.DialDefaultServer() - if err != nil { - t.Fatalf("error connection to database, %v", err) - } - defer c.Close() - - for _, cmd := range testCommands { - if err := c.Send(cmd.args[0].(string), cmd.args[1:]...); err != nil { - t.Fatalf("Send(%v) returned error %v", cmd.args, err) - } - } - reply, err := redis.Values(c.Do("")) - if err != nil { - t.Fatalf("Do() returned error %v", err) - } - if len(reply) != len(testCommands) { - t.Fatalf("len(reply)=%d, want %d", len(reply), len(testCommands)) - } - for i, cmd := range testCommands { - actual := reply[i] - if !reflect.DeepEqual(actual, cmd.expected) { - t.Errorf("Receive(%v) = %v, want %v", cmd.args, actual, cmd.expected) - } - } -} - -func TestRecvBeforeSend(t *testing.T) { - c, err := redis.DialDefaultServer() - if err != nil { - t.Fatalf("error connection to database, %v", err) - } - defer c.Close() - done := make(chan struct{}) - go func() { - c.Receive() - close(done) - }() - time.Sleep(time.Millisecond) - c.Send("PING") - c.Flush() - <-done - _, err = c.Do("") - if err != nil { - t.Fatalf("error=%v", err) - } -} - -func TestError(t *testing.T) { - c, err := redis.DialDefaultServer() - if err != nil { - t.Fatalf("error connection to database, %v", err) - } - defer c.Close() - - c.Do("SET", "key", "val") - _, err = c.Do("HSET", "key", "fld", "val") - if err == nil { - t.Errorf("Expected err for HSET on string key.") - } - if c.Err() != nil { - t.Errorf("Conn has Err()=%v, expect nil", c.Err()) - } - _, err = c.Do("SET", "key", "val") - if err != nil { - t.Errorf("Do(SET, key, val) returned error %v, expected nil.", err) - } -} - -func TestReadTimeout(t *testing.T) { - l, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("net.Listen returned %v", err) - } - defer l.Close() - - go func() { - for { - c, err := l.Accept() - if err != nil { - return - } - go func() { - time.Sleep(time.Second) - c.Write([]byte("+OK\r\n")) - c.Close() - }() - } - }() - - // Do - - c1, err := redis.Dial(l.Addr().Network(), l.Addr().String(), redis.DialReadTimeout(time.Millisecond)) - if err != nil { - t.Fatalf("redis.Dial returned %v", err) - } - defer c1.Close() - - _, err = c1.Do("PING") - if err == nil { - t.Fatalf("c1.Do() returned nil, expect error") - } - if c1.Err() == nil { - t.Fatalf("c1.Err() = nil, expect error") - } - - // Send/Flush/Receive - - c2, err := redis.Dial(l.Addr().Network(), l.Addr().String(), redis.DialReadTimeout(time.Millisecond)) - if err != nil { - t.Fatalf("redis.Dial returned %v", err) - } - defer c2.Close() - - c2.Send("PING") - c2.Flush() - _, err = c2.Receive() - if err == nil { - t.Fatalf("c2.Receive() returned nil, expect error") - } - if c2.Err() == nil { - t.Fatalf("c2.Err() = nil, expect error") - } -} - -var dialErrors = []struct { - rawurl string - expectedError string -}{ - { - "localhost", - "invalid redis URL scheme", - }, - // The error message for invalid hosts is diffferent in different - // versions of Go, so just check that there is an error message. - { - "redis://weird url", - "", - }, - { - "redis://foo:bar:baz", - "", - }, - { - "http://www.google.com", - "invalid redis URL scheme: http", - }, - { - "redis://localhost:6379/abc123", - "invalid database: abc123", - }, -} - -func TestDialURLErrors(t *testing.T) { - for _, d := range dialErrors { - _, err := redis.DialURL(d.rawurl) - if err == nil || !strings.Contains(err.Error(), d.expectedError) { - t.Errorf("DialURL did not return expected error (expected %v to contain %s)", err, d.expectedError) - } - } -} - -func TestDialURLPort(t *testing.T) { - checkPort := func(network, address string) (net.Conn, error) { - if address != "localhost:6379" { - t.Errorf("DialURL did not set port to 6379 by default (got %v)", address) - } - return nil, nil - } - _, err := redis.DialURL("redis://localhost", redis.DialNetDial(checkPort)) - if err != nil { - t.Error("dial error:", err) - } -} - -func TestDialURLHost(t *testing.T) { - checkHost := func(network, address string) (net.Conn, error) { - if address != "localhost:6379" { - t.Errorf("DialURL did not set host to localhost by default (got %v)", address) - } - return nil, nil - } - _, err := redis.DialURL("redis://:6379", redis.DialNetDial(checkHost)) - if err != nil { - t.Error("dial error:", err) - } -} - -func TestDialURLPassword(t *testing.T) { - var buf bytes.Buffer - _, err := redis.DialURL("redis://x:abc123@localhost", dialTestConn(strings.NewReader("+OK\r\n"), &buf)) - if err != nil { - t.Error("dial error:", err) - } - expected := "*2\r\n$4\r\nAUTH\r\n$6\r\nabc123\r\n" - actual := buf.String() - if actual != expected { - t.Errorf("commands = %q, want %q", actual, expected) - } -} - -func TestDialURLDatabase(t *testing.T) { - var buf bytes.Buffer - _, err := redis.DialURL("redis://localhost/3", dialTestConn(strings.NewReader("+OK\r\n"), &buf)) - if err != nil { - t.Error("dial error:", err) - } - expected := "*2\r\n$6\r\nSELECT\r\n$1\r\n3\r\n" - actual := buf.String() - if actual != expected { - t.Errorf("commands = %q, want %q", actual, expected) - } -} - -// Connect to local instance of Redis running on the default port. -func ExampleDial(x int) { - c, err := redis.Dial("tcp", ":6379") - if err != nil { - // handle error - } - defer c.Close() -} - -// Connect to remote instance of Redis using a URL. -func ExampleDialURL() { - c, err := redis.DialURL(os.Getenv("REDIS_URL")) - if err != nil { - // handle connection error - } - defer c.Close() -} - -// TextExecError tests handling of errors in a transaction. See -// http://redis.io/topics/transactions for information on how Redis handles -// errors in a transaction. -func TestExecError(t *testing.T) { - c, err := redis.DialDefaultServer() - if err != nil { - t.Fatalf("error connection to database, %v", err) - } - defer c.Close() - - // Execute commands that fail before EXEC is called. - - c.Do("DEL", "k0") - c.Do("ZADD", "k0", 0, 0) - c.Send("MULTI") - c.Send("NOTACOMMAND", "k0", 0, 0) - c.Send("ZINCRBY", "k0", 0, 0) - v, err := c.Do("EXEC") - if err == nil { - t.Fatalf("EXEC returned values %v, expected error", v) - } - - // Execute commands that fail after EXEC is called. The first command - // returns an error. - - c.Do("DEL", "k1") - c.Do("ZADD", "k1", 0, 0) - c.Send("MULTI") - c.Send("HSET", "k1", 0, 0) - c.Send("ZINCRBY", "k1", 0, 0) - v, err = c.Do("EXEC") - if err != nil { - t.Fatalf("EXEC returned error %v", err) - } - - vs, err := redis.Values(v, nil) - if err != nil { - t.Fatalf("Values(v) returned error %v", err) - } - - if len(vs) != 2 { - t.Fatalf("len(vs) == %d, want 2", len(vs)) - } - - if _, ok := vs[0].(error); !ok { - t.Fatalf("first result is type %T, expected error", vs[0]) - } - - if _, ok := vs[1].([]byte); !ok { - t.Fatalf("second result is type %T, expected []byte", vs[1]) - } - - // Execute commands that fail after EXEC is called. The second command - // returns an error. - - c.Do("ZADD", "k2", 0, 0) - c.Send("MULTI") - c.Send("ZINCRBY", "k2", 0, 0) - c.Send("HSET", "k2", 0, 0) - v, err = c.Do("EXEC") - if err != nil { - t.Fatalf("EXEC returned error %v", err) - } - - vs, err = redis.Values(v, nil) - if err != nil { - t.Fatalf("Values(v) returned error %v", err) - } - - if len(vs) != 2 { - t.Fatalf("len(vs) == %d, want 2", len(vs)) - } - - if _, ok := vs[0].([]byte); !ok { - t.Fatalf("first result is type %T, expected []byte", vs[0]) - } - - if _, ok := vs[1].(error); !ok { - t.Fatalf("second result is type %T, expected error", vs[2]) - } -} - -func BenchmarkDoEmpty(b *testing.B) { - b.StopTimer() - c, err := redis.DialDefaultServer() - if err != nil { - b.Fatal(err) - } - defer c.Close() - b.StartTimer() - for i := 0; i < b.N; i++ { - if _, err := c.Do(""); err != nil { - b.Fatal(err) - } - } -} - -func BenchmarkDoPing(b *testing.B) { - b.StopTimer() - c, err := redis.DialDefaultServer() - if err != nil { - b.Fatal(err) - } - defer c.Close() - b.StartTimer() - for i := 0; i < b.N; i++ { - if _, err := c.Do("PING"); err != nil { - b.Fatal(err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pool_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pool_test.go deleted file mode 100644 index 9419a128ff4..00000000000 --- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pool_test.go +++ /dev/null @@ -1,684 +0,0 @@ -// Copyright 2011 Gary Burd -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package redis_test - -import ( - "errors" - "io" - "reflect" - "sync" - "testing" - "time" - - "github.com/garyburd/redigo/redis" -) - -type poolTestConn struct { - d *poolDialer - err error - redis.Conn -} - -func (c *poolTestConn) Close() error { - c.d.mu.Lock() - c.d.open -= 1 - c.d.mu.Unlock() - return c.Conn.Close() -} - -func (c *poolTestConn) Err() error { return c.err } - -func (c *poolTestConn) Do(commandName string, args ...interface{}) (interface{}, error) { - if commandName == "ERR" { - c.err = args[0].(error) - commandName = "PING" - } - if commandName != "" { - c.d.commands = append(c.d.commands, commandName) - } - return c.Conn.Do(commandName, args...) -} - -func (c *poolTestConn) Send(commandName string, args ...interface{}) error { - c.d.commands = append(c.d.commands, commandName) - return c.Conn.Send(commandName, args...) -} - -type poolDialer struct { - mu sync.Mutex - t *testing.T - dialed int - open int - commands []string - dialErr error -} - -func (d *poolDialer) dial() (redis.Conn, error) { - d.mu.Lock() - d.dialed += 1 - dialErr := d.dialErr - d.mu.Unlock() - if dialErr != nil { - return nil, d.dialErr - } - c, err := redis.DialDefaultServer() - if err != nil { - return nil, err - } - d.mu.Lock() - d.open += 1 - d.mu.Unlock() - return &poolTestConn{d: d, Conn: c}, nil -} - -func (d *poolDialer) check(message string, p *redis.Pool, dialed, open int) { - d.mu.Lock() - if d.dialed != dialed { - d.t.Errorf("%s: dialed=%d, want %d", message, d.dialed, dialed) - } - if d.open != open { - d.t.Errorf("%s: open=%d, want %d", message, d.open, open) - } - if active := p.ActiveCount(); active != open { - d.t.Errorf("%s: active=%d, want %d", message, active, open) - } - d.mu.Unlock() -} - -func TestPoolReuse(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 2, - Dial: d.dial, - } - - for i := 0; i < 10; i++ { - c1 := p.Get() - c1.Do("PING") - c2 := p.Get() - c2.Do("PING") - c1.Close() - c2.Close() - } - - d.check("before close", p, 2, 2) - p.Close() - d.check("after close", p, 2, 0) -} - -func TestPoolMaxIdle(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 2, - Dial: d.dial, - } - defer p.Close() - - for i := 0; i < 10; i++ { - c1 := p.Get() - c1.Do("PING") - c2 := p.Get() - c2.Do("PING") - c3 := p.Get() - c3.Do("PING") - c1.Close() - c2.Close() - c3.Close() - } - d.check("before close", p, 12, 2) - p.Close() - d.check("after close", p, 12, 0) -} - -func TestPoolError(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 2, - Dial: d.dial, - } - defer p.Close() - - c := p.Get() - c.Do("ERR", io.EOF) - if c.Err() == nil { - t.Errorf("expected c.Err() != nil") - } - c.Close() - - c = p.Get() - c.Do("ERR", io.EOF) - c.Close() - - d.check(".", p, 2, 0) -} - -func TestPoolClose(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 2, - Dial: d.dial, - } - defer p.Close() - - c1 := p.Get() - c1.Do("PING") - c2 := p.Get() - c2.Do("PING") - c3 := p.Get() - c3.Do("PING") - - c1.Close() - if _, err := c1.Do("PING"); err == nil { - t.Errorf("expected error after connection closed") - } - - c2.Close() - c2.Close() - - p.Close() - - d.check("after pool close", p, 3, 1) - - if _, err := c1.Do("PING"); err == nil { - t.Errorf("expected error after connection and pool closed") - } - - c3.Close() - - d.check("after conn close", p, 3, 0) - - c1 = p.Get() - if _, err := c1.Do("PING"); err == nil { - t.Errorf("expected error after pool closed") - } -} - -func TestPoolTimeout(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 2, - IdleTimeout: 300 * time.Second, - Dial: d.dial, - } - defer p.Close() - - now := time.Now() - redis.SetNowFunc(func() time.Time { return now }) - defer redis.SetNowFunc(time.Now) - - c := p.Get() - c.Do("PING") - c.Close() - - d.check("1", p, 1, 1) - - now = now.Add(p.IdleTimeout) - - c = p.Get() - c.Do("PING") - c.Close() - - d.check("2", p, 2, 1) -} - -func TestPoolConcurrenSendReceive(t *testing.T) { - p := &redis.Pool{ - Dial: redis.DialDefaultServer, - } - defer p.Close() - - c := p.Get() - done := make(chan error, 1) - go func() { - _, err := c.Receive() - done <- err - }() - c.Send("PING") - c.Flush() - err := <-done - if err != nil { - t.Fatalf("Receive() returned error %v", err) - } - _, err = c.Do("") - if err != nil { - t.Fatalf("Do() returned error %v", err) - } - c.Close() -} - -func TestPoolBorrowCheck(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 2, - Dial: d.dial, - TestOnBorrow: func(redis.Conn, time.Time) error { return redis.Error("BLAH") }, - } - defer p.Close() - - for i := 0; i < 10; i++ { - c := p.Get() - c.Do("PING") - c.Close() - } - d.check("1", p, 10, 1) -} - -func TestPoolMaxActive(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 2, - MaxActive: 2, - Dial: d.dial, - } - defer p.Close() - - c1 := p.Get() - c1.Do("PING") - c2 := p.Get() - c2.Do("PING") - - d.check("1", p, 2, 2) - - c3 := p.Get() - if _, err := c3.Do("PING"); err != redis.ErrPoolExhausted { - t.Errorf("expected pool exhausted") - } - - c3.Close() - d.check("2", p, 2, 2) - c2.Close() - d.check("3", p, 2, 2) - - c3 = p.Get() - if _, err := c3.Do("PING"); err != nil { - t.Errorf("expected good channel, err=%v", err) - } - c3.Close() - - d.check("4", p, 2, 2) -} - -func TestPoolMonitorCleanup(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 2, - MaxActive: 2, - Dial: d.dial, - } - defer p.Close() - - c := p.Get() - c.Send("MONITOR") - c.Close() - - d.check("", p, 1, 0) -} - -func TestPoolPubSubCleanup(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 2, - MaxActive: 2, - Dial: d.dial, - } - defer p.Close() - - c := p.Get() - c.Send("SUBSCRIBE", "x") - c.Close() - - want := []string{"SUBSCRIBE", "UNSUBSCRIBE", "PUNSUBSCRIBE", "ECHO"} - if !reflect.DeepEqual(d.commands, want) { - t.Errorf("got commands %v, want %v", d.commands, want) - } - d.commands = nil - - c = p.Get() - c.Send("PSUBSCRIBE", "x*") - c.Close() - - want = []string{"PSUBSCRIBE", "UNSUBSCRIBE", "PUNSUBSCRIBE", "ECHO"} - if !reflect.DeepEqual(d.commands, want) { - t.Errorf("got commands %v, want %v", d.commands, want) - } - d.commands = nil -} - -func TestPoolTransactionCleanup(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 2, - MaxActive: 2, - Dial: d.dial, - } - defer p.Close() - - c := p.Get() - c.Do("WATCH", "key") - c.Do("PING") - c.Close() - - want := []string{"WATCH", "PING", "UNWATCH"} - if !reflect.DeepEqual(d.commands, want) { - t.Errorf("got commands %v, want %v", d.commands, want) - } - d.commands = nil - - c = p.Get() - c.Do("WATCH", "key") - c.Do("UNWATCH") - c.Do("PING") - c.Close() - - want = []string{"WATCH", "UNWATCH", "PING"} - if !reflect.DeepEqual(d.commands, want) { - t.Errorf("got commands %v, want %v", d.commands, want) - } - d.commands = nil - - c = p.Get() - c.Do("WATCH", "key") - c.Do("MULTI") - c.Do("PING") - c.Close() - - want = []string{"WATCH", "MULTI", "PING", "DISCARD"} - if !reflect.DeepEqual(d.commands, want) { - t.Errorf("got commands %v, want %v", d.commands, want) - } - d.commands = nil - - c = p.Get() - c.Do("WATCH", "key") - c.Do("MULTI") - c.Do("DISCARD") - c.Do("PING") - c.Close() - - want = []string{"WATCH", "MULTI", "DISCARD", "PING"} - if !reflect.DeepEqual(d.commands, want) { - t.Errorf("got commands %v, want %v", d.commands, want) - } - d.commands = nil - - c = p.Get() - c.Do("WATCH", "key") - c.Do("MULTI") - c.Do("EXEC") - c.Do("PING") - c.Close() - - want = []string{"WATCH", "MULTI", "EXEC", "PING"} - if !reflect.DeepEqual(d.commands, want) { - t.Errorf("got commands %v, want %v", d.commands, want) - } - d.commands = nil -} - -func startGoroutines(p *redis.Pool, cmd string, args ...interface{}) chan error { - errs := make(chan error, 10) - for i := 0; i < cap(errs); i++ { - go func() { - c := p.Get() - _, err := c.Do(cmd, args...) - errs <- err - c.Close() - }() - } - - // Wait for goroutines to block. - time.Sleep(time.Second / 4) - - return errs -} - -func TestWaitPool(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 1, - MaxActive: 1, - Dial: d.dial, - Wait: true, - } - defer p.Close() - - c := p.Get() - errs := startGoroutines(p, "PING") - d.check("before close", p, 1, 1) - c.Close() - timeout := time.After(2 * time.Second) - for i := 0; i < cap(errs); i++ { - select { - case err := <-errs: - if err != nil { - t.Fatal(err) - } - case <-timeout: - t.Fatalf("timeout waiting for blocked goroutine %d", i) - } - } - d.check("done", p, 1, 1) -} - -func TestWaitPoolClose(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 1, - MaxActive: 1, - Dial: d.dial, - Wait: true, - } - defer p.Close() - - c := p.Get() - if _, err := c.Do("PING"); err != nil { - t.Fatal(err) - } - errs := startGoroutines(p, "PING") - d.check("before close", p, 1, 1) - p.Close() - timeout := time.After(2 * time.Second) - for i := 0; i < cap(errs); i++ { - select { - case err := <-errs: - switch err { - case nil: - t.Fatal("blocked goroutine did not get error") - case redis.ErrPoolExhausted: - t.Fatal("blocked goroutine got pool exhausted error") - } - case <-timeout: - t.Fatal("timeout waiting for blocked goroutine") - } - } - c.Close() - d.check("done", p, 1, 0) -} - -func TestWaitPoolCommandError(t *testing.T) { - testErr := errors.New("test") - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 1, - MaxActive: 1, - Dial: d.dial, - Wait: true, - } - defer p.Close() - - c := p.Get() - errs := startGoroutines(p, "ERR", testErr) - d.check("before close", p, 1, 1) - c.Close() - timeout := time.After(2 * time.Second) - for i := 0; i < cap(errs); i++ { - select { - case err := <-errs: - if err != nil { - t.Fatal(err) - } - case <-timeout: - t.Fatalf("timeout waiting for blocked goroutine %d", i) - } - } - d.check("done", p, cap(errs), 0) -} - -func TestWaitPoolDialError(t *testing.T) { - testErr := errors.New("test") - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 1, - MaxActive: 1, - Dial: d.dial, - Wait: true, - } - defer p.Close() - - c := p.Get() - errs := startGoroutines(p, "ERR", testErr) - d.check("before close", p, 1, 1) - - d.dialErr = errors.New("dial") - c.Close() - - nilCount := 0 - errCount := 0 - timeout := time.After(2 * time.Second) - for i := 0; i < cap(errs); i++ { - select { - case err := <-errs: - switch err { - case nil: - nilCount++ - case d.dialErr: - errCount++ - default: - t.Fatalf("expected dial error or nil, got %v", err) - } - case <-timeout: - t.Fatalf("timeout waiting for blocked goroutine %d", i) - } - } - if nilCount != 1 { - t.Errorf("expected one nil error, got %d", nilCount) - } - if errCount != cap(errs)-1 { - t.Errorf("expected %d dial erors, got %d", cap(errs)-1, errCount) - } - d.check("done", p, cap(errs), 0) -} - -// Borrowing requires us to iterate over the idle connections, unlock the pool, -// and perform a blocking operation to check the connection still works. If -// TestOnBorrow fails, we must reacquire the lock and continue iteration. This -// test ensures that iteration will work correctly if multiple threads are -// iterating simultaneously. -func TestLocking_TestOnBorrowFails_PoolDoesntCrash(t *testing.T) { - const count = 100 - - // First we'll Create a pool where the pilfering of idle connections fails. - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: count, - MaxActive: count, - Dial: d.dial, - TestOnBorrow: func(c redis.Conn, t time.Time) error { - return errors.New("No way back into the real world.") - }, - } - defer p.Close() - - // Fill the pool with idle connections. - conns := make([]redis.Conn, count) - for i := range conns { - conns[i] = p.Get() - } - for i := range conns { - conns[i].Close() - } - - // Spawn a bunch of goroutines to thrash the pool. - var wg sync.WaitGroup - wg.Add(count) - for i := 0; i < count; i++ { - go func() { - c := p.Get() - if c.Err() != nil { - t.Errorf("pool get failed: %v", c.Err()) - } - c.Close() - wg.Done() - }() - } - wg.Wait() - if d.dialed != count*2 { - t.Errorf("Expected %d dials, got %d", count*2, d.dialed) - } -} - -func BenchmarkPoolGet(b *testing.B) { - b.StopTimer() - p := redis.Pool{Dial: redis.DialDefaultServer, MaxIdle: 2} - c := p.Get() - if err := c.Err(); err != nil { - b.Fatal(err) - } - c.Close() - defer p.Close() - b.StartTimer() - for i := 0; i < b.N; i++ { - c = p.Get() - c.Close() - } -} - -func BenchmarkPoolGetErr(b *testing.B) { - b.StopTimer() - p := redis.Pool{Dial: redis.DialDefaultServer, MaxIdle: 2} - c := p.Get() - if err := c.Err(); err != nil { - b.Fatal(err) - } - c.Close() - defer p.Close() - b.StartTimer() - for i := 0; i < b.N; i++ { - c = p.Get() - if err := c.Err(); err != nil { - b.Fatal(err) - } - c.Close() - } -} - -func BenchmarkPoolGetPing(b *testing.B) { - b.StopTimer() - p := redis.Pool{Dial: redis.DialDefaultServer, MaxIdle: 2} - c := p.Get() - if err := c.Err(); err != nil { - b.Fatal(err) - } - c.Close() - defer p.Close() - b.StartTimer() - for i := 0; i < b.N; i++ { - c = p.Get() - if _, err := c.Do("PING"); err != nil { - b.Fatal(err) - } - c.Close() - } -} diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pubsub_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pubsub_test.go deleted file mode 100644 index a3ed84e682d..00000000000 --- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pubsub_test.go +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright 2012 Gary Burd -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package redis_test - -import ( - "fmt" - "reflect" - "sync" - "testing" - - "github.com/garyburd/redigo/redis" -) - -func publish(channel, value interface{}) { - c, err := dial() - if err != nil { - fmt.Println(err) - return - } - defer c.Close() - c.Do("PUBLISH", channel, value) -} - -// Applications can receive pushed messages from one goroutine and manage subscriptions from another goroutine. -func ExamplePubSubConn() { - c, err := dial() - if err != nil { - fmt.Println(err) - return - } - defer c.Close() - var wg sync.WaitGroup - wg.Add(2) - - psc := redis.PubSubConn{Conn: c} - - // This goroutine receives and prints pushed notifications from the server. - // The goroutine exits when the connection is unsubscribed from all - // channels or there is an error. - go func() { - defer wg.Done() - for { - switch n := psc.Receive().(type) { - case redis.Message: - fmt.Printf("Message: %s %s\n", n.Channel, n.Data) - case redis.PMessage: - fmt.Printf("PMessage: %s %s %s\n", n.Pattern, n.Channel, n.Data) - case redis.Subscription: - fmt.Printf("Subscription: %s %s %d\n", n.Kind, n.Channel, n.Count) - if n.Count == 0 { - return - } - case error: - fmt.Printf("error: %v\n", n) - return - } - } - }() - - // This goroutine manages subscriptions for the connection. - go func() { - defer wg.Done() - - psc.Subscribe("example") - psc.PSubscribe("p*") - - // The following function calls publish a message using another - // connection to the Redis server. - publish("example", "hello") - publish("example", "world") - publish("pexample", "foo") - publish("pexample", "bar") - - // Unsubscribe from all connections. This will cause the receiving - // goroutine to exit. - psc.Unsubscribe() - psc.PUnsubscribe() - }() - - wg.Wait() - - // Output: - // Subscription: subscribe example 1 - // Subscription: psubscribe p* 2 - // Message: example hello - // Message: example world - // PMessage: p* pexample foo - // PMessage: p* pexample bar - // Subscription: unsubscribe example 1 - // Subscription: punsubscribe p* 0 -} - -func expectPushed(t *testing.T, c redis.PubSubConn, message string, expected interface{}) { - actual := c.Receive() - if !reflect.DeepEqual(actual, expected) { - t.Errorf("%s = %v, want %v", message, actual, expected) - } -} - -func TestPushed(t *testing.T) { - pc, err := redis.DialDefaultServer() - if err != nil { - t.Fatalf("error connection to database, %v", err) - } - defer pc.Close() - - sc, err := redis.DialDefaultServer() - if err != nil { - t.Fatalf("error connection to database, %v", err) - } - defer sc.Close() - - c := redis.PubSubConn{Conn: sc} - - c.Subscribe("c1") - expectPushed(t, c, "Subscribe(c1)", redis.Subscription{Kind: "subscribe", Channel: "c1", Count: 1}) - c.Subscribe("c2") - expectPushed(t, c, "Subscribe(c2)", redis.Subscription{Kind: "subscribe", Channel: "c2", Count: 2}) - c.PSubscribe("p1") - expectPushed(t, c, "PSubscribe(p1)", redis.Subscription{Kind: "psubscribe", Channel: "p1", Count: 3}) - c.PSubscribe("p2") - expectPushed(t, c, "PSubscribe(p2)", redis.Subscription{Kind: "psubscribe", Channel: "p2", Count: 4}) - c.PUnsubscribe() - expectPushed(t, c, "Punsubscribe(p1)", redis.Subscription{Kind: "punsubscribe", Channel: "p1", Count: 3}) - expectPushed(t, c, "Punsubscribe()", redis.Subscription{Kind: "punsubscribe", Channel: "p2", Count: 2}) - - pc.Do("PUBLISH", "c1", "hello") - expectPushed(t, c, "PUBLISH c1 hello", redis.Message{Channel: "c1", Data: []byte("hello")}) - - c.Ping("hello") - expectPushed(t, c, `Ping("hello")`, redis.Pong{"hello"}) - - c.Conn.Send("PING") - c.Conn.Flush() - expectPushed(t, c, `Send("PING")`, redis.Pong{}) -} diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/reply_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/reply_test.go deleted file mode 100644 index 84365bcbbd6..00000000000 --- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/reply_test.go +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright 2012 Gary Burd -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package redis_test - -import ( - "fmt" - "reflect" - "testing" - - "github.com/garyburd/redigo/redis" -) - -type valueError struct { - v interface{} - err error -} - -func ve(v interface{}, err error) valueError { - return valueError{v, err} -} - -var replyTests = []struct { - name interface{} - actual valueError - expected valueError -}{ - { - "ints([v1, v2])", - ve(redis.Ints([]interface{}{[]byte("4"), []byte("5")}, nil)), - ve([]int{4, 5}, nil), - }, - { - "ints(nil)", - ve(redis.Ints(nil, nil)), - ve([]int(nil), redis.ErrNil), - }, - { - "strings([v1, v2])", - ve(redis.Strings([]interface{}{[]byte("v1"), []byte("v2")}, nil)), - ve([]string{"v1", "v2"}, nil), - }, - { - "strings(nil)", - ve(redis.Strings(nil, nil)), - ve([]string(nil), redis.ErrNil), - }, - { - "values([v1, v2])", - ve(redis.Values([]interface{}{[]byte("v1"), []byte("v2")}, nil)), - ve([]interface{}{[]byte("v1"), []byte("v2")}, nil), - }, - { - "values(nil)", - ve(redis.Values(nil, nil)), - ve([]interface{}(nil), redis.ErrNil), - }, - { - "float64(1.0)", - ve(redis.Float64([]byte("1.0"), nil)), - ve(float64(1.0), nil), - }, - { - "float64(nil)", - ve(redis.Float64(nil, nil)), - ve(float64(0.0), redis.ErrNil), - }, - { - "uint64(1)", - ve(redis.Uint64(int64(1), nil)), - ve(uint64(1), nil), - }, - { - "uint64(-1)", - ve(redis.Uint64(int64(-1), nil)), - ve(uint64(0), redis.ErrNegativeInt), - }, -} - -func TestReply(t *testing.T) { - for _, rt := range replyTests { - if rt.actual.err != rt.expected.err { - t.Errorf("%s returned err %v, want %v", rt.name, rt.actual.err, rt.expected.err) - continue - } - if !reflect.DeepEqual(rt.actual.v, rt.expected.v) { - t.Errorf("%s=%+v, want %+v", rt.name, rt.actual.v, rt.expected.v) - } - } -} - -// dial wraps DialDefaultServer() with a more suitable function name for examples. -func dial() (redis.Conn, error) { - return redis.DialDefaultServer() -} - -func ExampleBool() { - c, err := dial() - if err != nil { - fmt.Println(err) - return - } - defer c.Close() - - c.Do("SET", "foo", 1) - exists, _ := redis.Bool(c.Do("EXISTS", "foo")) - fmt.Printf("%#v\n", exists) - // Output: - // true -} - -func ExampleInt() { - c, err := dial() - if err != nil { - fmt.Println(err) - return - } - defer c.Close() - - c.Do("SET", "k1", 1) - n, _ := redis.Int(c.Do("GET", "k1")) - fmt.Printf("%#v\n", n) - n, _ = redis.Int(c.Do("INCR", "k1")) - fmt.Printf("%#v\n", n) - // Output: - // 1 - // 2 -} - -func ExampleInts() { - c, err := dial() - if err != nil { - fmt.Println(err) - return - } - defer c.Close() - - c.Do("SADD", "set_with_integers", 4, 5, 6) - ints, _ := redis.Ints(c.Do("SMEMBERS", "set_with_integers")) - fmt.Printf("%#v\n", ints) - // Output: - // []int{4, 5, 6} -} - -func ExampleString() { - c, err := dial() - if err != nil { - fmt.Println(err) - return - } - defer c.Close() - - c.Do("SET", "hello", "world") - s, err := redis.String(c.Do("GET", "hello")) - fmt.Printf("%#v\n", s) - // Output: - // "world" -} diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/scan_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/scan_test.go deleted file mode 100644 index d364dff428a..00000000000 --- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/scan_test.go +++ /dev/null @@ -1,440 +0,0 @@ -// Copyright 2012 Gary Burd -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package redis_test - -import ( - "fmt" - "math" - "reflect" - "testing" - - "github.com/garyburd/redigo/redis" -) - -var scanConversionTests = []struct { - src interface{} - dest interface{} -}{ - {[]byte("-inf"), math.Inf(-1)}, - {[]byte("+inf"), math.Inf(1)}, - {[]byte("0"), float64(0)}, - {[]byte("3.14159"), float64(3.14159)}, - {[]byte("3.14"), float32(3.14)}, - {[]byte("-100"), int(-100)}, - {[]byte("101"), int(101)}, - {int64(102), int(102)}, - {[]byte("103"), uint(103)}, - {int64(104), uint(104)}, - {[]byte("105"), int8(105)}, - {int64(106), int8(106)}, - {[]byte("107"), uint8(107)}, - {int64(108), uint8(108)}, - {[]byte("0"), false}, - {int64(0), false}, - {[]byte("f"), false}, - {[]byte("1"), true}, - {int64(1), true}, - {[]byte("t"), true}, - {"hello", "hello"}, - {[]byte("hello"), "hello"}, - {[]byte("world"), []byte("world")}, - {[]interface{}{[]byte("foo")}, []interface{}{[]byte("foo")}}, - {[]interface{}{[]byte("foo")}, []string{"foo"}}, - {[]interface{}{[]byte("hello"), []byte("world")}, []string{"hello", "world"}}, - {[]interface{}{[]byte("bar")}, [][]byte{[]byte("bar")}}, - {[]interface{}{[]byte("1")}, []int{1}}, - {[]interface{}{[]byte("1"), []byte("2")}, []int{1, 2}}, - {[]interface{}{[]byte("1"), []byte("2")}, []float64{1, 2}}, - {[]interface{}{[]byte("1")}, []byte{1}}, - {[]interface{}{[]byte("1")}, []bool{true}}, -} - -func TestScanConversion(t *testing.T) { - for _, tt := range scanConversionTests { - values := []interface{}{tt.src} - dest := reflect.New(reflect.TypeOf(tt.dest)) - values, err := redis.Scan(values, dest.Interface()) - if err != nil { - t.Errorf("Scan(%v) returned error %v", tt, err) - continue - } - if !reflect.DeepEqual(tt.dest, dest.Elem().Interface()) { - t.Errorf("Scan(%v) returned %v, want %v", tt, dest.Elem().Interface(), tt.dest) - } - } -} - -var scanConversionErrorTests = []struct { - src interface{} - dest interface{} -}{ - {[]byte("1234"), byte(0)}, - {int64(1234), byte(0)}, - {[]byte("-1"), byte(0)}, - {int64(-1), byte(0)}, - {[]byte("junk"), false}, - {redis.Error("blah"), false}, -} - -func TestScanConversionError(t *testing.T) { - for _, tt := range scanConversionErrorTests { - values := []interface{}{tt.src} - dest := reflect.New(reflect.TypeOf(tt.dest)) - values, err := redis.Scan(values, dest.Interface()) - if err == nil { - t.Errorf("Scan(%v) did not return error", tt) - } - } -} - -func ExampleScan() { - c, err := dial() - if err != nil { - fmt.Println(err) - return - } - defer c.Close() - - c.Send("HMSET", "album:1", "title", "Red", "rating", 5) - c.Send("HMSET", "album:2", "title", "Earthbound", "rating", 1) - c.Send("HMSET", "album:3", "title", "Beat") - c.Send("LPUSH", "albums", "1") - c.Send("LPUSH", "albums", "2") - c.Send("LPUSH", "albums", "3") - values, err := redis.Values(c.Do("SORT", "albums", - "BY", "album:*->rating", - "GET", "album:*->title", - "GET", "album:*->rating")) - if err != nil { - fmt.Println(err) - return - } - - for len(values) > 0 { - var title string - rating := -1 // initialize to illegal value to detect nil. - values, err = redis.Scan(values, &title, &rating) - if err != nil { - fmt.Println(err) - return - } - if rating == -1 { - fmt.Println(title, "not-rated") - } else { - fmt.Println(title, rating) - } - } - // Output: - // Beat not-rated - // Earthbound 1 - // Red 5 -} - -type s0 struct { - X int - Y int `redis:"y"` - Bt bool -} - -type s1 struct { - X int `redis:"-"` - I int `redis:"i"` - U uint `redis:"u"` - S string `redis:"s"` - P []byte `redis:"p"` - B bool `redis:"b"` - Bt bool - Bf bool - s0 -} - -var scanStructTests = []struct { - title string - reply []string - value interface{} -}{ - {"basic", - []string{"i", "-1234", "u", "5678", "s", "hello", "p", "world", "b", "t", "Bt", "1", "Bf", "0", "X", "123", "y", "456"}, - &s1{I: -1234, U: 5678, S: "hello", P: []byte("world"), B: true, Bt: true, Bf: false, s0: s0{X: 123, Y: 456}}, - }, -} - -func TestScanStruct(t *testing.T) { - for _, tt := range scanStructTests { - - var reply []interface{} - for _, v := range tt.reply { - reply = append(reply, []byte(v)) - } - - value := reflect.New(reflect.ValueOf(tt.value).Type().Elem()) - - if err := redis.ScanStruct(reply, value.Interface()); err != nil { - t.Fatalf("ScanStruct(%s) returned error %v", tt.title, err) - } - - if !reflect.DeepEqual(value.Interface(), tt.value) { - t.Fatalf("ScanStruct(%s) returned %v, want %v", tt.title, value.Interface(), tt.value) - } - } -} - -func TestBadScanStructArgs(t *testing.T) { - x := []interface{}{"A", "b"} - test := func(v interface{}) { - if err := redis.ScanStruct(x, v); err == nil { - t.Errorf("Expect error for ScanStruct(%T, %T)", x, v) - } - } - - test(nil) - - var v0 *struct{} - test(v0) - - var v1 int - test(&v1) - - x = x[:1] - v2 := struct{ A string }{} - test(&v2) -} - -var scanSliceTests = []struct { - src []interface{} - fieldNames []string - ok bool - dest interface{} -}{ - { - []interface{}{[]byte("1"), nil, []byte("-1")}, - nil, - true, - []int{1, 0, -1}, - }, - { - []interface{}{[]byte("1"), nil, []byte("2")}, - nil, - true, - []uint{1, 0, 2}, - }, - { - []interface{}{[]byte("-1")}, - nil, - false, - []uint{1}, - }, - { - []interface{}{[]byte("hello"), nil, []byte("world")}, - nil, - true, - [][]byte{[]byte("hello"), nil, []byte("world")}, - }, - { - []interface{}{[]byte("hello"), nil, []byte("world")}, - nil, - true, - []string{"hello", "", "world"}, - }, - { - []interface{}{[]byte("a1"), []byte("b1"), []byte("a2"), []byte("b2")}, - nil, - true, - []struct{ A, B string }{{"a1", "b1"}, {"a2", "b2"}}, - }, - { - []interface{}{[]byte("a1"), []byte("b1")}, - nil, - false, - []struct{ A, B, C string }{{"a1", "b1", ""}}, - }, - { - []interface{}{[]byte("a1"), []byte("b1"), []byte("a2"), []byte("b2")}, - nil, - true, - []*struct{ A, B string }{{"a1", "b1"}, {"a2", "b2"}}, - }, - { - []interface{}{[]byte("a1"), []byte("b1"), []byte("a2"), []byte("b2")}, - []string{"A", "B"}, - true, - []struct{ A, C, B string }{{"a1", "", "b1"}, {"a2", "", "b2"}}, - }, - { - []interface{}{[]byte("a1"), []byte("b1"), []byte("a2"), []byte("b2")}, - nil, - false, - []struct{}{}, - }, -} - -func TestScanSlice(t *testing.T) { - for _, tt := range scanSliceTests { - - typ := reflect.ValueOf(tt.dest).Type() - dest := reflect.New(typ) - - err := redis.ScanSlice(tt.src, dest.Interface(), tt.fieldNames...) - if tt.ok != (err == nil) { - t.Errorf("ScanSlice(%v, []%s, %v) returned error %v", tt.src, typ, tt.fieldNames, err) - continue - } - if tt.ok && !reflect.DeepEqual(dest.Elem().Interface(), tt.dest) { - t.Errorf("ScanSlice(src, []%s) returned %#v, want %#v", typ, dest.Elem().Interface(), tt.dest) - } - } -} - -func ExampleScanSlice() { - c, err := dial() - if err != nil { - fmt.Println(err) - return - } - defer c.Close() - - c.Send("HMSET", "album:1", "title", "Red", "rating", 5) - c.Send("HMSET", "album:2", "title", "Earthbound", "rating", 1) - c.Send("HMSET", "album:3", "title", "Beat", "rating", 4) - c.Send("LPUSH", "albums", "1") - c.Send("LPUSH", "albums", "2") - c.Send("LPUSH", "albums", "3") - values, err := redis.Values(c.Do("SORT", "albums", - "BY", "album:*->rating", - "GET", "album:*->title", - "GET", "album:*->rating")) - if err != nil { - fmt.Println(err) - return - } - - var albums []struct { - Title string - Rating int - } - if err := redis.ScanSlice(values, &albums); err != nil { - fmt.Println(err) - return - } - fmt.Printf("%v\n", albums) - // Output: - // [{Earthbound 1} {Beat 4} {Red 5}] -} - -var argsTests = []struct { - title string - actual redis.Args - expected redis.Args -}{ - {"struct ptr", - redis.Args{}.AddFlat(&struct { - I int `redis:"i"` - U uint `redis:"u"` - S string `redis:"s"` - P []byte `redis:"p"` - M map[string]string `redis:"m"` - Bt bool - Bf bool - }{ - -1234, 5678, "hello", []byte("world"), map[string]string{"hello": "world"}, true, false, - }), - redis.Args{"i", int(-1234), "u", uint(5678), "s", "hello", "p", []byte("world"), "m", map[string]string{"hello": "world"}, "Bt", true, "Bf", false}, - }, - {"struct", - redis.Args{}.AddFlat(struct{ I int }{123}), - redis.Args{"I", 123}, - }, - {"slice", - redis.Args{}.Add(1).AddFlat([]string{"a", "b", "c"}).Add(2), - redis.Args{1, "a", "b", "c", 2}, - }, - {"struct omitempty", - redis.Args{}.AddFlat(&struct { - I int `redis:"i,omitempty"` - U uint `redis:"u,omitempty"` - S string `redis:"s,omitempty"` - P []byte `redis:"p,omitempty"` - M map[string]string `redis:"m,omitempty"` - Bt bool `redis:"Bt,omitempty"` - Bf bool `redis:"Bf,omitempty"` - }{ - 0, 0, "", []byte{}, map[string]string{}, true, false, - }), - redis.Args{"Bt", true}, - }, -} - -func TestArgs(t *testing.T) { - for _, tt := range argsTests { - if !reflect.DeepEqual(tt.actual, tt.expected) { - t.Fatalf("%s is %v, want %v", tt.title, tt.actual, tt.expected) - } - } -} - -func ExampleArgs() { - c, err := dial() - if err != nil { - fmt.Println(err) - return - } - defer c.Close() - - var p1, p2 struct { - Title string `redis:"title"` - Author string `redis:"author"` - Body string `redis:"body"` - } - - p1.Title = "Example" - p1.Author = "Gary" - p1.Body = "Hello" - - if _, err := c.Do("HMSET", redis.Args{}.Add("id1").AddFlat(&p1)...); err != nil { - fmt.Println(err) - return - } - - m := map[string]string{ - "title": "Example2", - "author": "Steve", - "body": "Map", - } - - if _, err := c.Do("HMSET", redis.Args{}.Add("id2").AddFlat(m)...); err != nil { - fmt.Println(err) - return - } - - for _, id := range []string{"id1", "id2"} { - - v, err := redis.Values(c.Do("HGETALL", id)) - if err != nil { - fmt.Println(err) - return - } - - if err := redis.ScanStruct(v, &p2); err != nil { - fmt.Println(err) - return - } - - fmt.Printf("%+v\n", p2) - } - - // Output: - // {Title:Example Author:Gary Body:Hello} - // {Title:Example2 Author:Steve Body:Map} -} diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/script_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/script_test.go deleted file mode 100644 index 42f3c0363cf..00000000000 --- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/script_test.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2012 Gary Burd -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package redis_test - -import ( - "fmt" - "reflect" - "testing" - "time" - - "github.com/garyburd/redigo/redis" -) - -func ExampleScript(c redis.Conn, reply interface{}, err error) { - // Initialize a package-level variable with a script. - var getScript = redis.NewScript(1, `return redis.call('get', KEYS[1])`) - - // In a function, use the script Do method to evaluate the script. The Do - // method optimistically uses the EVALSHA command. If the script is not - // loaded, then the Do method falls back to the EVAL command. - reply, err = getScript.Do(c, "foo") -} - -func TestScript(t *testing.T) { - c, err := redis.DialDefaultServer() - if err != nil { - t.Fatalf("error connection to database, %v", err) - } - defer c.Close() - - // To test fall back in Do, we make script unique by adding comment with current time. - script := fmt.Sprintf("--%d\nreturn {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}", time.Now().UnixNano()) - s := redis.NewScript(2, script) - reply := []interface{}{[]byte("key1"), []byte("key2"), []byte("arg1"), []byte("arg2")} - - v, err := s.Do(c, "key1", "key2", "arg1", "arg2") - if err != nil { - t.Errorf("s.Do(c, ...) returned %v", err) - } - - if !reflect.DeepEqual(v, reply) { - t.Errorf("s.Do(c, ..); = %v, want %v", v, reply) - } - - err = s.Load(c) - if err != nil { - t.Errorf("s.Load(c) returned %v", err) - } - - err = s.SendHash(c, "key1", "key2", "arg1", "arg2") - if err != nil { - t.Errorf("s.SendHash(c, ...) returned %v", err) - } - - err = c.Flush() - if err != nil { - t.Errorf("c.Flush() returned %v", err) - } - - v, err = c.Receive() - if !reflect.DeepEqual(v, reply) { - t.Errorf("s.SendHash(c, ..); c.Receive() = %v, want %v", v, reply) - } - - err = s.Send(c, "key1", "key2", "arg1", "arg2") - if err != nil { - t.Errorf("s.Send(c, ...) returned %v", err) - } - - err = c.Flush() - if err != nil { - t.Errorf("c.Flush() returned %v", err) - } - - v, err = c.Receive() - if !reflect.DeepEqual(v, reply) { - t.Errorf("s.Send(c, ..); c.Receive() = %v, want %v", v, reply) - } - -} diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/test_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/test_test.go deleted file mode 100644 index 7240fa1f350..00000000000 --- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/test_test.go +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright 2012 Gary Burd -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package redis - -import ( - "bufio" - "errors" - "flag" - "fmt" - "io" - "io/ioutil" - "os" - "os/exec" - "strconv" - "strings" - "sync" - "testing" - "time" -) - -func SetNowFunc(f func() time.Time) { - nowFunc = f -} - -var ( - ErrNegativeInt = errNegativeInt - - serverPath = flag.String("redis-server", "redis-server", "Path to redis server binary") - serverBasePort = flag.Int("redis-port", 16379, "Beginning of port range for test servers") - serverLogName = flag.String("redis-log", "", "Write Redis server logs to `filename`") - serverLog = ioutil.Discard - - defaultServerMu sync.Mutex - defaultServer *Server - defaultServerErr error -) - -type Server struct { - name string - cmd *exec.Cmd - done chan struct{} -} - -func NewServer(name string, args ...string) (*Server, error) { - s := &Server{ - name: name, - cmd: exec.Command(*serverPath, args...), - done: make(chan struct{}), - } - - r, err := s.cmd.StdoutPipe() - if err != nil { - return nil, err - } - - err = s.cmd.Start() - if err != nil { - return nil, err - } - - ready := make(chan error, 1) - go s.watch(r, ready) - - select { - case err = <-ready: - case <-time.After(time.Second * 10): - err = errors.New("timeout waiting for server to start") - } - - if err != nil { - s.Stop() - return nil, err - } - - return s, nil -} - -func (s *Server) watch(r io.Reader, ready chan error) { - fmt.Fprintf(serverLog, "%d START %s \n", s.cmd.Process.Pid, s.name) - var listening bool - var text string - scn := bufio.NewScanner(r) - for scn.Scan() { - text = scn.Text() - fmt.Fprintf(serverLog, "%s\n", text) - if !listening { - if strings.Contains(text, "The server is now ready to accept connections on port") { - listening = true - ready <- nil - } - } - } - if !listening { - ready <- fmt.Errorf("server exited: %s", text) - } - s.cmd.Wait() - fmt.Fprintf(serverLog, "%d STOP %s \n", s.cmd.Process.Pid, s.name) - close(s.done) -} - -func (s *Server) Stop() { - s.cmd.Process.Signal(os.Interrupt) - <-s.done -} - -// stopDefaultServer stops the server created by DialDefaultServer. -func stopDefaultServer() { - defaultServerMu.Lock() - defer defaultServerMu.Unlock() - if defaultServer != nil { - defaultServer.Stop() - defaultServer = nil - } -} - -// startDefaultServer starts the default server if not already running. -func startDefaultServer() error { - defaultServerMu.Lock() - defer defaultServerMu.Unlock() - if defaultServer != nil || defaultServerErr != nil { - return defaultServerErr - } - defaultServer, defaultServerErr = NewServer( - "default", - "--port", strconv.Itoa(*serverBasePort), - "--save", "", - "--appendonly", "no") - return defaultServerErr -} - -// DialDefaultServer starts the test server if not already started and dials a -// connection to the server. -func DialDefaultServer() (Conn, error) { - if err := startDefaultServer(); err != nil { - return nil, err - } - c, err := Dial("tcp", fmt.Sprintf(":%d", *serverBasePort), DialReadTimeout(1*time.Second), DialWriteTimeout(1*time.Second)) - if err != nil { - return nil, err - } - c.Do("FLUSHDB") - return c, nil -} - -func TestMain(m *testing.M) { - os.Exit(func() int { - flag.Parse() - - var f *os.File - if *serverLogName != "" { - var err error - f, err = os.OpenFile(*serverLogName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600) - if err != nil { - fmt.Fprintf(os.Stderr, "Error opening redis-log: %v\n", err) - return 1 - } - defer f.Close() - serverLog = f - } - - defer stopDefaultServer() - - return m.Run() - }()) -} diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/zpop_example_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/zpop_example_test.go deleted file mode 100644 index 1d86ee6ce8c..00000000000 --- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/zpop_example_test.go +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2013 Gary Burd -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package redis_test - -import ( - "fmt" - "github.com/garyburd/redigo/redis" -) - -// zpop pops a value from the ZSET key using WATCH/MULTI/EXEC commands. -func zpop(c redis.Conn, key string) (result string, err error) { - - defer func() { - // Return connection to normal state on error. - if err != nil { - c.Do("DISCARD") - } - }() - - // Loop until transaction is successful. - for { - if _, err := c.Do("WATCH", key); err != nil { - return "", err - } - - members, err := redis.Strings(c.Do("ZRANGE", key, 0, 0)) - if err != nil { - return "", err - } - if len(members) != 1 { - return "", redis.ErrNil - } - - c.Send("MULTI") - c.Send("ZREM", key, members[0]) - queued, err := c.Do("EXEC") - if err != nil { - return "", err - } - - if queued != nil { - result = members[0] - break - } - } - - return result, nil -} - -// zpopScript pops a value from a ZSET. -var zpopScript = redis.NewScript(1, ` - local r = redis.call('ZRANGE', KEYS[1], 0, 0) - if r ~= nil then - r = r[1] - redis.call('ZREM', KEYS[1], r) - end - return r -`) - -// This example implements ZPOP as described at -// http://redis.io/topics/transactions using WATCH/MULTI/EXEC and scripting. -func Example_zpop() { - c, err := dial() - if err != nil { - fmt.Println(err) - return - } - defer c.Close() - - // Add test data using a pipeline. - - for i, member := range []string{"red", "blue", "green"} { - c.Send("ZADD", "zset", i, member) - } - if _, err := c.Do(""); err != nil { - fmt.Println(err) - return - } - - // Pop using WATCH/MULTI/EXEC - - v, err := zpop(c, "zset") - if err != nil { - fmt.Println(err) - return - } - fmt.Println(v) - - // Pop using a script. - - v, err = redis.String(zpopScript.Do(c, "zset")) - if err != nil { - fmt.Println(err) - return - } - fmt.Println(v) - - // Output: - // red - // blue -} diff --git a/Godeps/_workspace/src/github.com/samuel/go-parser/parser/parser_test.go b/Godeps/_workspace/src/github.com/samuel/go-parser/parser/parser_test.go deleted file mode 100644 index f85d79bd2ed..00000000000 --- a/Godeps/_workspace/src/github.com/samuel/go-parser/parser/parser_test.go +++ /dev/null @@ -1,138 +0,0 @@ -package parser - -import ( - "io" - "reflect" - "testing" -) - -func testSimple(t *testing.T, name string, spec Spec, p Parser, in string, eok bool, exp interface{}) { - st := &State{ - Input: NewStringInput(in), - Spec: spec, - } - out, ok, err := p(st) - if err != nil { - t.Fatalf("%s returned error %s (in '%s' exp '%+v')", name, err.Error(), in, exp) - } - if ok != eok { - t.Fatalf("%s returned ok of %+v instead of %+v", name, ok, eok) - } - if !reflect.DeepEqual(out, exp) { - t.Fatalf("%s returned '%+v' instead of '%+v'", name, out, exp) - } -} - -func TestAll(t *testing.T) { - p := All( - String("1"), - String("test"), - ) - testSimple(t, "All", Spec{}, p, "1test", true, "test") - testSimple(t, "All", Spec{}, p, "1test222", true, "test") -} - -func TestAny(t *testing.T) { - p := Any( - String("1"), - String("test"), - ) - testSimple(t, "Any", Spec{}, p, "2", false, nil) - testSimple(t, "Any", Spec{}, p, "1", true, "1") - testSimple(t, "Any", Spec{}, p, "test1", true, "test") -} - -func TestMany(t *testing.T) { - p := Many( - String("1"), - ) - testSimple(t, "Many", Spec{}, p, "", true, []interface{}{}) - testSimple(t, "Many", Spec{}, p, "11", true, []interface{}{"1", "1"}) - testSimple(t, "Many", Spec{}, p, "1122", true, []interface{}{"1", "1"}) -} - -func TestMany1(t *testing.T) { - p := Many1( - String("1"), - ) - testSimple(t, "Many1", Spec{}, p, "3", false, nil) - testSimple(t, "Many1", Spec{}, p, "11", true, []interface{}{"1", "1"}) - testSimple(t, "Many1", Spec{}, p, "1122", true, []interface{}{"1", "1"}) -} - -func TestString(t *testing.T) { - p := String("test") - testSimple(t, "String", Spec{}, p, "test", true, "test") - testSimple(t, "String", Spec{}, p, "testaa", true, "test") -} - -func TestComments(t *testing.T) { - spec := Spec{ - CommentStart: "/*", - CommentEnd: "*/", - CommentLine: String("//"), - } - in := NewStringInput(`// this is a test - // only a test - /* this is - a multiline comment */`) - st := &State{Spec: spec, Input: in} - p := OneLineComment() - out, d, err := p(st) - if err != nil { - t.Fatalf("OneLinecomment returned error %s", err.Error()) - } - if !d { - t.Fatal("OneLineComment returned !ok") - } - exp := " this is a test" - if outString, ok := out.(string); !ok { - t.Fatal("OneLinecomment returned non-string") - } else if outString != exp { - t.Fatalf("OneLineComment returned '%s' instead of '%s'", outString, exp) - } -} - -func TestStringInput(t *testing.T) { - testString := "tes†ing mitä" - - in := NewStringInput(testString) - outString := "" - for { - r, err := in.Next() - if err == io.EOF { - break - } else if err != nil { - t.Fatalf("StringInput.Next returned error %s", err.Error()) - } - in.Pop(1) - outString += string(r) - } - - if testString != outString { - t.Fatalf("Next/Pop produced unmatched output of %#v instead of %#v", outString, testString) - } - - in = NewStringInput(testString) - in.Pop(1) - outString, err := in.Get(5) - if err != nil { - t.Fatal("Get(5) returned error %s", err.Error()) - } - if "es†in" != outString { - t.Fatalf("Get produced unmatched output of %#v instead of %#v", outString, "es†in") - } - - in = NewStringInput(testString) - outString, err = in.Get(12) - if err != nil { - t.Fatal("Get(12) returned error %s", err.Error()) - } - if testString != outString { - t.Fatalf("Get(len) produced unmatched output of %#v instead of %#v", outString, testString) - } - outString, err = in.Get(13) - if err != io.EOF { - t.Fatal("Get(len+1) returned error %+v but should have returned EOF", err) - } -} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions_test.go deleted file mode 100644 index 9c5bef87795..00000000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions_test.go +++ /dev/null @@ -1,911 +0,0 @@ -package assert - -import ( - "errors" - "io" - "math" - "reflect" - "regexp" - "testing" - "time" -) - -var ( - i interface{} - zeros = []interface{}{ - false, - byte(0), - complex64(0), - complex128(0), - float32(0), - float64(0), - int(0), - int8(0), - int16(0), - int32(0), - int64(0), - rune(0), - uint(0), - uint8(0), - uint16(0), - uint32(0), - uint64(0), - uintptr(0), - "", - [0]interface{}{}, - []interface{}(nil), - struct{ x int }{}, - (*interface{})(nil), - (func())(nil), - nil, - interface{}(nil), - map[interface{}]interface{}(nil), - (chan interface{})(nil), - (<-chan interface{})(nil), - (chan<- interface{})(nil), - } - nonZeros = []interface{}{ - true, - byte(1), - complex64(1), - complex128(1), - float32(1), - float64(1), - int(1), - int8(1), - int16(1), - int32(1), - int64(1), - rune(1), - uint(1), - uint8(1), - uint16(1), - uint32(1), - uint64(1), - uintptr(1), - "s", - [1]interface{}{1}, - []interface{}{}, - struct{ x int }{1}, - (*interface{})(&i), - (func())(func() {}), - interface{}(1), - map[interface{}]interface{}{}, - (chan interface{})(make(chan interface{})), - (<-chan interface{})(make(chan interface{})), - (chan<- interface{})(make(chan interface{})), - } -) - -// AssertionTesterInterface defines an interface to be used for testing assertion methods -type AssertionTesterInterface interface { - TestMethod() -} - -// AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface -type AssertionTesterConformingObject struct { -} - -func (a *AssertionTesterConformingObject) TestMethod() { -} - -// AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface -type AssertionTesterNonConformingObject struct { -} - -func TestObjectsAreEqual(t *testing.T) { - - if !ObjectsAreEqual("Hello World", "Hello World") { - t.Error("objectsAreEqual should return true") - } - if !ObjectsAreEqual(123, 123) { - t.Error("objectsAreEqual should return true") - } - if !ObjectsAreEqual(123.5, 123.5) { - t.Error("objectsAreEqual should return true") - } - if !ObjectsAreEqual([]byte("Hello World"), []byte("Hello World")) { - t.Error("objectsAreEqual should return true") - } - if !ObjectsAreEqual(nil, nil) { - t.Error("objectsAreEqual should return true") - } - if ObjectsAreEqual(map[int]int{5: 10}, map[int]int{10: 20}) { - t.Error("objectsAreEqual should return false") - } - if ObjectsAreEqual('x', "x") { - t.Error("objectsAreEqual should return false") - } - if ObjectsAreEqual("x", 'x') { - t.Error("objectsAreEqual should return false") - } - if ObjectsAreEqual(0, 0.1) { - t.Error("objectsAreEqual should return false") - } - if ObjectsAreEqual(0.1, 0) { - t.Error("objectsAreEqual should return false") - } - if ObjectsAreEqual(uint32(10), int32(10)) { - t.Error("objectsAreEqual should return false") - } - if !ObjectsAreEqualValues(uint32(10), int32(10)) { - t.Error("ObjectsAreEqualValues should return true") - } - -} - -func TestImplements(t *testing.T) { - - mockT := new(testing.T) - - if !Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) { - t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface") - } - if Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) { - t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface") - } - -} - -func TestIsType(t *testing.T) { - - mockT := new(testing.T) - - if !IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { - t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject") - } - if IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) { - t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject") - } - -} - -func TestEqual(t *testing.T) { - - mockT := new(testing.T) - - if !Equal(mockT, "Hello World", "Hello World") { - t.Error("Equal should return true") - } - if !Equal(mockT, 123, 123) { - t.Error("Equal should return true") - } - if !Equal(mockT, 123.5, 123.5) { - t.Error("Equal should return true") - } - if !Equal(mockT, []byte("Hello World"), []byte("Hello World")) { - t.Error("Equal should return true") - } - if !Equal(mockT, nil, nil) { - t.Error("Equal should return true") - } - if !Equal(mockT, int32(123), int32(123)) { - t.Error("Equal should return true") - } - if !Equal(mockT, uint64(123), uint64(123)) { - t.Error("Equal should return true") - } - -} - -func TestNotNil(t *testing.T) { - - mockT := new(testing.T) - - if !NotNil(mockT, new(AssertionTesterConformingObject)) { - t.Error("NotNil should return true: object is not nil") - } - if NotNil(mockT, nil) { - t.Error("NotNil should return false: object is nil") - } - if NotNil(mockT, (*struct{})(nil)) { - t.Error("NotNil should return false: object is (*struct{})(nil)") - } - -} - -func TestNil(t *testing.T) { - - mockT := new(testing.T) - - if !Nil(mockT, nil) { - t.Error("Nil should return true: object is nil") - } - if !Nil(mockT, (*struct{})(nil)) { - t.Error("Nil should return true: object is (*struct{})(nil)") - } - if Nil(mockT, new(AssertionTesterConformingObject)) { - t.Error("Nil should return false: object is not nil") - } - -} - -func TestTrue(t *testing.T) { - - mockT := new(testing.T) - - if !True(mockT, true) { - t.Error("True should return true") - } - if True(mockT, false) { - t.Error("True should return false") - } - -} - -func TestFalse(t *testing.T) { - - mockT := new(testing.T) - - if !False(mockT, false) { - t.Error("False should return true") - } - if False(mockT, true) { - t.Error("False should return false") - } - -} - -func TestExactly(t *testing.T) { - - mockT := new(testing.T) - - a := float32(1) - b := float64(1) - c := float32(1) - d := float32(2) - - if Exactly(mockT, a, b) { - t.Error("Exactly should return false") - } - if Exactly(mockT, a, d) { - t.Error("Exactly should return false") - } - if !Exactly(mockT, a, c) { - t.Error("Exactly should return true") - } - - if Exactly(mockT, nil, a) { - t.Error("Exactly should return false") - } - if Exactly(mockT, a, nil) { - t.Error("Exactly should return false") - } - -} - -func TestNotEqual(t *testing.T) { - - mockT := new(testing.T) - - if !NotEqual(mockT, "Hello World", "Hello World!") { - t.Error("NotEqual should return true") - } - if !NotEqual(mockT, 123, 1234) { - t.Error("NotEqual should return true") - } - if !NotEqual(mockT, 123.5, 123.55) { - t.Error("NotEqual should return true") - } - if !NotEqual(mockT, []byte("Hello World"), []byte("Hello World!")) { - t.Error("NotEqual should return true") - } - if !NotEqual(mockT, nil, new(AssertionTesterConformingObject)) { - t.Error("NotEqual should return true") - } - funcA := func() int { return 23 } - funcB := func() int { return 42 } - if !NotEqual(mockT, funcA, funcB) { - t.Error("NotEqual should return true") - } - - if NotEqual(mockT, "Hello World", "Hello World") { - t.Error("NotEqual should return false") - } - if NotEqual(mockT, 123, 123) { - t.Error("NotEqual should return false") - } - if NotEqual(mockT, 123.5, 123.5) { - t.Error("NotEqual should return false") - } - if NotEqual(mockT, []byte("Hello World"), []byte("Hello World")) { - t.Error("NotEqual should return false") - } - if NotEqual(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { - t.Error("NotEqual should return false") - } -} - -type A struct { - Name, Value string -} - -func TestContains(t *testing.T) { - - mockT := new(testing.T) - list := []string{"Foo", "Bar"} - complexList := []*A{ - {"b", "c"}, - {"d", "e"}, - {"g", "h"}, - {"j", "k"}, - } - - if !Contains(mockT, "Hello World", "Hello") { - t.Error("Contains should return true: \"Hello World\" contains \"Hello\"") - } - if Contains(mockT, "Hello World", "Salut") { - t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"") - } - - if !Contains(mockT, list, "Bar") { - t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Bar\"") - } - if Contains(mockT, list, "Salut") { - t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"") - } - if !Contains(mockT, complexList, &A{"g", "h"}) { - t.Error("Contains should return true: complexList contains {\"g\", \"h\"}") - } - if Contains(mockT, complexList, &A{"g", "e"}) { - t.Error("Contains should return false: complexList contains {\"g\", \"e\"}") - } -} - -func TestNotContains(t *testing.T) { - - mockT := new(testing.T) - list := []string{"Foo", "Bar"} - - if !NotContains(mockT, "Hello World", "Hello!") { - t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"") - } - if NotContains(mockT, "Hello World", "Hello") { - t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"") - } - - if !NotContains(mockT, list, "Foo!") { - t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"") - } - if NotContains(mockT, list, "Foo") { - t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") - } - -} - -func Test_includeElement(t *testing.T) { - - list1 := []string{"Foo", "Bar"} - list2 := []int{1, 2} - - ok, found := includeElement("Hello World", "World") - True(t, ok) - True(t, found) - - ok, found = includeElement(list1, "Foo") - True(t, ok) - True(t, found) - - ok, found = includeElement(list1, "Bar") - True(t, ok) - True(t, found) - - ok, found = includeElement(list2, 1) - True(t, ok) - True(t, found) - - ok, found = includeElement(list2, 2) - True(t, ok) - True(t, found) - - ok, found = includeElement(list1, "Foo!") - True(t, ok) - False(t, found) - - ok, found = includeElement(list2, 3) - True(t, ok) - False(t, found) - - ok, found = includeElement(list2, "1") - True(t, ok) - False(t, found) - - ok, found = includeElement(1433, "1") - False(t, ok) - False(t, found) - -} - -func TestCondition(t *testing.T) { - mockT := new(testing.T) - - if !Condition(mockT, func() bool { return true }, "Truth") { - t.Error("Condition should return true") - } - - if Condition(mockT, func() bool { return false }, "Lie") { - t.Error("Condition should return false") - } - -} - -func TestDidPanic(t *testing.T) { - - if funcDidPanic, _ := didPanic(func() { - panic("Panic!") - }); !funcDidPanic { - t.Error("didPanic should return true") - } - - if funcDidPanic, _ := didPanic(func() { - }); funcDidPanic { - t.Error("didPanic should return false") - } - -} - -func TestPanics(t *testing.T) { - - mockT := new(testing.T) - - if !Panics(mockT, func() { - panic("Panic!") - }) { - t.Error("Panics should return true") - } - - if Panics(mockT, func() { - }) { - t.Error("Panics should return false") - } - -} - -func TestNotPanics(t *testing.T) { - - mockT := new(testing.T) - - if !NotPanics(mockT, func() { - }) { - t.Error("NotPanics should return true") - } - - if NotPanics(mockT, func() { - panic("Panic!") - }) { - t.Error("NotPanics should return false") - } - -} - -func TestNoError(t *testing.T) { - - mockT := new(testing.T) - - // start with a nil error - var err error - - True(t, NoError(mockT, err), "NoError should return True for nil arg") - - // now set an error - err = errors.New("some error") - - False(t, NoError(mockT, err), "NoError with error should return False") - -} - -func TestError(t *testing.T) { - - mockT := new(testing.T) - - // start with a nil error - var err error - - False(t, Error(mockT, err), "Error should return False for nil arg") - - // now set an error - err = errors.New("some error") - - True(t, Error(mockT, err), "Error with error should return True") - -} - -func TestEqualError(t *testing.T) { - mockT := new(testing.T) - - // start with a nil error - var err error - False(t, EqualError(mockT, err, ""), - "EqualError should return false for nil arg") - - // now set an error - err = errors.New("some error") - False(t, EqualError(mockT, err, "Not some error"), - "EqualError should return false for different error string") - True(t, EqualError(mockT, err, "some error"), - "EqualError should return true") -} - -func Test_isEmpty(t *testing.T) { - - chWithValue := make(chan struct{}, 1) - chWithValue <- struct{}{} - - True(t, isEmpty("")) - True(t, isEmpty(nil)) - True(t, isEmpty([]string{})) - True(t, isEmpty(0)) - True(t, isEmpty(int32(0))) - True(t, isEmpty(int64(0))) - True(t, isEmpty(false)) - True(t, isEmpty(map[string]string{})) - True(t, isEmpty(new(time.Time))) - True(t, isEmpty(make(chan struct{}))) - False(t, isEmpty("something")) - False(t, isEmpty(errors.New("something"))) - False(t, isEmpty([]string{"something"})) - False(t, isEmpty(1)) - False(t, isEmpty(true)) - False(t, isEmpty(map[string]string{"Hello": "World"})) - False(t, isEmpty(chWithValue)) - -} - -func TestEmpty(t *testing.T) { - - mockT := new(testing.T) - chWithValue := make(chan struct{}, 1) - chWithValue <- struct{}{} - - True(t, Empty(mockT, ""), "Empty string is empty") - True(t, Empty(mockT, nil), "Nil is empty") - True(t, Empty(mockT, []string{}), "Empty string array is empty") - True(t, Empty(mockT, 0), "Zero int value is empty") - True(t, Empty(mockT, false), "False value is empty") - True(t, Empty(mockT, make(chan struct{})), "Channel without values is empty") - - False(t, Empty(mockT, "something"), "Non Empty string is not empty") - False(t, Empty(mockT, errors.New("something")), "Non nil object is not empty") - False(t, Empty(mockT, []string{"something"}), "Non empty string array is not empty") - False(t, Empty(mockT, 1), "Non-zero int value is not empty") - False(t, Empty(mockT, true), "True value is not empty") - False(t, Empty(mockT, chWithValue), "Channel with values is not empty") -} - -func TestNotEmpty(t *testing.T) { - - mockT := new(testing.T) - chWithValue := make(chan struct{}, 1) - chWithValue <- struct{}{} - - False(t, NotEmpty(mockT, ""), "Empty string is empty") - False(t, NotEmpty(mockT, nil), "Nil is empty") - False(t, NotEmpty(mockT, []string{}), "Empty string array is empty") - False(t, NotEmpty(mockT, 0), "Zero int value is empty") - False(t, NotEmpty(mockT, false), "False value is empty") - False(t, NotEmpty(mockT, make(chan struct{})), "Channel without values is empty") - - True(t, NotEmpty(mockT, "something"), "Non Empty string is not empty") - True(t, NotEmpty(mockT, errors.New("something")), "Non nil object is not empty") - True(t, NotEmpty(mockT, []string{"something"}), "Non empty string array is not empty") - True(t, NotEmpty(mockT, 1), "Non-zero int value is not empty") - True(t, NotEmpty(mockT, true), "True value is not empty") - True(t, NotEmpty(mockT, chWithValue), "Channel with values is not empty") -} - -func Test_getLen(t *testing.T) { - falseCases := []interface{}{ - nil, - 0, - true, - false, - 'A', - struct{}{}, - } - for _, v := range falseCases { - ok, l := getLen(v) - False(t, ok, "Expected getLen fail to get length of %#v", v) - Equal(t, 0, l, "getLen should return 0 for %#v", v) - } - - ch := make(chan int, 5) - ch <- 1 - ch <- 2 - ch <- 3 - trueCases := []struct { - v interface{} - l int - }{ - {[]int{1, 2, 3}, 3}, - {[...]int{1, 2, 3}, 3}, - {"ABC", 3}, - {map[int]int{1: 2, 2: 4, 3: 6}, 3}, - {ch, 3}, - - {[]int{}, 0}, - {map[int]int{}, 0}, - {make(chan int), 0}, - - {[]int(nil), 0}, - {map[int]int(nil), 0}, - {(chan int)(nil), 0}, - } - - for _, c := range trueCases { - ok, l := getLen(c.v) - True(t, ok, "Expected getLen success to get length of %#v", c.v) - Equal(t, c.l, l) - } -} - -func TestLen(t *testing.T) { - mockT := new(testing.T) - - False(t, Len(mockT, nil, 0), "nil does not have length") - False(t, Len(mockT, 0, 0), "int does not have length") - False(t, Len(mockT, true, 0), "true does not have length") - False(t, Len(mockT, false, 0), "false does not have length") - False(t, Len(mockT, 'A', 0), "Rune does not have length") - False(t, Len(mockT, struct{}{}, 0), "Struct does not have length") - - ch := make(chan int, 5) - ch <- 1 - ch <- 2 - ch <- 3 - - cases := []struct { - v interface{} - l int - }{ - {[]int{1, 2, 3}, 3}, - {[...]int{1, 2, 3}, 3}, - {"ABC", 3}, - {map[int]int{1: 2, 2: 4, 3: 6}, 3}, - {ch, 3}, - - {[]int{}, 0}, - {map[int]int{}, 0}, - {make(chan int), 0}, - - {[]int(nil), 0}, - {map[int]int(nil), 0}, - {(chan int)(nil), 0}, - } - - for _, c := range cases { - True(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l) - } - - cases = []struct { - v interface{} - l int - }{ - {[]int{1, 2, 3}, 4}, - {[...]int{1, 2, 3}, 2}, - {"ABC", 2}, - {map[int]int{1: 2, 2: 4, 3: 6}, 4}, - {ch, 2}, - - {[]int{}, 1}, - {map[int]int{}, 1}, - {make(chan int), 1}, - - {[]int(nil), 1}, - {map[int]int(nil), 1}, - {(chan int)(nil), 1}, - } - - for _, c := range cases { - False(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l) - } -} - -func TestWithinDuration(t *testing.T) { - - mockT := new(testing.T) - a := time.Now() - b := a.Add(10 * time.Second) - - True(t, WithinDuration(mockT, a, b, 10*time.Second), "A 10s difference is within a 10s time difference") - True(t, WithinDuration(mockT, b, a, 10*time.Second), "A 10s difference is within a 10s time difference") - - False(t, WithinDuration(mockT, a, b, 9*time.Second), "A 10s difference is not within a 9s time difference") - False(t, WithinDuration(mockT, b, a, 9*time.Second), "A 10s difference is not within a 9s time difference") - - False(t, WithinDuration(mockT, a, b, -9*time.Second), "A 10s difference is not within a 9s time difference") - False(t, WithinDuration(mockT, b, a, -9*time.Second), "A 10s difference is not within a 9s time difference") - - False(t, WithinDuration(mockT, a, b, -11*time.Second), "A 10s difference is not within a 9s time difference") - False(t, WithinDuration(mockT, b, a, -11*time.Second), "A 10s difference is not within a 9s time difference") -} - -func TestInDelta(t *testing.T) { - mockT := new(testing.T) - - True(t, InDelta(mockT, 1.001, 1, 0.01), "|1.001 - 1| <= 0.01") - True(t, InDelta(mockT, 1, 1.001, 0.01), "|1 - 1.001| <= 0.01") - True(t, InDelta(mockT, 1, 2, 1), "|1 - 2| <= 1") - False(t, InDelta(mockT, 1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail") - False(t, InDelta(mockT, 2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail") - False(t, InDelta(mockT, "", nil, 1), "Expected non numerals to fail") - False(t, InDelta(mockT, 42, math.NaN(), 0.01), "Expected NaN for actual to fail") - False(t, InDelta(mockT, math.NaN(), 42, 0.01), "Expected NaN for expected to fail") - - cases := []struct { - a, b interface{} - delta float64 - }{ - {uint8(2), uint8(1), 1}, - {uint16(2), uint16(1), 1}, - {uint32(2), uint32(1), 1}, - {uint64(2), uint64(1), 1}, - - {int(2), int(1), 1}, - {int8(2), int8(1), 1}, - {int16(2), int16(1), 1}, - {int32(2), int32(1), 1}, - {int64(2), int64(1), 1}, - - {float32(2), float32(1), 1}, - {float64(2), float64(1), 1}, - } - - for _, tc := range cases { - True(t, InDelta(mockT, tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta) - } -} - -func TestInDeltaSlice(t *testing.T) { - mockT := new(testing.T) - - True(t, InDeltaSlice(mockT, - []float64{1.001, 0.999}, - []float64{1, 1}, - 0.1), "{1.001, 0.009} is element-wise close to {1, 1} in delta=0.1") - - True(t, InDeltaSlice(mockT, - []float64{1, 2}, - []float64{0, 3}, - 1), "{1, 2} is element-wise close to {0, 3} in delta=1") - - False(t, InDeltaSlice(mockT, - []float64{1, 2}, - []float64{0, 3}, - 0.1), "{1, 2} is not element-wise close to {0, 3} in delta=0.1") - - False(t, InDeltaSlice(mockT, "", nil, 1), "Expected non numeral slices to fail") -} - -func TestInEpsilon(t *testing.T) { - mockT := new(testing.T) - - cases := []struct { - a, b interface{} - epsilon float64 - }{ - {uint8(2), uint16(2), .001}, - {2.1, 2.2, 0.1}, - {2.2, 2.1, 0.1}, - {-2.1, -2.2, 0.1}, - {-2.2, -2.1, 0.1}, - {uint64(100), uint8(101), 0.01}, - {0.1, -0.1, 2}, - } - - for _, tc := range cases { - True(t, InEpsilon(mockT, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) - } - - cases = []struct { - a, b interface{} - epsilon float64 - }{ - {uint8(2), int16(-2), .001}, - {uint64(100), uint8(102), 0.01}, - {2.1, 2.2, 0.001}, - {2.2, 2.1, 0.001}, - {2.1, -2.2, 1}, - {2.1, "bla-bla", 0}, - {0.1, -0.1, 1.99}, - } - - for _, tc := range cases { - False(t, InEpsilon(mockT, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) - } - -} - -func TestInEpsilonSlice(t *testing.T) { - mockT := new(testing.T) - - True(t, InEpsilonSlice(mockT, - []float64{2.2, 2.0}, - []float64{2.1, 2.1}, - 0.06), "{2.2, 2.0} is element-wise close to {2.1, 2.1} in espilon=0.06") - - False(t, InEpsilonSlice(mockT, - []float64{2.2, 2.0}, - []float64{2.1, 2.1}, - 0.04), "{2.2, 2.0} is not element-wise close to {2.1, 2.1} in espilon=0.04") - - False(t, InEpsilonSlice(mockT, "", nil, 1), "Expected non numeral slices to fail") -} - -func TestRegexp(t *testing.T) { - mockT := new(testing.T) - - cases := []struct { - rx, str string - }{ - {"^start", "start of the line"}, - {"end$", "in the end"}, - {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"}, - } - - for _, tc := range cases { - True(t, Regexp(mockT, tc.rx, tc.str)) - True(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str)) - False(t, NotRegexp(mockT, tc.rx, tc.str)) - False(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str)) - } - - cases = []struct { - rx, str string - }{ - {"^asdfastart", "Not the start of the line"}, - {"end$", "in the end."}, - {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"}, - } - - for _, tc := range cases { - False(t, Regexp(mockT, tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str) - False(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str)) - True(t, NotRegexp(mockT, tc.rx, tc.str)) - True(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str)) - } -} - -func testAutogeneratedFunction() { - defer func() { - if err := recover(); err == nil { - panic("did not panic") - } - CallerInfo() - }() - t := struct { - io.Closer - }{} - var c io.Closer - c = t - c.Close() -} - -func TestCallerInfoWithAutogeneratedFunctions(t *testing.T) { - NotPanics(t, func() { - testAutogeneratedFunction() - }) -} - -func TestZero(t *testing.T) { - mockT := new(testing.T) - - for _, test := range zeros { - True(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test))) - } - - for _, test := range nonZeros { - False(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test))) - } -} - -func TestNotZero(t *testing.T) { - mockT := new(testing.T) - - for _, test := range zeros { - False(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test))) - } - - for _, test := range nonZeros { - True(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test))) - } -} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions_test.go deleted file mode 100644 index 280d0ab7c8b..00000000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions_test.go +++ /dev/null @@ -1,537 +0,0 @@ -package assert - -import ( - "errors" - "regexp" - "testing" - "time" -) - -func TestImplementsWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) { - t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface") - } - if assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) { - t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface") - } -} - -func TestIsTypeWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { - t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject") - } - if assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) { - t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject") - } - -} - -func TestEqualWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.Equal("Hello World", "Hello World") { - t.Error("Equal should return true") - } - if !assert.Equal(123, 123) { - t.Error("Equal should return true") - } - if !assert.Equal(123.5, 123.5) { - t.Error("Equal should return true") - } - if !assert.Equal([]byte("Hello World"), []byte("Hello World")) { - t.Error("Equal should return true") - } - if !assert.Equal(nil, nil) { - t.Error("Equal should return true") - } -} - -func TestEqualValuesWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.EqualValues(uint32(10), int32(10)) { - t.Error("EqualValues should return true") - } -} - -func TestNotNilWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.NotNil(new(AssertionTesterConformingObject)) { - t.Error("NotNil should return true: object is not nil") - } - if assert.NotNil(nil) { - t.Error("NotNil should return false: object is nil") - } - -} - -func TestNilWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.Nil(nil) { - t.Error("Nil should return true: object is nil") - } - if assert.Nil(new(AssertionTesterConformingObject)) { - t.Error("Nil should return false: object is not nil") - } - -} - -func TestTrueWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.True(true) { - t.Error("True should return true") - } - if assert.True(false) { - t.Error("True should return false") - } - -} - -func TestFalseWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.False(false) { - t.Error("False should return true") - } - if assert.False(true) { - t.Error("False should return false") - } - -} - -func TestExactlyWrapper(t *testing.T) { - assert := New(new(testing.T)) - - a := float32(1) - b := float64(1) - c := float32(1) - d := float32(2) - - if assert.Exactly(a, b) { - t.Error("Exactly should return false") - } - if assert.Exactly(a, d) { - t.Error("Exactly should return false") - } - if !assert.Exactly(a, c) { - t.Error("Exactly should return true") - } - - if assert.Exactly(nil, a) { - t.Error("Exactly should return false") - } - if assert.Exactly(a, nil) { - t.Error("Exactly should return false") - } - -} - -func TestNotEqualWrapper(t *testing.T) { - - assert := New(new(testing.T)) - - if !assert.NotEqual("Hello World", "Hello World!") { - t.Error("NotEqual should return true") - } - if !assert.NotEqual(123, 1234) { - t.Error("NotEqual should return true") - } - if !assert.NotEqual(123.5, 123.55) { - t.Error("NotEqual should return true") - } - if !assert.NotEqual([]byte("Hello World"), []byte("Hello World!")) { - t.Error("NotEqual should return true") - } - if !assert.NotEqual(nil, new(AssertionTesterConformingObject)) { - t.Error("NotEqual should return true") - } -} - -func TestContainsWrapper(t *testing.T) { - - assert := New(new(testing.T)) - list := []string{"Foo", "Bar"} - - if !assert.Contains("Hello World", "Hello") { - t.Error("Contains should return true: \"Hello World\" contains \"Hello\"") - } - if assert.Contains("Hello World", "Salut") { - t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"") - } - - if !assert.Contains(list, "Foo") { - t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") - } - if assert.Contains(list, "Salut") { - t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"") - } - -} - -func TestNotContainsWrapper(t *testing.T) { - - assert := New(new(testing.T)) - list := []string{"Foo", "Bar"} - - if !assert.NotContains("Hello World", "Hello!") { - t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"") - } - if assert.NotContains("Hello World", "Hello") { - t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"") - } - - if !assert.NotContains(list, "Foo!") { - t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"") - } - if assert.NotContains(list, "Foo") { - t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") - } - -} - -func TestConditionWrapper(t *testing.T) { - - assert := New(new(testing.T)) - - if !assert.Condition(func() bool { return true }, "Truth") { - t.Error("Condition should return true") - } - - if assert.Condition(func() bool { return false }, "Lie") { - t.Error("Condition should return false") - } - -} - -func TestDidPanicWrapper(t *testing.T) { - - if funcDidPanic, _ := didPanic(func() { - panic("Panic!") - }); !funcDidPanic { - t.Error("didPanic should return true") - } - - if funcDidPanic, _ := didPanic(func() { - }); funcDidPanic { - t.Error("didPanic should return false") - } - -} - -func TestPanicsWrapper(t *testing.T) { - - assert := New(new(testing.T)) - - if !assert.Panics(func() { - panic("Panic!") - }) { - t.Error("Panics should return true") - } - - if assert.Panics(func() { - }) { - t.Error("Panics should return false") - } - -} - -func TestNotPanicsWrapper(t *testing.T) { - - assert := New(new(testing.T)) - - if !assert.NotPanics(func() { - }) { - t.Error("NotPanics should return true") - } - - if assert.NotPanics(func() { - panic("Panic!") - }) { - t.Error("NotPanics should return false") - } - -} - -func TestNoErrorWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - // start with a nil error - var err error - - assert.True(mockAssert.NoError(err), "NoError should return True for nil arg") - - // now set an error - err = errors.New("Some error") - - assert.False(mockAssert.NoError(err), "NoError with error should return False") - -} - -func TestErrorWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - // start with a nil error - var err error - - assert.False(mockAssert.Error(err), "Error should return False for nil arg") - - // now set an error - err = errors.New("Some error") - - assert.True(mockAssert.Error(err), "Error with error should return True") - -} - -func TestEqualErrorWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - // start with a nil error - var err error - assert.False(mockAssert.EqualError(err, ""), - "EqualError should return false for nil arg") - - // now set an error - err = errors.New("some error") - assert.False(mockAssert.EqualError(err, "Not some error"), - "EqualError should return false for different error string") - assert.True(mockAssert.EqualError(err, "some error"), - "EqualError should return true") -} - -func TestEmptyWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - assert.True(mockAssert.Empty(""), "Empty string is empty") - assert.True(mockAssert.Empty(nil), "Nil is empty") - assert.True(mockAssert.Empty([]string{}), "Empty string array is empty") - assert.True(mockAssert.Empty(0), "Zero int value is empty") - assert.True(mockAssert.Empty(false), "False value is empty") - - assert.False(mockAssert.Empty("something"), "Non Empty string is not empty") - assert.False(mockAssert.Empty(errors.New("something")), "Non nil object is not empty") - assert.False(mockAssert.Empty([]string{"something"}), "Non empty string array is not empty") - assert.False(mockAssert.Empty(1), "Non-zero int value is not empty") - assert.False(mockAssert.Empty(true), "True value is not empty") - -} - -func TestNotEmptyWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - assert.False(mockAssert.NotEmpty(""), "Empty string is empty") - assert.False(mockAssert.NotEmpty(nil), "Nil is empty") - assert.False(mockAssert.NotEmpty([]string{}), "Empty string array is empty") - assert.False(mockAssert.NotEmpty(0), "Zero int value is empty") - assert.False(mockAssert.NotEmpty(false), "False value is empty") - - assert.True(mockAssert.NotEmpty("something"), "Non Empty string is not empty") - assert.True(mockAssert.NotEmpty(errors.New("something")), "Non nil object is not empty") - assert.True(mockAssert.NotEmpty([]string{"something"}), "Non empty string array is not empty") - assert.True(mockAssert.NotEmpty(1), "Non-zero int value is not empty") - assert.True(mockAssert.NotEmpty(true), "True value is not empty") - -} - -func TestLenWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - assert.False(mockAssert.Len(nil, 0), "nil does not have length") - assert.False(mockAssert.Len(0, 0), "int does not have length") - assert.False(mockAssert.Len(true, 0), "true does not have length") - assert.False(mockAssert.Len(false, 0), "false does not have length") - assert.False(mockAssert.Len('A', 0), "Rune does not have length") - assert.False(mockAssert.Len(struct{}{}, 0), "Struct does not have length") - - ch := make(chan int, 5) - ch <- 1 - ch <- 2 - ch <- 3 - - cases := []struct { - v interface{} - l int - }{ - {[]int{1, 2, 3}, 3}, - {[...]int{1, 2, 3}, 3}, - {"ABC", 3}, - {map[int]int{1: 2, 2: 4, 3: 6}, 3}, - {ch, 3}, - - {[]int{}, 0}, - {map[int]int{}, 0}, - {make(chan int), 0}, - - {[]int(nil), 0}, - {map[int]int(nil), 0}, - {(chan int)(nil), 0}, - } - - for _, c := range cases { - assert.True(mockAssert.Len(c.v, c.l), "%#v have %d items", c.v, c.l) - } -} - -func TestWithinDurationWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - a := time.Now() - b := a.Add(10 * time.Second) - - assert.True(mockAssert.WithinDuration(a, b, 10*time.Second), "A 10s difference is within a 10s time difference") - assert.True(mockAssert.WithinDuration(b, a, 10*time.Second), "A 10s difference is within a 10s time difference") - - assert.False(mockAssert.WithinDuration(a, b, 9*time.Second), "A 10s difference is not within a 9s time difference") - assert.False(mockAssert.WithinDuration(b, a, 9*time.Second), "A 10s difference is not within a 9s time difference") - - assert.False(mockAssert.WithinDuration(a, b, -9*time.Second), "A 10s difference is not within a 9s time difference") - assert.False(mockAssert.WithinDuration(b, a, -9*time.Second), "A 10s difference is not within a 9s time difference") - - assert.False(mockAssert.WithinDuration(a, b, -11*time.Second), "A 10s difference is not within a 9s time difference") - assert.False(mockAssert.WithinDuration(b, a, -11*time.Second), "A 10s difference is not within a 9s time difference") -} - -func TestInDeltaWrapper(t *testing.T) { - assert := New(new(testing.T)) - - True(t, assert.InDelta(1.001, 1, 0.01), "|1.001 - 1| <= 0.01") - True(t, assert.InDelta(1, 1.001, 0.01), "|1 - 1.001| <= 0.01") - True(t, assert.InDelta(1, 2, 1), "|1 - 2| <= 1") - False(t, assert.InDelta(1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail") - False(t, assert.InDelta(2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail") - False(t, assert.InDelta("", nil, 1), "Expected non numerals to fail") - - cases := []struct { - a, b interface{} - delta float64 - }{ - {uint8(2), uint8(1), 1}, - {uint16(2), uint16(1), 1}, - {uint32(2), uint32(1), 1}, - {uint64(2), uint64(1), 1}, - - {int(2), int(1), 1}, - {int8(2), int8(1), 1}, - {int16(2), int16(1), 1}, - {int32(2), int32(1), 1}, - {int64(2), int64(1), 1}, - - {float32(2), float32(1), 1}, - {float64(2), float64(1), 1}, - } - - for _, tc := range cases { - True(t, assert.InDelta(tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta) - } -} - -func TestInEpsilonWrapper(t *testing.T) { - assert := New(new(testing.T)) - - cases := []struct { - a, b interface{} - epsilon float64 - }{ - {uint8(2), uint16(2), .001}, - {2.1, 2.2, 0.1}, - {2.2, 2.1, 0.1}, - {-2.1, -2.2, 0.1}, - {-2.2, -2.1, 0.1}, - {uint64(100), uint8(101), 0.01}, - {0.1, -0.1, 2}, - } - - for _, tc := range cases { - True(t, assert.InEpsilon(tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) - } - - cases = []struct { - a, b interface{} - epsilon float64 - }{ - {uint8(2), int16(-2), .001}, - {uint64(100), uint8(102), 0.01}, - {2.1, 2.2, 0.001}, - {2.2, 2.1, 0.001}, - {2.1, -2.2, 1}, - {2.1, "bla-bla", 0}, - {0.1, -0.1, 1.99}, - } - - for _, tc := range cases { - False(t, assert.InEpsilon(tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) - } -} - -func TestRegexpWrapper(t *testing.T) { - - assert := New(new(testing.T)) - - cases := []struct { - rx, str string - }{ - {"^start", "start of the line"}, - {"end$", "in the end"}, - {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"}, - } - - for _, tc := range cases { - True(t, assert.Regexp(tc.rx, tc.str)) - True(t, assert.Regexp(regexp.MustCompile(tc.rx), tc.str)) - False(t, assert.NotRegexp(tc.rx, tc.str)) - False(t, assert.NotRegexp(regexp.MustCompile(tc.rx), tc.str)) - } - - cases = []struct { - rx, str string - }{ - {"^asdfastart", "Not the start of the line"}, - {"end$", "in the end."}, - {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"}, - } - - for _, tc := range cases { - False(t, assert.Regexp(tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str) - False(t, assert.Regexp(regexp.MustCompile(tc.rx), tc.str)) - True(t, assert.NotRegexp(tc.rx, tc.str)) - True(t, assert.NotRegexp(regexp.MustCompile(tc.rx), tc.str)) - } -} - -func TestZeroWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - for _, test := range zeros { - assert.True(mockAssert.Zero(test), "Zero should return true for %v", test) - } - - for _, test := range nonZeros { - assert.False(mockAssert.Zero(test), "Zero should return false for %v", test) - } -} - -func TestNotZeroWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - for _, test := range zeros { - assert.False(mockAssert.NotZero(test), "Zero should return true for %v", test) - } - - for _, test := range nonZeros { - assert.True(mockAssert.NotZero(test), "Zero should return false for %v", test) - } -} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions_test.go deleted file mode 100644 index 684c2d5d1c5..00000000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package assert - -import ( - "fmt" - "net/http" - "net/url" - "testing" -) - -func httpOK(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) -} - -func httpRedirect(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusTemporaryRedirect) -} - -func httpError(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusInternalServerError) -} - -func TestHTTPStatuses(t *testing.T) { - assert := New(t) - mockT := new(testing.T) - - assert.Equal(HTTPSuccess(mockT, httpOK, "GET", "/", nil), true) - assert.Equal(HTTPSuccess(mockT, httpRedirect, "GET", "/", nil), false) - assert.Equal(HTTPSuccess(mockT, httpError, "GET", "/", nil), false) - - assert.Equal(HTTPRedirect(mockT, httpOK, "GET", "/", nil), false) - assert.Equal(HTTPRedirect(mockT, httpRedirect, "GET", "/", nil), true) - assert.Equal(HTTPRedirect(mockT, httpError, "GET", "/", nil), false) - - assert.Equal(HTTPError(mockT, httpOK, "GET", "/", nil), false) - assert.Equal(HTTPError(mockT, httpRedirect, "GET", "/", nil), false) - assert.Equal(HTTPError(mockT, httpError, "GET", "/", nil), true) -} - -func TestHTTPStatusesWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - assert.Equal(mockAssert.HTTPSuccess(httpOK, "GET", "/", nil), true) - assert.Equal(mockAssert.HTTPSuccess(httpRedirect, "GET", "/", nil), false) - assert.Equal(mockAssert.HTTPSuccess(httpError, "GET", "/", nil), false) - - assert.Equal(mockAssert.HTTPRedirect(httpOK, "GET", "/", nil), false) - assert.Equal(mockAssert.HTTPRedirect(httpRedirect, "GET", "/", nil), true) - assert.Equal(mockAssert.HTTPRedirect(httpError, "GET", "/", nil), false) - - assert.Equal(mockAssert.HTTPError(httpOK, "GET", "/", nil), false) - assert.Equal(mockAssert.HTTPError(httpRedirect, "GET", "/", nil), false) - assert.Equal(mockAssert.HTTPError(httpError, "GET", "/", nil), true) -} - -func httpHelloName(w http.ResponseWriter, r *http.Request) { - name := r.FormValue("name") - w.Write([]byte(fmt.Sprintf("Hello, %s!", name))) -} - -func TestHttpBody(t *testing.T) { - assert := New(t) - mockT := new(testing.T) - - assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) - assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) - assert.False(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) - - assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) - assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) - assert.True(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) -} - -func TestHttpBodyWrappers(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) - assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) - assert.False(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) - - assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) - assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) - assert.True(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) - -} diff --git a/Godeps/_workspace/src/github.com/tsg/gopacket/afpacket/afpacket_test.go b/Godeps/_workspace/src/github.com/tsg/gopacket/afpacket/afpacket_test.go deleted file mode 100644 index 57f6480d548..00000000000 --- a/Godeps/_workspace/src/github.com/tsg/gopacket/afpacket/afpacket_test.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2012 Google, Inc. All rights reserved. -// -// Use of this source code is governed by a BSD-style license -// that can be found in the LICENSE file in the root of the source -// tree. - -// +build linux - -package afpacket - -import ( - "reflect" - "testing" -) - -func TestParseOptions(t *testing.T) { - wanted1 := defaultOpts - wanted1.frameSize = 1 << 10 - wanted1.framesPerBlock = wanted1.blockSize / wanted1.frameSize - for i, test := range []struct { - opts []interface{} - want options - err bool - }{ - {opts: []interface{}{OptBlockSize(2)}, err: true}, - {opts: []interface{}{OptFrameSize(333)}, err: true}, - {opts: []interface{}{OptTPacketVersion(-3)}, err: true}, - {opts: []interface{}{OptTPacketVersion(5)}, err: true}, - {opts: []interface{}{OptFrameSize(1 << 10)}, want: wanted1}, - } { - got, err := parseOptions(test.opts...) - t.Logf("got: %#v\nerr: %v", got, err) - if test.err && err == nil || !test.err && err != nil { - t.Errorf("%d error mismatch, want error? %v. error: %v", i, test.err, err) - } - if !test.err && !reflect.DeepEqual(test.want, got) { - t.Errorf("%d opts mismatch, want\n%#v", i, test.want) - } - } -} diff --git a/Godeps/_workspace/src/github.com/tsg/gopacket/benchmark_test.go b/Godeps/_workspace/src/github.com/tsg/gopacket/benchmark_test.go deleted file mode 100644 index 74a1d28dfe4..00000000000 --- a/Godeps/_workspace/src/github.com/tsg/gopacket/benchmark_test.go +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright 2012, Google, Inc. All rights reserved. -// -// Use of this source code is governed by a BSD-style license -// that can be found in the LICENSE file in the root of the source -// tree. - -package gopacket - -import ( - "runtime" - "testing" -) - -// A few benchmarks for figuring out exactly how fast some underlying Go -// things are. - -type testError struct{} - -func (t *testError) Error() string { return "abc" } - -func BenchmarkTypeAssertion(b *testing.B) { - var e error = &testError{} - for i := 0; i < b.N; i++ { - _, _ = e.(*testError) - } -} - -func BenchmarkMapLookup(b *testing.B) { - m := map[LayerType]bool{ - LayerTypePayload: true, - } - for i := 0; i < b.N; i++ { - _ = m[LayerTypePayload] - } -} - -func BenchmarkNilMapLookup(b *testing.B) { - var m map[LayerType]bool - for i := 0; i < b.N; i++ { - _ = m[LayerTypePayload] - } -} - -func BenchmarkNilMapLookupWithNilCheck(b *testing.B) { - var m map[LayerType]bool - for i := 0; i < b.N; i++ { - if m != nil { - _ = m[LayerTypePayload] - } - } -} - -func BenchmarkArrayLookup(b *testing.B) { - m := make([]bool, 100) - for i := 0; i < b.N; i++ { - _ = m[LayerTypePayload] - } -} - -var testError1 = &testError{} -var testError2 error = testError1 - -func BenchmarkTypeToInterface1(b *testing.B) { - var e error - for i := 0; i < b.N; i++ { - e = testError1 - } - // Have to do someting with 'e' or the compiler complains about an unused - // variable. - testError2 = e -} -func BenchmarkTypeToInterface2(b *testing.B) { - var e error - for i := 0; i < b.N; i++ { - e = testError2 - } - // Have to do someting with 'e' or the compiler complains about an unused - // variable. - testError2 = e -} - -var decodeOpts DecodeOptions - -func decodeOptsByValue(_ DecodeOptions) {} -func decodeOptsByPointer(_ *DecodeOptions) {} -func BenchmarkPassDecodeOptionsByValue(b *testing.B) { - for i := 0; i < b.N; i++ { - decodeOptsByValue(decodeOpts) - } -} -func BenchmarkPassDecodeOptionsByPointer(b *testing.B) { - for i := 0; i < b.N; i++ { - decodeOptsByPointer(&decodeOpts) - } -} - -func BenchmarkLockOSThread(b *testing.B) { - for i := 0; i < b.N; i++ { - runtime.LockOSThread() - } -} -func BenchmarkUnlockOSThread(b *testing.B) { - for i := 0; i < b.N; i++ { - runtime.UnlockOSThread() - } -} -func lockUnlock() { - runtime.LockOSThread() - runtime.UnlockOSThread() -} -func lockDeferUnlock() { - runtime.LockOSThread() - defer runtime.UnlockOSThread() -} -func BenchmarkLockUnlockOSThread(b *testing.B) { - for i := 0; i < b.N; i++ { - lockUnlock() - } -} -func BenchmarkLockDeferUnlockOSThread(b *testing.B) { - for i := 0; i < b.N; i++ { - lockDeferUnlock() - } -} - -func BenchmarkUnbufferedChannel(b *testing.B) { - ca := make(chan bool) - cb := make(chan bool) - defer close(ca) - go func() { - defer close(cb) - for _ = range ca { - cb <- true - } - }() - for i := 0; i < b.N; i++ { - ca <- true - <-cb - } -} -func BenchmarkSmallBufferedChannel(b *testing.B) { - ca := make(chan bool, 1) - cb := make(chan bool, 1) - defer close(ca) - go func() { - defer close(cb) - for _ = range ca { - cb <- true - } - }() - for i := 0; i < b.N; i++ { - ca <- true - <-cb - } -} -func BenchmarkLargeBufferedChannel(b *testing.B) { - ca := make(chan bool, 1000) - cb := make(chan bool, 1000) - defer close(ca) - go func() { - defer close(cb) - for _ = range ca { - cb <- true - } - }() - for i := 0; i < b.N; i++ { - ca <- true - <-cb - } -} -func BenchmarkEndpointFastHashShort(b *testing.B) { - e := Endpoint{typ: 1, len: 2} - for i := 0; i < b.N; i++ { - e.FastHash() - } -} -func BenchmarkEndpointFastHashLong(b *testing.B) { - e := Endpoint{typ: 1, len: 16} - for i := 0; i < b.N; i++ { - e.FastHash() - } -} -func BenchmarkFlowFastHashShort(b *testing.B) { - e := Flow{typ: 1, slen: 2, dlen: 2} - for i := 0; i < b.N; i++ { - e.FastHash() - } -} -func BenchmarkFlowFastHashLong(b *testing.B) { - e := Flow{typ: 1, slen: 16, dlen: 16} - for i := 0; i < b.N; i++ { - e.FastHash() - } -} diff --git a/Godeps/_workspace/src/github.com/tsg/gopacket/bytediff/bytediff_test.go b/Godeps/_workspace/src/github.com/tsg/gopacket/bytediff/bytediff_test.go deleted file mode 100644 index 022ad4bc5ef..00000000000 --- a/Godeps/_workspace/src/github.com/tsg/gopacket/bytediff/bytediff_test.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2012 Google, Inc. All rights reserved. -// -// Use of this source code is governed by a BSD-style license -// that can be found in the LICENSE file in the root of the source -// tree. - -package bytediff - -import ( - "reflect" - "testing" -) - -func TestLCS(t *testing.T) { - for i, test := range []struct { - a, b []byte - indexA, indexB, length int - }{ - {[]byte{1, 2, 3}, []byte{1, 2, 3}, 0, 0, 3}, - {[]byte{0, 1, 2, 3}, []byte{1, 2, 3, 4}, 1, 0, 3}, - {[]byte{0, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3}, []byte{1, 2, 3, 4}, 4, 0, 4}, - {[]byte{1, 2, 2, 3, 4}, []byte{1, 2, 3, 4}, 2, 1, 3}, - {[]byte{0, 1, 2, 3, 4}, []byte{1, 1, 2, 2, 3, 4}, 2, 3, 3}, - } { - ia, ib, l := longestCommonSubstring(test.a, test.b) - if ia != test.indexA || ib != test.indexB || l != test.length { - t.Errorf("%d: want (%d %d %d) got (%d %d %d)", i, test.indexA, test.indexB, test.length, ia, ib, l) - } - } -} - -func TestDiff(t *testing.T) { - for i, test := range []struct { - a, b []byte - d Differences - }{ - { - []byte{0, 1, 2, 3, 4}, - []byte{1, 1, 2, 2, 3, 4}, - Differences{ - Difference{true, []byte{0}, []byte{}}, - Difference{false, []byte{1}, []byte{1}}, - Difference{true, []byte{}, []byte{1, 2}}, - Difference{false, []byte{2, 3, 4}, []byte{2, 3, 4}}, - }, - }, - } { - diffs := Diff(test.a, test.b) - if !reflect.DeepEqual(diffs, test.d) { - t.Errorf("%d want %v got %v", i, test.d, diffs) - } - } -} diff --git a/Godeps/_workspace/src/github.com/tsg/gopacket/layers/base_test.go b/Godeps/_workspace/src/github.com/tsg/gopacket/layers/base_test.go deleted file mode 100644 index f67e26f78df..00000000000 --- a/Godeps/_workspace/src/github.com/tsg/gopacket/layers/base_test.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2012, Google, Inc. All rights reserved. -// -// Use of this source code is governed by a BSD-style license -// that can be found in the LICENSE file in the root of the source -// tree. - -// This file contains some test helper functions. - -package layers - -import ( - "github.com/tsg/gopacket" - "testing" -) - -func min(a, b int) int { - if a < b { - return a - } - return b -} - -func checkLayers(p gopacket.Packet, want []gopacket.LayerType, t *testing.T) { - layers := p.Layers() - t.Log("Checking packet layers, want", want) - for _, l := range layers { - t.Logf(" Got layer %v, %d bytes, payload of %d bytes", l.LayerType(), - len(l.LayerContents()), len(l.LayerPayload())) - } - t.Log(p) - if len(layers) != len(want) { - t.Errorf(" Number of layers mismatch: got %d want %d", len(layers), - len(want)) - return - } - for i, l := range layers { - if l.LayerType() != want[i] { - t.Errorf(" Layer %d mismatch: got %v want %v", i, l.LayerType(), - want[i]) - } - } -} diff --git a/Godeps/_workspace/src/github.com/tsg/gopacket/layers/decode_test.go b/Godeps/_workspace/src/github.com/tsg/gopacket/layers/decode_test.go deleted file mode 100644 index 25d652d9bc8..00000000000 --- a/Godeps/_workspace/src/github.com/tsg/gopacket/layers/decode_test.go +++ /dev/null @@ -1,1243 +0,0 @@ -// Copyright 2012, Google, Inc. All rights reserved. -// Copyright 2009-2011 Andreas Krennmair. All rights reserved. -// -// Use of this source code is governed by a BSD-style license -// that can be found in the LICENSE file in the root of the source -// tree. - -package layers - -import ( - "bytes" - "encoding/hex" - "fmt" - "github.com/tsg/gopacket" - "github.com/tsg/gopacket/bytediff" - "net" - "reflect" - "strings" - "testing" -) - -var testSimpleTCPPacket []byte = []byte{ - 0x00, 0x00, 0x0c, 0x9f, 0xf0, 0x20, 0xbc, 0x30, 0x5b, 0xe8, 0xd3, 0x49, - 0x08, 0x00, 0x45, 0x00, 0x01, 0xa4, 0x39, 0xdf, 0x40, 0x00, 0x40, 0x06, - 0x55, 0x5a, 0xac, 0x11, 0x51, 0x49, 0xad, 0xde, 0xfe, 0xe1, 0xc5, 0xf7, - 0x00, 0x50, 0xc5, 0x7e, 0x0e, 0x48, 0x49, 0x07, 0x42, 0x32, 0x80, 0x18, - 0x00, 0x73, 0x9a, 0x8f, 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x03, 0x77, - 0x37, 0x9c, 0x42, 0x77, 0x5e, 0x3a, 0x47, 0x45, 0x54, 0x20, 0x2f, 0x20, - 0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31, 0x0d, 0x0a, 0x48, 0x6f, - 0x73, 0x74, 0x3a, 0x20, 0x77, 0x77, 0x77, 0x2e, 0x66, 0x69, 0x73, 0x68, - 0x2e, 0x63, 0x6f, 0x6d, 0x0d, 0x0a, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, - 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x6b, 0x65, 0x65, 0x70, 0x2d, 0x61, - 0x6c, 0x69, 0x76, 0x65, 0x0d, 0x0a, 0x55, 0x73, 0x65, 0x72, 0x2d, 0x41, - 0x67, 0x65, 0x6e, 0x74, 0x3a, 0x20, 0x4d, 0x6f, 0x7a, 0x69, 0x6c, 0x6c, - 0x61, 0x2f, 0x35, 0x2e, 0x30, 0x20, 0x28, 0x58, 0x31, 0x31, 0x3b, 0x20, - 0x4c, 0x69, 0x6e, 0x75, 0x78, 0x20, 0x78, 0x38, 0x36, 0x5f, 0x36, 0x34, - 0x29, 0x20, 0x41, 0x70, 0x70, 0x6c, 0x65, 0x57, 0x65, 0x62, 0x4b, 0x69, - 0x74, 0x2f, 0x35, 0x33, 0x35, 0x2e, 0x32, 0x20, 0x28, 0x4b, 0x48, 0x54, - 0x4d, 0x4c, 0x2c, 0x20, 0x6c, 0x69, 0x6b, 0x65, 0x20, 0x47, 0x65, 0x63, - 0x6b, 0x6f, 0x29, 0x20, 0x43, 0x68, 0x72, 0x6f, 0x6d, 0x65, 0x2f, 0x31, - 0x35, 0x2e, 0x30, 0x2e, 0x38, 0x37, 0x34, 0x2e, 0x31, 0x32, 0x31, 0x20, - 0x53, 0x61, 0x66, 0x61, 0x72, 0x69, 0x2f, 0x35, 0x33, 0x35, 0x2e, 0x32, - 0x0d, 0x0a, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x3a, 0x20, 0x74, 0x65, - 0x78, 0x74, 0x2f, 0x68, 0x74, 0x6d, 0x6c, 0x2c, 0x61, 0x70, 0x70, 0x6c, - 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x78, 0x68, 0x74, 0x6d, - 0x6c, 0x2b, 0x78, 0x6d, 0x6c, 0x2c, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, - 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x78, 0x6d, 0x6c, 0x3b, 0x71, 0x3d, - 0x30, 0x2e, 0x39, 0x2c, 0x2a, 0x2f, 0x2a, 0x3b, 0x71, 0x3d, 0x30, 0x2e, - 0x38, 0x0d, 0x0a, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x45, 0x6e, - 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x3a, 0x20, 0x67, 0x7a, 0x69, 0x70, - 0x2c, 0x64, 0x65, 0x66, 0x6c, 0x61, 0x74, 0x65, 0x2c, 0x73, 0x64, 0x63, - 0x68, 0x0d, 0x0a, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x4c, 0x61, - 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x3a, 0x20, 0x65, 0x6e, 0x2d, 0x55, - 0x53, 0x2c, 0x65, 0x6e, 0x3b, 0x71, 0x3d, 0x30, 0x2e, 0x38, 0x0d, 0x0a, - 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x43, 0x68, 0x61, 0x72, 0x73, - 0x65, 0x74, 0x3a, 0x20, 0x49, 0x53, 0x4f, 0x2d, 0x38, 0x38, 0x35, 0x39, - 0x2d, 0x31, 0x2c, 0x75, 0x74, 0x66, 0x2d, 0x38, 0x3b, 0x71, 0x3d, 0x30, - 0x2e, 0x37, 0x2c, 0x2a, 0x3b, 0x71, 0x3d, 0x30, 0x2e, 0x33, 0x0d, 0x0a, - 0x0d, 0x0a, -} - -var testDecodeOptions = gopacket.DecodeOptions{ - SkipDecodeRecovery: true, -} - -type nilDecodeFeedback struct{} - -func (n *nilDecodeFeedback) SetTruncated() {} - -// Benchmarks for actual gopacket code - -func BenchmarkLayerClassSliceContains(b *testing.B) { - lc := gopacket.NewLayerClassSlice([]gopacket.LayerType{LayerTypeTCP, LayerTypeEthernet}) - for i := 0; i < b.N; i++ { - _ = lc.Contains(LayerTypeTCP) - } -} - -func BenchmarkLayerClassMapContains(b *testing.B) { - lc := gopacket.NewLayerClassMap([]gopacket.LayerType{LayerTypeTCP, LayerTypeEthernet}) - for i := 0; i < b.N; i++ { - _ = lc.Contains(LayerTypeTCP) - } -} - -func BenchmarkLazyNoCopyEthLayer(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testSimpleTCPPacket, LinkTypeEthernet, gopacket.DecodeOptions{Lazy: true, NoCopy: true}).Layer(LayerTypeEthernet) - } -} - -func BenchmarkLazyNoCopyIPLayer(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testSimpleTCPPacket, LinkTypeEthernet, gopacket.DecodeOptions{Lazy: true, NoCopy: true}).Layer(LayerTypeIPv4) - } -} - -func BenchmarkLazyNoCopyTCPLayer(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testSimpleTCPPacket, LinkTypeEthernet, gopacket.DecodeOptions{Lazy: true, NoCopy: true}).Layer(LayerTypeTCP) - } -} - -func BenchmarkLazyNoCopyAllLayers(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testSimpleTCPPacket, LinkTypeEthernet, gopacket.DecodeOptions{Lazy: true, NoCopy: true}).Layers() - } -} - -func BenchmarkDefault(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testSimpleTCPPacket, LinkTypeEthernet, gopacket.Default) - } -} - -func getSerializeLayers() []gopacket.SerializableLayer { - p := gopacket.NewPacket(testSimpleTCPPacket, LinkTypeEthernet, testDecodeOptions) - slayers := []gopacket.SerializableLayer{} - for _, l := range p.Layers() { - slayers = append(slayers, l.(gopacket.SerializableLayer)) - } - p.Layer(LayerTypeTCP).(*TCP).SetNetworkLayerForChecksum( - p.NetworkLayer()) - return slayers -} - -func BenchmarkSerializeTcpNoOptions(b *testing.B) { - slayers := getSerializeLayers() - buf := gopacket.NewSerializeBuffer() - opts := gopacket.SerializeOptions{} - for i := 0; i < b.N; i++ { - gopacket.SerializeLayers(buf, opts, slayers...) - } -} - -func BenchmarkSerializeTcpFixLengths(b *testing.B) { - slayers := getSerializeLayers() - buf := gopacket.NewSerializeBuffer() - opts := gopacket.SerializeOptions{FixLengths: true} - for i := 0; i < b.N; i++ { - gopacket.SerializeLayers(buf, opts, slayers...) - } -} - -func BenchmarkSerializeTcpComputeChecksums(b *testing.B) { - slayers := getSerializeLayers() - buf := gopacket.NewSerializeBuffer() - opts := gopacket.SerializeOptions{ComputeChecksums: true} - for i := 0; i < b.N; i++ { - gopacket.SerializeLayers(buf, opts, slayers...) - } -} - -func BenchmarkSerializeTcpFixLengthsComputeChecksums(b *testing.B) { - slayers := getSerializeLayers() - buf := gopacket.NewSerializeBuffer() - opts := gopacket.SerializeOptions{FixLengths: true, ComputeChecksums: true} - for i := 0; i < b.N; i++ { - gopacket.SerializeLayers(buf, opts, slayers...) - } -} - -func BenchmarkLazy(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testSimpleTCPPacket, LinkTypeEthernet, gopacket.Lazy) - } -} - -func BenchmarkNoCopy(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testSimpleTCPPacket, LinkTypeEthernet, gopacket.NoCopy) - } -} - -func BenchmarkLazyNoCopy(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testSimpleTCPPacket, LinkTypeEthernet, gopacket.DecodeOptions{Lazy: true, NoCopy: true}) - } -} - -func BenchmarkKnownStack(b *testing.B) { - stack := []gopacket.DecodingLayer{&Ethernet{}, &IPv4{}, &TCP{}, &gopacket.Payload{}} - var nf gopacket.DecodeFeedback = &nilDecodeFeedback{} - for i := 0; i < b.N; i++ { - data := testSimpleTCPPacket[:] - for _, d := range stack { - _ = d.DecodeFromBytes(data, nf) - data = d.LayerPayload() - } - } -} - -func BenchmarkDecodingLayerParserIgnorePanic(b *testing.B) { - decoded := make([]gopacket.LayerType, 0, 20) - dlp := gopacket.NewDecodingLayerParser(LayerTypeEthernet, &Ethernet{}, &IPv4{}, &TCP{}, &gopacket.Payload{}) - dlp.IgnorePanic = true - for i := 0; i < b.N; i++ { - dlp.DecodeLayers(testSimpleTCPPacket, &decoded) - } -} - -func BenchmarkDecodingLayerParserHandlePanic(b *testing.B) { - decoded := make([]gopacket.LayerType, 0, 20) - dlp := gopacket.NewDecodingLayerParser(LayerTypeEthernet, &Ethernet{}, &IPv4{}, &TCP{}, &gopacket.Payload{}) - dlp.IgnorePanic = false - for i := 0; i < b.N; i++ { - dlp.DecodeLayers(testSimpleTCPPacket, &decoded) - } -} - -func BenchmarkAlloc(b *testing.B) { - for i := 0; i < b.N; i++ { - _ = &TCP{} - } -} - -func BenchmarkFlow(b *testing.B) { - p := gopacket.NewPacket(testSimpleTCPPacket, LinkTypeEthernet, gopacket.DecodeOptions{Lazy: true, NoCopy: true}) - net := p.NetworkLayer() - for i := 0; i < b.N; i++ { - net.NetworkFlow() - } -} - -func BenchmarkEndpoints(b *testing.B) { - p := gopacket.NewPacket(testSimpleTCPPacket, LinkTypeEthernet, gopacket.DecodeOptions{Lazy: true, NoCopy: true}) - flow := p.NetworkLayer().NetworkFlow() - for i := 0; i < b.N; i++ { - flow.Endpoints() - } -} - -func BenchmarkTCPLayerFromDecodedPacket(b *testing.B) { - b.StopTimer() - p := gopacket.NewPacket(testSimpleTCPPacket, LinkTypeEthernet, testDecodeOptions) - b.StartTimer() - for i := 0; i < b.N; i++ { - _ = p.Layer(LayerTypeTCP) - } -} - -func BenchmarkTCPLayerClassFromDecodedPacket(b *testing.B) { - b.StopTimer() - p := gopacket.NewPacket(testSimpleTCPPacket, LinkTypeEthernet, testDecodeOptions) - lc := gopacket.NewLayerClass([]gopacket.LayerType{LayerTypeTCP}) - b.StartTimer() - for i := 0; i < b.N; i++ { - _ = p.LayerClass(lc) - } -} - -func BenchmarkTCPTransportLayerFromDecodedPacket(b *testing.B) { - b.StopTimer() - p := gopacket.NewPacket(testSimpleTCPPacket, LinkTypeEthernet, testDecodeOptions) - b.StartTimer() - for i := 0; i < b.N; i++ { - _ = p.TransportLayer() - } -} - -func testDecoder([]byte, gopacket.PacketBuilder) error { - return nil -} - -func BenchmarkDecodeFuncCallOverheadDirectCall(b *testing.B) { - var data []byte - var pb gopacket.PacketBuilder - for i := 0; i < b.N; i++ { - _ = testDecoder(data, pb) - } -} - -func BenchmarkDecodeFuncCallOverheadDecoderCall(b *testing.B) { - d := gopacket.DecodeFunc(testDecoder) - var data []byte - var pb gopacket.PacketBuilder - for i := 0; i < b.N; i++ { - _ = d.Decode(data, pb) - } -} - -func BenchmarkDecodeFuncCallOverheadArrayCall(b *testing.B) { - EthernetTypeMetadata[1] = EnumMetadata{DecodeWith: gopacket.DecodeFunc(testDecoder)} - d := EthernetType(1) - var data []byte - var pb gopacket.PacketBuilder - for i := 0; i < b.N; i++ { - _ = d.Decode(data, pb) - } -} - -func BenchmarkFmtVerboseString(b *testing.B) { - b.StopTimer() - p := gopacket.NewPacket(testSimpleTCPPacket, LinkTypeEthernet, testDecodeOptions) - b.StartTimer() - for i := 0; i < b.N; i++ { - fmt.Sprintf("%#v", p) - } -} - -func BenchmarkPacketString(b *testing.B) { - b.StopTimer() - p := gopacket.NewPacket(testSimpleTCPPacket, LinkTypeEthernet, testDecodeOptions) - b.StartTimer() - for i := 0; i < b.N; i++ { - p.String() - } -} - -func BenchmarkPacketDumpString(b *testing.B) { - b.StopTimer() - p := gopacket.NewPacket(testSimpleTCPPacket, LinkTypeEthernet, testDecodeOptions) - b.StartTimer() - for i := 0; i < b.N; i++ { - p.String() - } -} - -// TestFlowMapKey makes sure a flow and an endpoint can be used as map keys. -func TestFlowMapKey(t *testing.T) { - _ = map[gopacket.Flow]bool{} - _ = map[gopacket.Endpoint]bool{} - _ = map[[2]gopacket.Flow]bool{} -} - -func TestDecodeSimpleTCPPacket(t *testing.T) { - equal := func(desc, want string, got fmt.Stringer) { - if want != got.String() { - t.Errorf("%s: got %q want %q", desc, got.String(), want) - } - } - p := gopacket.NewPacket(testSimpleTCPPacket, LinkTypeEthernet, gopacket.DecodeOptions{Lazy: true, NoCopy: true}) - if eth := p.LinkLayer(); eth == nil { - t.Error("No ethernet layer found") - } else { - equal("Eth Src", "bc:30:5b:e8:d3:49", eth.LinkFlow().Src()) - equal("Eth Dst", "00:00:0c:9f:f0:20", eth.LinkFlow().Dst()) - } - if net := p.NetworkLayer(); net == nil { - t.Error("No net layer found") - } else if ip, ok := net.(*IPv4); !ok { - t.Error("Net layer is not IP layer") - } else { - equal("IP Src", "172.17.81.73", net.NetworkFlow().Src()) - equal("IP Dst", "173.222.254.225", net.NetworkFlow().Dst()) - want := &IPv4{ - BaseLayer: BaseLayer{testSimpleTCPPacket[14:34], testSimpleTCPPacket[34:]}, - Version: 4, - IHL: 5, - TOS: 0, - Length: 420, - Id: 14815, - Flags: 0x02, - FragOffset: 0, - TTL: 64, - Protocol: 6, - Checksum: 0x555A, - SrcIP: []byte{172, 17, 81, 73}, - DstIP: []byte{173, 222, 254, 225}, - } - if !reflect.DeepEqual(ip, want) { - t.Errorf("IP layer mismatch, \ngot %#v\nwant %#v\n", ip, want) - } - } - if trans := p.TransportLayer(); trans == nil { - t.Error("No transport layer found") - } else if tcp, ok := trans.(*TCP); !ok { - t.Error("Transport layer is not TCP layer") - } else { - equal("TCP Src", "50679", trans.TransportFlow().Src()) - equal("TCP Dst", "80", trans.TransportFlow().Dst()) - want := &TCP{ - BaseLayer: BaseLayer{testSimpleTCPPacket[34:66], testSimpleTCPPacket[66:]}, - SrcPort: 50679, - DstPort: 80, - Seq: 0xc57e0e48, - Ack: 0x49074232, - DataOffset: 8, - ACK: true, - PSH: true, - Window: 0x73, - Checksum: 0x9a8f, - Urgent: 0, - sPort: []byte{0xc5, 0xf7}, - dPort: []byte{0x0, 0x50}, - Options: []TCPOption{ - TCPOption{ - OptionType: 0x1, - OptionLength: 0x1, - }, - TCPOption{ - OptionType: 0x1, - OptionLength: 0x1, - }, - TCPOption{ - OptionType: 0x8, - OptionLength: 0xa, - OptionData: []byte{0x3, 0x77, 0x37, 0x9c, 0x42, 0x77, 0x5e, 0x3a}, - }, - }, - opts: [4]TCPOption{ - TCPOption{ - OptionType: 0x1, - OptionLength: 0x1, - }, - TCPOption{ - OptionType: 0x1, - OptionLength: 0x1, - }, - TCPOption{ - OptionType: 0x8, - OptionLength: 0xa, - OptionData: []byte{0x3, 0x77, 0x37, 0x9c, 0x42, 0x77, 0x5e, 0x3a}, - }, - TCPOption{}, - }, - } - if !reflect.DeepEqual(tcp, want) { - t.Errorf("TCP layer mismatch\ngot %#v\nwant %#v", tcp, want) - } - } - if payload, ok := p.Layer(gopacket.LayerTypePayload).(*gopacket.Payload); payload == nil || !ok { - t.Error("No payload layer found") - } else { - if string(payload.Payload()) != "GET / HTTP/1.1\r\nHost: www.fish.com\r\nConnection: keep-alive\r\nUser-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Encoding: gzip,deflate,sdch\r\nAccept-Language: en-US,en;q=0.8\r\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\r\n\r\n" { - t.Error("--- Payload STRING ---\n", string(payload.Payload()), "\n--- Payload BYTES ---\n", payload.Payload()) - } - } - - // Test re-serialization. - testSerialization(t, p, testSimpleTCPPacket) -} - -type canSetNetLayer interface { - SetNetworkLayerForChecksum(gopacket.NetworkLayer) error -} - -func testSerialization(t *testing.T, p gopacket.Packet, data []byte) { - for _, opts := range []gopacket.SerializeOptions{ - gopacket.SerializeOptions{}, - gopacket.SerializeOptions{FixLengths: true}, - gopacket.SerializeOptions{ComputeChecksums: true}, - gopacket.SerializeOptions{FixLengths: true, ComputeChecksums: true}, - } { - testSerializationWithOpts(t, p, data, opts) - } -} - -func testSerializationWithOpts(t *testing.T, p gopacket.Packet, data []byte, opts gopacket.SerializeOptions) { - // Test re-serialization. - slayers := []gopacket.SerializableLayer{} - for _, l := range p.Layers() { - slayers = append(slayers, l.(gopacket.SerializableLayer)) - if h, ok := l.(canSetNetLayer); ok { - if err := h.SetNetworkLayerForChecksum(p.NetworkLayer()); err != nil { - t.Fatal("can't set network layer:", err) - } - } - } - buf := gopacket.NewSerializeBuffer() - err := gopacket.SerializeLayers(buf, opts, slayers...) - if err != nil { - t.Errorf("unable to reserialize layers with opts %#v: %v", opts, err) - } else if !bytes.Equal(buf.Bytes(), data) { - t.Errorf("serialization failure with opts %#v:\n---want---\n%v\n---got---\n%v\nBASH-colorized diff, want->got:\n%v\n\n---PACKET---\n%v", - opts, hex.Dump(data), hex.Dump(buf.Bytes()), bytediff.BashOutput.String(bytediff.Diff(data, buf.Bytes())), p) - } -} - -// Makes sure packet payload doesn't display the 6 trailing null of this packet -// as part of the payload. They're actually the ethernet trailer. -func TestDecodeSmallTCPPacketHasEmptyPayload(t *testing.T) { - smallPacket := []byte{ - 0xbc, 0x30, 0x5b, 0xe8, 0xd3, 0x49, 0xb8, 0xac, 0x6f, 0x92, 0xd5, 0xbf, - 0x08, 0x00, 0x45, 0x00, 0x00, 0x28, 0x00, 0x00, 0x40, 0x00, 0x40, 0x06, - 0x3f, 0x9f, 0xac, 0x11, 0x51, 0xc5, 0xac, 0x11, 0x51, 0x49, 0x00, 0x63, - 0x9a, 0xef, 0x00, 0x00, 0x00, 0x00, 0x2e, 0xc1, 0x27, 0x83, 0x50, 0x14, - 0x00, 0x00, 0xc3, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - } - p := gopacket.NewPacket(smallPacket, LinkTypeEthernet, testDecodeOptions) - - if payload := p.Layer(gopacket.LayerTypePayload); payload != nil { - t.Error("Payload found for empty TCP packet") - } - - testSerialization(t, p, smallPacket) -} - -func TestDecodeVLANPacket(t *testing.T) { - p := gopacket.NewPacket( - []byte{ - 0x00, 0x10, 0xdb, 0xff, 0x10, 0x00, 0x00, 0x15, 0x2c, 0x9d, 0xcc, 0x00, - 0x81, 0x00, 0x01, 0xf7, 0x08, 0x00, 0x45, 0x00, 0x00, 0x28, 0x29, 0x8d, - 0x40, 0x00, 0x7d, 0x06, 0x83, 0xa0, 0xac, 0x1b, 0xca, 0x8e, 0x45, 0x16, - 0x94, 0xe2, 0xd4, 0x0a, 0x00, 0x50, 0xdf, 0xab, 0x9c, 0xc6, 0xcd, 0x1e, - 0xe5, 0xd1, 0x50, 0x10, 0x01, 0x00, 0x5a, 0x74, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, - }, LinkTypeEthernet, testDecodeOptions) - if err := p.ErrorLayer(); err != nil { - t.Error("Error while parsing vlan packet:", err) - } - if vlan := p.Layer(LayerTypeDot1Q); vlan == nil { - t.Error("Didn't detect vlan") - } else if _, ok := vlan.(*Dot1Q); !ok { - t.Error("LayerTypeDot1Q layer is not a Dot1Q object") - } - for i, l := range p.Layers() { - t.Logf("Layer %d: %#v", i, l) - } - want := []gopacket.LayerType{LayerTypeEthernet, LayerTypeDot1Q, LayerTypeIPv4, LayerTypeTCP} - checkLayers(p, want, t) -} - -func TestDecodeSCTPPackets(t *testing.T) { - sctpPackets := [][]byte{ - []byte{ // INIT - 0x00, 0x00, 0x0c, 0x9f, 0xf0, 0x1f, 0x24, 0xbe, 0x05, 0x27, 0x0b, 0x17, 0x08, 0x00, 0x45, 0x02, - 0x00, 0x44, 0x00, 0x00, 0x40, 0x00, 0x40, 0x84, 0xc4, 0x22, 0xac, 0x1d, 0x14, 0x0f, 0xac, 0x19, - 0x09, 0xcc, 0x27, 0x0f, 0x22, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x19, 0x6b, 0x0b, 0x40, 0x01, 0x00, - 0x00, 0x24, 0xb6, 0x96, 0xb0, 0x9e, 0x00, 0x01, 0xc0, 0x00, 0x00, 0x0a, 0xff, 0xff, 0xdb, 0x85, - 0x60, 0x23, 0x00, 0x0c, 0x00, 0x06, 0x00, 0x05, 0x00, 0x00, 0x80, 0x00, 0x00, 0x04, 0xc0, 0x00, - 0x00, 0x04, - }, []byte{ // INIT ACK - 0x24, 0xbe, 0x05, 0x27, 0x0b, 0x17, 0x00, 0x1f, 0xca, 0xb3, 0x76, 0x40, 0x08, 0x00, 0x45, 0x20, - 0x01, 0x24, 0x00, 0x00, 0x40, 0x00, 0x36, 0x84, 0xcd, 0x24, 0xac, 0x19, 0x09, 0xcc, 0xac, 0x1d, - 0x14, 0x0f, 0x22, 0xb8, 0x27, 0x0f, 0xb6, 0x96, 0xb0, 0x9e, 0x4b, 0xab, 0x40, 0x9a, 0x02, 0x00, - 0x01, 0x04, 0x32, 0x80, 0xfb, 0x42, 0x00, 0x00, 0xf4, 0x00, 0x00, 0x0a, 0x00, 0x0a, 0x85, 0x98, - 0xb1, 0x26, 0x00, 0x07, 0x00, 0xe8, 0xd3, 0x08, 0xce, 0xe2, 0x52, 0x95, 0xcc, 0x09, 0xa1, 0x4c, - 0x6f, 0xa7, 0x9e, 0xba, 0x03, 0xa1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x42, 0xfb, 0x80, 0x32, 0x9e, 0xb0, - 0x96, 0xb6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x46, 0xc2, 0x50, 0x00, 0x00, - 0x00, 0x00, 0x5e, 0x25, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x0a, 0x00, 0x26, 0xb1, - 0x98, 0x85, 0x02, 0x00, 0x27, 0x0f, 0xac, 0x1d, 0x14, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb8, 0x22, - 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x02, 0x00, 0x24, 0x6a, 0x72, 0x5c, 0x1c, 0x3c, 0xaa, - 0x7a, 0xcd, 0xd3, 0x8f, 0x52, 0x78, 0x7c, 0x77, 0xfd, 0x46, 0xbd, 0x72, 0x82, 0xc1, 0x1f, 0x70, - 0x44, 0xcc, 0xc7, 0x9b, 0x9b, 0x7b, 0x13, 0x54, 0x3f, 0x89, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x24, 0xb6, 0x96, - 0xb0, 0x9e, 0x00, 0x01, 0xc0, 0x00, 0x00, 0x0a, 0xff, 0xff, 0xdb, 0x85, 0x60, 0x23, 0x00, 0x0c, - 0x00, 0x06, 0x00, 0x05, 0x00, 0x00, 0x80, 0x00, 0x00, 0x04, 0xc0, 0x00, 0x00, 0x04, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x04, 0xc0, 0x00, - 0x00, 0x04, - }, []byte{ // COOKIE ECHO, DATA - 0x00, 0x00, 0x0c, 0x9f, 0xf0, 0x1f, 0x24, 0xbe, 0x05, 0x27, 0x0b, 0x17, 0x08, 0x00, 0x45, 0x02, - 0x01, 0x20, 0x00, 0x00, 0x40, 0x00, 0x40, 0x84, 0xc3, 0x46, 0xac, 0x1d, 0x14, 0x0f, 0xac, 0x19, - 0x09, 0xcc, 0x27, 0x0f, 0x22, 0xb8, 0x32, 0x80, 0xfb, 0x42, 0x01, 0xf9, 0xf3, 0xa9, 0x0a, 0x00, - 0x00, 0xe8, 0xd3, 0x08, 0xce, 0xe2, 0x52, 0x95, 0xcc, 0x09, 0xa1, 0x4c, 0x6f, 0xa7, 0x9e, 0xba, - 0x03, 0xa1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x42, 0xfb, 0x80, 0x32, 0x9e, 0xb0, 0x96, 0xb6, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x46, 0xc2, 0x50, 0x00, 0x00, 0x00, 0x00, 0x5e, 0x25, - 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x0a, 0x00, 0x26, 0xb1, 0x98, 0x85, 0x02, 0x00, - 0x27, 0x0f, 0xac, 0x1d, 0x14, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb8, 0x22, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x80, 0x02, 0x00, 0x24, 0x6a, 0x72, 0x5c, 0x1c, 0x3c, 0xaa, 0x7a, 0xcd, 0xd3, 0x8f, - 0x52, 0x78, 0x7c, 0x77, 0xfd, 0x46, 0xbd, 0x72, 0x82, 0xc1, 0x1f, 0x70, 0x44, 0xcc, 0xc7, 0x9b, - 0x9b, 0x7b, 0x13, 0x54, 0x3f, 0x89, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x24, 0xb6, 0x96, 0xb0, 0x9e, 0x00, 0x01, - 0xc0, 0x00, 0x00, 0x0a, 0xff, 0xff, 0xdb, 0x85, 0x60, 0x23, 0x00, 0x0c, 0x00, 0x06, 0x00, 0x05, - 0x00, 0x00, 0x80, 0x00, 0x00, 0x04, 0xc0, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x16, 0xdb, 0x85, 0x60, 0x23, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x6f, 0x6f, 0x21, 0x0a, 0x00, 0x00, 0x00, - }, []byte{ // COOKIE ACK, SACK - 0x24, 0xbe, 0x05, 0x27, 0x0b, 0x17, 0x00, 0x1f, 0xca, 0xb3, 0x76, 0x40, 0x08, 0x00, 0x45, 0x20, - 0x00, 0x34, 0x00, 0x00, 0x40, 0x00, 0x36, 0x84, 0xce, 0x14, 0xac, 0x19, 0x09, 0xcc, 0xac, 0x1d, - 0x14, 0x0f, 0x22, 0xb8, 0x27, 0x0f, 0xb6, 0x96, 0xb0, 0x9e, 0xed, 0x64, 0x30, 0x98, 0x0b, 0x00, - 0x00, 0x04, 0x03, 0x00, 0x00, 0x10, 0xdb, 0x85, 0x60, 0x23, 0x00, 0x00, 0xf3, 0xfa, 0x00, 0x00, - 0x00, 0x00, - }, []byte{ // DATA - 0x00, 0x00, 0x0c, 0x9f, 0xf0, 0x1f, 0x24, 0xbe, 0x05, 0x27, 0x0b, 0x17, 0x08, 0x00, 0x45, 0x02, - 0x00, 0x3c, 0x00, 0x00, 0x40, 0x00, 0x40, 0x84, 0xc4, 0x2a, 0xac, 0x1d, 0x14, 0x0f, 0xac, 0x19, - 0x09, 0xcc, 0x27, 0x0f, 0x22, 0xb8, 0x32, 0x80, 0xfb, 0x42, 0xa1, 0xe3, 0xb2, 0x31, 0x00, 0x03, - 0x00, 0x19, 0xdb, 0x85, 0x60, 0x24, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x62, 0x69, - 0x7a, 0x7a, 0x6c, 0x65, 0x21, 0x0a, 0x00, 0x00, 0x00, 0x00, - }, []byte{ // SACK - 0x24, 0xbe, 0x05, 0x27, 0x0b, 0x17, 0x00, 0x1f, 0xca, 0xb3, 0x76, 0x40, 0x08, 0x00, 0x45, 0x20, - 0x00, 0x30, 0x00, 0x00, 0x40, 0x00, 0x36, 0x84, 0xce, 0x18, 0xac, 0x19, 0x09, 0xcc, 0xac, 0x1d, - 0x14, 0x0f, 0x22, 0xb8, 0x27, 0x0f, 0xb6, 0x96, 0xb0, 0x9e, 0xfa, 0x49, 0x94, 0x3a, 0x03, 0x00, - 0x00, 0x10, 0xdb, 0x85, 0x60, 0x24, 0x00, 0x00, 0xf4, 0x00, 0x00, 0x00, 0x00, 0x00, - }, []byte{ // SHUTDOWN - 0x00, 0x00, 0x0c, 0x9f, 0xf0, 0x1f, 0x24, 0xbe, 0x05, 0x27, 0x0b, 0x17, 0x08, 0x00, 0x45, 0x02, - 0x00, 0x28, 0x00, 0x00, 0x40, 0x00, 0x40, 0x84, 0xc4, 0x3e, 0xac, 0x1d, 0x14, 0x0f, 0xac, 0x19, - 0x09, 0xcc, 0x27, 0x0f, 0x22, 0xb8, 0x32, 0x80, 0xfb, 0x42, 0x3f, 0x29, 0x59, 0x23, 0x07, 0x00, - 0x00, 0x08, 0x85, 0x98, 0xb1, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - }, []byte{ // SHUTDOWN ACK - 0x24, 0xbe, 0x05, 0x27, 0x0b, 0x17, 0x00, 0x1f, 0xca, 0xb3, 0x76, 0x40, 0x08, 0x00, 0x45, 0x20, - 0x00, 0x24, 0x00, 0x00, 0x40, 0x00, 0x36, 0x84, 0xce, 0x24, 0xac, 0x19, 0x09, 0xcc, 0xac, 0x1d, - 0x14, 0x0f, 0x22, 0xb8, 0x27, 0x0f, 0xb6, 0x96, 0xb0, 0x9e, 0xb2, 0xc8, 0x99, 0x24, 0x08, 0x00, - 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - }, []byte{ // SHUTDOWN COMPLETE - 0x00, 0x00, 0x0c, 0x9f, 0xf0, 0x1f, 0x24, 0xbe, 0x05, 0x27, 0x0b, 0x17, 0x08, 0x00, 0x45, 0x02, - 0x00, 0x24, 0x00, 0x00, 0x40, 0x00, 0x40, 0x84, 0xc4, 0x42, 0xac, 0x1d, 0x14, 0x0f, 0xac, 0x19, - 0x09, 0xcc, 0x27, 0x0f, 0x22, 0xb8, 0x32, 0x80, 0xfb, 0x42, 0xa8, 0xd1, 0x86, 0x85, 0x0e, 0x00, - 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - }} - wantLayers := [][]gopacket.LayerType{ - []gopacket.LayerType{LayerTypeSCTPInit}, - []gopacket.LayerType{LayerTypeSCTPInitAck}, - []gopacket.LayerType{LayerTypeSCTPCookieEcho, LayerTypeSCTPData}, - []gopacket.LayerType{LayerTypeSCTPCookieAck, LayerTypeSCTPSack}, - []gopacket.LayerType{LayerTypeSCTPData}, - []gopacket.LayerType{LayerTypeSCTPSack}, - []gopacket.LayerType{LayerTypeSCTPShutdown}, - []gopacket.LayerType{LayerTypeSCTPShutdownAck}, - []gopacket.LayerType{LayerTypeSCTPShutdownComplete}, - } - for i, data := range sctpPackets { - p := gopacket.NewPacket(data, LinkTypeEthernet, testDecodeOptions) - for _, typ := range wantLayers[i] { - if p.Layer(typ) == nil { - t.Errorf("Packet %d missing layer type %v, got:", i, typ) - for _, layer := range p.Layers() { - t.Errorf("\t%v", layer.LayerType()) - } - if p.ErrorLayer() != nil { - t.Error("\tPacket layer error:", p.ErrorLayer().Error()) - } - } - } - // Test re-serialization. - testSerializationWithOpts(t, p, data, gopacket.SerializeOptions{FixLengths: true, ComputeChecksums: true}) - } -} - -func TestDecodeCiscoDiscovery(t *testing.T) { - // http://wiki.wireshark.org/SampleCaptures?action=AttachFile&do=get&target=cdp_v2.pcap - data := []byte{ - 0x01, 0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x00, 0x0b, 0xbe, 0x18, 0x9a, 0x41, 0x01, 0xc3, 0xaa, 0xaa, - 0x03, 0x00, 0x00, 0x0c, 0x20, 0x00, 0x02, 0xb4, 0x09, 0xa0, 0x00, 0x01, 0x00, 0x0c, 0x6d, 0x79, - 0x73, 0x77, 0x69, 0x74, 0x63, 0x68, 0x00, 0x02, 0x00, 0x11, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, - 0xcc, 0x00, 0x04, 0xc0, 0xa8, 0x00, 0xfd, 0x00, 0x03, 0x00, 0x13, 0x46, 0x61, 0x73, 0x74, 0x45, - 0x74, 0x68, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x30, 0x2f, 0x31, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, - 0x00, 0x28, 0x00, 0x05, 0x01, 0x14, 0x43, 0x69, 0x73, 0x63, 0x6f, 0x20, 0x49, 0x6e, 0x74, 0x65, - 0x72, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x20, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, - 0x6e, 0x67, 0x20, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x20, 0x53, 0x6f, 0x66, 0x74, 0x77, 0x61, - 0x72, 0x65, 0x20, 0x0a, 0x49, 0x4f, 0x53, 0x20, 0x28, 0x74, 0x6d, 0x29, 0x20, 0x43, 0x32, 0x39, - 0x35, 0x30, 0x20, 0x53, 0x6f, 0x66, 0x74, 0x77, 0x61, 0x72, 0x65, 0x20, 0x28, 0x43, 0x32, 0x39, - 0x35, 0x30, 0x2d, 0x49, 0x36, 0x4b, 0x32, 0x4c, 0x32, 0x51, 0x34, 0x2d, 0x4d, 0x29, 0x2c, 0x20, - 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x31, 0x32, 0x2e, 0x31, 0x28, 0x32, 0x32, 0x29, - 0x45, 0x41, 0x31, 0x34, 0x2c, 0x20, 0x52, 0x45, 0x4c, 0x45, 0x41, 0x53, 0x45, 0x20, 0x53, 0x4f, - 0x46, 0x54, 0x57, 0x41, 0x52, 0x45, 0x20, 0x28, 0x66, 0x63, 0x31, 0x29, 0x0a, 0x54, 0x65, 0x63, - 0x68, 0x6e, 0x69, 0x63, 0x61, 0x6c, 0x20, 0x53, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x3a, 0x20, - 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x63, 0x69, 0x73, 0x63, 0x6f, - 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x65, 0x63, 0x68, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, - 0x0a, 0x43, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x28, 0x63, 0x29, 0x20, 0x31, - 0x39, 0x38, 0x36, 0x2d, 0x32, 0x30, 0x31, 0x30, 0x20, 0x62, 0x79, 0x20, 0x63, 0x69, 0x73, 0x63, - 0x6f, 0x20, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x73, 0x2c, 0x20, 0x49, 0x6e, 0x63, 0x2e, 0x0a, - 0x43, 0x6f, 0x6d, 0x70, 0x69, 0x6c, 0x65, 0x64, 0x20, 0x54, 0x75, 0x65, 0x20, 0x32, 0x36, 0x2d, - 0x4f, 0x63, 0x74, 0x2d, 0x31, 0x30, 0x20, 0x31, 0x30, 0x3a, 0x33, 0x35, 0x20, 0x62, 0x79, 0x20, - 0x6e, 0x62, 0x75, 0x72, 0x72, 0x61, 0x00, 0x06, 0x00, 0x15, 0x63, 0x69, 0x73, 0x63, 0x6f, 0x20, - 0x57, 0x53, 0x2d, 0x43, 0x32, 0x39, 0x35, 0x30, 0x2d, 0x31, 0x32, 0x00, 0x08, 0x00, 0x24, 0x00, - 0x00, 0x0c, 0x01, 0x12, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x01, 0x02, 0x20, 0xff, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0xbe, 0x18, 0x9a, 0x40, 0xff, 0x00, 0x00, 0x00, - 0x09, 0x00, 0x0c, 0x4d, 0x59, 0x44, 0x4f, 0x4d, 0x41, 0x49, 0x4e, 0x00, 0x0a, 0x00, 0x06, 0x00, - 0x01, 0x00, 0x0b, 0x00, 0x05, 0x01, 0x00, 0x12, 0x00, 0x05, 0x00, 0x00, 0x13, 0x00, 0x05, 0x00, - 0x00, 0x16, 0x00, 0x11, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0xcc, 0x00, 0x04, 0xc0, 0xa8, 0x00, - 0xfd, - } - p := gopacket.NewPacket(data, LinkTypeEthernet, testDecodeOptions) - wantLayers := []gopacket.LayerType{LayerTypeEthernet, LayerTypeLLC, LayerTypeSNAP, LayerTypeCiscoDiscovery, LayerTypeCiscoDiscoveryInfo} - checkLayers(p, wantLayers, t) - - want := &CiscoDiscoveryInfo{ - CDPHello: CDPHello{ - OUI: []byte{0, 0, 12}, - ProtocolID: 274, - ClusterMaster: []byte{0, 0, 0, 0}, - Unknown1: []byte{255, 255, 255, 255}, - Version: 1, - SubVersion: 2, - Status: 32, - Unknown2: 255, - ClusterCommander: net.HardwareAddr{0, 0, 0, 0, 0, 0}, - SwitchMAC: net.HardwareAddr{0, 0x0b, 0xbe, 0x18, 0x9a, 0x40}, - Unknown3: 255, - ManagementVLAN: 0, - }, - DeviceID: "myswitch", - Addresses: []net.IP{net.IPv4(192, 168, 0, 253)}, - PortID: "FastEthernet0/1", - Capabilities: CDPCapabilities{false, false, false, true, false, true, false, false, false}, - Version: "Cisco Internetwork Operating System Software \nIOS (tm) C2950 Software (C2950-I6K2L2Q4-M), Version 12.1(22)EA14, RELEASE SOFTWARE (fc1)\nTechnical Support: http://www.cisco.com/techsupport\nCopyright (c) 1986-2010 by cisco Systems, Inc.\nCompiled Tue 26-Oct-10 10:35 by nburra", - Platform: "cisco WS-C2950-12", - VTPDomain: "MYDOMAIN", - NativeVLAN: 1, - FullDuplex: true, - MgmtAddresses: []net.IP{net.IPv4(192, 168, 0, 253)}, - BaseLayer: BaseLayer{Contents: data[26:]}, - } - cdpL := p.Layer(LayerTypeCiscoDiscoveryInfo) - info, _ := cdpL.(*CiscoDiscoveryInfo) - if !reflect.DeepEqual(info, want) { - t.Errorf("Values mismatch, \ngot %#v\nwant %#v\n", info, want) - } -} - -func TestDecodeLinkLayerDiscovery(t *testing.T) { - // http://wiki.wireshark.org/SampleCaptures?action=AttachFile&do=get&target=lldp.detailed.pcap - data := []byte{ - 0x01, 0x80, 0xc2, 0x00, 0x00, 0x0e, 0x00, 0x01, 0x30, 0xf9, 0xad, 0xa0, - 0x88, 0xcc, 0x02, 0x07, 0x04, 0x00, 0x01, 0x30, 0xf9, 0xad, 0xa0, 0x04, - 0x04, 0x05, 0x31, 0x2f, 0x31, 0x06, 0x02, 0x00, 0x78, 0x08, 0x17, 0x53, - 0x75, 0x6d, 0x6d, 0x69, 0x74, 0x33, 0x30, 0x30, 0x2d, 0x34, 0x38, 0x2d, - 0x50, 0x6f, 0x72, 0x74, 0x20, 0x31, 0x30, 0x30, 0x31, 0x00, 0x0a, 0x0d, - 0x53, 0x75, 0x6d, 0x6d, 0x69, 0x74, 0x33, 0x30, 0x30, 0x2d, 0x34, 0x38, - 0x00, 0x0c, 0x4c, 0x53, 0x75, 0x6d, 0x6d, 0x69, 0x74, 0x33, 0x30, 0x30, - 0x2d, 0x34, 0x38, 0x20, 0x2d, 0x20, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, - 0x6e, 0x20, 0x37, 0x2e, 0x34, 0x65, 0x2e, 0x31, 0x20, 0x28, 0x42, 0x75, - 0x69, 0x6c, 0x64, 0x20, 0x35, 0x29, 0x20, 0x62, 0x79, 0x20, 0x52, 0x65, - 0x6c, 0x65, 0x61, 0x73, 0x65, 0x5f, 0x4d, 0x61, 0x73, 0x74, 0x65, 0x72, - 0x20, 0x30, 0x35, 0x2f, 0x32, 0x37, 0x2f, 0x30, 0x35, 0x20, 0x30, 0x34, - 0x3a, 0x35, 0x33, 0x3a, 0x31, 0x31, 0x00, 0x0e, 0x04, 0x00, 0x14, 0x00, - 0x14, 0x10, 0x0e, 0x07, 0x06, 0x00, 0x01, 0x30, 0xf9, 0xad, 0xa0, 0x02, - 0x00, 0x00, 0x03, 0xe9, 0x00, 0xfe, 0x07, 0x00, 0x12, 0x0f, 0x02, 0x07, - 0x01, 0x00, 0xfe, 0x09, 0x00, 0x12, 0x0f, 0x01, 0x03, 0x6c, 0x00, 0x00, - 0x10, 0xfe, 0x09, 0x00, 0x12, 0x0f, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, - 0xfe, 0x06, 0x00, 0x12, 0x0f, 0x04, 0x05, 0xf2, 0xfe, 0x06, 0x00, 0x80, - 0xc2, 0x01, 0x01, 0xe8, 0xfe, 0x07, 0x00, 0x80, 0xc2, 0x02, 0x01, 0x00, - 0x00, 0xfe, 0x17, 0x00, 0x80, 0xc2, 0x03, 0x01, 0xe8, 0x10, 0x76, 0x32, - 0x2d, 0x30, 0x34, 0x38, 0x38, 0x2d, 0x30, 0x33, 0x2d, 0x30, 0x35, 0x30, - 0x35, 0x00, 0xfe, 0x05, 0x00, 0x80, 0xc2, 0x04, 0x00, 0x00, 0x00, - } - - p := gopacket.NewPacket(data, LinkTypeEthernet, testDecodeOptions) - wantLayers := []gopacket.LayerType{LayerTypeEthernet, LayerTypeLinkLayerDiscovery, LayerTypeLinkLayerDiscoveryInfo} - checkLayers(p, wantLayers, t) - lldpL := p.Layer(LayerTypeLinkLayerDiscovery) - lldp := lldpL.(*LinkLayerDiscovery) - want := &LinkLayerDiscovery{ - ChassisID: LLDPChassisID{LLDPChassisIDSubTypeMACAddr, []byte{0x00, 0x01, 0x30, 0xf9, 0xad, 0xa0}}, - PortID: LLDPPortID{LLDPPortIDSubtypeIfaceName, []byte("1/1")}, - TTL: 120, - BaseLayer: BaseLayer{Contents: data[14:]}, - } - lldp.Values = nil // test these in next stage - if !reflect.DeepEqual(lldp, want) { - t.Errorf("Values mismatch, \ngot %#v\nwant %#v\n", lldp, want) - } - - infoL := p.Layer(LayerTypeLinkLayerDiscoveryInfo) - info := infoL.(*LinkLayerDiscoveryInfo) - wantinfo := &LinkLayerDiscoveryInfo{ - PortDescription: "Summit300-48-Port 1001\x00", - SysName: "Summit300-48\x00", - SysDescription: "Summit300-48 - Version 7.4e.1 (Build 5) by Release_Master 05/27/05 04:53:11\x00", - SysCapabilities: LLDPSysCapabilities{ - SystemCap: LLDPCapabilities{Bridge: true, Router: true}, - EnabledCap: LLDPCapabilities{Bridge: true, Router: true}, - }, - MgmtAddress: LLDPMgmtAddress{IANAAddressFamily802, []byte{0x00, 0x01, 0x30, 0xf9, 0xad, 0xa0}, LLDPInterfaceSubtypeifIndex, 1001, ""}, - OrgTLVs: []LLDPOrgSpecificTLV{ - LLDPOrgSpecificTLV{OUI: 0x120f, SubType: 0x2, Info: []uint8{0x7, 0x1, 0x0}}, - LLDPOrgSpecificTLV{OUI: 0x120f, SubType: 0x1, Info: []uint8{0x3, 0x6c, 0x0, 0x0, 0x10}}, - LLDPOrgSpecificTLV{OUI: 0x120f, SubType: 0x3, Info: []uint8{0x1, 0x0, 0x0, 0x0, 0x0}}, - LLDPOrgSpecificTLV{OUI: 0x120f, SubType: 0x4, Info: []uint8{0x5, 0xf2}}, - LLDPOrgSpecificTLV{OUI: 0x80c2, SubType: 0x1, Info: []uint8{0x1, 0xe8}}, - LLDPOrgSpecificTLV{OUI: 0x80c2, SubType: 0x2, Info: []uint8{0x1, 0x0, 0x0}}, - LLDPOrgSpecificTLV{OUI: 0x80c2, SubType: 0x3, Info: []uint8{0x1, 0xe8, 0x10, 0x76, 0x32, 0x2d, 0x30, 0x34, 0x38, 0x38, 0x2d, 0x30, 0x33, 0x2d, 0x30, 0x35, 0x30, 0x35, 0x0}}, - LLDPOrgSpecificTLV{OUI: 0x80c2, SubType: 0x4, Info: []uint8{0x0}}, - }, - Unknown: nil, - } - if !reflect.DeepEqual(info, wantinfo) { - t.Errorf("Values mismatch, \ngot %#v\nwant %#v\n", info, wantinfo) - } - info8021, err := info.Decode8021() - if err != nil { - t.Errorf("8021 Values decode error: %v", err) - } - want8021 := LLDPInfo8021{ - PVID: 488, - PPVIDs: []PortProtocolVLANID{PortProtocolVLANID{false, false, 0}}, - VLANNames: []VLANName{VLANName{488, "v2-0488-03-0505\x00"}}, - ProtocolIdentities: nil, - VIDUsageDigest: 0, - ManagementVID: 0, - LinkAggregation: LLDPLinkAggregation{false, false, 0}, - } - if !reflect.DeepEqual(info8021, want8021) { - t.Errorf("Values mismatch, \ngot %#v\nwant %#v\n", info8021, want8021) - } - info8023, err := info.Decode8023() - if err != nil { - t.Errorf("8023 Values decode error: %v", err) - } - want8023 := LLDPInfo8023{ - LinkAggregation: LLDPLinkAggregation{true, false, 0}, - MACPHYConfigStatus: LLDPMACPHYConfigStatus{true, true, 0x6c00, 0x0010}, - PowerViaMDI: LLDPPowerViaMDI8023{true, true, true, false, 1, 0, 0, 0, 0, 0, 0}, - MTU: 1522, - } - - if !reflect.DeepEqual(info8023, want8023) { - t.Errorf("Values mismatch, \ngot %#v\nwant %#v\n", info8023, want8023) - } - - // http://wiki.wireshark.org/SampleCaptures?action=AttachFile&do=get&target=lldpmed_civicloc.pcap - data = []byte{ - 0x01, 0x80, 0xc2, 0x00, 0x00, 0x0e, 0x00, 0x13, 0x21, 0x57, 0xca, 0x7f, - 0x88, 0xcc, 0x02, 0x07, 0x04, 0x00, 0x13, 0x21, 0x57, 0xca, 0x40, 0x04, - 0x02, 0x07, 0x31, 0x06, 0x02, 0x00, 0x78, 0x08, 0x01, 0x31, 0x0a, 0x1a, - 0x50, 0x72, 0x6f, 0x43, 0x75, 0x72, 0x76, 0x65, 0x20, 0x53, 0x77, 0x69, - 0x74, 0x63, 0x68, 0x20, 0x32, 0x36, 0x30, 0x30, 0x2d, 0x38, 0x2d, 0x50, - 0x57, 0x52, 0x0c, 0x5f, 0x50, 0x72, 0x6f, 0x43, 0x75, 0x72, 0x76, 0x65, - 0x20, 0x4a, 0x38, 0x37, 0x36, 0x32, 0x41, 0x20, 0x53, 0x77, 0x69, 0x74, - 0x63, 0x68, 0x20, 0x32, 0x36, 0x30, 0x30, 0x2d, 0x38, 0x2d, 0x50, 0x57, - 0x52, 0x2c, 0x20, 0x72, 0x65, 0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x20, - 0x48, 0x2e, 0x30, 0x38, 0x2e, 0x38, 0x39, 0x2c, 0x20, 0x52, 0x4f, 0x4d, - 0x20, 0x48, 0x2e, 0x30, 0x38, 0x2e, 0x35, 0x58, 0x20, 0x28, 0x2f, 0x73, - 0x77, 0x2f, 0x63, 0x6f, 0x64, 0x65, 0x2f, 0x62, 0x75, 0x69, 0x6c, 0x64, - 0x2f, 0x66, 0x69, 0x73, 0x68, 0x28, 0x74, 0x73, 0x5f, 0x30, 0x38, 0x5f, - 0x35, 0x29, 0x29, 0x0e, 0x04, 0x00, 0x14, 0x00, 0x04, 0x10, 0x0c, 0x05, - 0x01, 0x0f, 0xff, 0x7a, 0x94, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, - 0x09, 0x00, 0x12, 0x0f, 0x01, 0x03, 0x6c, 0x00, 0x00, 0x10, 0xfe, 0x07, - 0x00, 0x12, 0xbb, 0x01, 0x00, 0x0f, 0x04, 0xfe, 0x08, 0x00, 0x12, 0xbb, - 0x02, 0x01, 0x40, 0x65, 0xae, 0xfe, 0x2e, 0x00, 0x12, 0xbb, 0x03, 0x02, - 0x28, 0x02, 0x55, 0x53, 0x01, 0x02, 0x43, 0x41, 0x03, 0x09, 0x52, 0x6f, - 0x73, 0x65, 0x76, 0x69, 0x6c, 0x6c, 0x65, 0x06, 0x09, 0x46, 0x6f, 0x6f, - 0x74, 0x68, 0x69, 0x6c, 0x6c, 0x73, 0x13, 0x04, 0x38, 0x30, 0x30, 0x30, - 0x1a, 0x03, 0x52, 0x33, 0x4c, 0xfe, 0x07, 0x00, 0x12, 0xbb, 0x04, 0x03, - 0x00, 0x41, 0x00, 0x00, - } - - p = gopacket.NewPacket(data, LinkTypeEthernet, testDecodeOptions) - wantLayers = []gopacket.LayerType{LayerTypeEthernet, LayerTypeLinkLayerDiscovery, LayerTypeLinkLayerDiscoveryInfo} - checkLayers(p, wantLayers, t) - lldpL = p.Layer(LayerTypeLinkLayerDiscovery) - lldp = lldpL.(*LinkLayerDiscovery) - want = &LinkLayerDiscovery{ - ChassisID: LLDPChassisID{LLDPChassisIDSubTypeMACAddr, []byte{0x00, 0x13, 0x21, 0x57, 0xca, 0x40}}, - PortID: LLDPPortID{LLDPPortIDSubtypeLocal, []byte("1")}, - TTL: 120, - BaseLayer: BaseLayer{Contents: data[14:]}, - } - lldp.Values = nil // test these in next stage - if !reflect.DeepEqual(lldp, want) { - t.Errorf("Values mismatch, \ngot %#v\nwant %#v\n", lldp, want) - } - - infoL = p.Layer(LayerTypeLinkLayerDiscoveryInfo) - info = infoL.(*LinkLayerDiscoveryInfo) - wantinfo = &LinkLayerDiscoveryInfo{ - PortDescription: "1", - SysName: "ProCurve Switch 2600-8-PWR", - SysDescription: "ProCurve J8762A Switch 2600-8-PWR, revision H.08.89, ROM H.08.5X (/sw/code/build/fish(ts_08_5))", - SysCapabilities: LLDPSysCapabilities{ - SystemCap: LLDPCapabilities{Bridge: true, Router: true}, - EnabledCap: LLDPCapabilities{Bridge: true}, - }, - MgmtAddress: LLDPMgmtAddress{IANAAddressFamilyIPV4, []byte{0x0f, 0xff, 0x7a, 0x94}, LLDPInterfaceSubtypeifIndex, 0, ""}, - OrgTLVs: []LLDPOrgSpecificTLV{ - LLDPOrgSpecificTLV{OUI: 0x120f, SubType: 0x1, Info: []uint8{0x3, 0x6c, 0x0, 0x0, 0x10}}, - LLDPOrgSpecificTLV{OUI: 0x12bb, SubType: 0x1, Info: []uint8{0x0, 0xf, 0x4}}, - LLDPOrgSpecificTLV{OUI: 0x12bb, SubType: 0x2, Info: []uint8{0x1, 0x40, 0x65, 0xae}}, - LLDPOrgSpecificTLV{OUI: 0x12bb, SubType: 0x3, Info: []uint8{0x2, 0x28, 0x2, 0x55, 0x53, 0x1, 0x2, 0x43, 0x41, 0x3, 0x9, 0x52, 0x6f, 0x73, 0x65, 0x76, 0x69, 0x6c, 0x6c, 0x65, 0x6, 0x9, 0x46, 0x6f, 0x6f, 0x74, 0x68, 0x69, 0x6c, 0x6c, 0x73, 0x13, 0x4, 0x38, 0x30, 0x30, 0x30, 0x1a, 0x3, 0x52, 0x33, 0x4c}}, - LLDPOrgSpecificTLV{OUI: 0x12bb, SubType: 0x4, Info: []uint8{0x3, 0x0, 0x41}}, - }, - Unknown: nil, - } - if !reflect.DeepEqual(info, wantinfo) { - t.Errorf("Values mismatch, \ngot %#v\nwant %#v\n", info, wantinfo) - } - info8023, err = info.Decode8023() - if err != nil { - t.Errorf("8023 Values decode error: %v", err) - } - want8023 = LLDPInfo8023{ - MACPHYConfigStatus: LLDPMACPHYConfigStatus{true, true, 0x6c00, 0x0010}, - } - - if !reflect.DeepEqual(info8023, want8023) { - t.Errorf("Values mismatch, \ngot %#v\nwant %#v\n", info8023, want8023) - } - - infoMedia, err := info.DecodeMedia() - if err != nil { - t.Errorf("8023 Values decode error: %v", err) - } - wantMedia := LLDPInfoMedia{ - MediaCapabilities: LLDPMediaCapabilities{true, true, true, true, false, false, LLDPMediaClassNetwork}, - NetworkPolicy: LLDPNetworkPolicy{LLDPAppTypeVoice, true, true, 50, 6, 46}, - Location: LLDPLocation{Format: LLDPLocationFormatAddress, Address: LLDPLocationAddress{ - What: LLDPLocationAddressWhatClient, - CountryCode: "US", - AddressLines: []LLDPLocationAddressLine{ - LLDPLocationAddressLine{LLDPLocationAddressTypeNational, "CA"}, - LLDPLocationAddressLine{LLDPLocationAddressTypeCity, "Roseville"}, - LLDPLocationAddressLine{LLDPLocationAddressTypeStreet, "Foothills"}, - LLDPLocationAddressLine{LLDPLocationAddressTypeHouseNum, "8000"}, - LLDPLocationAddressLine{LLDPLocationAddressTypeUnit, "R3L"}, - }, - }}, - PowerViaMDI: LLDPPowerViaMDI{0, 0, LLDPPowerPriorityLow, 6500}, - } - - if !reflect.DeepEqual(infoMedia, wantMedia) { - t.Errorf("Values mismatch, \ngot %#v\nwant %#v\n", infoMedia, wantMedia) - } - -} - -func TestDecodeNortelDiscovery(t *testing.T) { - // http://www.thetechfirm.com/packets/nortel_btdp/btdp_nai.enc - data := []byte{ - 0x01, 0x00, 0x81, 0x00, 0x01, 0x00, 0x00, 0x04, 0x38, 0xe0, 0xcc, 0xde, - 0x00, 0x13, 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x81, 0x01, 0xa2, 0xac, 0x13, - 0x58, 0x03, 0x00, 0x04, 0x15, 0x30, 0x0c, 0x02, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x04, 0x38, 0xe0, 0xcc, 0xde, 0x80, 0x6a, 0x00, 0x01, 0x14, 0x00, - 0x02, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - } - p := gopacket.NewPacket(data, LinkTypeEthernet, testDecodeOptions) - wantLayers := []gopacket.LayerType{LayerTypeEthernet, LayerTypeLLC, LayerTypeSNAP, LayerTypeNortelDiscovery} - checkLayers(p, wantLayers, t) - - want := &NortelDiscovery{ - IPAddress: []byte{172, 19, 88, 3}, - SegmentID: []byte{0x00, 0x04, 0x15}, - Chassis: NDPChassisBayStack450101001000Switches, - Backplane: NDPBackplaneEthernetFastEthernetGigabitEthernet, - State: NDPStateHeartbeat, - NumLinks: 0, - } - ndpL := p.Layer(LayerTypeNortelDiscovery) - info, _ := ndpL.(*NortelDiscovery) - if !reflect.DeepEqual(info, want) { - t.Errorf("Values mismatch, \ngot %#v\nwant %#v\n", info, want) - } -} - -func TestDecodeIPv6Jumbogram(t *testing.T) { - // Haven't found any of these in the wild or on example pcaps online, so had - // to generate one myself via scapy. Unfortunately, scapy can only - // str(packet) for packets with length < 65536, due to limitations in python's - // struct library, so I generated the header with: - // Ether() / IPv6(src='::1', dst='::2') / IPv6ExtHdrHopByHop(options=[Jumbo(jumboplen=70000)]) / TCP(sport=8888, dport=80) - // then added the payload manually ("payload" * 9996). The checksums here are - // not correct, but we don't check, so who cares ;) - dataStr := "\x00\x1f\xca\xb3v@$\xbe\x05'\x0b\x17\x86\xdd`\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x06\x00\xc2\x04\x00\x01\x11p\"\xb8\x00P\x00\x00\x00\x00\x00\x00\x00\x00P\x02 \x00l\xd8\x00\x00" - payload := strings.Repeat("payload", 9996) - data := []byte(dataStr + payload) - p := gopacket.NewPacket(data, LinkTypeEthernet, testDecodeOptions) - checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeIPv6, LayerTypeIPv6HopByHop, LayerTypeTCP, gopacket.LayerTypePayload}, t) - if p.ApplicationLayer() == nil { - t.Error("Packet has no application layer") - } else if string(p.ApplicationLayer().Payload()) != payload { - t.Errorf("Jumbogram payload wrong") - } - // Check truncated for jumbograms - data = data[:len(data)-1] - p = gopacket.NewPacket(data, LinkTypeEthernet, testDecodeOptions) - checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeIPv6, LayerTypeIPv6HopByHop, LayerTypeTCP, gopacket.LayerTypePayload}, t) - if !p.Metadata().Truncated { - t.Error("Jumbogram should be truncated") - } -} - -func TestDecodeUDPPacketTooSmall(t *testing.T) { - data := []byte{ - 0x00, 0x15, 0x2c, 0x9d, 0xcc, 0x00, 0x00, 0x10, 0xdb, 0xff, 0x10, 0x00, 0x81, 0x00, 0x01, 0xf7, - 0x08, 0x00, 0x45, 0x60, 0x00, 0x3c, 0x0f, 0xa9, 0x00, 0x00, 0x6e, 0x11, 0x01, 0x0a, 0x47, 0xe6, - 0xee, 0x2e, 0xac, 0x16, 0x59, 0x73, 0x00, 0x50, 0x00, 0x50, 0x00, 0x28, 0x4d, 0xad, 0x00, 0x67, - 0x00, 0x01, 0x00, 0x72, 0xd5, 0xc7, 0xf1, 0x07, 0x00, 0x00, 0x01, 0x01, 0x00, 0x0d, 0x00, 0x00, - 0x00, 0x14, 0x00, 0x00, 0x19, 0xba, - } - p := gopacket.NewPacket(data, LinkTypeEthernet, testDecodeOptions) - checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeDot1Q, LayerTypeIPv4, LayerTypeUDP, gopacket.LayerTypePayload}, t) - if !p.Metadata().Truncated { - t.Error("UDP short packet should be truncated") - } -} - -func TestDecodingLayerParserFullTCPPacket(t *testing.T) { - dlp := gopacket.NewDecodingLayerParser(LayerTypeEthernet, &Ethernet{}, &IPv4{}, &TCP{}, &gopacket.Payload{}) - decoded := make([]gopacket.LayerType, 1) - err := dlp.DecodeLayers(testSimpleTCPPacket, &decoded) - if err != nil { - t.Error("Error from dlp parser: ", err) - } - if len(decoded) != 4 { - t.Error("Expected 4 layers parsed, instead got ", len(decoded)) - } -} - -// testICMP is the packet: -// 15:49:15.773265 IP 72.14.222.226 > 172.29.20.15: ICMP host 10.66.73.201 unreachable - admin prohibited filter, length 36 -// 0x0000: 24be 0527 0b17 001f cab3 75c0 0800 4500 $..'......u...E. -// 0x0010: 0038 0000 0000 fc01 d7a7 480e dee2 ac1d .8........H..... -// 0x0020: 140f 030d 946e 0000 0000 4520 004d 0000 .....n....E..M.. -// 0x0030: 4000 3e11 2849 ac1d 140f 0a42 49c9 8ecc @.>.(I.....BI... -// 0x0040: 62e1 0039 769d b..9v. -var testICMP = []byte{ - 0x24, 0xbe, 0x05, 0x27, 0x0b, 0x17, 0x00, 0x1f, 0xca, 0xb3, 0x75, 0xc0, 0x08, 0x00, 0x45, 0x00, - 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x01, 0xd7, 0xa7, 0x48, 0x0e, 0xde, 0xe2, 0xac, 0x1d, - 0x14, 0x0f, 0x03, 0x0d, 0x94, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x45, 0x20, 0x00, 0x4d, 0x00, 0x00, - 0x40, 0x00, 0x3e, 0x11, 0x28, 0x49, 0xac, 0x1d, 0x14, 0x0f, 0x0a, 0x42, 0x49, 0xc9, 0x8e, 0xcc, - 0x62, 0xe1, 0x00, 0x39, 0x76, 0x9d, -} - -func TestICMP(t *testing.T) { - p := gopacket.NewPacket(testICMP, LinkTypeEthernet, testDecodeOptions) - if p.ErrorLayer() != nil { - t.Error("Failed to decode packet:", p.ErrorLayer().Error()) - } - checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeIPv4, LayerTypeICMPv4, gopacket.LayerTypePayload}, t) - testSerialization(t, p, testICMP) -} -func BenchmarkDecodeICMP(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testICMP, LinkTypeEthernet, gopacket.NoCopy) - } -} - -// testICMP6 is the packet: -// 16:17:37.758937 IP6 fe80::21f:caff:feb3:75c0 > 2620:0:1005:0:26be:5ff:fe27:b17: ICMP6, neighbor solicitation, who has 2620:0:1005:0:26be:5ff:fe27:b17, length 32 -// 0x0000: 24be 0527 0b17 001f cab3 75c0 86dd 6e00 $..'......u...n. -// 0x0010: 0000 0020 3aff fe80 0000 0000 0000 021f ....:........... -// 0x0020: caff feb3 75c0 2620 0000 1005 0000 26be ....u.&.......&. -// 0x0030: 05ff fe27 0b17 8700 1eba 0000 0000 2620 ...'..........&. -// 0x0040: 0000 1005 0000 26be 05ff fe27 0b17 0101 ......&....'.... -// 0x0050: 001f cab3 75c0 ....u. -var testICMP6 = []byte{ - 0x24, 0xbe, 0x05, 0x27, 0x0b, 0x17, 0x00, 0x1f, 0xca, 0xb3, 0x75, 0xc0, 0x86, 0xdd, 0x6e, 0x00, - 0x00, 0x00, 0x00, 0x20, 0x3a, 0xff, 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x1f, - 0xca, 0xff, 0xfe, 0xb3, 0x75, 0xc0, 0x26, 0x20, 0x00, 0x00, 0x10, 0x05, 0x00, 0x00, 0x26, 0xbe, - 0x05, 0xff, 0xfe, 0x27, 0x0b, 0x17, 0x87, 0x00, 0x1e, 0xba, 0x00, 0x00, 0x00, 0x00, 0x26, 0x20, - 0x00, 0x00, 0x10, 0x05, 0x00, 0x00, 0x26, 0xbe, 0x05, 0xff, 0xfe, 0x27, 0x0b, 0x17, 0x01, 0x01, - 0x00, 0x1f, 0xca, 0xb3, 0x75, 0xc0, -} - -func TestICMP6(t *testing.T) { - p := gopacket.NewPacket(testICMP6, LinkTypeEthernet, testDecodeOptions) - if p.ErrorLayer() != nil { - t.Error("Failed to decode packet:", p.ErrorLayer().Error()) - } - checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeIPv6, LayerTypeICMPv6, gopacket.LayerTypePayload}, t) - testSerialization(t, p, testICMP6) -} -func BenchmarkDecodeICMP6(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testICMP6, LinkTypeEthernet, gopacket.NoCopy) - } -} - -// testMPLS is the packet: -// 12:48:57.201014 MPLS (label 29, exp 0, [S], ttl 255) IP 10.1.2.1 > 10.34.0.1: ICMP echo request, id 2618, seq 1579, length 80 -// 0x0000: 0030 96e6 fc39 0030 9605 2838 8847 0001 .0...9.0..(8.G.. -// 0x0010: d1ff 4500 0064 000b 0000 ff01 a569 0a01 ..E..d.......i.. -// 0x0020: 0201 0a22 0001 0800 3a76 0a3a 062b 0000 ..."....:v.:.+.. -// 0x0030: 0000 001f 3350 abcd abcd abcd abcd abcd ....3P.......... -// 0x0040: abcd abcd abcd abcd abcd abcd abcd abcd ................ -// 0x0050: abcd abcd abcd abcd abcd abcd abcd abcd ................ -// 0x0060: abcd abcd abcd abcd abcd abcd abcd abcd ................ -// 0x0070: abcd abcd abcd ...... -var testMPLS = []byte{ - 0x00, 0x30, 0x96, 0xe6, 0xfc, 0x39, 0x00, 0x30, 0x96, 0x05, 0x28, 0x38, 0x88, 0x47, 0x00, 0x01, - 0xd1, 0xff, 0x45, 0x00, 0x00, 0x64, 0x00, 0x0b, 0x00, 0x00, 0xff, 0x01, 0xa5, 0x69, 0x0a, 0x01, - 0x02, 0x01, 0x0a, 0x22, 0x00, 0x01, 0x08, 0x00, 0x3a, 0x76, 0x0a, 0x3a, 0x06, 0x2b, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x1f, 0x33, 0x50, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, - 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, - 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, - 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, - 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, -} - -func TestMPLS(t *testing.T) { - p := gopacket.NewPacket(testMPLS, LinkTypeEthernet, testDecodeOptions) - if p.ErrorLayer() != nil { - t.Error("Failed to decode packet:", p.ErrorLayer().Error()) - } - checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeMPLS, LayerTypeIPv4, LayerTypeICMPv4, gopacket.LayerTypePayload}, t) - testSerialization(t, p, testMPLS) -} -func BenchmarkDecodeMPLS(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testMPLS, LinkTypeEthernet, gopacket.NoCopy) - } -} - -// testPPPoE_ICMPv6 is the packet: -// 07:43:31.091560 PPPoE [ses 0x11] IP6 fe80::c801:eff:fe88:8 > ff02::1: ICMP6, neighbor advertisement, tgt is fe80::c801:eff:fe88:8, length 24 -// 0x0000: cc05 0e88 0000 ca01 0e88 0006 8864 1100 .............d.. -// 0x0010: 0011 0042 0057 6e00 0000 0018 3aff fe80 ...B.Wn.....:... -// 0x0020: 0000 0000 0000 c801 0eff fe88 0008 ff02 ................ -// 0x0030: 0000 0000 0000 0000 0000 0000 0001 8800 ................ -// 0x0040: 5083 8000 0000 fe80 0000 0000 0000 c801 P............... -// 0x0050: 0eff fe88 0008 ...... -var testPPPoE_ICMPv6 = []byte{ - 0xcc, 0x05, 0x0e, 0x88, 0x00, 0x00, 0xca, 0x01, 0x0e, 0x88, 0x00, 0x06, 0x88, 0x64, 0x11, 0x00, - 0x00, 0x11, 0x00, 0x42, 0x00, 0x57, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3a, 0xff, 0xfe, 0x80, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc8, 0x01, 0x0e, 0xff, 0xfe, 0x88, 0x00, 0x08, 0xff, 0x02, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x88, 0x00, - 0x50, 0x83, 0x80, 0x00, 0x00, 0x00, 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc8, 0x01, - 0x0e, 0xff, 0xfe, 0x88, 0x00, 0x08, -} - -func TestPPPoE_ICMPv6(t *testing.T) { - p := gopacket.NewPacket(testPPPoE_ICMPv6, LinkTypeEthernet, testDecodeOptions) - if p.ErrorLayer() != nil { - t.Error("Failed to decode packet:", p.ErrorLayer().Error()) - } - checkLayers(p, []gopacket.LayerType{ - LayerTypeEthernet, - LayerTypePPPoE, - LayerTypePPP, - LayerTypeIPv6, - LayerTypeICMPv6, - gopacket.LayerTypePayload, - }, t) - testSerialization(t, p, testPPPoE_ICMPv6) -} -func BenchmarkDecodePPPoE_ICMPv6(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testPPPoE_ICMPv6, LinkTypeEthernet, gopacket.NoCopy) - } -} - -var testPFLog_UDP = []byte{ - 0x3d, 0x02, 0x00, 0x00, 0x65, 0x6e, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x6c, 0x6f, 0x67, 0x67, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xae, 0xff, 0xff, 0xff, 0x7f, - 0xa0, 0x86, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xb8, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, - 0x45, 0x00, 0x00, 0x2c, 0x02, 0x16, 0x00, 0x00, 0x40, 0x11, 0x4e, 0xb0, 0xac, 0x17, 0xe8, 0xcc, - 0xac, 0x17, 0xe8, 0xff, 0xf0, 0xff, 0x21, 0xa4, 0x00, 0x18, 0x2a, 0x25, 0x50, 0x4e, 0x4a, 0x50, - 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -} - -func TestPFLog_UDP(t *testing.T) { - p := gopacket.NewPacket(testPFLog_UDP, LinkTypePFLog, testDecodeOptions) - if p.ErrorLayer() != nil { - t.Error("Failed to decode packet:", p.ErrorLayer().Error()) - } - checkLayers(p, []gopacket.LayerType{ - LayerTypePFLog, - LayerTypeIPv4, - LayerTypeUDP, - gopacket.LayerTypePayload, - }, t) -} - -func TestRegressionDot1QPriority(t *testing.T) { - d := &Dot1Q{ - Priority: 2, - } - out := gopacket.NewSerializeBuffer() - gopacket.SerializeLayers(out, gopacket.SerializeOptions{}, d) - if err := d.DecodeFromBytes(out.Bytes(), gopacket.NilDecodeFeedback); err != nil { - t.Errorf("could not decode encoded dot1q") - } else if d.Priority != 2 { - t.Errorf("priority mismatch, want 2 got %d", d.Priority) - } -} - -// testPacketMPLSInMPLS is the packet: -// 15:27:44.753678 MPLS (label 18, exp 0, ttl 255) (label 16, exp 0, [S], ttl -// 255) IP 10.31.0.1 > 10.34.0.1: ICMP echo request, id 3941, seq 4768, length -// 80 -// 0x0000: 0030 96e6 fc39 0030 9605 2838 8847 0001 .0...9.0..(8.G.. -// 0x0010: 20ff 0001 01ff 4500 0064 0050 0000 ff01 ......E..d.P.... -// 0x0020: a706 0a1f 0001 0a22 0001 0800 bd11 0f65 .......".......e -// 0x0030: 12a0 0000 0000 0053 9ee0 abcd abcd abcd .......S........ -// 0x0040: abcd abcd abcd abcd abcd abcd abcd abcd ................ -// 0x0050: abcd abcd abcd abcd abcd abcd abcd abcd ................ -// 0x0060: abcd abcd abcd abcd abcd abcd abcd abcd ................ -// 0x0070: abcd abcd abcd abcd abcd .......... -var testPacketMPLSInMPLS = []byte{ - 0x00, 0x30, 0x96, 0xe6, 0xfc, 0x39, 0x00, 0x30, 0x96, 0x05, 0x28, 0x38, 0x88, 0x47, 0x00, 0x01, - 0x20, 0xff, 0x00, 0x01, 0x01, 0xff, 0x45, 0x00, 0x00, 0x64, 0x00, 0x50, 0x00, 0x00, 0xff, 0x01, - 0xa7, 0x06, 0x0a, 0x1f, 0x00, 0x01, 0x0a, 0x22, 0x00, 0x01, 0x08, 0x00, 0xbd, 0x11, 0x0f, 0x65, - 0x12, 0xa0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x53, 0x9e, 0xe0, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, - 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, - 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, - 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, - 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, 0xab, 0xcd, -} - -func TestPacketMPLSInMPLS(t *testing.T) { - p := gopacket.NewPacket(testPacketMPLSInMPLS, LinkTypeEthernet, testDecodeOptions) - if p.ErrorLayer() != nil { - t.Error("Failed to decode packet:", p.ErrorLayer().Error()) - } - checkLayers(p, []gopacket.LayerType{ - LayerTypeEthernet, - LayerTypeMPLS, - LayerTypeMPLS, - LayerTypeIPv4, - LayerTypeICMPv4, - gopacket.LayerTypePayload}, t) -} - -// testPacketIPv4Fragmented is the packet: -// 22:11:26.616090 IP 10.1.1.1.31915 > 129.111.30.27.20197: UDP, length 28 -// 0x0000: 0000 39cf d9cd 0040 33d9 7cfd 0800 4500 ..9....@3.|...E. -// 0x0010: 0038 00f2 2000 4011 af37 0a01 0101 816f .8....@..7.....o -// 0x0020: 1e1b 7cab 4ee5 0024 0000 0000 0000 0000 ..|.N..$........ -// 0x0030: 0000 0000 0000 0000 0000 0000 0000 0000 ................ -// 0x0040: 0000 0000 0000 ...... -var testPacketIPv4Fragmented = []byte{ - 0x00, 0x00, 0x39, 0xcf, 0xd9, 0xcd, 0x00, 0x40, 0x33, 0xd9, 0x7c, 0xfd, 0x08, 0x00, 0x45, 0x00, - 0x00, 0x38, 0x00, 0xf2, 0x20, 0x00, 0x40, 0x11, 0xaf, 0x37, 0x0a, 0x01, 0x01, 0x01, 0x81, 0x6f, - 0x1e, 0x1b, 0x7c, 0xab, 0x4e, 0xe5, 0x00, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -} - -func TestPacketIPv4Fragmented(t *testing.T) { - p := gopacket.NewPacket(testPacketIPv4Fragmented, LinkTypeEthernet, testDecodeOptions) - if p.ErrorLayer() != nil { - t.Error("Failed to decode packet:", p.ErrorLayer().Error()) - } - checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeIPv4, gopacket.LayerTypeFragment}, t) - testSerializationWithOpts(t, p, testPacketIPv4Fragmented, gopacket.SerializeOptions{FixLengths: true, ComputeChecksums: true}) -} - -// testPacketDNSRegression is the packet: -// 11:08:05.708342 IP 109.194.160.4.57766 > 95.211.92.14.53: 63000% [1au] A? picslife.ru. (40) -// 0x0000: 0022 19b6 7e22 000f 35bb 0b40 0800 4500 ."..~"..5..@..E. -// 0x0010: 0044 89c4 0000 3811 2f3d 6dc2 a004 5fd3 .D....8./=m..._. -// 0x0020: 5c0e e1a6 0035 0030 a597 f618 0010 0001 \....5.0........ -// 0x0030: 0000 0000 0001 0870 6963 736c 6966 6502 .......picslife. -// 0x0040: 7275 0000 0100 0100 0029 1000 0000 8000 ru.......)...... -// 0x0050: 0000 .. -var testPacketDNSRegression = []byte{ - 0x00, 0x22, 0x19, 0xb6, 0x7e, 0x22, 0x00, 0x0f, 0x35, 0xbb, 0x0b, 0x40, 0x08, 0x00, 0x45, 0x00, - 0x00, 0x44, 0x89, 0xc4, 0x00, 0x00, 0x38, 0x11, 0x2f, 0x3d, 0x6d, 0xc2, 0xa0, 0x04, 0x5f, 0xd3, - 0x5c, 0x0e, 0xe1, 0xa6, 0x00, 0x35, 0x00, 0x30, 0xa5, 0x97, 0xf6, 0x18, 0x00, 0x10, 0x00, 0x01, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x08, 0x70, 0x69, 0x63, 0x73, 0x6c, 0x69, 0x66, 0x65, 0x02, - 0x72, 0x75, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x29, 0x10, 0x00, 0x00, 0x00, 0x80, 0x00, - 0x00, 0x00, -} - -func TestPacketDNSRegression(t *testing.T) { - p := gopacket.NewPacket(testPacketDNSRegression, LinkTypeEthernet, testDecodeOptions) - if p.ErrorLayer() != nil { - t.Error("Failed to decode packet:", p.ErrorLayer().Error()) - } - checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeIPv4, LayerTypeUDP, LayerTypeDNS}, t) -} -func BenchmarkDecodePacketDNSRegression(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testPacketDNSRegression, LinkTypeEthernet, gopacket.NoCopy) - } -} diff --git a/Godeps/_workspace/src/github.com/tsg/gopacket/layers/dot11_test.go b/Godeps/_workspace/src/github.com/tsg/gopacket/layers/dot11_test.go deleted file mode 100644 index e13fa0cec78..00000000000 --- a/Godeps/_workspace/src/github.com/tsg/gopacket/layers/dot11_test.go +++ /dev/null @@ -1,498 +0,0 @@ -// Copyright 2014, Google, Inc. All rights reserved. -// -// Use of this source code is governed by a BSD-style license -// that can be found in the LICENSE file in the root of the source -// tree. - -package layers - -import ( - _ "fmt" - "github.com/tsg/gopacket" - "net" - "reflect" - "testing" -) - -// Generator: python layers/test_creator.py --layerType=LayerTypeRadioTap --linkType=LinkTypeIEEE80211Radio --name=Dot11%s ~/Downloads/mesh.pcap -// http://wiki.wireshark.org/SampleCaptures#Sample_Captures - -// testPacketDot11CtrlCTS is the packet: -// 09:28:41.830560 20604983us tsft short preamble 24.0 Mb/s 5240 MHz 11a -79dB signal -92dB noise antenna 1 Clear-To-Send RA:d8:a2:5e:97:61:c1 -// 0x0000: 0000 1900 6f08 0000 3768 3a01 0000 0000 ....o...7h:..... -// 0x0010: 1230 7814 4001 b1a4 01c4 0094 00d8 a25e .0x.@..........^ -// 0x0020: 9761 c136 5095 8e .a.6P.. - -var testPacketDot11CtrlCTS = []byte{ - 0x00, 0x00, 0x19, 0x00, 0x6f, 0x08, 0x00, 0x00, 0x37, 0x68, 0x3a, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x12, 0x30, 0x78, 0x14, 0x40, 0x01, 0xb1, 0xa4, 0x01, 0xc4, 0x00, 0x94, 0x00, 0xd8, 0xa2, 0x5e, - 0x97, 0x61, 0xc1, 0x36, 0x50, 0x95, 0x8e, -} - -func TestPacketDot11CtrlCTS(t *testing.T) { - p := gopacket.NewPacket(testPacketDot11CtrlCTS, LinkTypeIEEE80211Radio, gopacket.Default) - if p.ErrorLayer() != nil { - t.Error("Failed to decode packet:", p.ErrorLayer().Error()) - } - checkLayers(p, []gopacket.LayerType{LayerTypeRadioTap, LayerTypeDot11}, t) - - if got, ok := p.Layer(LayerTypeRadioTap).(*RadioTap); ok { - want := &RadioTap{ - BaseLayer: BaseLayer{ - Contents: []uint8{0x0, 0x0, 0x19, 0x0, 0x6f, 0x8, 0x0, 0x0, 0x37, 0x68, 0x3a, 0x1, 0x0, 0x0, 0x0, 0x0, 0x12, 0x30, 0x78, 0x14, 0x40, 0x1, 0xb1, 0xa4, 0x1}, - Payload: []uint8{0xc4, 0x0, 0x94, 0x0, 0xd8, 0xa2, 0x5e, 0x97, 0x61, 0xc1, 0x36, 0x50, 0x95, 0x8e}, - }, - Version: 0x0, - Length: 0x19, - Present: 0x86f, - TSFT: 0x13a6837, - Flags: 0x12, - Rate: 0x30, - ChannelFrequency: 0x1478, - ChannelFlags: 0x40, - FHSS: 0x0, - DBMAntennaSignal: 1, - DBMAntennaNoise: -79, - LockQuality: 0x0, - TxAttenuation: 0x0, - DBTxAttenuation: 0x0, - DBMTxPower: 0, - Antenna: 0xa4, - DBAntennaSignal: 0x0, - DBAntennaNoise: 0x0, - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("RadioTap packet processing failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", got, want) - } - } - - if got, ok := p.Layer(LayerTypeDot11).(*Dot11); ok { - if !got.ChecksumValid() { - t.Errorf("Dot11 packet processing failed:\nchecksum failed. got :\n%#v\n\n", got) - } - - want := &Dot11{ - BaseLayer: BaseLayer{ - Contents: []uint8{0xc4, 0x0, 0x94, 0x0, 0xd8, 0xa2, 0x5e, 0x97, 0x61, 0xc1}, - Payload: []uint8{}, - }, - Type: Dot11TypeCtrlCTS, - Proto: 0x0, - Flags: 0x0, - DurationID: 0x94, - Address1: net.HardwareAddr{0xd8, 0xa2, 0x5e, 0x97, 0x61, 0xc1}, // check - Address2: net.HardwareAddr(nil), - Address3: net.HardwareAddr(nil), - Address4: net.HardwareAddr(nil), - Checksum: 0x8e955036, - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("Dot11 packet processing failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", got, want) - } - } -} - -func BenchmarkDecodePacketDot11CtrlCTS(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testPacketDot11CtrlCTS, LinkTypeIEEE80211Radio, gopacket.NoCopy) - } -} - -// testPacketDot11MgmtBeacon is the packet: -// 06:14:26.492772 637444841us tsft short preamble 6.0 Mb/s -40dB signal -96dB noise antenna 2 5180 MHz 11a Beacon () [6.0* 9.0 12.0* 18.0 24.0* 36.0 48.0 54.0 Mbit] IBSS CH: 36 -// 0x0000: 0000 2000 6708 0400 e9a2 fe25 0000 0000 ....g......%.... -// 0x0010: 220c d8a0 0200 0000 4001 0000 3c14 2411 ".......@...<.$. -// 0x0020: 8000 0000 ffff ffff ffff 0003 7f07 a016 ................ -// 0x0030: 0000 0000 0000 d09b 3840 1028 0000 0000 ........8@.(.... -// 0x0040: 6400 0005 0000 0108 8c12 9824 b048 606c d..........$.H`l -// 0x0050: 0301 2405 0400 0100 0007 2a55 5320 2401 ..$.......*US.$. -// 0x0060: 1128 0111 2c01 1130 0111 3401 1738 0117 .(..,..0..4..8.. -// 0x0070: 3c01 1740 0117 9501 1e99 011e 9d01 1ea1 <..@............ -// 0x0080: 011e a501 1e20 0100 dd18 0050 f202 0101 ...........P.... -// 0x0090: 0000 03a4 0000 27a4 0000 4243 5e00 6232 ......'...BC^.b2 -// 0x00a0: 2f00 340c 6672 6565 6273 642d 6d65 7368 /.4.freebsd-mesh -// 0x00b0: 3317 0100 0fac 0000 0fac 0000 0fac ff00 3............... -// 0x00c0: 0fac ff00 0fac ff00 df ......... -var testPacketDot11MgmtBeacon = []byte{ - 0x00, 0x00, 0x20, 0x00, 0x67, 0x08, 0x04, 0x00, 0xe9, 0xa2, 0xfe, 0x25, 0x00, 0x00, 0x00, 0x00, - 0x22, 0x0c, 0xd8, 0xa0, 0x02, 0x00, 0x00, 0x00, 0x40, 0x01, 0x00, 0x00, 0x3c, 0x14, 0x24, 0x11, - 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x03, 0x7f, 0x07, 0xa0, 0x16, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x9b, 0x38, 0x40, 0x10, 0x28, 0x00, 0x00, 0x00, 0x00, - 0x64, 0x00, 0x00, 0x05, 0x00, 0x00, 0x01, 0x08, 0x8c, 0x12, 0x98, 0x24, 0xb0, 0x48, 0x60, 0x6c, - 0x03, 0x01, 0x24, 0x05, 0x04, 0x00, 0x01, 0x00, 0x00, 0x07, 0x2a, 0x55, 0x53, 0x20, 0x24, 0x01, - 0x11, 0x28, 0x01, 0x11, 0x2c, 0x01, 0x11, 0x30, 0x01, 0x11, 0x34, 0x01, 0x17, 0x38, 0x01, 0x17, - 0x3c, 0x01, 0x17, 0x40, 0x01, 0x17, 0x95, 0x01, 0x1e, 0x99, 0x01, 0x1e, 0x9d, 0x01, 0x1e, 0xa1, - 0x01, 0x1e, 0xa5, 0x01, 0x1e, 0x20, 0x01, 0x00, 0xdd, 0x18, 0x00, 0x50, 0xf2, 0x02, 0x01, 0x01, - 0x00, 0x00, 0x03, 0xa4, 0x00, 0x00, 0x27, 0xa4, 0x00, 0x00, 0x42, 0x43, 0x5e, 0x00, 0x62, 0x32, - 0x2f, 0x00, 0x34, 0x0c, 0x66, 0x72, 0x65, 0x65, 0x62, 0x73, 0x64, 0x2d, 0x6d, 0x65, 0x73, 0x68, - 0x33, 0x17, 0x01, 0x00, 0x0f, 0xac, 0x00, 0x00, 0x0f, 0xac, 0x00, 0x00, 0x0f, 0xac, 0xff, 0x00, - 0x0f, 0xac, 0xff, 0x00, 0x0f, 0xac, 0xff, 0x00, 0xdf, -} - -func TestPacketDot11MgmtBeacon(t *testing.T) { - p := gopacket.NewPacket(testPacketDot11MgmtBeacon, LinkTypeIEEE80211Radio, gopacket.Default) - if p.ErrorLayer() != nil { - t.Error("Failed to decode packet:", p.ErrorLayer().Error()) - } - - checkLayers(p, []gopacket.LayerType{LayerTypeRadioTap, LayerTypeDot11, LayerTypeDot11MgmtBeacon}, t) - - if got, ok := p.Layer(LayerTypeRadioTap).(*RadioTap); ok { - want := &RadioTap{BaseLayer: BaseLayer{Contents: []uint8{0x0, 0x0, 0x20, 0x0, 0x67, 0x8, 0x4, 0x0, 0xe9, 0xa2, 0xfe, 0x25, 0x0, 0x0, 0x0, 0x0, 0x22, 0xc, 0xd8, 0xa0, 0x2, 0x0, 0x0, 0x0, 0x40, 0x1, 0x0, 0x0, 0x3c, 0x14, 0x24, 0x11}, Payload: []uint8{0x80, 0x0, 0x0, 0x0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0, 0x3, 0x7f, 0x7, 0xa0, 0x16, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xd0, 0x9b, 0x38, 0x40, 0x10, 0x28, 0x0, 0x0, 0x0, 0x0, 0x64, 0x0, 0x0, 0x5, 0x0, 0x0, 0x1, 0x8, 0x8c, 0x12, 0x98, 0x24, 0xb0, 0x48, 0x60, 0x6c, 0x3, 0x1, 0x24, 0x5, 0x4, 0x0, 0x1, 0x0, 0x0, 0x7, 0x2a, 0x55, 0x53, 0x20, 0x24, 0x1, 0x11, 0x28, 0x1, 0x11, 0x2c, 0x1, 0x11, 0x30, 0x1, 0x11, 0x34, 0x1, 0x17, 0x38, 0x1, 0x17, 0x3c, 0x1, 0x17, 0x40, 0x1, 0x17, 0x95, 0x1, 0x1e, 0x99, 0x1, 0x1e, 0x9d, 0x1, 0x1e, 0xa1, 0x1, 0x1e, 0xa5, 0x1, 0x1e, 0x20, 0x1, 0x0, 0xdd, 0x18, 0x0, 0x50, 0xf2, 0x2, 0x1, 0x1, 0x0, 0x0, 0x3, 0xa4, 0x0, 0x0, 0x27, 0xa4, 0x0, 0x0, 0x42, 0x43, 0x5e, 0x0, 0x62, 0x32, 0x2f, 0x0, 0x34, 0xc, 0x66, 0x72, 0x65, 0x65, 0x62, 0x73, 0x64, 0x2d, 0x6d, 0x65, 0x73, 0x68, 0x33, 0x17, 0x1, 0x0, 0xf, 0xac, 0x0, 0x0, 0xf, 0xac, 0x0, 0x0, 0xf, 0xac, 0xff, 0x0, 0xf, 0xac, 0xff, 0x0, 0xf, 0xac, 0xff, 0x0, 0xdf}}, Version: 0x0, Length: 0x20, Present: 0x40867, TSFT: 0x25fea2e9, Flags: 0x22, Rate: 0xc, ChannelFrequency: 0x0, ChannelFlags: 0x0, FHSS: 0x0, DBMAntennaSignal: -40, DBMAntennaNoise: -96, LockQuality: 0x0, TxAttenuation: 0x0, DBTxAttenuation: 0x0, DBMTxPower: 0, Antenna: 0x2, DBAntennaSignal: 0x0, DBAntennaNoise: 0x0} - - if !reflect.DeepEqual(got, want) { - t.Errorf("RadioTap packet processing failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", got, want) - } - } - - if got, ok := p.Layer(LayerTypeDot11).(*Dot11); ok { - want := &Dot11{ - BaseLayer: BaseLayer{ - Contents: []uint8{0x80, 0x0, 0x0, 0x0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0, 0x3, 0x7f, 0x7, 0xa0, 0x16, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xd0, 0x9b}, - Payload: []uint8{0x38, 0x40, 0x10, 0x28, 0x0, 0x0, 0x0, 0x0, 0x64, 0x0, 0x0, 0x5, 0x0, 0x0, 0x1, 0x8, 0x8c, 0x12, 0x98, 0x24, 0xb0, 0x48, 0x60, 0x6c, 0x3, 0x1, 0x24, 0x5, 0x4, 0x0, 0x1, 0x0, 0x0, 0x7, 0x2a, 0x55, 0x53, 0x20, 0x24, 0x1, 0x11, 0x28, 0x1, 0x11, 0x2c, 0x1, 0x11, 0x30, 0x1, 0x11, 0x34, 0x1, 0x17, 0x38, 0x1, 0x17, 0x3c, 0x1, 0x17, 0x40, 0x1, 0x17, 0x95, 0x1, 0x1e, 0x99, 0x1, 0x1e, 0x9d, 0x1, 0x1e, 0xa1, 0x1, 0x1e, 0xa5, 0x1, 0x1e, 0x20, 0x1, 0x0, 0xdd, 0x18, 0x0, 0x50, 0xf2, 0x2, 0x1, 0x1, 0x0, 0x0, 0x3, 0xa4, 0x0, 0x0, 0x27, 0xa4, 0x0, 0x0, 0x42, 0x43, 0x5e, 0x0, 0x62, 0x32, 0x2f, 0x0, 0x34, 0xc, 0x66, 0x72, 0x65, 0x65, 0x62, 0x73, 0x64, 0x2d, 0x6d, 0x65, 0x73, 0x68, 0x33, 0x17, 0x1, 0x0, 0xf, 0xac, 0x0, 0x0, 0xf, 0xac, 0x0, 0x0, 0xf, 0xac, 0xff, 0x0, 0xf, 0xac, 0xff, 0x0, 0xf}, - }, - Type: Dot11TypeMgmtBeacon, - Proto: 0x0, - Flags: 0x0, - DurationID: 0x0, - Address1: net.HardwareAddr{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, - Address2: net.HardwareAddr{0x0, 0x3, 0x7f, 0x7, 0xa0, 0x16}, - Address3: net.HardwareAddr{0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, - Address4: net.HardwareAddr(nil), - SequenceNumber: 0x26f, FragmentNumber: 0x10, - Checksum: 0xdf00ffac, - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("Dot11 packet processing failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", got, want) - } - } -} - -func BenchmarkDecodePacketDot11MgmtBeacon(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testPacketDot11MgmtBeacon, LinkTypeIEEE80211Radio, gopacket.NoCopy) - } -} - -// testPacketDot11DataQOSData is the packet: -// 06:14:27.838634 638790765us tsft short preamble 54.0 Mb/s -51dB signal -96dB noise antenna 2 5180 MHz 11a CF +QoS ARP, Request who-has 140.180.51.68 tell 169.254.247.0, length 28 -// 0x0000: 0000 2000 6708 0400 6d2c 1326 0000 0000 ....g...m,.&.... -// 0x0010: 226c cda0 0200 0000 4001 0000 3c14 2411 "l......@...<.$. -// 0x0020: 8801 2c00 0603 7f07 a016 0019 e3d3 5352 ..,...........SR -// 0x0030: ffff ffff ffff 5064 0000 50aa aaaa 0300 ......Pd..P..... -// 0x0040: 0000 0806 0001 0800 0604 0001 0019 e3d3 ................ -// 0x0050: 5352 a9fe f700 0000 0000 0000 8cb4 3344 SR............3D -var testPacketDot11DataQOSData = []byte{ - 0x00, 0x00, 0x20, 0x00, 0x67, 0x08, 0x04, 0x00, 0x6d, 0x2c, 0x13, 0x26, 0x00, 0x00, 0x00, 0x00, - 0x22, 0x6c, 0xcd, 0xa0, 0x02, 0x00, 0x00, 0x00, 0x40, 0x01, 0x00, 0x00, 0x3c, 0x14, 0x24, 0x11, - 0x88, 0x01, 0x2c, 0x00, 0x06, 0x03, 0x7f, 0x07, 0xa0, 0x16, 0x00, 0x19, 0xe3, 0xd3, 0x53, 0x52, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x50, 0x64, 0x00, 0x00, 0x50, 0xaa, 0xaa, 0xaa, 0x03, 0x00, - 0x00, 0x00, 0x08, 0x06, 0x00, 0x01, 0x08, 0x00, 0x06, 0x04, 0x00, 0x01, 0x00, 0x19, 0xe3, 0xd3, - 0x53, 0x52, 0xa9, 0xfe, 0xf7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8c, 0xb4, 0x33, 0x44, -} - -func TestPacketDot11DataQOSData(t *testing.T) { - p := gopacket.NewPacket(testPacketDot11DataQOSData, LinkTypeIEEE80211Radio, gopacket.Default) - if p.ErrorLayer() != nil { - t.Error("Failed to decode packet:", p.ErrorLayer().Error()) - } - checkLayers(p, []gopacket.LayerType{LayerTypeRadioTap, LayerTypeDot11, LayerTypeDot11DataQOSData, LayerTypeDot11Data, LayerTypeLLC, LayerTypeSNAP, LayerTypeARP}, t) - - if got, ok := p.Layer(LayerTypeARP).(*ARP); ok { - want := &ARP{BaseLayer: BaseLayer{ - Contents: []uint8{0x0, 0x1, 0x8, 0x0, 0x6, 0x4, 0x0, 0x1, 0x0, 0x19, 0xe3, 0xd3, 0x53, 0x52, 0xa9, 0xfe, 0xf7, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8c, 0xb4, 0x33, 0x44}, - Payload: []uint8{}, - }, - AddrType: 0x1, - Protocol: 0x800, - HwAddressSize: 0x6, - ProtAddressSize: 0x4, - Operation: 0x1, - SourceHwAddress: []uint8{0x0, 0x19, 0xe3, 0xd3, 0x53, 0x52}, - SourceProtAddress: []uint8{0xa9, 0xfe, 0xf7, 0x0}, - DstHwAddress: []uint8{0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, - DstProtAddress: []uint8{0x8c, 0xb4, 0x33, 0x44}, - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("ARP packet processing failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", got, want) - } - } -} -func BenchmarkDecodePacketDot11DataQOSData(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testPacketDot11DataQOSData, LinkTypeIEEE80211Radio, gopacket.NoCopy) - } -} - -// this test is failing, this has probably todo with the datapad - -// testPacketDot11MgmtAction is the packet: -// 06:14:23.248019 634199967us tsft short preamble 6.0 Mb/s -41dB signal -96dB noise antenna 1 5180 MHz 11a Action (00:03:7f:07:a0:16): Reserved(32) Act#0 -// 0x0000: 0000 2000 6708 0400 9f1f cd25 0000 0000 ....g......%.... -// 0x0010: 220c d7a0 0100 0000 4001 0000 3c14 2411 ".......@...<.$. -// 0x0020: d000 0000 ffff ffff ffff 0003 7f07 a016 ................ -// 0x0030: 0003 7f07 a016 a002 2000 4425 0001 1e06 ..........D%.... -// 0x0040: 0000 0000 037f 0342 5206 0000 0088 1300 .......BR....... -// 0x0050: 0030 0b00 0001 0600 16cb ace5 f900 0000 .0.............. -// 0x0060: 00 . -var testPacketDot11MgmtAction = []byte{ - 0x00, 0x00, 0x20, 0x00, 0x67, 0x08, 0x04, 0x00, 0x9f, 0x1f, 0xcd, 0x25, 0x00, 0x00, 0x00, 0x00, - 0x22, 0x0c, 0xd7, 0xa0, 0x01, 0x00, 0x00, 0x00, 0x40, 0x01, 0x00, 0x00, 0x3c, 0x14, 0x24, 0x11, - 0xd0, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x03, 0x7f, 0x07, 0xa0, 0x16, - 0x00, 0x03, 0x7f, 0x07, 0xa0, 0x16, 0xa0, 0x02, 0x20, 0x00, 0x44, 0x25, 0x00, 0x01, 0x1e, 0x06, - 0x00, 0x00, 0x00, 0x00, 0x03, 0x7f, 0x03, 0x42, 0x52, 0x06, 0x00, 0x00, 0x00, 0x88, 0x13, 0x00, - 0x00, 0x30, 0x0b, 0x00, 0x00, 0x01, 0x06, 0x00, 0x16, 0xcb, 0xac, 0xe5, 0xf9, 0x00, 0x00, 0x00, - 0x00, -} - -func TestPacketDot11MgmtAction(t *testing.T) { - p := gopacket.NewPacket(testPacketDot11MgmtAction, LinkTypeIEEE80211Radio, gopacket.Default) - if p.ErrorLayer() != nil { - t.Error("Failed to decode packet:", p.ErrorLayer().Error()) - } - checkLayers(p, []gopacket.LayerType{LayerTypeRadioTap, LayerTypeDot11, LayerTypeDot11MgmtAction}, t) - - want := `PACKET: 97 bytes -- Layer 1 (32 bytes) = RadioTap {Contents=[..32..] Payload=[..65..] Version=0 Length=32 Present=264295 TSFT=634199967 Flags=SHORT-PREAMBLE,DATAPAD Rate=6 Mb/s ChannelFrequency=0 MHz ChannelFlags= FHSS=0 DBMAntennaSignal=-41 DBMAntennaNoise=-96 LockQuality=0 TxAttenuation=0 DBTxAttenuation=0 DBMTxPower=0 Antenna=1 DBAntennaSignal=0 DBAntennaNoise=0} -- Layer 2 (24 bytes) = Dot11 {Contents=[..24..] Payload=[..37..] Type=MgmtAction Proto=0 Flags= DurationID=0 Address1=ff:ff:ff:ff:ff:ff Address2=00:03:7f:07:a0:16 Address3=00:03:7f:07:a0:16 Address4= SequenceNumber=10 FragmentNumber=32 Checksum=0} -- Layer 3 (37 bytes) = Dot11MgmtAction {Contents=[..37..] Payload=[]} -` - if got := p.String(); got != want { - t.Errorf("packet string mismatch:\n---got---\n%q\n---want---\n%q", got, want) - } - if _, ok := p.Layer(LayerTypeDot11).(*Dot11); !ok { - t.Errorf("could not get Dot11 layer from packet") - } else { - // See note above: this checksum fails most likely due to datapad. - // wireshark also says this packet is malformed, so I'm not going to waste - // too much more time on it. - // if !got.ChecksumValid() { t.Errorf("Dot11 packet processing failed: checksum failed") } - } -} -func BenchmarkDecodePacketDot11MgmtAction(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testPacketDot11MgmtAction, LinkTypeIEEE80211Radio, gopacket.NoCopy) - } -} - -// testPacketDot11CtrlAck is the packet: -// 06:14:27.838669 638758038us tsft short preamble 24.0 Mb/s -39dB signal -96dB noise antenna 2 5180 MHz 11a Acknowledgment RA:00:19:e3:d3:53:52 -// 0x0000: 0000 2000 6708 0400 96ac 1226 0000 0000 ....g......&.... -// 0x0010: 2230 d9a0 0200 0000 4001 0000 3c14 2411 "0......@...<.$. -// 0x0020: d400 0000 0019 e3d3 5352 46e9 7687 ........SRF.v. -var testPacketDot11CtrlAck = []byte{ - 0x00, 0x00, 0x20, 0x00, 0x67, 0x08, 0x04, 0x00, 0x96, 0xac, 0x12, 0x26, 0x00, 0x00, 0x00, 0x00, - 0x22, 0x30, 0xd9, 0xa0, 0x02, 0x00, 0x00, 0x00, 0x40, 0x01, 0x00, 0x00, 0x3c, 0x14, 0x24, 0x11, - 0xd4, 0x00, 0x00, 0x00, 0x00, 0x19, 0xe3, 0xd3, 0x53, 0x52, 0x46, 0xe9, 0x76, 0x87, -} - -func TestPacketDot11CtrlAck(t *testing.T) { - p := gopacket.NewPacket(testPacketDot11CtrlAck, LinkTypeIEEE80211Radio, gopacket.Default) - if p.ErrorLayer() != nil { - t.Error("Failed to decode packet:", p.ErrorLayer().Error()) - } - checkLayers(p, []gopacket.LayerType{LayerTypeRadioTap, LayerTypeDot11}, t) - - if got, ok := p.Layer(LayerTypeDot11).(*Dot11); ok { - if !got.ChecksumValid() { - t.Errorf("Dot11 packet processing failed:\nchecksum failed. got :\n%#v\n\n", got) - } - } - - if got, ok := p.Layer(LayerTypeDot11).(*Dot11); ok { - want := &Dot11{ - BaseLayer: BaseLayer{ - Contents: []uint8{0xd4, 0x0, 0x0, 0x0, 0x0, 0x19, 0xe3, 0xd3, 0x53, 0x52}, - Payload: []uint8{}, - }, - Type: Dot11TypeCtrlAck, - Proto: 0x0, - Flags: 0x0, - DurationID: 0x0, - Address1: net.HardwareAddr{0x0, 0x19, 0xe3, 0xd3, 0x53, 0x52}, - Address2: net.HardwareAddr(nil), - Address3: net.HardwareAddr(nil), - Address4: net.HardwareAddr(nil), - Checksum: 0x8776e946, - } - if !reflect.DeepEqual(got, want) { - t.Errorf("Dot11 packet processing failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", got, want) - } - } -} -func BenchmarkDecodePacketDot11CtrlAck(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testPacketDot11CtrlAck, LinkTypeIEEE80211Radio, gopacket.NoCopy) - } -} - -// testPacketDot11DataARP is the packet: -// 06:14:11.512316 622463798us tsft short preamble 6.0 Mb/s -39dB signal -96dB noise antenna 2 5180 MHz 11a ARP, Request who-has 67.8.14.54 tell 169.254.247.0, length 28 -// 0x0000: 0000 2000 6708 0400 360b 1a25 0000 0000 ....g...6..%.... -// 0x0010: 220c d9a0 0200 0000 4001 0000 3c14 2411 ".......@...<.$. -// 0x0020: 0802 0000 ffff ffff ffff 0603 7f07 a016 ................ -// 0x0030: 0019 e3d3 5352 e07f aaaa 0300 0000 0806 ....SR.......... -// 0x0040: 0001 0800 0604 0001 0019 e3d3 5352 a9fe ............SR.. -// 0x0050: f700 0000 0000 0000 4308 0e36 ........C..6 -var testPacketDot11DataARP = []byte{ - 0x00, 0x00, 0x20, 0x00, 0x67, 0x08, 0x04, 0x00, 0x36, 0x0b, 0x1a, 0x25, 0x00, 0x00, 0x00, 0x00, - 0x22, 0x0c, 0xd9, 0xa0, 0x02, 0x00, 0x00, 0x00, 0x40, 0x01, 0x00, 0x00, 0x3c, 0x14, 0x24, 0x11, - 0x08, 0x02, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x06, 0x03, 0x7f, 0x07, 0xa0, 0x16, - 0x00, 0x19, 0xe3, 0xd3, 0x53, 0x52, 0xe0, 0x7f, 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00, 0x08, 0x06, - 0x00, 0x01, 0x08, 0x00, 0x06, 0x04, 0x00, 0x01, 0x00, 0x19, 0xe3, 0xd3, 0x53, 0x52, 0xa9, 0xfe, - 0xf7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x43, 0x08, 0x0e, 0x36, -} - -func TestPacketDot11DataARP(t *testing.T) { - p := gopacket.NewPacket(testPacketDot11DataARP, LinkTypeIEEE80211Radio, gopacket.Default) - if p.ErrorLayer() != nil { - t.Error("Failed to decode packet:", p.ErrorLayer().Error()) - } - checkLayers(p, []gopacket.LayerType{LayerTypeRadioTap, LayerTypeDot11, LayerTypeDot11Data, LayerTypeLLC, LayerTypeSNAP, LayerTypeARP}, t) - - if got, ok := p.Layer(LayerTypeARP).(*ARP); ok { - want := &ARP{ - BaseLayer: BaseLayer{ - Contents: []uint8{0x0, 0x1, 0x8, 0x0, 0x6, 0x4, 0x0, 0x1, 0x0, 0x19, 0xe3, 0xd3, 0x53, 0x52, 0xa9, 0xfe, 0xf7, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x43, 0x8, 0xe, 0x36}, - Payload: []uint8{}, - }, - AddrType: 0x1, - Protocol: 0x800, - HwAddressSize: 0x6, - ProtAddressSize: 0x4, - Operation: 0x1, - SourceHwAddress: []uint8{0x0, 0x19, 0xe3, 0xd3, 0x53, 0x52}, - SourceProtAddress: []uint8{0xa9, 0xfe, 0xf7, 0x0}, - DstHwAddress: []uint8{0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, - DstProtAddress: []uint8{0x43, 0x8, 0xe, 0x36}, - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("ARP packet processing failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", got, want) - } - } -} - -func BenchmarkDecodePacketDot11DataARP(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testPacketDot11DataARP, LinkTypeIEEE80211Radio, gopacket.NoCopy) - } -} - -// testPacketDot11DataIP is the packet: -// 06:14:21.388622 632340487us tsft short preamble 6.0 Mb/s -40dB signal -96dB noise antenna 1 5180 MHz 11a IP 0.0.0.0.68 > 255.255.255.255.67: BOOTP/DHCP, Request from 00:19:e3:d3:53:52, length 300 -// 0x0000: 0000 2000 6708 0400 07c0 b025 0000 0000 ....g......%.... -// 0x0010: 220c d8a0 0100 0000 4001 0000 3c14 2411 ".......@...<.$. -// 0x0020: 0802 0000 ffff ffff ffff 0603 7f07 a016 ................ -// 0x0030: 0019 e3d3 5352 4095 aaaa 0300 0000 0800 ....SR@......... -// 0x0040: 4500 0148 c514 0000 ff11 f590 0000 0000 E..H............ -// 0x0050: ffff ffff 0044 0043 0134 2b39 0101 0600 .....D.C.4+9.... -// 0x0060: 131f 8c43 003c 0000 0000 0000 0000 0000 ...C.<.......... -// 0x0070: 0000 0000 0000 0000 0019 e3d3 5352 0000 ............SR.. -// 0x0080: 0000 0000 0000 0000 0000 0000 0000 0000 ................ -// 0x0090: 0000 0000 0000 0000 0000 0000 0000 0000 ................ -// 0x00a0: 0000 0000 0000 0000 0000 0000 0000 0000 ................ -// 0x00b0: 0000 0000 0000 0000 0000 0000 0000 0000 ................ -// 0x00c0: 0000 0000 0000 0000 0000 0000 0000 0000 ................ -// 0x00d0: 0000 0000 0000 0000 0000 0000 0000 0000 ................ -// 0x00e0: 0000 0000 0000 0000 0000 0000 0000 0000 ................ -// 0x00f0: 0000 0000 0000 0000 0000 0000 0000 0000 ................ -// 0x0100: 0000 0000 0000 0000 0000 0000 0000 0000 ................ -// 0x0110: 0000 0000 0000 0000 0000 0000 0000 0000 ................ -// 0x0120: 0000 0000 0000 0000 0000 0000 0000 0000 ................ -// 0x0130: 0000 0000 0000 0000 0000 0000 0000 0000 ................ -// 0x0140: 0000 0000 0000 0000 6382 5363 3501 0137 ........c.Sc5..7 -// 0x0150: 0a01 0306 0f77 5ffc 2c2e 2f39 0205 dc3d .....w_.,./9...= -// 0x0160: 0701 0019 e3d3 5352 3304 0076 a700 0c0b ......SR3..v.... -// 0x0170: 4d61 6369 6e74 6f73 682d 34ff 0000 0000 Macintosh-4..... -// 0x0180: 0000 0000 0000 0000 ........ -var testPacketDot11DataIP = []byte{ - 0x00, 0x00, 0x20, 0x00, 0x67, 0x08, 0x04, 0x00, 0x07, 0xc0, 0xb0, 0x25, 0x00, 0x00, 0x00, 0x00, - 0x22, 0x0c, 0xd8, 0xa0, 0x01, 0x00, 0x00, 0x00, 0x40, 0x01, 0x00, 0x00, 0x3c, 0x14, 0x24, 0x11, - 0x08, 0x02, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x06, 0x03, 0x7f, 0x07, 0xa0, 0x16, - 0x00, 0x19, 0xe3, 0xd3, 0x53, 0x52, 0x40, 0x95, 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00, 0x08, 0x00, - 0x45, 0x00, 0x01, 0x48, 0xc5, 0x14, 0x00, 0x00, 0xff, 0x11, 0xf5, 0x90, 0x00, 0x00, 0x00, 0x00, - 0xff, 0xff, 0xff, 0xff, 0x00, 0x44, 0x00, 0x43, 0x01, 0x34, 0x2b, 0x39, 0x01, 0x01, 0x06, 0x00, - 0x13, 0x1f, 0x8c, 0x43, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x19, 0xe3, 0xd3, 0x53, 0x52, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x82, 0x53, 0x63, 0x35, 0x01, 0x01, 0x37, - 0x0a, 0x01, 0x03, 0x06, 0x0f, 0x77, 0x5f, 0xfc, 0x2c, 0x2e, 0x2f, 0x39, 0x02, 0x05, 0xdc, 0x3d, - 0x07, 0x01, 0x00, 0x19, 0xe3, 0xd3, 0x53, 0x52, 0x33, 0x04, 0x00, 0x76, 0xa7, 0x00, 0x0c, 0x0b, - 0x4d, 0x61, 0x63, 0x69, 0x6e, 0x74, 0x6f, 0x73, 0x68, 0x2d, 0x34, 0xff, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -} - -func TestPacketDot11DataIP(t *testing.T) { - p := gopacket.NewPacket(testPacketDot11DataIP, LinkTypeIEEE80211Radio, gopacket.Default) - if p.ErrorLayer() != nil { - t.Error("Failed to decode packet:", p.ErrorLayer().Error()) - } - checkLayers(p, []gopacket.LayerType{LayerTypeRadioTap, LayerTypeDot11, LayerTypeDot11Data, LayerTypeLLC, LayerTypeSNAP, LayerTypeIPv4, LayerTypeUDP, gopacket.LayerTypePayload}, t) -} -func BenchmarkDecodePacketDot11DataIP(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testPacketDot11DataIP, LinkTypeIEEE80211Radio, gopacket.NoCopy) - } -} - -// Encrypted - -/// testPacketP6196 is the packet: -// 09:28:41.830631 20605036us tsft wep -69dB signal -92dB noise antenna 1 5240 MHz 11a ht/40- 162.0 Mb/s MCS 12 40 MHz lon GI mixed BCC FEC [bit 20] CF +QoS Data IV:50a9 Pad 20 KeyID 0 -// 0x0000: 0000 3000 6b08 1c00 6c68 3a01 0000 0000 ..0.k...lh:..... -// 0x0010: 1400 7814 4001 bba4 0160 0e1a 4001 0400 ..x.@....`..@... -// 0x0020: 7814 3022 1f01 0cff b10d 0000 0400 0000 x.0"............ -// 0x0030: 8841 2c00 0025 9c42 c262 d8a2 5e97 61c1 .A,..%.B.b..^.a. -// 0x0040: 0025 9c42 c25f 10db 0000 a950 0020 0000 .%.B._.....P.... -// 0x0050: 0000 f8ab a97e 3fbd d6e1 785b 0040 5f15 .....~?...x[.@_. -// 0x0060: 7123 8711 bd1f ffb9 e5b3 84bb ec2a 0a90 q#...........*.. -// 0x0070: d0a0 1a6f 9033 1083 5179 a0da f833 3a00 ...o.3..Qy...3:. -// 0x0080: 5471 f596 539b 1823 a33c 4908 545c 266a Tq..S..#. fe80::21f:caff:feb3:7640: ICMP6, neighbor advertisement, tgt is 2620:0:1005:0:26be:5ff:fe27:b17, length 24 -// 0x0000: 001f cab3 7640 24be 0527 0b17 86dd 6000 ....v@$..'....`. -// 0x0010: 0000 0018 3aff 2620 0000 1005 0000 26be ....:.&.......&. -// 0x0020: 05ff fe27 0b17 fe80 0000 0000 0000 021f ...'............ -// 0x0030: caff feb3 7640 8800 1ed6 4000 0000 2620 ....v@....@...&. -// 0x0040: 0000 1005 0000 26be 05ff fe27 0b17 ......&....'.. -var testPacketICMPv6 = []byte{ - 0x00, 0x1f, 0xca, 0xb3, 0x76, 0x40, 0x24, 0xbe, 0x05, 0x27, 0x0b, 0x17, 0x86, 0xdd, 0x60, 0x00, - 0x00, 0x00, 0x00, 0x18, 0x3a, 0xff, 0x26, 0x20, 0x00, 0x00, 0x10, 0x05, 0x00, 0x00, 0x26, 0xbe, - 0x05, 0xff, 0xfe, 0x27, 0x0b, 0x17, 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x1f, - 0xca, 0xff, 0xfe, 0xb3, 0x76, 0x40, 0x88, 0x00, 0x1e, 0xd6, 0x40, 0x00, 0x00, 0x00, 0x26, 0x20, - 0x00, 0x00, 0x10, 0x05, 0x00, 0x00, 0x26, 0xbe, 0x05, 0xff, 0xfe, 0x27, 0x0b, 0x17, -} - -func TestPacketICMPv6(t *testing.T) { - p := gopacket.NewPacket(testPacketICMPv6, LinkTypeEthernet, gopacket.Default) - if p.ErrorLayer() != nil { - t.Error("Failed to decode packet:", p.ErrorLayer().Error()) - } - checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeIPv6, LayerTypeICMPv6, gopacket.LayerTypePayload}, t) - if got, ok := p.Layer(LayerTypeIPv6).(*IPv6); ok { - want := &IPv6{ - BaseLayer: BaseLayer{ - Contents: []byte{0x60, 0x0, 0x0, 0x0, 0x0, 0x18, - 0x3a, 0xff, 0x26, 0x20, 0x0, 0x0, 0x10, 0x5, 0x0, 0x0, 0x26, 0xbe, 0x5, - 0xff, 0xfe, 0x27, 0xb, 0x17, 0xfe, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x2, 0x1f, 0xca, 0xff, 0xfe, 0xb3, 0x76, 0x40}, - Payload: []byte{0x88, 0x0, 0x1e, 0xd6, 0x40, 0x0, 0x0, 0x0, 0x26, 0x20, - 0x0, 0x0, 0x10, 0x5, 0x0, 0x0, 0x26, 0xbe, 0x5, 0xff, 0xfe, 0x27, 0xb, - 0x17}, - }, - Version: 6, - TrafficClass: 0, - FlowLabel: 0, - Length: 24, - NextHeader: IPProtocolICMPv6, - HopLimit: 255, - SrcIP: net.IP{0x26, 0x20, 0x0, 0x0, 0x10, 0x5, 0x0, 0x0, 0x26, 0xbe, 0x5, 0xff, 0xfe, 0x27, 0xb, 0x17}, - DstIP: net.IP{0xfe, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2, 0x1f, 0xca, 0xff, 0xfe, 0xb3, 0x76, 0x40}, - } - if !reflect.DeepEqual(got, want) { - t.Errorf("IPv6 packet processing failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", got, want) - } - } else { - t.Error("No IPv6 layer type found in packet") - } - if got, ok := p.Layer(LayerTypeICMPv6).(*ICMPv6); ok { - want := &ICMPv6{ - BaseLayer: BaseLayer{ - Contents: []byte{0x88, 0x0, 0x1e, 0xd6, 0x40, 0x0, 0x0, 0x0}, - Payload: []byte{0x26, 0x20, 0x0, 0x0, 0x10, - 0x5, 0x0, 0x0, 0x26, 0xbe, 0x5, 0xff, 0xfe, 0x27, 0xb, 0x17}, - }, - TypeCode: 0x8800, - Checksum: 0x1ed6, - TypeBytes: []byte{0x40, 0x0, 0x0, 0x0}, - } - if !reflect.DeepEqual(got, want) { - t.Errorf("ICMPv6 packet processing failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", got, want) - } - if got.TypeCode.String() != "NeighborAdvertisement(0)" { - t.Errorf("ICMPv6 type code, got %q want 'NeighborAdvertisement(0)'", got.TypeCode.String()) - } - } else { - t.Error("No ICMPv6 layer type found in packet") - } -} diff --git a/Godeps/_workspace/src/github.com/tsg/gopacket/layers/ipsec_test.go b/Godeps/_workspace/src/github.com/tsg/gopacket/layers/ipsec_test.go deleted file mode 100644 index 9dbf344159d..00000000000 --- a/Godeps/_workspace/src/github.com/tsg/gopacket/layers/ipsec_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2012, Google, Inc. All rights reserved. -// -// Use of this source code is governed by a BSD-style license -// that can be found in the LICENSE file in the root of the source -// tree. - -package layers - -import ( - "github.com/tsg/gopacket" - "testing" -) - -// testPacketIPSecESP is the packet: -// 04:30:37.629376 IP 190.0.0.1 > 190.0.0.2: ESP(spi=0x0000006e,seq=0x13), length 116 -// 0x0000: 0000 0000 0012 0011 434a d70a 0800 4500 ........CJ....E. -// 0x0010: 0088 0000 4000 4032 be40 be00 0001 be00 ....@.@2.@...... -// 0x0020: 0002 0000 006e 0000 0013 82f4 1077 0418 .....n.......w.. -// 0x0030: e8ce dc45 1bac 22bb daaf 2ad2 c2e8 315b ...E.."...*...1[ -// 0x0040: ce9a 39da 2aae cf43 3716 70ab 7e7c 4676 ..9.*..C7.p.~|Fv -// 0x0050: c3fc d109 c990 274d f81c 6534 9a40 a0ef ......'M..e4.@.. -// 0x0060: 46b1 7da5 05af dda8 d0ba 6e23 d1ee 1f10 F.}.......n#.... -// 0x0070: 730c 7371 03b1 445c 2f70 852f 8475 12fb s.sq..D\/p./.u.. -// 0x0080: b057 a19b a617 bae7 09ca 8836 942f 3334 .W.........6./34 -// 0x0090: 312b 96d2 a4e3 1+.... -var testPacketIPSecESP = []byte{ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x00, 0x11, 0x43, 0x4a, 0xd7, 0x0a, 0x08, 0x00, 0x45, 0x00, - 0x00, 0x88, 0x00, 0x00, 0x40, 0x00, 0x40, 0x32, 0xbe, 0x40, 0xbe, 0x00, 0x00, 0x01, 0xbe, 0x00, - 0x00, 0x02, 0x00, 0x00, 0x00, 0x6e, 0x00, 0x00, 0x00, 0x13, 0x82, 0xf4, 0x10, 0x77, 0x04, 0x18, - 0xe8, 0xce, 0xdc, 0x45, 0x1b, 0xac, 0x22, 0xbb, 0xda, 0xaf, 0x2a, 0xd2, 0xc2, 0xe8, 0x31, 0x5b, - 0xce, 0x9a, 0x39, 0xda, 0x2a, 0xae, 0xcf, 0x43, 0x37, 0x16, 0x70, 0xab, 0x7e, 0x7c, 0x46, 0x76, - 0xc3, 0xfc, 0xd1, 0x09, 0xc9, 0x90, 0x27, 0x4d, 0xf8, 0x1c, 0x65, 0x34, 0x9a, 0x40, 0xa0, 0xef, - 0x46, 0xb1, 0x7d, 0xa5, 0x05, 0xaf, 0xdd, 0xa8, 0xd0, 0xba, 0x6e, 0x23, 0xd1, 0xee, 0x1f, 0x10, - 0x73, 0x0c, 0x73, 0x71, 0x03, 0xb1, 0x44, 0x5c, 0x2f, 0x70, 0x85, 0x2f, 0x84, 0x75, 0x12, 0xfb, - 0xb0, 0x57, 0xa1, 0x9b, 0xa6, 0x17, 0xba, 0xe7, 0x09, 0xca, 0x88, 0x36, 0x94, 0x2f, 0x33, 0x34, - 0x31, 0x2b, 0x96, 0xd2, 0xa4, 0xe3, -} - -func TestPacketIPSecESP(t *testing.T) { - p := gopacket.NewPacket(testPacketIPSecESP, LinkTypeEthernet, gopacket.Default) - if p.ErrorLayer() != nil { - t.Error("Failed to decode packet:", p.ErrorLayer().Error()) - } - checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeIPv4, LayerTypeIPSecESP}, t) -} -func BenchmarkDecodePacketIPSecESP(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testPacketIPSecESP, LinkTypeEthernet, gopacket.NoCopy) - } -} diff --git a/Godeps/_workspace/src/github.com/tsg/gopacket/layers/udp_test.go b/Godeps/_workspace/src/github.com/tsg/gopacket/layers/udp_test.go deleted file mode 100644 index 659850f86f7..00000000000 --- a/Godeps/_workspace/src/github.com/tsg/gopacket/layers/udp_test.go +++ /dev/null @@ -1,372 +0,0 @@ -// Copyright 2012, Google, Inc. All rights reserved. -// Copyright 2009-2011 Andreas Krennmair. All rights reserved. -// -// Use of this source code is governed by a BSD-style license -// that can be found in the LICENSE file in the root of the source -// tree. - -package layers - -import ( - "reflect" - "testing" - - "github.com/tsg/gopacket" -) - -// testUDPPacketDNS is the packet: -// 10:33:07.883637 IP 172.16.255.1.53 > 172.29.20.15.35181: 47320 7/0/0 MX ALT2.ASPMX.L.GOOGLE.com. 20, MX ASPMX2.GOOGLEMAIL.com. 30, MX ASPMX3.GOOGLEMAIL.com. 30, MX ASPMX4.GOOGLEMAIL.com. 30, MX ASPMX5.GOOGLEMAIL.com. 30, MX ASPMX.L.GOOGLE.com. 10, MX ALT1.ASPMX.L.GOOGLE.com. 20 (202) -// 0x0000: 24be 0527 0b17 001f cab3 75c0 0800 4500 $..'......u...E. -// 0x0010: 00e6 68cf 0000 3f11 a6f9 ac10 ff01 ac1d ..h...?......... -// 0x0020: 140f 0035 896d 00d2 754a b8d8 8180 0001 ...5.m..uJ...... -// 0x0030: 0007 0000 0000 0478 6b63 6403 636f 6d00 .......xkcd.com. -// 0x0040: 000f 0001 c00c 000f 0001 0000 0258 0018 .............X.. -// 0x0050: 0014 0441 4c54 3205 4153 504d 5801 4c06 ...ALT2.ASPMX.L. -// 0x0060: 474f 4f47 4c45 c011 c00c 000f 0001 0000 GOOGLE.......... -// 0x0070: 0258 0016 001e 0641 5350 4d58 320a 474f .X.....ASPMX2.GO -// 0x0080: 4f47 4c45 4d41 494c c011 c00c 000f 0001 OGLEMAIL........ -// 0x0090: 0000 0258 000b 001e 0641 5350 4d58 33c0 ...X.....ASPMX3. -// 0x00a0: 53c0 0c00 0f00 0100 0002 5800 0b00 1e06 S.........X..... -// 0x00b0: 4153 504d 5834 c053 c00c 000f 0001 0000 ASPMX4.S........ -// 0x00c0: 0258 000b 001e 0641 5350 4d58 35c0 53c0 .X.....ASPMX5.S. -// 0x00d0: 0c00 0f00 0100 0002 5800 0400 0ac0 2dc0 ........X.....-. -// 0x00e0: 0c00 0f00 0100 0002 5800 0900 1404 414c ........X.....AL -// 0x00f0: 5431 c02d T1.- -// Packet generated by doing DNS query for 'xkcd.com' -var testUDPPacketDNS = []byte{ - 0x24, 0xbe, 0x05, 0x27, 0x0b, 0x17, 0x00, 0x1f, 0xca, 0xb3, 0x75, 0xc0, 0x08, 0x00, 0x45, 0x00, - 0x00, 0xe6, 0x68, 0xcf, 0x00, 0x00, 0x3f, 0x11, 0xa6, 0xf9, 0xac, 0x10, 0xff, 0x01, 0xac, 0x1d, - 0x14, 0x0f, 0x00, 0x35, 0x89, 0x6d, 0x00, 0xd2, 0x75, 0x4a, 0xb8, 0xd8, 0x81, 0x80, 0x00, 0x01, - 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x04, 0x78, 0x6b, 0x63, 0x64, 0x03, 0x63, 0x6f, 0x6d, 0x00, - 0x00, 0x0f, 0x00, 0x01, 0xc0, 0x0c, 0x00, 0x0f, 0x00, 0x01, 0x00, 0x00, 0x02, 0x58, 0x00, 0x18, - 0x00, 0x14, 0x04, 0x41, 0x4c, 0x54, 0x32, 0x05, 0x41, 0x53, 0x50, 0x4d, 0x58, 0x01, 0x4c, 0x06, - 0x47, 0x4f, 0x4f, 0x47, 0x4c, 0x45, 0xc0, 0x11, 0xc0, 0x0c, 0x00, 0x0f, 0x00, 0x01, 0x00, 0x00, - 0x02, 0x58, 0x00, 0x16, 0x00, 0x1e, 0x06, 0x41, 0x53, 0x50, 0x4d, 0x58, 0x32, 0x0a, 0x47, 0x4f, - 0x4f, 0x47, 0x4c, 0x45, 0x4d, 0x41, 0x49, 0x4c, 0xc0, 0x11, 0xc0, 0x0c, 0x00, 0x0f, 0x00, 0x01, - 0x00, 0x00, 0x02, 0x58, 0x00, 0x0b, 0x00, 0x1e, 0x06, 0x41, 0x53, 0x50, 0x4d, 0x58, 0x33, 0xc0, - 0x53, 0xc0, 0x0c, 0x00, 0x0f, 0x00, 0x01, 0x00, 0x00, 0x02, 0x58, 0x00, 0x0b, 0x00, 0x1e, 0x06, - 0x41, 0x53, 0x50, 0x4d, 0x58, 0x34, 0xc0, 0x53, 0xc0, 0x0c, 0x00, 0x0f, 0x00, 0x01, 0x00, 0x00, - 0x02, 0x58, 0x00, 0x0b, 0x00, 0x1e, 0x06, 0x41, 0x53, 0x50, 0x4d, 0x58, 0x35, 0xc0, 0x53, 0xc0, - 0x0c, 0x00, 0x0f, 0x00, 0x01, 0x00, 0x00, 0x02, 0x58, 0x00, 0x04, 0x00, 0x0a, 0xc0, 0x2d, 0xc0, - 0x0c, 0x00, 0x0f, 0x00, 0x01, 0x00, 0x00, 0x02, 0x58, 0x00, 0x09, 0x00, 0x14, 0x04, 0x41, 0x4c, - 0x54, 0x31, 0xc0, 0x2d, -} - -func TestUDPPacketDNS(t *testing.T) { - p := gopacket.NewPacket(testUDPPacketDNS, LinkTypeEthernet, gopacket.Default) - if p.ErrorLayer() != nil { - t.Error("Failed to decode packet:", p.ErrorLayer().Error()) - } - checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeIPv4, LayerTypeUDP, LayerTypeDNS}, t) - if got, ok := p.TransportLayer().(*UDP); ok { - want := &UDP{ - BaseLayer: BaseLayer{ - Contents: []byte{0x0, 0x35, 0x89, 0x6d, 0x0, 0xd2, 0x75, 0x4a}, - Payload: []byte{0xb8, 0xd8, 0x81, 0x80, 0x0, 0x1, 0x0, - 0x7, 0x0, 0x0, 0x0, 0x0, 0x4, 0x78, 0x6b, 0x63, 0x64, 0x3, 0x63, 0x6f, - 0x6d, 0x0, 0x0, 0xf, 0x0, 0x1, 0xc0, 0xc, 0x0, 0xf, 0x0, 0x1, 0x0, 0x0, - 0x2, 0x58, 0x0, 0x18, 0x0, 0x14, 0x4, 0x41, 0x4c, 0x54, 0x32, 0x5, 0x41, - 0x53, 0x50, 0x4d, 0x58, 0x1, 0x4c, 0x6, 0x47, 0x4f, 0x4f, 0x47, 0x4c, - 0x45, 0xc0, 0x11, 0xc0, 0xc, 0x0, 0xf, 0x0, 0x1, 0x0, 0x0, 0x2, 0x58, 0x0, - 0x16, 0x0, 0x1e, 0x6, 0x41, 0x53, 0x50, 0x4d, 0x58, 0x32, 0xa, 0x47, 0x4f, - 0x4f, 0x47, 0x4c, 0x45, 0x4d, 0x41, 0x49, 0x4c, 0xc0, 0x11, 0xc0, 0xc, - 0x0, 0xf, 0x0, 0x1, 0x0, 0x0, 0x2, 0x58, 0x0, 0xb, 0x0, 0x1e, 0x6, 0x41, - 0x53, 0x50, 0x4d, 0x58, 0x33, 0xc0, 0x53, 0xc0, 0xc, 0x0, 0xf, 0x0, 0x1, - 0x0, 0x0, 0x2, 0x58, 0x0, 0xb, 0x0, 0x1e, 0x6, 0x41, 0x53, 0x50, 0x4d, - 0x58, 0x34, 0xc0, 0x53, 0xc0, 0xc, 0x0, 0xf, 0x0, 0x1, 0x0, 0x0, 0x2, - 0x58, 0x0, 0xb, 0x0, 0x1e, 0x6, 0x41, 0x53, 0x50, 0x4d, 0x58, 0x35, 0xc0, - 0x53, 0xc0, 0xc, 0x0, 0xf, 0x0, 0x1, 0x0, 0x0, 0x2, 0x58, 0x0, 0x4, 0x0, - 0xa, 0xc0, 0x2d, 0xc0, 0xc, 0x0, 0xf, 0x0, 0x1, 0x0, 0x0, 0x2, 0x58, 0x0, - 0x9, 0x0, 0x14, 0x4, 0x41, 0x4c, 0x54, 0x31, 0xc0, 0x2d}, - }, - SrcPort: 53, - DstPort: 35181, - Length: 210, - Checksum: 30026, - sPort: []byte{0x0, 0x35}, - dPort: []byte{0x89, 0x6d}, - } - if !reflect.DeepEqual(got, want) { - t.Errorf("UDP packet mismatch:\ngot :\n%#v\n\nwant :\n%#v\n\n", got, want) - } - } else { - t.Error("Transport layer packet not UDP") - } -} - -func loadDNS(dnspacket []byte, t *testing.T) *DNS { - p := gopacket.NewPacket(dnspacket, LinkTypeEthernet, gopacket.Default) - if p.ErrorLayer() != nil { - t.Error("Failed to decode packet:", p.ErrorLayer().Error()) - } - checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeIPv4, - LayerTypeUDP, LayerTypeDNS}, t) - - dnsL := p.Layer(LayerTypeDNS) - if dnsL == nil { - t.Error("No DNS Layer found") - } - - dns, ok := dnsL.(*DNS) - if !ok { - return nil - } - return dns -} - -var testDNSQueryA = []byte{ - 0xfe, 0x54, 0x00, 0x3e, 0x00, 0x96, 0x52, 0x54, /* .T.>..RT */ - 0x00, 0xbd, 0x1c, 0x70, 0x08, 0x00, 0x45, 0x00, /* ...p..E. */ - 0x00, 0x3c, 0x22, 0xe0, 0x00, 0x00, 0x40, 0x11, /* .<"...@. */ - 0xe2, 0x38, 0xc0, 0xa8, 0x7a, 0x46, 0xc0, 0xa8, /* .8..zF.. */ - 0x7a, 0x01, 0xc3, 0x35, 0x00, 0x35, 0x00, 0x28, /* z..5.5.( */ - 0x75, 0xd2, 0x52, 0x41, 0x01, 0x00, 0x00, 0x01, /* u.RA.... */ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x77, /* .......w */ - 0x77, 0x77, 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, /* ww.googl */ - 0x65, 0x03, 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, /* e.com... */ - 0x00, 0x01, /* .. */ -} - -func TestDNSQueryA(t *testing.T) { - dns := loadDNS(testDNSQueryA, t) - if dns == nil { - t.Fatal("Failed to get a pointer to DNS struct") - } - - if uint16(len(dns.Questions)) != dns.QDCount { - t.Fatal("Invalid query decoding, not the right number of questions") - } - - if string(dns.Questions[0].Name) != "www.google.com" { - t.Errorf("Invalid query decoding, expecting 'www.google.com', got '%s'", - dns.Questions[0].Name) - } - if dns.Questions[0].Class != DNSClassIN { - t.Errorf("Invalid query decoding, expecting Class IN, got '%d'", - dns.Questions[0].Class) - } - - if dns.Questions[0].Type != DNSTypeA { - t.Errorf("Invalid query decoding, expecting Type A, got '%d'", - dns.Questions[0].Type) - } -} - -var testDNSRRA = []byte{ - 0x52, 0x54, 0x00, 0xbd, 0x1c, 0x70, 0xfe, 0x54, /* RT...p.T */ - 0x00, 0x3e, 0x00, 0x96, 0x08, 0x00, 0x45, 0x00, /* .>....E. */ - 0x01, 0x24, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, /* .$..@.@. */ - 0xc4, 0x30, 0xc0, 0xa8, 0x7a, 0x01, 0xc0, 0xa8, /* .0..z... */ - 0x7a, 0x46, 0x00, 0x35, 0xc3, 0x35, 0x01, 0x10, /* zF.5.5.. */ - 0x76, 0xba, 0x52, 0x41, 0x81, 0x80, 0x00, 0x01, /* v.RA.... */ - 0x00, 0x06, 0x00, 0x04, 0x00, 0x04, 0x03, 0x77, /* .......w */ - 0x77, 0x77, 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, /* ww.googl */ - 0x65, 0x03, 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, /* e.com... */ - 0x00, 0x01, 0xc0, 0x0c, 0x00, 0x01, 0x00, 0x01, /* ........ */ - 0x00, 0x00, 0x01, 0x2c, 0x00, 0x04, 0x4a, 0x7d, /* ...,..J} */ - 0xc3, 0x67, 0xc0, 0x0c, 0x00, 0x01, 0x00, 0x01, /* .g...... */ - 0x00, 0x00, 0x01, 0x2c, 0x00, 0x04, 0x4a, 0x7d, /* ...,..J} */ - 0xc3, 0x68, 0xc0, 0x0c, 0x00, 0x01, 0x00, 0x01, /* .h...... */ - 0x00, 0x00, 0x01, 0x2c, 0x00, 0x04, 0x4a, 0x7d, /* ...,..J} */ - 0xc3, 0x69, 0xc0, 0x0c, 0x00, 0x01, 0x00, 0x01, /* .i...... */ - 0x00, 0x00, 0x01, 0x2c, 0x00, 0x04, 0x4a, 0x7d, /* ...,..J} */ - 0xc3, 0x6a, 0xc0, 0x0c, 0x00, 0x01, 0x00, 0x01, /* .j...... */ - 0x00, 0x00, 0x01, 0x2c, 0x00, 0x04, 0x4a, 0x7d, /* ...,..J} */ - 0xc3, 0x93, 0xc0, 0x0c, 0x00, 0x01, 0x00, 0x01, /* ........ */ - 0x00, 0x00, 0x01, 0x2c, 0x00, 0x04, 0x4a, 0x7d, /* ...,..J} */ - 0xc3, 0x63, 0xc0, 0x10, 0x00, 0x02, 0x00, 0x01, /* .c...... */ - 0x00, 0x02, 0xa3, 0x00, 0x00, 0x06, 0x03, 0x6e, /* .......n */ - 0x73, 0x32, 0xc0, 0x10, 0xc0, 0x10, 0x00, 0x02, /* s2...... */ - 0x00, 0x01, 0x00, 0x02, 0xa3, 0x00, 0x00, 0x06, /* ........ */ - 0x03, 0x6e, 0x73, 0x33, 0xc0, 0x10, 0xc0, 0x10, /* .ns3.... */ - 0x00, 0x02, 0x00, 0x01, 0x00, 0x02, 0xa3, 0x00, /* ........ */ - 0x00, 0x06, 0x03, 0x6e, 0x73, 0x31, 0xc0, 0x10, /* ...ns1.. */ - 0xc0, 0x10, 0x00, 0x02, 0x00, 0x01, 0x00, 0x02, /* ........ */ - 0xa3, 0x00, 0x00, 0x06, 0x03, 0x6e, 0x73, 0x34, /* .....ns4 */ - 0xc0, 0x10, 0xc0, 0xb0, 0x00, 0x01, 0x00, 0x01, /* ........ */ - 0x00, 0x02, 0xa3, 0x00, 0x00, 0x04, 0xd8, 0xef, /* ........ */ - 0x20, 0x0a, 0xc0, 0x8c, 0x00, 0x01, 0x00, 0x01, /* ....... */ - 0x00, 0x02, 0xa3, 0x00, 0x00, 0x04, 0xd8, 0xef, /* ........ */ - 0x22, 0x0a, 0xc0, 0x9e, 0x00, 0x01, 0x00, 0x01, /* "....... */ - 0x00, 0x02, 0xa3, 0x00, 0x00, 0x04, 0xd8, 0xef, /* ........ */ - 0x24, 0x0a, 0xc0, 0xc2, 0x00, 0x01, 0x00, 0x01, /* $....... */ - 0x00, 0x02, 0xa3, 0x00, 0x00, 0x04, 0xd8, 0xef, /* ........ */ - 0x26, 0x0a, /* &. */ -} - -func TestDNSRRA(t *testing.T) { - dns := loadDNS(testDNSRRA, t) - if dns == nil { - t.Fatal("Failed to get a pointer to DNS struct") - return - } - - if uint16(len(dns.Questions)) != dns.QDCount { - t.Fatal("Invalid query decoding, not the right number of questions") - } else if uint16(len(dns.Answers)) != dns.ANCount { - t.Fatal("Invalid query decoding, not the right number of answers") - } else if uint16(len(dns.Authorities)) != dns.NSCount { - t.Fatal("Invalid query decoding, not the right number of authorities") - } else if uint16(len(dns.Additionals)) != dns.ARCount { - t.Fatal("Invalid query decoding, not the right number of additionals info") - } - - if string(dns.Questions[0].Name) != "www.google.com" { - t.Errorf("Invalid query decoding, expecting 'www.google.com', got '%s'", - dns.Questions[0].Name) - } - if string(dns.Answers[0].Name) != "www.google.com" { - t.Errorf("Invalid query decoding, expecting 'www.google.com', got '%d'", - dns.Questions[0].Class) - } - if dns.Answers[0].Class != DNSClassIN { - t.Errorf("Invalid query decoding, expecting Class IN, got '%d'", - dns.Questions[0].Class) - } - if dns.Answers[0].Type != DNSTypeA { - t.Errorf("Invalid query decoding, expecting Type A, got '%d'", - dns.Questions[0].Type) - } - if !dns.Answers[0].IP.Equal([]byte{74, 125, 195, 103}) { - t.Errorf("Invalid query decoding, invalid IP address,"+ - " expecting '74.125.195.103', got '%s'", - dns.Answers[0].IP.String()) - } - if len(dns.Answers) != 6 { - t.Errorf("No correct number of answers, expecting 6, go '%d'", - len(dns.Answers)) - } - if len(dns.Authorities) != 4 { - t.Errorf("No correct number of answers, expecting 4, go '%d'", - len(dns.Answers)) - } - if len(dns.Additionals) != 4 { - t.Errorf("No correct number of answers, expecting 4, go '%d'", - len(dns.Answers)) - } else { - for i, want := range []string{ - "ns1.google.com", - "ns2.google.com", - "ns3.google.com", - "ns4.google.com", - } { - if got := string(dns.Additionals[i].Name); got != want { - t.Errorf("got %q want %q", got, want) - } - } - } -} - -var testDNSAAAA = []byte{ - 0x52, 0x54, 0x00, 0xbd, 0x1c, 0x70, 0xfe, 0x54, /* RT...p.T */ - 0x00, 0x3e, 0x00, 0x96, 0x08, 0x00, 0x45, 0x00, /* .>....E. */ - 0x00, 0xe0, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, /* ....@.@. */ - 0xc4, 0x74, 0xc0, 0xa8, 0x7a, 0x01, 0xc0, 0xa8, /* .t..z... */ - 0x7a, 0x46, 0x00, 0x35, 0xdb, 0x13, 0x00, 0xcc, /* zF.5.... */ - 0x76, 0x76, 0xf3, 0x03, 0x81, 0x80, 0x00, 0x01, /* vv...... */ - 0x00, 0x01, 0x00, 0x04, 0x00, 0x04, 0x03, 0x77, /* .......w */ - 0x77, 0x77, 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, /* ww.googl */ - 0x65, 0x03, 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x1c, /* e.com... */ - 0x00, 0x01, 0xc0, 0x0c, 0x00, 0x1c, 0x00, 0x01, /* ........ */ - 0x00, 0x00, 0x01, 0x2c, 0x00, 0x10, 0x2a, 0x00, /* ...,..*. */ - 0x14, 0x50, 0x40, 0x0c, 0x0c, 0x01, 0x00, 0x00, /* .P@..... */ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x69, 0xc0, 0x10, /* .....i.. */ - 0x00, 0x02, 0x00, 0x01, 0x00, 0x02, 0xa3, 0x00, /* ........ */ - 0x00, 0x06, 0x03, 0x6e, 0x73, 0x34, 0xc0, 0x10, /* ...ns4.. */ - 0xc0, 0x10, 0x00, 0x02, 0x00, 0x01, 0x00, 0x02, /* ........ */ - 0xa3, 0x00, 0x00, 0x06, 0x03, 0x6e, 0x73, 0x32, /* .....ns2 */ - 0xc0, 0x10, 0xc0, 0x10, 0x00, 0x02, 0x00, 0x01, /* ........ */ - 0x00, 0x02, 0xa3, 0x00, 0x00, 0x06, 0x03, 0x6e, /* .......n */ - 0x73, 0x31, 0xc0, 0x10, 0xc0, 0x10, 0x00, 0x02, /* s1...... */ - 0x00, 0x01, 0x00, 0x02, 0xa3, 0x00, 0x00, 0x06, /* ........ */ - 0x03, 0x6e, 0x73, 0x33, 0xc0, 0x10, 0xc0, 0x6c, /* .ns3...l */ - 0x00, 0x01, 0x00, 0x01, 0x00, 0x02, 0xa3, 0x00, /* ........ */ - 0x00, 0x04, 0xd8, 0xef, 0x20, 0x0a, 0xc0, 0x5a, /* .... ..Z */ - 0x00, 0x01, 0x00, 0x01, 0x00, 0x02, 0xa3, 0x00, /* ........ */ - 0x00, 0x04, 0xd8, 0xef, 0x22, 0x0a, 0xc0, 0x7e, /* ...."..~ */ - 0x00, 0x01, 0x00, 0x01, 0x00, 0x02, 0xa3, 0x00, /* ........ */ - 0x00, 0x04, 0xd8, 0xef, 0x24, 0x0a, 0xc0, 0x48, /* ....$..H */ - 0x00, 0x01, 0x00, 0x01, 0x00, 0x02, 0xa3, 0x00, /* ........ */ - 0x00, 0x04, 0xd8, 0xef, 0x26, 0x0a, /* ....&. */ -} - -func TestDNSAAAA(t *testing.T) { - dns := loadDNS(testDNSAAAA, t) - if dns == nil { - t.Error("Failed to get a pointer to DNS struct") - return - } - - if len(dns.Questions) != 1 { - t.Error("Invalid number of question") - return - } - if dns.Questions[0].Type != DNSTypeAAAA { - t.Errorf("Invalid question, Type is not AAAA, found %d", - dns.Questions[0].Type) - } - - if len(dns.Answers) != 1 { - t.Error("Invalid number of answers") - } - if !dns.Answers[0].IP.Equal([]byte{0x2a, 0x00, 0x14, 0x50, 0x40, - 0x0c, 0x0c, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x69}) { - t.Error("Invalid IP address, found ", - dns.Answers[0].IP.String()) - } -} - -var testDNSMXSOA = []byte{ - 0x52, 0x54, 0x00, 0xbd, 0x1c, 0x70, 0xfe, 0x54, /* RT...p.T */ - 0x00, 0x3e, 0x00, 0x96, 0x08, 0x00, 0x45, 0x00, /* .>....E. */ - 0x00, 0x6e, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, /* .n..@.@. */ - 0xc4, 0xe6, 0xc0, 0xa8, 0x7a, 0x01, 0xc0, 0xa8, /* ....z... */ - 0x7a, 0x46, 0x00, 0x35, 0x9c, 0x60, 0x00, 0x5a, /* zF.5.`.Z */ - 0x76, 0x04, 0xfc, 0x7a, 0x81, 0x80, 0x00, 0x01, /* v..z.... */ - 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0x77, /* .......w */ - 0x77, 0x77, 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, /* ww.googl */ - 0x65, 0x03, 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x0f, /* e.com... */ - 0x00, 0x01, 0xc0, 0x10, 0x00, 0x06, 0x00, 0x01, /* ........ */ - 0x00, 0x00, 0x00, 0x3c, 0x00, 0x26, 0x03, 0x6e, /* ...<.&.n */ - 0x73, 0x31, 0xc0, 0x10, 0x09, 0x64, 0x6e, 0x73, /* s1...dns */ - 0x2d, 0x61, 0x64, 0x6d, 0x69, 0x6e, 0xc0, 0x10, /* -admin.. */ - 0x00, 0x17, 0x9f, 0x64, 0x00, 0x00, 0x1c, 0x20, /* ...d... */ - 0x00, 0x00, 0x07, 0x08, 0x00, 0x12, 0x75, 0x00, /* ......u. */ - 0x00, 0x00, 0x01, 0x2c, /* ..., */ -} - -func TestDNSMXSOA(t *testing.T) { - dns := loadDNS(testDNSMXSOA, t) - if dns == nil { - t.Error("Failed to get a pointer to DNS struct") - return - } - - if len(dns.Authorities) != 1 { - t.Error("Invalid number of authoritative answers, found ", - len(dns.Authorities)) - return - } -} - -func BenchmarkDecodeDNS(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testDNSQueryA, LinkTypeEthernet, gopacket.NoCopy) - } -} -func BenchmarkDecodeDNSLayer(b *testing.B) { - var dns DNS - for i := 0; i < b.N; i++ { - dns.DecodeFromBytes(testDNSAAAA[ /*eth*/ 14+ /*ipv4*/ 20+ /*udp*/ 8:], gopacket.NilDecodeFeedback) - } -} -func TestDNSDoesNotMalloc(t *testing.T) { - var dns DNS - if n := testing.AllocsPerRun(1000, func() { - if err := dns.DecodeFromBytes(testDNSAAAA[ /*eth*/ 14+ /*ipv4*/ 20+ /*udp*/ 8:], gopacket.NilDecodeFeedback); err != nil { - t.Fatal(err) - } - }); n > 0 { - t.Error(n, "mallocs decoding DNS") - } -} diff --git a/Godeps/_workspace/src/github.com/tsg/gopacket/layers/usb_test.go b/Godeps/_workspace/src/github.com/tsg/gopacket/layers/usb_test.go deleted file mode 100644 index 429c4164e54..00000000000 --- a/Godeps/_workspace/src/github.com/tsg/gopacket/layers/usb_test.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2014, Google, Inc. All rights reserved. -// -// Use of this source code is governed by a BSD-style license -// that can be found in the LICENSE file in the root of the source -// tree. - -package layers - -import ( - _ "fmt" - "github.com/tsg/gopacket" - "reflect" - "testing" -) - -// Generator python layers/test_creator.py --link_type USB --name USB dongle.pcap -// http://wiki.wireshark.org/SampleCaptures#Sample_Captures - -// testPacketUSB0 is the packet: -// 02:41:04.689546 INTERRUPT COMPLETE to 2:1:1 -// 0x0000: 0038 4a3b 0088 ffff 4301 8101 0200 2d00 .8J;....C.....-. -// 0x0010: c0d3 5b50 0000 0000 8a85 0a00 0000 0000 ..[P............ -// 0x0020: 0100 0000 0100 0000 0000 0000 0000 0000 ................ -// 0x0030: 8000 0000 0000 0000 0002 0000 0000 0000 ................ -// 0x0040: 04 . -var testPacketUSB0 = []byte{ - 0x00, 0x38, 0x4a, 0x3b, 0x00, 0x88, 0xff, 0xff, 0x43, 0x01, 0x81, 0x01, 0x02, 0x00, 0x2d, 0x00, - 0xc0, 0xd3, 0x5b, 0x50, 0x00, 0x00, 0x00, 0x00, 0x8a, 0x85, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x04, -} - -func TestPacketUSB0(t *testing.T) { - p := gopacket.NewPacket(testPacketUSB0, LinkTypeLinuxUSB, gopacket.Default) - if p.ErrorLayer() != nil { - t.Error("Failed to decode packet:", p.ErrorLayer().Error()) - } - checkLayers(p, []gopacket.LayerType{LayerTypeUSB, LayerTypeUSBInterrupt}, t) - - if got, ok := p.Layer(LayerTypeUSB).(*USB); ok { - want := &USB{ - BaseLayer: BaseLayer{ - Contents: []uint8{0x0, 0x38, 0x4a, 0x3b, 0x0, 0x88, 0xff, 0xff, 0x43, 0x1, 0x81, 0x1, 0x2, 0x0, 0x2d, 0x0, 0xc0, 0xd3, 0x5b, 0x50, 0x0, 0x0, 0x0, 0x0, 0x8a, 0x85, 0xa, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0}, - Payload: []uint8{0x4}, - }, - ID: 0xffff88003b4a3800, - EventType: USBEventTypeComplete, - TransferType: USBTransportTypeInterrupt, - Direction: 0x1, - EndpointNumber: 0x1, - DeviceAddress: 0x1, - BusID: 0x2, - TimestampSec: 1348195264, - TimestampUsec: 689546, - Setup: false, - Data: true, - Status: 0, - UrbLength: 0x1, - UrbDataLength: 0x1, - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("USB packet processing failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", got, want) - } - } - -} -func BenchmarkDecodePacketUSB0(b *testing.B) { - for i := 0; i < b.N; i++ { - gopacket.NewPacket(testPacketUSB0, LinkTypeLinuxUSB, gopacket.NoCopy) - } -} diff --git a/Godeps/_workspace/src/github.com/tsg/gopacket/macs/benchmark_test.go b/Godeps/_workspace/src/github.com/tsg/gopacket/macs/benchmark_test.go deleted file mode 100644 index 33af5c263fe..00000000000 --- a/Godeps/_workspace/src/github.com/tsg/gopacket/macs/benchmark_test.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2012 Google, Inc. All rights reserved. -// -// Use of this source code is governed by a BSD-style license -// that can be found in the LICENSE file in the root of the source -// tree. - -package macs - -import ( - "testing" -) - -func BenchmarkCheckEthernetPrefix(b *testing.B) { - key := [3]byte{5, 5, 5} - for i := 0; i < b.N; i++ { - _ = ValidMACPrefixMap[key] - } -} diff --git a/Godeps/_workspace/src/github.com/tsg/gopacket/pcap/pcap_test.go b/Godeps/_workspace/src/github.com/tsg/gopacket/pcap/pcap_test.go deleted file mode 100644 index 1a946701786..00000000000 --- a/Godeps/_workspace/src/github.com/tsg/gopacket/pcap/pcap_test.go +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2012 Google, Inc. All rights reserved. -// -// Use of this source code is governed by a BSD-style license -// that can be found in the LICENSE file in the root of the source -// tree. - -package pcap - -import ( - "fmt" - "io" - "log" - "testing" - - "github.com/tsg/gopacket" - "github.com/tsg/gopacket/layers" -) - -func TestPcapFileRead(t *testing.T) { - for _, file := range []struct { - filename string - num int - expectedLayers []gopacket.LayerType - }{ - {"test_loopback.pcap", - 24, - []gopacket.LayerType{ - layers.LayerTypeLoopback, - layers.LayerTypeIPv6, - layers.LayerTypeTCP, - }, - }, - {"test_ethernet.pcap", - 16, - []gopacket.LayerType{ - layers.LayerTypeEthernet, - layers.LayerTypeIPv4, - layers.LayerTypeTCP, - }, - }, - {"test_dns.pcap", - 10, - []gopacket.LayerType{ - layers.LayerTypeEthernet, - layers.LayerTypeIPv4, - layers.LayerTypeUDP, - layers.LayerTypeDNS, - }, - }, - } { - t.Logf("\n\n\n\nProcessing file %s\n\n\n\n", file.filename) - - packets := []gopacket.Packet{} - if handle, err := OpenOffline(file.filename); err != nil { - t.Fatal(err) - } else { - packetSource := gopacket.NewPacketSource(handle, handle.LinkType()) - for packet := range packetSource.Packets() { - packets = append(packets, packet) - } - } - if len(packets) != file.num { - t.Fatal("Incorrect number of packets, want", file.num, "got", len(packets)) - } - for i, p := range packets { - t.Log(p.Dump()) - for _, layertype := range file.expectedLayers { - if p.Layer(layertype) == nil { - t.Fatal("Packet", i, "has no layer type\n%s", layertype, p.Dump()) - } - } - } - } -} - -func TestBPF(t *testing.T) { - handle, err := OpenOffline("test_ethernet.pcap") - if err != nil { - t.Fatal(err) - } - - for _, expected := range []struct { - expr string - Error bool - Result bool - }{ - {"foobar", true, false}, - {"tcp[tcpflags] & (tcp-syn|tcp-ack) == (tcp-syn|tcp-ack)", false, true}, - {"tcp[tcpflags] & (tcp-syn|tcp-ack) == tcp-ack", false, true}, - {"udp", false, false}, - } { - data, ci, err := handle.ReadPacketData() - if err != nil { - t.Fatal(err) - } - t.Log("Testing filter", expected.expr) - if bpf, err := handle.NewBPF(expected.expr); err != nil { - if !expected.Error { - t.Error(err, "while compiling filter was unexpected") - } - } else if expected.Error { - t.Error("expected error but didn't see one") - } else if matches := bpf.Matches(ci, data); matches != expected.Result { - t.Error("Filter result was", matches, "but should be", expected.Result) - } - } -} - -func ExampleBPF() { - handle, err := OpenOffline("test_ethernet.pcap") - if err != nil { - log.Fatal(err) - } - synack, err := handle.NewBPF("tcp[tcpflags] & (tcp-syn|tcp-ack) == (tcp-syn|tcp-ack)") - if err != nil { - log.Fatal(err) - } - syn, err := handle.NewBPF("tcp[tcpflags] & (tcp-syn|tcp-ack) == tcp-syn") - if err != nil { - log.Fatal(err) - } - for { - data, ci, err := handle.ReadPacketData() - switch { - case err == io.EOF: - return - case err != nil: - log.Fatal(err) - case synack.Matches(ci, data): - fmt.Println("SYN/ACK packet") - case syn.Matches(ci, data): - fmt.Println("SYN packet") - default: - fmt.Println("SYN flag not set") - } - } - // Output: - // SYN packet - // SYN/ACK packet - // SYN flag not set - // SYN flag not set - // SYN flag not set - // SYN flag not set - // SYN flag not set - // SYN flag not set - // SYN flag not set - // SYN flag not set - // SYN flag not set - // SYN flag not set - // SYN flag not set - // SYN flag not set - // SYN flag not set - // SYN flag not set -} diff --git a/Godeps/_workspace/src/github.com/tsg/gopacket/pcap/pcapgo_test.go b/Godeps/_workspace/src/github.com/tsg/gopacket/pcap/pcapgo_test.go deleted file mode 100644 index 19fbc30d45a..00000000000 --- a/Godeps/_workspace/src/github.com/tsg/gopacket/pcap/pcapgo_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2012 Google, Inc. All rights reserved. -// -// Use of this source code is governed by a BSD-style license -// that can be found in the LICENSE file in the root of the source -// tree. - -package pcap - -import ( - "bytes" - "github.com/tsg/gopacket" - "github.com/tsg/gopacket/layers" - "github.com/tsg/gopacket/pcapgo" - "io/ioutil" - "reflect" - "testing" - "time" -) - -func TestPCAPGoWrite(t *testing.T) { - f, err := ioutil.TempFile("", "pcapgo") - if err != nil { - t.Fatal(err) - } - data := []byte{0xab, 0xcd, 0xef, 0x01, 0x02, 0x03, 0x04} - ci := gopacket.CaptureInfo{ - Timestamp: time.Unix(12345667, 1234567000), - Length: 700, - CaptureLength: len(data), - } - func() { - defer f.Close() - w := pcapgo.NewWriter(f) - if err := w.WriteFileHeader(65536, layers.LinkTypeEthernet); err != nil { - t.Fatal(err) - } - if err := w.WritePacket(ci, data); err != nil { - t.Fatal(err) - } - }() - h, err := OpenOffline(f.Name()) - if err != nil { - t.Fatal(err) - } - defer h.Close() - gotData, gotCI, err := h.ReadPacketData() - if err != nil { - t.Fatal("could not read first packet:", err) - } - if !bytes.Equal(gotData, data) { - t.Errorf("byte mismatch:\nwant: %v\n got: %v", data, gotData) - } - if !reflect.DeepEqual(ci, gotCI) { - t.Errorf("CI mismatch:\nwant: %v\n got: %v", ci, gotCI) - } -} diff --git a/Godeps/_workspace/src/github.com/tsg/gopacket/pcapgo/write_test.go b/Godeps/_workspace/src/github.com/tsg/gopacket/pcapgo/write_test.go deleted file mode 100644 index 0f36b8ec808..00000000000 --- a/Godeps/_workspace/src/github.com/tsg/gopacket/pcapgo/write_test.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2012 Google, Inc. All rights reserved. -// -// Use of this source code is governed by a BSD-style license -// that can be found in the LICENSE file in the root of the source -// tree. - -package pcapgo - -import ( - "bytes" - "github.com/tsg/gopacket" - "testing" - "time" -) - -func TestWriteHeader(t *testing.T) { - var buf bytes.Buffer - w := NewWriter(&buf) - w.WriteFileHeader(0x1234, 0x56) - want := []byte{ - 0xd4, 0xc3, 0xb2, 0xa1, 0x02, 0x00, 0x04, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x34, 0x12, 0x00, 0x00, 0x56, 0x00, 0x00, 0x00, - } - if got := buf.Bytes(); !bytes.Equal(got, want) { - t.Errorf("buf mismatch:\nwant: %+v\ngot: %+v", want, got) - } -} - -func TestWritePacket(t *testing.T) { - ci := gopacket.CaptureInfo{ - Timestamp: time.Unix(0x01020304, 0xAA*1000), - Length: 0xABCD, - CaptureLength: 10, - } - data := []byte{9, 8, 7, 6, 5, 4, 3, 2, 1, 0} - var buf bytes.Buffer - w := NewWriter(&buf) - w.WritePacket(ci, data) - want := []byte{ - 0x04, 0x03, 0x02, 0x01, 0xAA, 0x00, 0x00, 0x00, - 0x0A, 0x00, 0x00, 0x00, 0xCD, 0xAB, 0x00, 0x00, - 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00, - } - if got := buf.Bytes(); !bytes.Equal(got, want) { - t.Errorf("buf mismatch:\nwant: %+v\ngot: %+v", want, got) - } -} - -func TestCaptureInfoErrors(t *testing.T) { - data := []byte{1, 2, 3, 4} - ts := time.Unix(0, 0) - for _, test := range []gopacket.CaptureInfo{ - gopacket.CaptureInfo{ - Timestamp: ts, - Length: 5, - CaptureLength: 5, - }, - gopacket.CaptureInfo{ - Timestamp: ts, - Length: 3, - CaptureLength: 4, - }, - } { - var buf bytes.Buffer - w := NewWriter(&buf) - if err := w.WritePacket(test, data); err == nil { - t.Errorf("CaptureInfo %+v should have error", test) - } - } -} diff --git a/Godeps/_workspace/src/github.com/tsg/gopacket/tcpassembly/assembly_test.go b/Godeps/_workspace/src/github.com/tsg/gopacket/tcpassembly/assembly_test.go deleted file mode 100644 index f40b2fad678..00000000000 --- a/Godeps/_workspace/src/github.com/tsg/gopacket/tcpassembly/assembly_test.go +++ /dev/null @@ -1,562 +0,0 @@ -// Copyright 2012 Google, Inc. All rights reserved. -// -// Use of this source code is governed by a BSD-style license -// that can be found in the LICENSE file in the root of the source -// tree. - -package tcpassembly - -import ( - "github.com/tsg/gopacket" - "github.com/tsg/gopacket/layers" - "net" - "reflect" - "testing" - "time" -) - -var netFlow gopacket.Flow - -func init() { - netFlow, _ = gopacket.FlowFromEndpoints( - layers.NewIPEndpoint(net.IP{1, 2, 3, 4}), - layers.NewIPEndpoint(net.IP{5, 6, 7, 8})) -} - -type testSequence struct { - in layers.TCP - want []Reassembly -} - -type testFactory struct { - reassembly []Reassembly -} - -func (t *testFactory) New(a, b gopacket.Flow) Stream { - return t -} -func (t *testFactory) Reassembled(r []Reassembly) { - t.reassembly = r - for i := 0; i < len(r); i++ { - t.reassembly[i].Seen = time.Time{} - } -} -func (t *testFactory) ReassemblyComplete() { -} - -func test(t *testing.T, s []testSequence) { - fact := &testFactory{} - p := NewStreamPool(fact) - a := NewAssembler(p) - a.MaxBufferedPagesPerConnection = 4 - for i, test := range s { - fact.reassembly = []Reassembly{} - a.Assemble(netFlow, &test.in) - if !reflect.DeepEqual(fact.reassembly, test.want) { - t.Fatalf("test %v:\nwant: %v\n got: %v\n", i, test.want, fact.reassembly) - } - } -} - -func TestReorder(t *testing.T) { - test(t, []testSequence{ - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 1001, - BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3}}, - }, - want: []Reassembly{}, - }, - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 1004, - BaseLayer: layers.BaseLayer{Payload: []byte{2, 2, 3}}, - }, - want: []Reassembly{}, - }, - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 1010, - BaseLayer: layers.BaseLayer{Payload: []byte{4, 2, 3}}, - }, - want: []Reassembly{}, - }, - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 1007, - BaseLayer: layers.BaseLayer{Payload: []byte{3, 2, 3}}, - }, - want: []Reassembly{ - Reassembly{ - Skip: -1, - Bytes: []byte{1, 2, 3}, - }, - Reassembly{ - Bytes: []byte{2, 2, 3}, - }, - Reassembly{ - Bytes: []byte{3, 2, 3}, - }, - Reassembly{ - Bytes: []byte{4, 2, 3}, - }, - }, - }, - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 1016, - BaseLayer: layers.BaseLayer{Payload: []byte{2, 2, 3}}, - }, - want: []Reassembly{}, - }, - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 1019, - BaseLayer: layers.BaseLayer{Payload: []byte{3, 2, 3}}, - }, - want: []Reassembly{}, - }, - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 1013, - BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3}}, - }, - want: []Reassembly{ - Reassembly{ - Bytes: []byte{1, 2, 3}, - }, - Reassembly{ - Bytes: []byte{2, 2, 3}, - }, - Reassembly{ - Bytes: []byte{3, 2, 3}, - }, - }, - }, - }) -} - -func TestMaxPerSkip(t *testing.T) { - test(t, []testSequence{ - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 1000, - SYN: true, - BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3}}, - }, - want: []Reassembly{ - Reassembly{ - Start: true, - Bytes: []byte{1, 2, 3}, - }, - }, - }, - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 1007, - BaseLayer: layers.BaseLayer{Payload: []byte{3, 2, 3}}, - }, - want: []Reassembly{}, - }, - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 1010, - BaseLayer: layers.BaseLayer{Payload: []byte{4, 2, 3}}, - }, - want: []Reassembly{}, - }, - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 1013, - BaseLayer: layers.BaseLayer{Payload: []byte{5, 2, 3}}, - }, - want: []Reassembly{}, - }, - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 1016, - BaseLayer: layers.BaseLayer{Payload: []byte{6, 2, 3}}, - }, - want: []Reassembly{ - Reassembly{ - Skip: 3, - Bytes: []byte{3, 2, 3}, - }, - Reassembly{ - Bytes: []byte{4, 2, 3}, - }, - Reassembly{ - Bytes: []byte{5, 2, 3}, - }, - Reassembly{ - Bytes: []byte{6, 2, 3}, - }, - }, - }, - }) -} - -func TestReorderFast(t *testing.T) { - test(t, []testSequence{ - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - SYN: true, - Seq: 1000, - BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3}}, - }, - want: []Reassembly{ - Reassembly{ - Start: true, - Bytes: []byte{1, 2, 3}, - }, - }, - }, - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 1007, - BaseLayer: layers.BaseLayer{Payload: []byte{3, 2, 3}}, - }, - want: []Reassembly{}, - }, - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 1004, - BaseLayer: layers.BaseLayer{Payload: []byte{2, 2, 3}}, - }, - want: []Reassembly{ - Reassembly{ - Bytes: []byte{2, 2, 3}, - }, - Reassembly{ - Bytes: []byte{3, 2, 3}, - }, - }, - }, - }) -} - -func TestOverlap(t *testing.T) { - test(t, []testSequence{ - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - SYN: true, - Seq: 1000, - BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}}, - }, - want: []Reassembly{ - Reassembly{ - Start: true, - Bytes: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, - }, - }, - }, - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 1007, - BaseLayer: layers.BaseLayer{Payload: []byte{7, 8, 9, 0, 1, 2, 3, 4, 5}}, - }, - want: []Reassembly{ - Reassembly{ - Bytes: []byte{1, 2, 3, 4, 5}, - }, - }, - }, - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 1010, - BaseLayer: layers.BaseLayer{Payload: []byte{0, 1, 2, 3, 4, 5, 6, 7}}, - }, - want: []Reassembly{ - Reassembly{ - Bytes: []byte{6, 7}, - }, - }, - }, - }) -} - -func TestBufferedOverlap(t *testing.T) { - test(t, []testSequence{ - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 1007, - BaseLayer: layers.BaseLayer{Payload: []byte{7, 8, 9, 0, 1, 2, 3, 4, 5}}, - }, - want: []Reassembly{}, - }, - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 1010, - BaseLayer: layers.BaseLayer{Payload: []byte{0, 1, 2, 3, 4, 5, 6, 7}}, - }, - want: []Reassembly{}, - }, - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - SYN: true, - Seq: 1000, - BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}}, - }, - want: []Reassembly{ - Reassembly{ - Start: true, - Bytes: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, - }, - Reassembly{ - Bytes: []byte{1, 2, 3, 4, 5}, - }, - Reassembly{ - Bytes: []byte{6, 7}, - }, - }, - }, - }) -} - -func TestOverrun1(t *testing.T) { - test(t, []testSequence{ - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - SYN: true, - Seq: 0xFFFFFFFF, - BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}}, - }, - want: []Reassembly{ - Reassembly{ - Start: true, - Bytes: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, - }, - }, - }, - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 10, - BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3, 4}}, - }, - want: []Reassembly{ - Reassembly{ - Bytes: []byte{1, 2, 3, 4}, - }, - }, - }, - }) -} - -func TestOverrun2(t *testing.T) { - test(t, []testSequence{ - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 10, - BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3, 4}}, - }, - want: []Reassembly{}, - }, - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - SYN: true, - Seq: 0xFFFFFFFF, - BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}}, - }, - want: []Reassembly{ - Reassembly{ - Start: true, - Bytes: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, - }, - Reassembly{ - Bytes: []byte{1, 2, 3, 4}, - }, - }, - }, - }) -} - -func TestCacheLargePacket(t *testing.T) { - data := make([]byte, pageBytes*3) - test(t, []testSequence{ - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 1001, - BaseLayer: layers.BaseLayer{Payload: data}, - }, - want: []Reassembly{}, - }, - { - in: layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 1000, - SYN: true, - BaseLayer: layers.BaseLayer{Payload: []byte{}}, - }, - want: []Reassembly{ - Reassembly{ - Start: true, - Bytes: []byte{}, - }, - Reassembly{ - Bytes: data[:pageBytes], - }, - Reassembly{ - Bytes: data[pageBytes : pageBytes*2], - }, - Reassembly{ - Bytes: data[pageBytes*2 : pageBytes*3], - }, - }, - }, - }) -} - -func BenchmarkSingleStream(b *testing.B) { - t := layers.TCP{ - SrcPort: 1, - DstPort: 2, - SYN: true, - Seq: 1000, - BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}}, - } - a := NewAssembler(NewStreamPool(&testFactory{})) - for i := 0; i < b.N; i++ { - a.Assemble(netFlow, &t) - if t.SYN { - t.SYN = false - t.Seq++ - } - t.Seq += 10 - } -} - -func BenchmarkSingleStreamSkips(b *testing.B) { - t := layers.TCP{ - SrcPort: 1, - DstPort: 2, - SYN: true, - Seq: 1000, - BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}}, - } - a := NewAssembler(NewStreamPool(&testFactory{})) - skipped := false - for i := 0; i < b.N; i++ { - if i%10 == 9 { - t.Seq += 10 - skipped = true - } else if skipped { - t.Seq -= 20 - } - a.Assemble(netFlow, &t) - if t.SYN { - t.SYN = false - t.Seq++ - } - t.Seq += 10 - if skipped { - t.Seq += 10 - skipped = false - } - } -} - -func BenchmarkSingleStreamLoss(b *testing.B) { - t := layers.TCP{ - SrcPort: 1, - DstPort: 2, - SYN: true, - Seq: 1000, - BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}}, - } - a := NewAssembler(NewStreamPool(&testFactory{})) - for i := 0; i < b.N; i++ { - a.Assemble(netFlow, &t) - t.SYN = false - t.Seq += 11 - } -} - -func BenchmarkMultiStreamGrow(b *testing.B) { - t := layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 0, - BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}}, - } - a := NewAssembler(NewStreamPool(&testFactory{})) - for i := 0; i < b.N; i++ { - t.SrcPort = layers.TCPPort(i) - a.Assemble(netFlow, &t) - t.Seq += 10 - } -} - -func BenchmarkMultiStreamConn(b *testing.B) { - t := layers.TCP{ - SrcPort: 1, - DstPort: 2, - Seq: 0, - SYN: true, - BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}}, - } - a := NewAssembler(NewStreamPool(&testFactory{})) - for i := 0; i < b.N; i++ { - t.SrcPort = layers.TCPPort(i) - a.Assemble(netFlow, &t) - if i%65536 == 65535 { - if t.SYN { - t.SYN = false - t.Seq += 1 - } - t.Seq += 10 - } - } -} diff --git a/Godeps/_workspace/src/github.com/tsg/gopacket/tcpassembly/tcpreader/reader_test.go b/Godeps/_workspace/src/github.com/tsg/gopacket/tcpassembly/tcpreader/reader_test.go deleted file mode 100644 index 78b6f179866..00000000000 --- a/Godeps/_workspace/src/github.com/tsg/gopacket/tcpassembly/tcpreader/reader_test.go +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright 2012 Google, Inc. All rights reserved. -// -// Use of this source code is governed by a BSD-style license -// that can be found in the LICENSE file in the root of the source -// tree. - -package tcpreader - -import ( - "bytes" - "fmt" - "github.com/tsg/gopacket" - "github.com/tsg/gopacket/layers" - "github.com/tsg/gopacket/tcpassembly" - "io" - "net" - "testing" -) - -var netFlow gopacket.Flow - -func init() { - netFlow, _ = gopacket.FlowFromEndpoints( - layers.NewIPEndpoint(net.IP{1, 2, 3, 4}), - layers.NewIPEndpoint(net.IP{5, 6, 7, 8})) -} - -type readReturn struct { - data []byte - err error -} -type readSequence struct { - in []layers.TCP - want []readReturn -} -type testReaderFactory struct { - lossErrors bool - readSize int - ReaderStream - output chan []byte -} - -func (t *testReaderFactory) New(a, b gopacket.Flow) tcpassembly.Stream { - return &t.ReaderStream -} - -func testReadSequence(t *testing.T, lossErrors bool, readSize int, seq readSequence) { - f := &testReaderFactory{ReaderStream: NewReaderStream()} - f.ReaderStream.LossErrors = lossErrors - p := tcpassembly.NewStreamPool(f) - a := tcpassembly.NewAssembler(p) - buf := make([]byte, readSize) - go func() { - for i, test := range seq.in { - fmt.Println("Assembling", i) - a.Assemble(netFlow, &test) - fmt.Println("Assembly done") - } - }() - for i, test := range seq.want { - fmt.Println("Waiting for read", i) - n, err := f.Read(buf[:]) - fmt.Println("Got read") - if n != len(test.data) { - t.Errorf("test %d want %d bytes, got %d bytes", i, len(test.data), n) - } else if err != test.err { - t.Errorf("test %d want err %v, got err %v", i, test.err, err) - } else if !bytes.Equal(buf[:n], test.data) { - t.Errorf("test %d\nwant: %v\n got: %v\n", i, test.data, buf[:n]) - } - } - fmt.Println("All done reads") -} - -func TestRead(t *testing.T) { - testReadSequence(t, false, 10, readSequence{ - in: []layers.TCP{ - { - SYN: true, - SrcPort: 1, - DstPort: 2, - Seq: 1000, - BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3}}, - }, - { - FIN: true, - SrcPort: 1, - DstPort: 2, - Seq: 1004, - }, - }, - want: []readReturn{ - {data: []byte{1, 2, 3}}, - {err: io.EOF}, - }, - }) -} - -func TestReadSmallChunks(t *testing.T) { - testReadSequence(t, false, 2, readSequence{ - in: []layers.TCP{ - { - SYN: true, - SrcPort: 1, - DstPort: 2, - Seq: 1000, - BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3}}, - }, - { - FIN: true, - SrcPort: 1, - DstPort: 2, - Seq: 1004, - }, - }, - want: []readReturn{ - {data: []byte{1, 2}}, - {data: []byte{3}}, - {err: io.EOF}, - }, - }) -} - -func ExampleDiscardBytesToEOF() { - b := bytes.NewBuffer([]byte{1, 2, 3, 4, 5}) - fmt.Println(DiscardBytesToEOF(b)) - // Output: - // 5 -} diff --git a/Godeps/_workspace/src/github.com/tsg/gopacket/writer_test.go b/Godeps/_workspace/src/github.com/tsg/gopacket/writer_test.go deleted file mode 100644 index e19069b7eb6..00000000000 --- a/Godeps/_workspace/src/github.com/tsg/gopacket/writer_test.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2012 Google, Inc. All rights reserved. -// -// Use of this source code is governed by a BSD-style license -// that can be found in the LICENSE file in the root of the source -// tree. - -package gopacket - -import ( - "fmt" - "testing" -) - -func TestExponentialSizeIncreasePrepend(t *testing.T) { - var b serializeBuffer - for i, test := range []struct { - prepend, size int - }{ - {2, 2}, - {2, 4}, - {2, 8}, - {2, 8}, - {2, 16}, - {2, 16}, - {2, 16}, - {2, 16}, - {2, 32}, - } { - b.PrependBytes(test.prepend) - if test.size != cap(b.data) { - t.Error(i, "size want", test.size, "got", cap(b.data)) - } - } - b.Clear() - if b.start != 32 { - t.Error(b.start) - } -} - -func TestExponentialSizeIncreaseAppend(t *testing.T) { - var b serializeBuffer - for i, test := range []struct { - appnd, size int - }{ - {2, 2}, - {2, 4}, - {2, 8}, - {2, 8}, - {2, 16}, - {2, 16}, - {2, 16}, - {2, 16}, - {2, 32}, - } { - b.AppendBytes(test.appnd) - if test.size != cap(b.data) { - t.Error(i, "size want", test.size, "got", cap(b.data)) - } - } - b.Clear() - if b.start != 0 { - t.Error(b.start) - } -} - -func ExampleSerializeBuffer() { - b := NewSerializeBuffer() - fmt.Println("1:", b.Bytes()) - bytes, _ := b.PrependBytes(3) - copy(bytes, []byte{1, 2, 3}) - fmt.Println("2:", b.Bytes()) - bytes, _ = b.AppendBytes(2) - copy(bytes, []byte{4, 5}) - fmt.Println("3:", b.Bytes()) - bytes, _ = b.PrependBytes(1) - copy(bytes, []byte{0}) - fmt.Println("4:", b.Bytes()) - bytes, _ = b.AppendBytes(3) - copy(bytes, []byte{6, 7, 8}) - fmt.Println("5:", b.Bytes()) - b.Clear() - fmt.Println("6:", b.Bytes()) - bytes, _ = b.PrependBytes(2) - copy(bytes, []byte{9, 9}) - fmt.Println("7:", b.Bytes()) - // Output: - // 1: [] - // 2: [1 2 3] - // 3: [1 2 3 4 5] - // 4: [0 1 2 3 4 5] - // 5: [0 1 2 3 4 5 6 7 8] - // 6: [] - // 7: [9 9] -} diff --git a/Godeps/_workspace/src/gopkg.in/yaml.v2/decode_test.go b/Godeps/_workspace/src/gopkg.in/yaml.v2/decode_test.go deleted file mode 100644 index 04fdd9e72ca..00000000000 --- a/Godeps/_workspace/src/gopkg.in/yaml.v2/decode_test.go +++ /dev/null @@ -1,966 +0,0 @@ -package yaml_test - -import ( - "errors" - . "gopkg.in/check.v1" - "gopkg.in/yaml.v2" - "math" - "net" - "reflect" - "strings" - "time" -) - -var unmarshalIntTest = 123 - -var unmarshalTests = []struct { - data string - value interface{} -}{ - { - "", - &struct{}{}, - }, { - "{}", &struct{}{}, - }, { - "v: hi", - map[string]string{"v": "hi"}, - }, { - "v: hi", map[string]interface{}{"v": "hi"}, - }, { - "v: true", - map[string]string{"v": "true"}, - }, { - "v: true", - map[string]interface{}{"v": true}, - }, { - "v: 10", - map[string]interface{}{"v": 10}, - }, { - "v: 0b10", - map[string]interface{}{"v": 2}, - }, { - "v: 0xA", - map[string]interface{}{"v": 10}, - }, { - "v: 4294967296", - map[string]int64{"v": 4294967296}, - }, { - "v: 0.1", - map[string]interface{}{"v": 0.1}, - }, { - "v: .1", - map[string]interface{}{"v": 0.1}, - }, { - "v: .Inf", - map[string]interface{}{"v": math.Inf(+1)}, - }, { - "v: -.Inf", - map[string]interface{}{"v": math.Inf(-1)}, - }, { - "v: -10", - map[string]interface{}{"v": -10}, - }, { - "v: -.1", - map[string]interface{}{"v": -0.1}, - }, - - // Simple values. - { - "123", - &unmarshalIntTest, - }, - - // Floats from spec - { - "canonical: 6.8523e+5", - map[string]interface{}{"canonical": 6.8523e+5}, - }, { - "expo: 685.230_15e+03", - map[string]interface{}{"expo": 685.23015e+03}, - }, { - "fixed: 685_230.15", - map[string]interface{}{"fixed": 685230.15}, - }, { - "neginf: -.inf", - map[string]interface{}{"neginf": math.Inf(-1)}, - }, { - "fixed: 685_230.15", - map[string]float64{"fixed": 685230.15}, - }, - //{"sexa: 190:20:30.15", map[string]interface{}{"sexa": 0}}, // Unsupported - //{"notanum: .NaN", map[string]interface{}{"notanum": math.NaN()}}, // Equality of NaN fails. - - // Bools from spec - { - "canonical: y", - map[string]interface{}{"canonical": true}, - }, { - "answer: NO", - map[string]interface{}{"answer": false}, - }, { - "logical: True", - map[string]interface{}{"logical": true}, - }, { - "option: on", - map[string]interface{}{"option": true}, - }, { - "option: on", - map[string]bool{"option": true}, - }, - // Ints from spec - { - "canonical: 685230", - map[string]interface{}{"canonical": 685230}, - }, { - "decimal: +685_230", - map[string]interface{}{"decimal": 685230}, - }, { - "octal: 02472256", - map[string]interface{}{"octal": 685230}, - }, { - "hexa: 0x_0A_74_AE", - map[string]interface{}{"hexa": 685230}, - }, { - "bin: 0b1010_0111_0100_1010_1110", - map[string]interface{}{"bin": 685230}, - }, { - "bin: -0b101010", - map[string]interface{}{"bin": -42}, - }, { - "decimal: +685_230", - map[string]int{"decimal": 685230}, - }, - - //{"sexa: 190:20:30", map[string]interface{}{"sexa": 0}}, // Unsupported - - // Nulls from spec - { - "empty:", - map[string]interface{}{"empty": nil}, - }, { - "canonical: ~", - map[string]interface{}{"canonical": nil}, - }, { - "english: null", - map[string]interface{}{"english": nil}, - }, { - "~: null key", - map[interface{}]string{nil: "null key"}, - }, { - "empty:", - map[string]*bool{"empty": nil}, - }, - - // Flow sequence - { - "seq: [A,B]", - map[string]interface{}{"seq": []interface{}{"A", "B"}}, - }, { - "seq: [A,B,C,]", - map[string][]string{"seq": []string{"A", "B", "C"}}, - }, { - "seq: [A,1,C]", - map[string][]string{"seq": []string{"A", "1", "C"}}, - }, { - "seq: [A,1,C]", - map[string][]int{"seq": []int{1}}, - }, { - "seq: [A,1,C]", - map[string]interface{}{"seq": []interface{}{"A", 1, "C"}}, - }, - // Block sequence - { - "seq:\n - A\n - B", - map[string]interface{}{"seq": []interface{}{"A", "B"}}, - }, { - "seq:\n - A\n - B\n - C", - map[string][]string{"seq": []string{"A", "B", "C"}}, - }, { - "seq:\n - A\n - 1\n - C", - map[string][]string{"seq": []string{"A", "1", "C"}}, - }, { - "seq:\n - A\n - 1\n - C", - map[string][]int{"seq": []int{1}}, - }, { - "seq:\n - A\n - 1\n - C", - map[string]interface{}{"seq": []interface{}{"A", 1, "C"}}, - }, - - // Literal block scalar - { - "scalar: | # Comment\n\n literal\n\n \ttext\n\n", - map[string]string{"scalar": "\nliteral\n\n\ttext\n"}, - }, - - // Folded block scalar - { - "scalar: > # Comment\n\n folded\n line\n \n next\n line\n * one\n * two\n\n last\n line\n\n", - map[string]string{"scalar": "\nfolded line\nnext line\n * one\n * two\n\nlast line\n"}, - }, - - // Map inside interface with no type hints. - { - "a: {b: c}", - map[interface{}]interface{}{"a": map[interface{}]interface{}{"b": "c"}}, - }, - - // Structs and type conversions. - { - "hello: world", - &struct{ Hello string }{"world"}, - }, { - "a: {b: c}", - &struct{ A struct{ B string } }{struct{ B string }{"c"}}, - }, { - "a: {b: c}", - &struct{ A *struct{ B string } }{&struct{ B string }{"c"}}, - }, { - "a: {b: c}", - &struct{ A map[string]string }{map[string]string{"b": "c"}}, - }, { - "a: {b: c}", - &struct{ A *map[string]string }{&map[string]string{"b": "c"}}, - }, { - "a:", - &struct{ A map[string]string }{}, - }, { - "a: 1", - &struct{ A int }{1}, - }, { - "a: 1", - &struct{ A float64 }{1}, - }, { - "a: 1.0", - &struct{ A int }{1}, - }, { - "a: 1.0", - &struct{ A uint }{1}, - }, { - "a: [1, 2]", - &struct{ A []int }{[]int{1, 2}}, - }, { - "a: 1", - &struct{ B int }{0}, - }, { - "a: 1", - &struct { - B int "a" - }{1}, - }, { - "a: y", - &struct{ A bool }{true}, - }, - - // Some cross type conversions - { - "v: 42", - map[string]uint{"v": 42}, - }, { - "v: -42", - map[string]uint{}, - }, { - "v: 4294967296", - map[string]uint64{"v": 4294967296}, - }, { - "v: -4294967296", - map[string]uint64{}, - }, - - // int - { - "int_max: 2147483647", - map[string]int{"int_max": math.MaxInt32}, - }, - { - "int_min: -2147483648", - map[string]int{"int_min": math.MinInt32}, - }, - { - "int_overflow: 9223372036854775808", // math.MaxInt64 + 1 - map[string]int{}, - }, - - // int64 - { - "int64_max: 9223372036854775807", - map[string]int64{"int64_max": math.MaxInt64}, - }, - { - "int64_max_base2: 0b111111111111111111111111111111111111111111111111111111111111111", - map[string]int64{"int64_max_base2": math.MaxInt64}, - }, - { - "int64_min: -9223372036854775808", - map[string]int64{"int64_min": math.MinInt64}, - }, - { - "int64_neg_base2: -0b111111111111111111111111111111111111111111111111111111111111111", - map[string]int64{"int64_neg_base2": -math.MaxInt64}, - }, - { - "int64_overflow: 9223372036854775808", // math.MaxInt64 + 1 - map[string]int64{}, - }, - - // uint - { - "uint_min: 0", - map[string]uint{"uint_min": 0}, - }, - { - "uint_max: 4294967295", - map[string]uint{"uint_max": math.MaxUint32}, - }, - { - "uint_underflow: -1", - map[string]uint{}, - }, - - // uint64 - { - "uint64_min: 0", - map[string]uint{"uint64_min": 0}, - }, - { - "uint64_max: 18446744073709551615", - map[string]uint64{"uint64_max": math.MaxUint64}, - }, - { - "uint64_max_base2: 0b1111111111111111111111111111111111111111111111111111111111111111", - map[string]uint64{"uint64_max_base2": math.MaxUint64}, - }, - { - "uint64_maxint64: 9223372036854775807", - map[string]uint64{"uint64_maxint64": math.MaxInt64}, - }, - { - "uint64_underflow: -1", - map[string]uint64{}, - }, - - // float32 - { - "float32_max: 3.40282346638528859811704183484516925440e+38", - map[string]float32{"float32_max": math.MaxFloat32}, - }, - { - "float32_nonzero: 1.401298464324817070923729583289916131280e-45", - map[string]float32{"float32_nonzero": math.SmallestNonzeroFloat32}, - }, - { - "float32_maxuint64: 18446744073709551615", - map[string]float32{"float32_maxuint64": float32(math.MaxUint64)}, - }, - { - "float32_maxuint64+1: 18446744073709551616", - map[string]float32{"float32_maxuint64+1": float32(math.MaxUint64 + 1)}, - }, - - // float64 - { - "float64_max: 1.797693134862315708145274237317043567981e+308", - map[string]float64{"float64_max": math.MaxFloat64}, - }, - { - "float64_nonzero: 4.940656458412465441765687928682213723651e-324", - map[string]float64{"float64_nonzero": math.SmallestNonzeroFloat64}, - }, - { - "float64_maxuint64: 18446744073709551615", - map[string]float64{"float64_maxuint64": float64(math.MaxUint64)}, - }, - { - "float64_maxuint64+1: 18446744073709551616", - map[string]float64{"float64_maxuint64+1": float64(math.MaxUint64 + 1)}, - }, - - // Overflow cases. - { - "v: 4294967297", - map[string]int32{}, - }, { - "v: 128", - map[string]int8{}, - }, - - // Quoted values. - { - "'1': '\"2\"'", - map[interface{}]interface{}{"1": "\"2\""}, - }, { - "v:\n- A\n- 'B\n\n C'\n", - map[string][]string{"v": []string{"A", "B\nC"}}, - }, - - // Explicit tags. - { - "v: !!float '1.1'", - map[string]interface{}{"v": 1.1}, - }, { - "v: !!null ''", - map[string]interface{}{"v": nil}, - }, { - "%TAG !y! tag:yaml.org,2002:\n---\nv: !y!int '1'", - map[string]interface{}{"v": 1}, - }, - - // Anchors and aliases. - { - "a: &x 1\nb: &y 2\nc: *x\nd: *y\n", - &struct{ A, B, C, D int }{1, 2, 1, 2}, - }, { - "a: &a {c: 1}\nb: *a", - &struct { - A, B struct { - C int - } - }{struct{ C int }{1}, struct{ C int }{1}}, - }, { - "a: &a [1, 2]\nb: *a", - &struct{ B []int }{[]int{1, 2}}, - }, { - "b: *a\na: &a {c: 1}", - &struct { - A, B struct { - C int - } - }{struct{ C int }{1}, struct{ C int }{1}}, - }, - - // Bug #1133337 - { - "foo: ''", - map[string]*string{"foo": new(string)}, - }, { - "foo: null", - map[string]string{"foo": ""}, - }, { - "foo: null", - map[string]interface{}{"foo": nil}, - }, - - // Ignored field - { - "a: 1\nb: 2\n", - &struct { - A int - B int "-" - }{1, 0}, - }, - - // Bug #1191981 - { - "" + - "%YAML 1.1\n" + - "--- !!str\n" + - `"Generic line break (no glyph)\n\` + "\n" + - ` Generic line break (glyphed)\n\` + "\n" + - ` Line separator\u2028\` + "\n" + - ` Paragraph separator\u2029"` + "\n", - "" + - "Generic line break (no glyph)\n" + - "Generic line break (glyphed)\n" + - "Line separator\u2028Paragraph separator\u2029", - }, - - // Struct inlining - { - "a: 1\nb: 2\nc: 3\n", - &struct { - A int - C inlineB `yaml:",inline"` - }{1, inlineB{2, inlineC{3}}}, - }, - - // Map inlining - { - "a: 1\nb: 2\nc: 3\n", - &struct { - A int - C map[string]int `yaml:",inline"` - }{1, map[string]int{"b": 2, "c": 3}}, - }, - - // bug 1243827 - { - "a: -b_c", - map[string]interface{}{"a": "-b_c"}, - }, - { - "a: +b_c", - map[string]interface{}{"a": "+b_c"}, - }, - { - "a: 50cent_of_dollar", - map[string]interface{}{"a": "50cent_of_dollar"}, - }, - - // Duration - { - "a: 3s", - map[string]time.Duration{"a": 3 * time.Second}, - }, - - // Issue #24. - { - "a: ", - map[string]string{"a": ""}, - }, - - // Base 60 floats are obsolete and unsupported. - { - "a: 1:1\n", - map[string]string{"a": "1:1"}, - }, - - // Binary data. - { - "a: !!binary gIGC\n", - map[string]string{"a": "\x80\x81\x82"}, - }, { - "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n", - map[string]string{"a": strings.Repeat("\x90", 54)}, - }, { - "a: !!binary |\n " + strings.Repeat("A", 70) + "\n ==\n", - map[string]string{"a": strings.Repeat("\x00", 52)}, - }, - - // Ordered maps. - { - "{b: 2, a: 1, d: 4, c: 3, sub: {e: 5}}", - &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}}, - }, - - // Issue #39. - { - "a:\n b:\n c: d\n", - map[string]struct{ B interface{} }{"a": {map[interface{}]interface{}{"c": "d"}}}, - }, - - // Custom map type. - { - "a: {b: c}", - M{"a": M{"b": "c"}}, - }, - - // Support encoding.TextUnmarshaler. - { - "a: 1.2.3.4\n", - map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)}, - }, - { - "a: 2015-02-24T18:19:39Z\n", - map[string]time.Time{"a": time.Unix(1424801979, 0)}, - }, - - // Encode empty lists as zero-length slices. - { - "a: []", - &struct{ A []int }{[]int{}}, - }, -} - -type M map[interface{}]interface{} - -type inlineB struct { - B int - inlineC `yaml:",inline"` -} - -type inlineC struct { - C int -} - -func (s *S) TestUnmarshal(c *C) { - for _, item := range unmarshalTests { - t := reflect.ValueOf(item.value).Type() - var value interface{} - switch t.Kind() { - case reflect.Map: - value = reflect.MakeMap(t).Interface() - case reflect.String: - value = reflect.New(t).Interface() - case reflect.Ptr: - value = reflect.New(t.Elem()).Interface() - default: - c.Fatalf("missing case for %s", t) - } - err := yaml.Unmarshal([]byte(item.data), value) - if _, ok := err.(*yaml.TypeError); !ok { - c.Assert(err, IsNil) - } - if t.Kind() == reflect.String { - c.Assert(*value.(*string), Equals, item.value) - } else { - c.Assert(value, DeepEquals, item.value) - } - } -} - -func (s *S) TestUnmarshalNaN(c *C) { - value := map[string]interface{}{} - err := yaml.Unmarshal([]byte("notanum: .NaN"), &value) - c.Assert(err, IsNil) - c.Assert(math.IsNaN(value["notanum"].(float64)), Equals, true) -} - -var unmarshalErrorTests = []struct { - data, error string -}{ - {"v: !!float 'error'", "yaml: cannot decode !!str `error` as a !!float"}, - {"v: [A,", "yaml: line 1: did not find expected node content"}, - {"v:\n- [A,", "yaml: line 2: did not find expected node content"}, - {"a: *b\n", "yaml: unknown anchor 'b' referenced"}, - {"a: &a\n b: *a\n", "yaml: anchor 'a' value contains itself"}, - {"value: -", "yaml: block sequence entries are not allowed in this context"}, - {"a: !!binary ==", "yaml: !!binary value contains invalid base64 data"}, - {"{[.]}", `yaml: invalid map key: \[\]interface \{\}\{"\."\}`}, - {"{{.}}", `yaml: invalid map key: map\[interface\ \{\}\]interface \{\}\{".":interface \{\}\(nil\)\}`}, -} - -func (s *S) TestUnmarshalErrors(c *C) { - for _, item := range unmarshalErrorTests { - var value interface{} - err := yaml.Unmarshal([]byte(item.data), &value) - c.Assert(err, ErrorMatches, item.error, Commentf("Partial unmarshal: %#v", value)) - } -} - -var unmarshalerTests = []struct { - data, tag string - value interface{} -}{ - {"_: {hi: there}", "!!map", map[interface{}]interface{}{"hi": "there"}}, - {"_: [1,A]", "!!seq", []interface{}{1, "A"}}, - {"_: 10", "!!int", 10}, - {"_: null", "!!null", nil}, - {`_: BAR!`, "!!str", "BAR!"}, - {`_: "BAR!"`, "!!str", "BAR!"}, - {"_: !!foo 'BAR!'", "!!foo", "BAR!"}, -} - -var unmarshalerResult = map[int]error{} - -type unmarshalerType struct { - value interface{} -} - -func (o *unmarshalerType) UnmarshalYAML(unmarshal func(v interface{}) error) error { - if err := unmarshal(&o.value); err != nil { - return err - } - if i, ok := o.value.(int); ok { - if result, ok := unmarshalerResult[i]; ok { - return result - } - } - return nil -} - -type unmarshalerPointer struct { - Field *unmarshalerType "_" -} - -type unmarshalerValue struct { - Field unmarshalerType "_" -} - -func (s *S) TestUnmarshalerPointerField(c *C) { - for _, item := range unmarshalerTests { - obj := &unmarshalerPointer{} - err := yaml.Unmarshal([]byte(item.data), obj) - c.Assert(err, IsNil) - if item.value == nil { - c.Assert(obj.Field, IsNil) - } else { - c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value)) - c.Assert(obj.Field.value, DeepEquals, item.value) - } - } -} - -func (s *S) TestUnmarshalerValueField(c *C) { - for _, item := range unmarshalerTests { - obj := &unmarshalerValue{} - err := yaml.Unmarshal([]byte(item.data), obj) - c.Assert(err, IsNil) - c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value)) - c.Assert(obj.Field.value, DeepEquals, item.value) - } -} - -func (s *S) TestUnmarshalerWholeDocument(c *C) { - obj := &unmarshalerType{} - err := yaml.Unmarshal([]byte(unmarshalerTests[0].data), obj) - c.Assert(err, IsNil) - value, ok := obj.value.(map[interface{}]interface{}) - c.Assert(ok, Equals, true, Commentf("value: %#v", obj.value)) - c.Assert(value["_"], DeepEquals, unmarshalerTests[0].value) -} - -func (s *S) TestUnmarshalerTypeError(c *C) { - unmarshalerResult[2] = &yaml.TypeError{[]string{"foo"}} - unmarshalerResult[4] = &yaml.TypeError{[]string{"bar"}} - defer func() { - delete(unmarshalerResult, 2) - delete(unmarshalerResult, 4) - }() - - type T struct { - Before int - After int - M map[string]*unmarshalerType - } - var v T - data := `{before: A, m: {abc: 1, def: 2, ghi: 3, jkl: 4}, after: B}` - err := yaml.Unmarshal([]byte(data), &v) - c.Assert(err, ErrorMatches, ""+ - "yaml: unmarshal errors:\n"+ - " line 1: cannot unmarshal !!str `A` into int\n"+ - " foo\n"+ - " bar\n"+ - " line 1: cannot unmarshal !!str `B` into int") - c.Assert(v.M["abc"], NotNil) - c.Assert(v.M["def"], IsNil) - c.Assert(v.M["ghi"], NotNil) - c.Assert(v.M["jkl"], IsNil) - - c.Assert(v.M["abc"].value, Equals, 1) - c.Assert(v.M["ghi"].value, Equals, 3) -} - -type proxyTypeError struct{} - -func (v *proxyTypeError) UnmarshalYAML(unmarshal func(interface{}) error) error { - var s string - var a int32 - var b int64 - if err := unmarshal(&s); err != nil { - panic(err) - } - if s == "a" { - if err := unmarshal(&b); err == nil { - panic("should have failed") - } - return unmarshal(&a) - } - if err := unmarshal(&a); err == nil { - panic("should have failed") - } - return unmarshal(&b) -} - -func (s *S) TestUnmarshalerTypeErrorProxying(c *C) { - type T struct { - Before int - After int - M map[string]*proxyTypeError - } - var v T - data := `{before: A, m: {abc: a, def: b}, after: B}` - err := yaml.Unmarshal([]byte(data), &v) - c.Assert(err, ErrorMatches, ""+ - "yaml: unmarshal errors:\n"+ - " line 1: cannot unmarshal !!str `A` into int\n"+ - " line 1: cannot unmarshal !!str `a` into int32\n"+ - " line 1: cannot unmarshal !!str `b` into int64\n"+ - " line 1: cannot unmarshal !!str `B` into int") -} - -type failingUnmarshaler struct{} - -var failingErr = errors.New("failingErr") - -func (ft *failingUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error { - return failingErr -} - -func (s *S) TestUnmarshalerError(c *C) { - err := yaml.Unmarshal([]byte("a: b"), &failingUnmarshaler{}) - c.Assert(err, Equals, failingErr) -} - -type sliceUnmarshaler []int - -func (su *sliceUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error { - var slice []int - err := unmarshal(&slice) - if err == nil { - *su = slice - return nil - } - - var intVal int - err = unmarshal(&intVal) - if err == nil { - *su = []int{intVal} - return nil - } - - return err -} - -func (s *S) TestUnmarshalerRetry(c *C) { - var su sliceUnmarshaler - err := yaml.Unmarshal([]byte("[1, 2, 3]"), &su) - c.Assert(err, IsNil) - c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1, 2, 3})) - - err = yaml.Unmarshal([]byte("1"), &su) - c.Assert(err, IsNil) - c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1})) -} - -// From http://yaml.org/type/merge.html -var mergeTests = ` -anchors: - list: - - &CENTER { "x": 1, "y": 2 } - - &LEFT { "x": 0, "y": 2 } - - &BIG { "r": 10 } - - &SMALL { "r": 1 } - -# All the following maps are equal: - -plain: - # Explicit keys - "x": 1 - "y": 2 - "r": 10 - label: center/big - -mergeOne: - # Merge one map - << : *CENTER - "r": 10 - label: center/big - -mergeMultiple: - # Merge multiple maps - << : [ *CENTER, *BIG ] - label: center/big - -override: - # Override - << : [ *BIG, *LEFT, *SMALL ] - "x": 1 - label: center/big - -shortTag: - # Explicit short merge tag - !!merge "<<" : [ *CENTER, *BIG ] - label: center/big - -longTag: - # Explicit merge long tag - ! "<<" : [ *CENTER, *BIG ] - label: center/big - -inlineMap: - # Inlined map - << : {"x": 1, "y": 2, "r": 10} - label: center/big - -inlineSequenceMap: - # Inlined map in sequence - << : [ *CENTER, {"r": 10} ] - label: center/big -` - -func (s *S) TestMerge(c *C) { - var want = map[interface{}]interface{}{ - "x": 1, - "y": 2, - "r": 10, - "label": "center/big", - } - - var m map[interface{}]interface{} - err := yaml.Unmarshal([]byte(mergeTests), &m) - c.Assert(err, IsNil) - for name, test := range m { - if name == "anchors" { - continue - } - c.Assert(test, DeepEquals, want, Commentf("test %q failed", name)) - } -} - -func (s *S) TestMergeStruct(c *C) { - type Data struct { - X, Y, R int - Label string - } - want := Data{1, 2, 10, "center/big"} - - var m map[string]Data - err := yaml.Unmarshal([]byte(mergeTests), &m) - c.Assert(err, IsNil) - for name, test := range m { - if name == "anchors" { - continue - } - c.Assert(test, Equals, want, Commentf("test %q failed", name)) - } -} - -var unmarshalNullTests = []func() interface{}{ - func() interface{} { var v interface{}; v = "v"; return &v }, - func() interface{} { var s = "s"; return &s }, - func() interface{} { var s = "s"; sptr := &s; return &sptr }, - func() interface{} { var i = 1; return &i }, - func() interface{} { var i = 1; iptr := &i; return &iptr }, - func() interface{} { m := map[string]int{"s": 1}; return &m }, - func() interface{} { m := map[string]int{"s": 1}; return m }, -} - -func (s *S) TestUnmarshalNull(c *C) { - for _, test := range unmarshalNullTests { - item := test() - zero := reflect.Zero(reflect.TypeOf(item).Elem()).Interface() - err := yaml.Unmarshal([]byte("null"), item) - c.Assert(err, IsNil) - if reflect.TypeOf(item).Kind() == reflect.Map { - c.Assert(reflect.ValueOf(item).Interface(), DeepEquals, reflect.MakeMap(reflect.TypeOf(item)).Interface()) - } else { - c.Assert(reflect.ValueOf(item).Elem().Interface(), DeepEquals, zero) - } - } -} - -func (s *S) TestUnmarshalSliceOnPreset(c *C) { - // Issue #48. - v := struct{ A []int }{[]int{1}} - yaml.Unmarshal([]byte("a: [2]"), &v) - c.Assert(v.A, DeepEquals, []int{2}) -} - -//var data []byte -//func init() { -// var err error -// data, err = ioutil.ReadFile("/tmp/file.yaml") -// if err != nil { -// panic(err) -// } -//} -// -//func (s *S) BenchmarkUnmarshal(c *C) { -// var err error -// for i := 0; i < c.N; i++ { -// var v map[string]interface{} -// err = yaml.Unmarshal(data, &v) -// } -// if err != nil { -// panic(err) -// } -//} -// -//func (s *S) BenchmarkMarshal(c *C) { -// var v map[string]interface{} -// yaml.Unmarshal(data, &v) -// c.ResetTimer() -// for i := 0; i < c.N; i++ { -// yaml.Marshal(&v) -// } -//} diff --git a/Godeps/_workspace/src/gopkg.in/yaml.v2/encode_test.go b/Godeps/_workspace/src/gopkg.in/yaml.v2/encode_test.go deleted file mode 100644 index 84099bd3850..00000000000 --- a/Godeps/_workspace/src/gopkg.in/yaml.v2/encode_test.go +++ /dev/null @@ -1,501 +0,0 @@ -package yaml_test - -import ( - "fmt" - "math" - "strconv" - "strings" - "time" - - . "gopkg.in/check.v1" - "gopkg.in/yaml.v2" - "net" - "os" -) - -var marshalIntTest = 123 - -var marshalTests = []struct { - value interface{} - data string -}{ - { - nil, - "null\n", - }, { - &struct{}{}, - "{}\n", - }, { - map[string]string{"v": "hi"}, - "v: hi\n", - }, { - map[string]interface{}{"v": "hi"}, - "v: hi\n", - }, { - map[string]string{"v": "true"}, - "v: \"true\"\n", - }, { - map[string]string{"v": "false"}, - "v: \"false\"\n", - }, { - map[string]interface{}{"v": true}, - "v: true\n", - }, { - map[string]interface{}{"v": false}, - "v: false\n", - }, { - map[string]interface{}{"v": 10}, - "v: 10\n", - }, { - map[string]interface{}{"v": -10}, - "v: -10\n", - }, { - map[string]uint{"v": 42}, - "v: 42\n", - }, { - map[string]interface{}{"v": int64(4294967296)}, - "v: 4294967296\n", - }, { - map[string]int64{"v": int64(4294967296)}, - "v: 4294967296\n", - }, { - map[string]uint64{"v": 4294967296}, - "v: 4294967296\n", - }, { - map[string]interface{}{"v": "10"}, - "v: \"10\"\n", - }, { - map[string]interface{}{"v": 0.1}, - "v: 0.1\n", - }, { - map[string]interface{}{"v": float64(0.1)}, - "v: 0.1\n", - }, { - map[string]interface{}{"v": -0.1}, - "v: -0.1\n", - }, { - map[string]interface{}{"v": math.Inf(+1)}, - "v: .inf\n", - }, { - map[string]interface{}{"v": math.Inf(-1)}, - "v: -.inf\n", - }, { - map[string]interface{}{"v": math.NaN()}, - "v: .nan\n", - }, { - map[string]interface{}{"v": nil}, - "v: null\n", - }, { - map[string]interface{}{"v": ""}, - "v: \"\"\n", - }, { - map[string][]string{"v": []string{"A", "B"}}, - "v:\n- A\n- B\n", - }, { - map[string][]string{"v": []string{"A", "B\nC"}}, - "v:\n- A\n- |-\n B\n C\n", - }, { - map[string][]interface{}{"v": []interface{}{"A", 1, map[string][]int{"B": []int{2, 3}}}}, - "v:\n- A\n- 1\n- B:\n - 2\n - 3\n", - }, { - map[string]interface{}{"a": map[interface{}]interface{}{"b": "c"}}, - "a:\n b: c\n", - }, { - map[string]interface{}{"a": "-"}, - "a: '-'\n", - }, - - // Simple values. - { - &marshalIntTest, - "123\n", - }, - - // Structures - { - &struct{ Hello string }{"world"}, - "hello: world\n", - }, { - &struct { - A struct { - B string - } - }{struct{ B string }{"c"}}, - "a:\n b: c\n", - }, { - &struct { - A *struct { - B string - } - }{&struct{ B string }{"c"}}, - "a:\n b: c\n", - }, { - &struct { - A *struct { - B string - } - }{}, - "a: null\n", - }, { - &struct{ A int }{1}, - "a: 1\n", - }, { - &struct{ A []int }{[]int{1, 2}}, - "a:\n- 1\n- 2\n", - }, { - &struct { - B int "a" - }{1}, - "a: 1\n", - }, { - &struct{ A bool }{true}, - "a: true\n", - }, - - // Conditional flag - { - &struct { - A int "a,omitempty" - B int "b,omitempty" - }{1, 0}, - "a: 1\n", - }, { - &struct { - A int "a,omitempty" - B int "b,omitempty" - }{0, 0}, - "{}\n", - }, { - &struct { - A *struct{ X, y int } "a,omitempty,flow" - }{&struct{ X, y int }{1, 2}}, - "a: {x: 1}\n", - }, { - &struct { - A *struct{ X, y int } "a,omitempty,flow" - }{nil}, - "{}\n", - }, { - &struct { - A *struct{ X, y int } "a,omitempty,flow" - }{&struct{ X, y int }{}}, - "a: {x: 0}\n", - }, { - &struct { - A struct{ X, y int } "a,omitempty,flow" - }{struct{ X, y int }{1, 2}}, - "a: {x: 1}\n", - }, { - &struct { - A struct{ X, y int } "a,omitempty,flow" - }{struct{ X, y int }{0, 1}}, - "{}\n", - }, { - &struct { - A float64 "a,omitempty" - B float64 "b,omitempty" - }{1, 0}, - "a: 1\n", - }, - - // Flow flag - { - &struct { - A []int "a,flow" - }{[]int{1, 2}}, - "a: [1, 2]\n", - }, { - &struct { - A map[string]string "a,flow" - }{map[string]string{"b": "c", "d": "e"}}, - "a: {b: c, d: e}\n", - }, { - &struct { - A struct { - B, D string - } "a,flow" - }{struct{ B, D string }{"c", "e"}}, - "a: {b: c, d: e}\n", - }, - - // Unexported field - { - &struct { - u int - A int - }{0, 1}, - "a: 1\n", - }, - - // Ignored field - { - &struct { - A int - B int "-" - }{1, 2}, - "a: 1\n", - }, - - // Struct inlining - { - &struct { - A int - C inlineB `yaml:",inline"` - }{1, inlineB{2, inlineC{3}}}, - "a: 1\nb: 2\nc: 3\n", - }, - - // Map inlining - { - &struct { - A int - C map[string]int `yaml:",inline"` - }{1, map[string]int{"b": 2, "c": 3}}, - "a: 1\nb: 2\nc: 3\n", - }, - - // Duration - { - map[string]time.Duration{"a": 3 * time.Second}, - "a: 3s\n", - }, - - // Issue #24: bug in map merging logic. - { - map[string]string{"a": ""}, - "a: \n", - }, - - // Issue #34: marshal unsupported base 60 floats quoted for compatibility - // with old YAML 1.1 parsers. - { - map[string]string{"a": "1:1"}, - "a: \"1:1\"\n", - }, - - // Binary data. - { - map[string]string{"a": "\x00"}, - "a: \"\\0\"\n", - }, { - map[string]string{"a": "\x80\x81\x82"}, - "a: !!binary gIGC\n", - }, { - map[string]string{"a": strings.Repeat("\x90", 54)}, - "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n", - }, - - // Ordered maps. - { - &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}}, - "b: 2\na: 1\nd: 4\nc: 3\nsub:\n e: 5\n", - }, - - // Encode unicode as utf-8 rather than in escaped form. - { - map[string]string{"a": "你好"}, - "a: 你好\n", - }, - - // Support encoding.TextMarshaler. - { - map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)}, - "a: 1.2.3.4\n", - }, - { - map[string]time.Time{"a": time.Unix(1424801979, 0)}, - "a: 2015-02-24T18:19:39Z\n", - }, - - // Ensure strings containing ": " are quoted (reported as PR #43, but not reproducible). - { - map[string]string{"a": "b: c"}, - "a: 'b: c'\n", - }, - - // Containing hash mark ('#') in string should be quoted - { - map[string]string{"a": "Hello #comment"}, - "a: 'Hello #comment'\n", - }, - { - map[string]string{"a": "你好 #comment"}, - "a: '你好 #comment'\n", - }, -} - -func (s *S) TestMarshal(c *C) { - defer os.Setenv("TZ", os.Getenv("TZ")) - os.Setenv("TZ", "UTC") - for _, item := range marshalTests { - data, err := yaml.Marshal(item.value) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, item.data) - } -} - -var marshalErrorTests = []struct { - value interface{} - error string - panic string -}{{ - value: &struct { - B int - inlineB ",inline" - }{1, inlineB{2, inlineC{3}}}, - panic: `Duplicated key 'b' in struct struct \{ B int; .*`, -}, { - value: &struct { - A int - B map[string]int ",inline" - }{1, map[string]int{"a": 2}}, - panic: `Can't have key "a" in inlined map; conflicts with struct field`, -}} - -func (s *S) TestMarshalErrors(c *C) { - for _, item := range marshalErrorTests { - if item.panic != "" { - c.Assert(func() { yaml.Marshal(item.value) }, PanicMatches, item.panic) - } else { - _, err := yaml.Marshal(item.value) - c.Assert(err, ErrorMatches, item.error) - } - } -} - -func (s *S) TestMarshalTypeCache(c *C) { - var data []byte - var err error - func() { - type T struct{ A int } - data, err = yaml.Marshal(&T{}) - c.Assert(err, IsNil) - }() - func() { - type T struct{ B int } - data, err = yaml.Marshal(&T{}) - c.Assert(err, IsNil) - }() - c.Assert(string(data), Equals, "b: 0\n") -} - -var marshalerTests = []struct { - data string - value interface{} -}{ - {"_:\n hi: there\n", map[interface{}]interface{}{"hi": "there"}}, - {"_:\n- 1\n- A\n", []interface{}{1, "A"}}, - {"_: 10\n", 10}, - {"_: null\n", nil}, - {"_: BAR!\n", "BAR!"}, -} - -type marshalerType struct { - value interface{} -} - -func (o marshalerType) MarshalText() ([]byte, error) { - panic("MarshalText called on type with MarshalYAML") -} - -func (o marshalerType) MarshalYAML() (interface{}, error) { - return o.value, nil -} - -type marshalerValue struct { - Field marshalerType "_" -} - -func (s *S) TestMarshaler(c *C) { - for _, item := range marshalerTests { - obj := &marshalerValue{} - obj.Field.value = item.value - data, err := yaml.Marshal(obj) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, string(item.data)) - } -} - -func (s *S) TestMarshalerWholeDocument(c *C) { - obj := &marshalerType{} - obj.value = map[string]string{"hello": "world!"} - data, err := yaml.Marshal(obj) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, "hello: world!\n") -} - -type failingMarshaler struct{} - -func (ft *failingMarshaler) MarshalYAML() (interface{}, error) { - return nil, failingErr -} - -func (s *S) TestMarshalerError(c *C) { - _, err := yaml.Marshal(&failingMarshaler{}) - c.Assert(err, Equals, failingErr) -} - -func (s *S) TestSortedOutput(c *C) { - order := []interface{}{ - false, - true, - 1, - uint(1), - 1.0, - 1.1, - 1.2, - 2, - uint(2), - 2.0, - 2.1, - "", - ".1", - ".2", - ".a", - "1", - "2", - "a!10", - "a/2", - "a/10", - "a~10", - "ab/1", - "b/1", - "b/01", - "b/2", - "b/02", - "b/3", - "b/03", - "b1", - "b01", - "b3", - "c2.10", - "c10.2", - "d1", - "d12", - "d12a", - } - m := make(map[interface{}]int) - for _, k := range order { - m[k] = 1 - } - data, err := yaml.Marshal(m) - c.Assert(err, IsNil) - out := "\n" + string(data) - last := 0 - for i, k := range order { - repr := fmt.Sprint(k) - if s, ok := k.(string); ok { - if _, err = strconv.ParseFloat(repr, 32); s == "" || err == nil { - repr = `"` + repr + `"` - } - } - index := strings.Index(out, "\n"+repr+":") - if index == -1 { - c.Fatalf("%#v is not in the output: %#v", k, out) - } - if index < last { - c.Fatalf("%#v was generated before %#v: %q", k, order[i-1], out) - } - last = index - } -} diff --git a/Godeps/_workspace/src/gopkg.in/yaml.v2/suite_test.go b/Godeps/_workspace/src/gopkg.in/yaml.v2/suite_test.go deleted file mode 100644 index c5cf1ed4f6e..00000000000 --- a/Godeps/_workspace/src/gopkg.in/yaml.v2/suite_test.go +++ /dev/null @@ -1,12 +0,0 @@ -package yaml_test - -import ( - . "gopkg.in/check.v1" - "testing" -) - -func Test(t *testing.T) { TestingT(t) } - -type S struct{} - -var _ = Suite(&S{}) diff --git a/Godeps/_workspace/src/labix.org/v2/mgo/bson/bson_test.go b/Godeps/_workspace/src/labix.org/v2/mgo/bson/bson_test.go deleted file mode 100644 index 5f5f100caeb..00000000000 --- a/Godeps/_workspace/src/labix.org/v2/mgo/bson/bson_test.go +++ /dev/null @@ -1,1419 +0,0 @@ -// BSON library for Go -// -// Copyright (c) 2010-2012 - Gustavo Niemeyer -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this -// list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// gobson - BSON library for Go. - -package bson_test - -import ( - "encoding/binary" - "encoding/json" - "errors" - . "launchpad.net/gocheck" - "labix.org/v2/mgo/bson" - "net/url" - "reflect" - "testing" - "time" -) - -func TestAll(t *testing.T) { - TestingT(t) -} - -type S struct{} - -var _ = Suite(&S{}) - -// Wrap up the document elements contained in data, prepending the int32 -// length of the data, and appending the '\x00' value closing the document. -func wrapInDoc(data string) string { - result := make([]byte, len(data)+5) - binary.LittleEndian.PutUint32(result, uint32(len(result))) - copy(result[4:], []byte(data)) - return string(result) -} - -func makeZeroDoc(value interface{}) (zero interface{}) { - v := reflect.ValueOf(value) - t := v.Type() - switch t.Kind() { - case reflect.Map: - mv := reflect.MakeMap(t) - zero = mv.Interface() - case reflect.Ptr: - pv := reflect.New(v.Type().Elem()) - zero = pv.Interface() - case reflect.Slice: - zero = reflect.New(t).Interface() - default: - panic("unsupported doc type") - } - return zero -} - -func testUnmarshal(c *C, data string, obj interface{}) { - zero := makeZeroDoc(obj) - err := bson.Unmarshal([]byte(data), zero) - c.Assert(err, IsNil) - c.Assert(zero, DeepEquals, obj) -} - -type testItemType struct { - obj interface{} - data string -} - -// -------------------------------------------------------------------------- -// Samples from bsonspec.org: - -var sampleItems = []testItemType{ - {bson.M{"hello": "world"}, - "\x16\x00\x00\x00\x02hello\x00\x06\x00\x00\x00world\x00\x00"}, - {bson.M{"BSON": []interface{}{"awesome", float64(5.05), 1986}}, - "1\x00\x00\x00\x04BSON\x00&\x00\x00\x00\x020\x00\x08\x00\x00\x00" + - "awesome\x00\x011\x00333333\x14@\x102\x00\xc2\x07\x00\x00\x00\x00"}, -} - -func (s *S) TestMarshalSampleItems(c *C) { - for i, item := range sampleItems { - data, err := bson.Marshal(item.obj) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, item.data, Commentf("Failed on item %d", i)) - } -} - -func (s *S) TestUnmarshalSampleItems(c *C) { - for i, item := range sampleItems { - value := bson.M{} - err := bson.Unmarshal([]byte(item.data), value) - c.Assert(err, IsNil) - c.Assert(value, DeepEquals, item.obj, Commentf("Failed on item %d", i)) - } -} - -// -------------------------------------------------------------------------- -// Every type, ordered by the type flag. These are not wrapped with the -// length and last \x00 from the document. wrapInDoc() computes them. -// Note that all of them should be supported as two-way conversions. - -var allItems = []testItemType{ - {bson.M{}, - ""}, - {bson.M{"_": float64(5.05)}, - "\x01_\x00333333\x14@"}, - {bson.M{"_": "yo"}, - "\x02_\x00\x03\x00\x00\x00yo\x00"}, - {bson.M{"_": bson.M{"a": true}}, - "\x03_\x00\x09\x00\x00\x00\x08a\x00\x01\x00"}, - {bson.M{"_": []interface{}{true, false}}, - "\x04_\x00\r\x00\x00\x00\x080\x00\x01\x081\x00\x00\x00"}, - {bson.M{"_": []byte("yo")}, - "\x05_\x00\x02\x00\x00\x00\x00yo"}, - {bson.M{"_": bson.Binary{0x80, []byte("udef")}}, - "\x05_\x00\x04\x00\x00\x00\x80udef"}, - {bson.M{"_": bson.Undefined}, // Obsolete, but still seen in the wild. - "\x06_\x00"}, - {bson.M{"_": bson.ObjectId("0123456789ab")}, - "\x07_\x000123456789ab"}, - {bson.M{"_": false}, - "\x08_\x00\x00"}, - {bson.M{"_": true}, - "\x08_\x00\x01"}, - {bson.M{"_": time.Unix(0, 258e6)}, // Note the NS <=> MS conversion. - "\x09_\x00\x02\x01\x00\x00\x00\x00\x00\x00"}, - {bson.M{"_": nil}, - "\x0A_\x00"}, - {bson.M{"_": bson.RegEx{"ab", "cd"}}, - "\x0B_\x00ab\x00cd\x00"}, - {bson.M{"_": bson.JavaScript{"code", nil}}, - "\x0D_\x00\x05\x00\x00\x00code\x00"}, - {bson.M{"_": bson.Symbol("sym")}, - "\x0E_\x00\x04\x00\x00\x00sym\x00"}, - {bson.M{"_": bson.JavaScript{"code", bson.M{"": nil}}}, - "\x0F_\x00\x14\x00\x00\x00\x05\x00\x00\x00code\x00" + - "\x07\x00\x00\x00\x0A\x00\x00"}, - {bson.M{"_": 258}, - "\x10_\x00\x02\x01\x00\x00"}, - {bson.M{"_": bson.MongoTimestamp(258)}, - "\x11_\x00\x02\x01\x00\x00\x00\x00\x00\x00"}, - {bson.M{"_": int64(258)}, - "\x12_\x00\x02\x01\x00\x00\x00\x00\x00\x00"}, - {bson.M{"_": int64(258 << 32)}, - "\x12_\x00\x00\x00\x00\x00\x02\x01\x00\x00"}, - {bson.M{"_": bson.MaxKey}, - "\x7F_\x00"}, - {bson.M{"_": bson.MinKey}, - "\xFF_\x00"}, -} - -func (s *S) TestMarshalAllItems(c *C) { - for i, item := range allItems { - data, err := bson.Marshal(item.obj) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, wrapInDoc(item.data), Commentf("Failed on item %d: %#v", i, item)) - } -} - -func (s *S) TestUnmarshalAllItems(c *C) { - for i, item := range allItems { - value := bson.M{} - err := bson.Unmarshal([]byte(wrapInDoc(item.data)), value) - c.Assert(err, IsNil) - c.Assert(value, DeepEquals, item.obj, Commentf("Failed on item %d: %#v", i, item)) - } -} - -func (s *S) TestUnmarshalRawAllItems(c *C) { - for i, item := range allItems { - if len(item.data) == 0 { - continue - } - value := item.obj.(bson.M)["_"] - if value == nil { - continue - } - pv := reflect.New(reflect.ValueOf(value).Type()) - raw := bson.Raw{item.data[0], []byte(item.data[3:])} - c.Logf("Unmarshal raw: %#v, %#v", raw, pv.Interface()) - err := raw.Unmarshal(pv.Interface()) - c.Assert(err, IsNil) - c.Assert(pv.Elem().Interface(), DeepEquals, value, Commentf("Failed on item %d: %#v", i, item)) - } -} - -func (s *S) TestUnmarshalRawIncompatible(c *C) { - raw := bson.Raw{0x08, []byte{0x01}} // true - err := raw.Unmarshal(&struct{}{}) - c.Assert(err, ErrorMatches, "BSON kind 0x08 isn't compatible with type struct \\{\\}") -} - -func (s *S) TestUnmarshalZeroesStruct(c *C) { - data, err := bson.Marshal(bson.M{"b": 2}) - c.Assert(err, IsNil) - type T struct{ A, B int } - v := T{A: 1} - err = bson.Unmarshal(data, &v) - c.Assert(err, IsNil) - c.Assert(v.A, Equals, 0) - c.Assert(v.B, Equals, 2) -} - -func (s *S) TestUnmarshalZeroesMap(c *C) { - data, err := bson.Marshal(bson.M{"b": 2}) - c.Assert(err, IsNil) - m := bson.M{"a": 1} - err = bson.Unmarshal(data, &m) - c.Assert(err, IsNil) - c.Assert(m, DeepEquals, bson.M{"b": 2}) -} - -func (s *S) TestUnmarshalNonNilInterface(c *C) { - data, err := bson.Marshal(bson.M{"b": 2}) - c.Assert(err, IsNil) - m := bson.M{"a": 1} - var i interface{} - i = m - err = bson.Unmarshal(data, &i) - c.Assert(err, IsNil) - c.Assert(i, DeepEquals, bson.M{"b": 2}) - c.Assert(m, DeepEquals, bson.M{"a": 1}) -} - -// -------------------------------------------------------------------------- -// Some one way marshaling operations which would unmarshal differently. - -var oneWayMarshalItems = []testItemType{ - // These are being passed as pointers, and will unmarshal as values. - {bson.M{"": &bson.Binary{0x02, []byte("old")}}, - "\x05\x00\x07\x00\x00\x00\x02\x03\x00\x00\x00old"}, - {bson.M{"": &bson.Binary{0x80, []byte("udef")}}, - "\x05\x00\x04\x00\x00\x00\x80udef"}, - {bson.M{"": &bson.RegEx{"ab", "cd"}}, - "\x0B\x00ab\x00cd\x00"}, - {bson.M{"": &bson.JavaScript{"code", nil}}, - "\x0D\x00\x05\x00\x00\x00code\x00"}, - {bson.M{"": &bson.JavaScript{"code", bson.M{"": nil}}}, - "\x0F\x00\x14\x00\x00\x00\x05\x00\x00\x00code\x00" + - "\x07\x00\x00\x00\x0A\x00\x00"}, - - // There's no float32 type in BSON. Will encode as a float64. - {bson.M{"": float32(5.05)}, - "\x01\x00\x00\x00\x00@33\x14@"}, - - // The array will be unmarshaled as a slice instead. - {bson.M{"": [2]bool{true, false}}, - "\x04\x00\r\x00\x00\x00\x080\x00\x01\x081\x00\x00\x00"}, - - // The typed slice will be unmarshaled as []interface{}. - {bson.M{"": []bool{true, false}}, - "\x04\x00\r\x00\x00\x00\x080\x00\x01\x081\x00\x00\x00"}, - - // Will unmarshal as a []byte. - {bson.M{"": bson.Binary{0x00, []byte("yo")}}, - "\x05\x00\x02\x00\x00\x00\x00yo"}, - {bson.M{"": bson.Binary{0x02, []byte("old")}}, - "\x05\x00\x07\x00\x00\x00\x02\x03\x00\x00\x00old"}, - - // No way to preserve the type information here. We might encode as a zero - // value, but this would mean that pointer values in structs wouldn't be - // able to correctly distinguish between unset and set to the zero value. - {bson.M{"": (*byte)(nil)}, - "\x0A\x00"}, - - // No int types smaller than int32 in BSON. Could encode this as a char, - // but it would still be ambiguous, take more, and be awkward in Go when - // loaded without typing information. - {bson.M{"": byte(8)}, - "\x10\x00\x08\x00\x00\x00"}, - - // There are no unsigned types in BSON. Will unmarshal as int32 or int64. - {bson.M{"": uint32(258)}, - "\x10\x00\x02\x01\x00\x00"}, - {bson.M{"": uint64(258)}, - "\x12\x00\x02\x01\x00\x00\x00\x00\x00\x00"}, - {bson.M{"": uint64(258 << 32)}, - "\x12\x00\x00\x00\x00\x00\x02\x01\x00\x00"}, - - // This will unmarshal as int. - {bson.M{"": int32(258)}, - "\x10\x00\x02\x01\x00\x00"}, - - // That's a special case. The unsigned value is too large for an int32, - // so an int64 is used instead. - {bson.M{"": uint32(1<<32 - 1)}, - "\x12\x00\xFF\xFF\xFF\xFF\x00\x00\x00\x00"}, - {bson.M{"": uint(1<<32 - 1)}, - "\x12\x00\xFF\xFF\xFF\xFF\x00\x00\x00\x00"}, -} - -func (s *S) TestOneWayMarshalItems(c *C) { - for i, item := range oneWayMarshalItems { - data, err := bson.Marshal(item.obj) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, wrapInDoc(item.data), - Commentf("Failed on item %d", i)) - } -} - -// -------------------------------------------------------------------------- -// Two-way tests for user-defined structures using the samples -// from bsonspec.org. - -type specSample1 struct { - Hello string -} - -type specSample2 struct { - BSON []interface{} "BSON" -} - -var structSampleItems = []testItemType{ - {&specSample1{"world"}, - "\x16\x00\x00\x00\x02hello\x00\x06\x00\x00\x00world\x00\x00"}, - {&specSample2{[]interface{}{"awesome", float64(5.05), 1986}}, - "1\x00\x00\x00\x04BSON\x00&\x00\x00\x00\x020\x00\x08\x00\x00\x00" + - "awesome\x00\x011\x00333333\x14@\x102\x00\xc2\x07\x00\x00\x00\x00"}, -} - -func (s *S) TestMarshalStructSampleItems(c *C) { - for i, item := range structSampleItems { - data, err := bson.Marshal(item.obj) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, item.data, - Commentf("Failed on item %d", i)) - } -} - -func (s *S) TestUnmarshalStructSampleItems(c *C) { - for _, item := range structSampleItems { - testUnmarshal(c, item.data, item.obj) - } -} - -func (s *S) Test64bitInt(c *C) { - var i int64 = (1 << 31) - if int(i) > 0 { - data, err := bson.Marshal(bson.M{"i": int(i)}) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, wrapInDoc("\x12i\x00\x00\x00\x00\x80\x00\x00\x00\x00")) - - var result struct { I int } - err = bson.Unmarshal(data, &result) - c.Assert(err, IsNil) - c.Assert(int64(result.I), Equals, i) - } -} - -// -------------------------------------------------------------------------- -// Generic two-way struct marshaling tests. - -var bytevar = byte(8) -var byteptr = &bytevar - -var structItems = []testItemType{ - {&struct{ Ptr *byte }{nil}, - "\x0Aptr\x00"}, - {&struct{ Ptr *byte }{&bytevar}, - "\x10ptr\x00\x08\x00\x00\x00"}, - {&struct{ Ptr **byte }{&byteptr}, - "\x10ptr\x00\x08\x00\x00\x00"}, - {&struct{ Byte byte }{8}, - "\x10byte\x00\x08\x00\x00\x00"}, - {&struct{ Byte byte }{0}, - "\x10byte\x00\x00\x00\x00\x00"}, - {&struct { - V byte "Tag" - }{8}, - "\x10Tag\x00\x08\x00\x00\x00"}, - {&struct { - V *struct { - Byte byte - } - }{&struct{ Byte byte }{8}}, - "\x03v\x00" + "\x0f\x00\x00\x00\x10byte\x00\b\x00\x00\x00\x00"}, - {&struct{ priv byte }{}, ""}, - - // The order of the dumped fields should be the same in the struct. - {&struct{ A, C, B, D, F, E *byte }{}, - "\x0Aa\x00\x0Ac\x00\x0Ab\x00\x0Ad\x00\x0Af\x00\x0Ae\x00"}, - - {&struct{ V bson.Raw }{bson.Raw{0x03, []byte("\x0f\x00\x00\x00\x10byte\x00\b\x00\x00\x00\x00")}}, - "\x03v\x00" + "\x0f\x00\x00\x00\x10byte\x00\b\x00\x00\x00\x00"}, - {&struct{ V bson.Raw }{bson.Raw{0x10, []byte("\x00\x00\x00\x00")}}, - "\x10v\x00" + "\x00\x00\x00\x00"}, - - // Byte arrays. - {&struct{ V [2]byte }{[2]byte{'y', 'o'}}, - "\x05v\x00\x02\x00\x00\x00\x00yo"}, -} - -func (s *S) TestMarshalStructItems(c *C) { - for i, item := range structItems { - data, err := bson.Marshal(item.obj) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, wrapInDoc(item.data), - Commentf("Failed on item %d", i)) - } -} - -func (s *S) TestUnmarshalStructItems(c *C) { - for _, item := range structItems { - testUnmarshal(c, wrapInDoc(item.data), item.obj) - } -} - -func (s *S) TestUnmarshalRawStructItems(c *C) { - for i, item := range structItems { - raw := bson.Raw{0x03, []byte(wrapInDoc(item.data))} - zero := makeZeroDoc(item.obj) - err := raw.Unmarshal(zero) - c.Assert(err, IsNil) - c.Assert(zero, DeepEquals, item.obj, Commentf("Failed on item %d: %#v", i, item)) - } -} - -func (s *S) TestUnmarshalRawNil(c *C) { - // Regression test: shouldn't try to nil out the pointer itself, - // as it's not settable. - raw := bson.Raw{0x0A, []byte{}} - err := raw.Unmarshal(&struct{}{}) - c.Assert(err, IsNil) -} - -// -------------------------------------------------------------------------- -// One-way marshaling tests. - -type dOnIface struct { - D interface{} -} - -type ignoreField struct { - Before string - Ignore string `bson:"-"` - After string -} - -var marshalItems = []testItemType{ - // Ordered document dump. Will unmarshal as a dictionary by default. - {bson.D{{"a", nil}, {"c", nil}, {"b", nil}, {"d", nil}, {"f", nil}, {"e", true}}, - "\x0Aa\x00\x0Ac\x00\x0Ab\x00\x0Ad\x00\x0Af\x00\x08e\x00\x01"}, - {MyD{{"a", nil}, {"c", nil}, {"b", nil}, {"d", nil}, {"f", nil}, {"e", true}}, - "\x0Aa\x00\x0Ac\x00\x0Ab\x00\x0Ad\x00\x0Af\x00\x08e\x00\x01"}, - {&dOnIface{bson.D{{"a", nil}, {"c", nil}, {"b", nil}, {"d", true}}}, - "\x03d\x00" + wrapInDoc("\x0Aa\x00\x0Ac\x00\x0Ab\x00\x08d\x00\x01")}, - {&ignoreField{"before", "ignore", "after"}, - "\x02before\x00\a\x00\x00\x00before\x00\x02after\x00\x06\x00\x00\x00after\x00"}, - - // Marshalling a Raw document does nothing. - {bson.Raw{0x03, []byte(wrapInDoc("anything"))}, - "anything"}, - {bson.Raw{Data: []byte(wrapInDoc("anything"))}, - "anything"}, -} - -func (s *S) TestMarshalOneWayItems(c *C) { - for _, item := range marshalItems { - data, err := bson.Marshal(item.obj) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, wrapInDoc(item.data)) - } -} - -// -------------------------------------------------------------------------- -// One-way unmarshaling tests. - -var unmarshalItems = []testItemType{ - // Field is private. Should not attempt to unmarshal it. - {&struct{ priv byte }{}, - "\x10priv\x00\x08\x00\x00\x00"}, - - // Wrong casing. Field names are lowercased. - {&struct{ Byte byte }{}, - "\x10Byte\x00\x08\x00\x00\x00"}, - - // Ignore non-existing field. - {&struct{ Byte byte }{9}, - "\x10boot\x00\x08\x00\x00\x00" + "\x10byte\x00\x09\x00\x00\x00"}, - - // Do not unmarshal on ignored field. - {&ignoreField{"before", "", "after"}, - "\x02before\x00\a\x00\x00\x00before\x00" + - "\x02-\x00\a\x00\x00\x00ignore\x00" + - "\x02after\x00\x06\x00\x00\x00after\x00"}, - - // Ignore unsuitable types silently. - {map[string]string{"str": "s"}, - "\x02str\x00\x02\x00\x00\x00s\x00" + "\x10int\x00\x01\x00\x00\x00"}, - {map[string][]int{"array": []int{5, 9}}, - "\x04array\x00" + wrapInDoc("\x100\x00\x05\x00\x00\x00"+"\x021\x00\x02\x00\x00\x00s\x00"+"\x102\x00\x09\x00\x00\x00")}, - - // Wrong type. Shouldn't init pointer. - {&struct{ Str *byte }{}, - "\x02str\x00\x02\x00\x00\x00s\x00"}, - {&struct{ Str *struct{ Str string } }{}, - "\x02str\x00\x02\x00\x00\x00s\x00"}, - - // Ordered document. - {&struct{ bson.D }{bson.D{{"a", nil}, {"c", nil}, {"b", nil}, {"d", true}}}, - "\x03d\x00" + wrapInDoc("\x0Aa\x00\x0Ac\x00\x0Ab\x00\x08d\x00\x01")}, - - // Raw document. - {&bson.Raw{0x03, []byte(wrapInDoc("\x10byte\x00\x08\x00\x00\x00"))}, - "\x10byte\x00\x08\x00\x00\x00"}, - - // Decode old binary. - {bson.M{"_": []byte("old")}, - "\x05_\x00\x07\x00\x00\x00\x02\x03\x00\x00\x00old"}, - - // Decode old binary without length. According to the spec, this shouldn't happen. - {bson.M{"_": []byte("old")}, - "\x05_\x00\x03\x00\x00\x00\x02old"}, -} - -func (s *S) TestUnmarshalOneWayItems(c *C) { - for _, item := range unmarshalItems { - testUnmarshal(c, wrapInDoc(item.data), item.obj) - } -} - -func (s *S) TestUnmarshalNilInStruct(c *C) { - // Nil is the default value, so we need to ensure it's indeed being set. - b := byte(1) - v := &struct{ Ptr *byte }{&b} - err := bson.Unmarshal([]byte(wrapInDoc("\x0Aptr\x00")), v) - c.Assert(err, IsNil) - c.Assert(v, DeepEquals, &struct{ Ptr *byte }{nil}) -} - -// -------------------------------------------------------------------------- -// Marshalling error cases. - -type structWithDupKeys struct { - Name byte - Other byte "name" // Tag should precede. -} - -var marshalErrorItems = []testItemType{ - {bson.M{"": uint64(1 << 63)}, - "BSON has no uint64 type, and value is too large to fit correctly in an int64"}, - {bson.M{"": bson.ObjectId("tooshort")}, - "ObjectIDs must be exactly 12 bytes long \\(got 8\\)"}, - {int64(123), - "Can't marshal int64 as a BSON document"}, - {bson.M{"": 1i}, - "Can't marshal complex128 in a BSON document"}, - {&structWithDupKeys{}, - "Duplicated key 'name' in struct bson_test.structWithDupKeys"}, - {bson.Raw{0x0A, []byte{}}, - "Attempted to unmarshal Raw kind 10 as a document"}, - {&inlineCantPtr{&struct{ A, B int }{1, 2}}, - "Option ,inline needs a struct value or map field"}, - {&inlineDupName{1, struct{ A, B int }{2, 3}}, - "Duplicated key 'a' in struct bson_test.inlineDupName"}, - {&inlineDupMap{}, - "Multiple ,inline maps in struct bson_test.inlineDupMap"}, - {&inlineBadKeyMap{}, - "Option ,inline needs a map with string keys in struct bson_test.inlineBadKeyMap"}, - {&inlineMap{A: 1, M: map[string]interface{}{"a": 1}}, - `Can't have key "a" in inlined map; conflicts with struct field`}, -} - -func (s *S) TestMarshalErrorItems(c *C) { - for _, item := range marshalErrorItems { - data, err := bson.Marshal(item.obj) - c.Assert(err, ErrorMatches, item.data) - c.Assert(data, IsNil) - } -} - -// -------------------------------------------------------------------------- -// Unmarshalling error cases. - -type unmarshalErrorType struct { - obj interface{} - data string - error string -} - -var unmarshalErrorItems = []unmarshalErrorType{ - // Tag name conflicts with existing parameter. - {&structWithDupKeys{}, - "\x10name\x00\x08\x00\x00\x00", - "Duplicated key 'name' in struct bson_test.structWithDupKeys"}, - - // Non-string map key. - {map[int]interface{}{}, - "\x10name\x00\x08\x00\x00\x00", - "BSON map must have string keys. Got: map\\[int\\]interface \\{\\}"}, - - {nil, - "\xEEname\x00", - "Unknown element kind \\(0xEE\\)"}, - - {struct{ Name bool }{}, - "\x10name\x00\x08\x00\x00\x00", - "Unmarshal can't deal with struct values. Use a pointer."}, - - {123, - "\x10name\x00\x08\x00\x00\x00", - "Unmarshal needs a map or a pointer to a struct."}, -} - -func (s *S) TestUnmarshalErrorItems(c *C) { - for _, item := range unmarshalErrorItems { - data := []byte(wrapInDoc(item.data)) - var value interface{} - switch reflect.ValueOf(item.obj).Kind() { - case reflect.Map, reflect.Ptr: - value = makeZeroDoc(item.obj) - case reflect.Invalid: - value = bson.M{} - default: - value = item.obj - } - err := bson.Unmarshal(data, value) - c.Assert(err, ErrorMatches, item.error) - } -} - -type unmarshalRawErrorType struct { - obj interface{} - raw bson.Raw - error string -} - -var unmarshalRawErrorItems = []unmarshalRawErrorType{ - // Tag name conflicts with existing parameter. - {&structWithDupKeys{}, - bson.Raw{0x03, []byte("\x10byte\x00\x08\x00\x00\x00")}, - "Duplicated key 'name' in struct bson_test.structWithDupKeys"}, - - {&struct{}{}, - bson.Raw{0xEE, []byte{}}, - "Unknown element kind \\(0xEE\\)"}, - - {struct{ Name bool }{}, - bson.Raw{0x10, []byte("\x08\x00\x00\x00")}, - "Raw Unmarshal can't deal with struct values. Use a pointer."}, - - {123, - bson.Raw{0x10, []byte("\x08\x00\x00\x00")}, - "Raw Unmarshal needs a map or a valid pointer."}, -} - -func (s *S) TestUnmarshalRawErrorItems(c *C) { - for i, item := range unmarshalRawErrorItems { - err := item.raw.Unmarshal(item.obj) - c.Assert(err, ErrorMatches, item.error, Commentf("Failed on item %d: %#v\n", i, item)) - } -} - -var corruptedData = []string{ - "\x04\x00\x00\x00\x00", // Shorter than minimum - "\x06\x00\x00\x00\x00", // Not enough data - "\x05\x00\x00", // Broken length - "\x05\x00\x00\x00\xff", // Corrupted termination - "\x0A\x00\x00\x00\x0Aooop\x00", // Unfinished C string - - // Array end past end of string (s[2]=0x07 is correct) - wrapInDoc("\x04\x00\x09\x00\x00\x00\x0A\x00\x00"), - - // Array end within string, but past acceptable. - wrapInDoc("\x04\x00\x08\x00\x00\x00\x0A\x00\x00"), - - // Document end within string, but past acceptable. - wrapInDoc("\x03\x00\x08\x00\x00\x00\x0A\x00\x00"), - - // String with corrupted end. - wrapInDoc("\x02\x00\x03\x00\x00\x00yo\xFF"), -} - -func (s *S) TestUnmarshalMapDocumentTooShort(c *C) { - for _, data := range corruptedData { - err := bson.Unmarshal([]byte(data), bson.M{}) - c.Assert(err, ErrorMatches, "Document is corrupted") - - err = bson.Unmarshal([]byte(data), &struct{}{}) - c.Assert(err, ErrorMatches, "Document is corrupted") - } -} - -// -------------------------------------------------------------------------- -// Setter test cases. - -var setterResult = map[string]error{} - -type setterType struct { - received interface{} -} - -func (o *setterType) SetBSON(raw bson.Raw) error { - err := raw.Unmarshal(&o.received) - if err != nil { - panic("The panic:" + err.Error()) - } - if s, ok := o.received.(string); ok { - if result, ok := setterResult[s]; ok { - return result - } - } - return nil -} - -type ptrSetterDoc struct { - Field *setterType "_" -} - -type valSetterDoc struct { - Field setterType "_" -} - -func (s *S) TestUnmarshalAllItemsWithPtrSetter(c *C) { - for _, item := range allItems { - for i := 0; i != 2; i++ { - var field *setterType - if i == 0 { - obj := &ptrSetterDoc{} - err := bson.Unmarshal([]byte(wrapInDoc(item.data)), obj) - c.Assert(err, IsNil) - field = obj.Field - } else { - obj := &valSetterDoc{} - err := bson.Unmarshal([]byte(wrapInDoc(item.data)), obj) - c.Assert(err, IsNil) - field = &obj.Field - } - if item.data == "" { - // Nothing to unmarshal. Should be untouched. - if i == 0 { - c.Assert(field, IsNil) - } else { - c.Assert(field.received, IsNil) - } - } else { - expected := item.obj.(bson.M)["_"] - c.Assert(field, NotNil, Commentf("Pointer not initialized (%#v)", expected)) - c.Assert(field.received, DeepEquals, expected) - } - } - } -} - -func (s *S) TestUnmarshalWholeDocumentWithSetter(c *C) { - obj := &setterType{} - err := bson.Unmarshal([]byte(sampleItems[0].data), obj) - c.Assert(err, IsNil) - c.Assert(obj.received, DeepEquals, bson.M{"hello": "world"}) -} - -func (s *S) TestUnmarshalSetterOmits(c *C) { - setterResult["2"] = &bson.TypeError{} - setterResult["4"] = &bson.TypeError{} - defer func() { - delete(setterResult, "2") - delete(setterResult, "4") - }() - - m := map[string]*setterType{} - data := wrapInDoc("\x02abc\x00\x02\x00\x00\x001\x00" + - "\x02def\x00\x02\x00\x00\x002\x00" + - "\x02ghi\x00\x02\x00\x00\x003\x00" + - "\x02jkl\x00\x02\x00\x00\x004\x00") - err := bson.Unmarshal([]byte(data), m) - c.Assert(err, IsNil) - c.Assert(m["abc"], NotNil) - c.Assert(m["def"], IsNil) - c.Assert(m["ghi"], NotNil) - c.Assert(m["jkl"], IsNil) - - c.Assert(m["abc"].received, Equals, "1") - c.Assert(m["ghi"].received, Equals, "3") -} - -func (s *S) TestUnmarshalSetterErrors(c *C) { - boom := errors.New("BOOM") - setterResult["2"] = boom - defer delete(setterResult, "2") - - m := map[string]*setterType{} - data := wrapInDoc("\x02abc\x00\x02\x00\x00\x001\x00" + - "\x02def\x00\x02\x00\x00\x002\x00" + - "\x02ghi\x00\x02\x00\x00\x003\x00") - err := bson.Unmarshal([]byte(data), m) - c.Assert(err, Equals, boom) - c.Assert(m["abc"], NotNil) - c.Assert(m["def"], IsNil) - c.Assert(m["ghi"], IsNil) - - c.Assert(m["abc"].received, Equals, "1") -} - -func (s *S) TestDMap(c *C) { - d := bson.D{{"a", 1}, {"b", 2}} - c.Assert(d.Map(), DeepEquals, bson.M{"a": 1, "b": 2}) -} - -func (s *S) TestUnmarshalSetterSetZero(c *C) { - setterResult["foo"] = bson.SetZero - defer delete(setterResult, "field") - - data, err := bson.Marshal(bson.M{"field": "foo"}) - c.Assert(err, IsNil) - - m := map[string]*setterType{} - err = bson.Unmarshal([]byte(data), m) - c.Assert(err, IsNil) - - value, ok := m["field"] - c.Assert(ok, Equals, true) - c.Assert(value, IsNil) -} - - -// -------------------------------------------------------------------------- -// Getter test cases. - -type typeWithGetter struct { - result interface{} - err error -} - -func (t *typeWithGetter) GetBSON() (interface{}, error) { - return t.result, t.err -} - -type docWithGetterField struct { - Field *typeWithGetter "_" -} - -func (s *S) TestMarshalAllItemsWithGetter(c *C) { - for i, item := range allItems { - if item.data == "" { - continue - } - obj := &docWithGetterField{} - obj.Field = &typeWithGetter{result: item.obj.(bson.M)["_"]} - data, err := bson.Marshal(obj) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, wrapInDoc(item.data), - Commentf("Failed on item #%d", i)) - } -} - -func (s *S) TestMarshalWholeDocumentWithGetter(c *C) { - obj := &typeWithGetter{result: sampleItems[0].obj} - data, err := bson.Marshal(obj) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, sampleItems[0].data) -} - -func (s *S) TestGetterErrors(c *C) { - e := errors.New("oops") - - obj1 := &docWithGetterField{} - obj1.Field = &typeWithGetter{sampleItems[0].obj, e} - data, err := bson.Marshal(obj1) - c.Assert(err, ErrorMatches, "oops") - c.Assert(data, IsNil) - - obj2 := &typeWithGetter{sampleItems[0].obj, e} - data, err = bson.Marshal(obj2) - c.Assert(err, ErrorMatches, "oops") - c.Assert(data, IsNil) -} - -type intGetter int64 - -func (t intGetter) GetBSON() (interface{}, error) { - return int64(t), nil -} - -type typeWithIntGetter struct { - V intGetter ",minsize" -} - -func (s *S) TestMarshalShortWithGetter(c *C) { - obj := typeWithIntGetter{42} - data, err := bson.Marshal(obj) - c.Assert(err, IsNil) - m := bson.M{} - err = bson.Unmarshal(data, m) - c.Assert(m["v"], Equals, 42) -} - -// -------------------------------------------------------------------------- -// Cross-type conversion tests. - -type crossTypeItem struct { - obj1 interface{} - obj2 interface{} -} - -type condStr struct { - V string ",omitempty" -} -type condStrNS struct { - V string `a:"A" bson:",omitempty" b:"B"` -} -type condBool struct { - V bool ",omitempty" -} -type condInt struct { - V int ",omitempty" -} -type condUInt struct { - V uint ",omitempty" -} -type condFloat struct { - V float64 ",omitempty" -} -type condIface struct { - V interface{} ",omitempty" -} -type condPtr struct { - V *bool ",omitempty" -} -type condSlice struct { - V []string ",omitempty" -} -type condMap struct { - V map[string]int ",omitempty" -} -type namedCondStr struct { - V string "myv,omitempty" -} -type condTime struct { - V time.Time ",omitempty" -} - -type shortInt struct { - V int64 ",minsize" -} -type shortUint struct { - V uint64 ",minsize" -} -type shortIface struct { - V interface{} ",minsize" -} -type shortPtr struct { - V *int64 ",minsize" -} -type shortNonEmptyInt struct { - V int64 ",minsize,omitempty" -} - -type inlineInt struct { - V struct{ A, B int } ",inline" -} -type inlineCantPtr struct { - V *struct{ A, B int } ",inline" -} -type inlineDupName struct { - A int - V struct{ A, B int } ",inline" -} -type inlineMap struct { - A int - M map[string]interface{} ",inline" -} -type inlineMapInt struct { - A int - M map[string]int ",inline" -} -type inlineMapMyM struct { - A int - M MyM ",inline" -} -type inlineDupMap struct { - M1 map[string]interface{} ",inline" - M2 map[string]interface{} ",inline" -} -type inlineBadKeyMap struct { - M map[int]int ",inline" -} - -type MyBytes []byte -type MyBool bool -type MyD []bson.DocElem -type MyM map[string]interface{} - -var truevar = true -var falsevar = false - -var int64var = int64(42) -var int64ptr = &int64var -var intvar = int(42) -var intptr = &intvar - -func parseURL(s string) *url.URL { - u, err := url.Parse(s) - if err != nil { - panic(err) - } - return u -} - -// That's a pretty fun test. It will dump the first item, generate a zero -// value equivalent to the second one, load the dumped data onto it, and then -// verify that the resulting value is deep-equal to the untouched second value. -// Then, it will do the same in the *opposite* direction! -var twoWayCrossItems = []crossTypeItem{ - // int<=>int - {&struct{ I int }{42}, &struct{ I int8 }{42}}, - {&struct{ I int }{42}, &struct{ I int32 }{42}}, - {&struct{ I int }{42}, &struct{ I int64 }{42}}, - {&struct{ I int8 }{42}, &struct{ I int32 }{42}}, - {&struct{ I int8 }{42}, &struct{ I int64 }{42}}, - {&struct{ I int32 }{42}, &struct{ I int64 }{42}}, - - // uint<=>uint - {&struct{ I uint }{42}, &struct{ I uint8 }{42}}, - {&struct{ I uint }{42}, &struct{ I uint32 }{42}}, - {&struct{ I uint }{42}, &struct{ I uint64 }{42}}, - {&struct{ I uint8 }{42}, &struct{ I uint32 }{42}}, - {&struct{ I uint8 }{42}, &struct{ I uint64 }{42}}, - {&struct{ I uint32 }{42}, &struct{ I uint64 }{42}}, - - // float32<=>float64 - {&struct{ I float32 }{42}, &struct{ I float64 }{42}}, - - // int<=>uint - {&struct{ I uint }{42}, &struct{ I int }{42}}, - {&struct{ I uint }{42}, &struct{ I int8 }{42}}, - {&struct{ I uint }{42}, &struct{ I int32 }{42}}, - {&struct{ I uint }{42}, &struct{ I int64 }{42}}, - {&struct{ I uint8 }{42}, &struct{ I int }{42}}, - {&struct{ I uint8 }{42}, &struct{ I int8 }{42}}, - {&struct{ I uint8 }{42}, &struct{ I int32 }{42}}, - {&struct{ I uint8 }{42}, &struct{ I int64 }{42}}, - {&struct{ I uint32 }{42}, &struct{ I int }{42}}, - {&struct{ I uint32 }{42}, &struct{ I int8 }{42}}, - {&struct{ I uint32 }{42}, &struct{ I int32 }{42}}, - {&struct{ I uint32 }{42}, &struct{ I int64 }{42}}, - {&struct{ I uint64 }{42}, &struct{ I int }{42}}, - {&struct{ I uint64 }{42}, &struct{ I int8 }{42}}, - {&struct{ I uint64 }{42}, &struct{ I int32 }{42}}, - {&struct{ I uint64 }{42}, &struct{ I int64 }{42}}, - - // int <=> float - {&struct{ I int }{42}, &struct{ I float64 }{42}}, - - // int <=> bool - {&struct{ I int }{1}, &struct{ I bool }{true}}, - {&struct{ I int }{0}, &struct{ I bool }{false}}, - - // uint <=> float64 - {&struct{ I uint }{42}, &struct{ I float64 }{42}}, - - // uint <=> bool - {&struct{ I uint }{1}, &struct{ I bool }{true}}, - {&struct{ I uint }{0}, &struct{ I bool }{false}}, - - // float64 <=> bool - {&struct{ I float64 }{1}, &struct{ I bool }{true}}, - {&struct{ I float64 }{0}, &struct{ I bool }{false}}, - - // string <=> string and string <=> []byte - {&struct{ S []byte }{[]byte("abc")}, &struct{ S string }{"abc"}}, - {&struct{ S []byte }{[]byte("def")}, &struct{ S bson.Symbol }{"def"}}, - {&struct{ S string }{"ghi"}, &struct{ S bson.Symbol }{"ghi"}}, - - // map <=> struct - {&struct { - A struct { - B, C int - } - }{struct{ B, C int }{1, 2}}, - map[string]map[string]int{"a": map[string]int{"b": 1, "c": 2}}}, - - {&struct{ A bson.Symbol }{"abc"}, map[string]string{"a": "abc"}}, - {&struct{ A bson.Symbol }{"abc"}, map[string][]byte{"a": []byte("abc")}}, - {&struct{ A []byte }{[]byte("abc")}, map[string]string{"a": "abc"}}, - {&struct{ A uint }{42}, map[string]int{"a": 42}}, - {&struct{ A uint }{42}, map[string]float64{"a": 42}}, - {&struct{ A uint }{1}, map[string]bool{"a": true}}, - {&struct{ A int }{42}, map[string]uint{"a": 42}}, - {&struct{ A int }{42}, map[string]float64{"a": 42}}, - {&struct{ A int }{1}, map[string]bool{"a": true}}, - {&struct{ A float64 }{42}, map[string]float32{"a": 42}}, - {&struct{ A float64 }{42}, map[string]int{"a": 42}}, - {&struct{ A float64 }{42}, map[string]uint{"a": 42}}, - {&struct{ A float64 }{1}, map[string]bool{"a": true}}, - {&struct{ A bool }{true}, map[string]int{"a": 1}}, - {&struct{ A bool }{true}, map[string]uint{"a": 1}}, - {&struct{ A bool }{true}, map[string]float64{"a": 1}}, - {&struct{ A **byte }{&byteptr}, map[string]byte{"a": 8}}, - - // url.URL <=> string - {&struct{ URL *url.URL }{parseURL("h://e.c/p")}, map[string]string{"url": "h://e.c/p"}}, - {&struct{ URL url.URL }{*parseURL("h://e.c/p")}, map[string]string{"url": "h://e.c/p"}}, - - // Slices - {&struct{ S []int }{[]int{1, 2, 3}}, map[string][]int{"s": []int{1, 2, 3}}}, - {&struct{ S *[]int }{&[]int{1, 2, 3}}, map[string][]int{"s": []int{1, 2, 3}}}, - - // Conditionals - {&condBool{true}, map[string]bool{"v": true}}, - {&condBool{}, map[string]bool{}}, - {&condInt{1}, map[string]int{"v": 1}}, - {&condInt{}, map[string]int{}}, - {&condUInt{1}, map[string]uint{"v": 1}}, - {&condUInt{}, map[string]uint{}}, - {&condFloat{}, map[string]int{}}, - {&condStr{"yo"}, map[string]string{"v": "yo"}}, - {&condStr{}, map[string]string{}}, - {&condStrNS{"yo"}, map[string]string{"v": "yo"}}, - {&condStrNS{}, map[string]string{}}, - {&condSlice{[]string{"yo"}}, map[string][]string{"v": []string{"yo"}}}, - {&condSlice{}, map[string][]string{}}, - {&condMap{map[string]int{"k": 1}}, bson.M{"v": bson.M{"k": 1}}}, - {&condMap{}, map[string][]string{}}, - {&condIface{"yo"}, map[string]string{"v": "yo"}}, - {&condIface{""}, map[string]string{"v": ""}}, - {&condIface{}, map[string]string{}}, - {&condPtr{&truevar}, map[string]bool{"v": true}}, - {&condPtr{&falsevar}, map[string]bool{"v": false}}, - {&condPtr{}, map[string]string{}}, - - {&condTime{time.Unix(123456789, 123e6)}, map[string]time.Time{"v": time.Unix(123456789, 123e6)}}, - {&condTime{}, map[string]string{}}, - - {&namedCondStr{"yo"}, map[string]string{"myv": "yo"}}, - {&namedCondStr{}, map[string]string{}}, - - {&shortInt{1}, map[string]interface{}{"v": 1}}, - {&shortInt{1 << 30}, map[string]interface{}{"v": 1 << 30}}, - {&shortInt{1 << 31}, map[string]interface{}{"v": int64(1 << 31)}}, - {&shortUint{1 << 30}, map[string]interface{}{"v": 1 << 30}}, - {&shortUint{1 << 31}, map[string]interface{}{"v": int64(1 << 31)}}, - {&shortIface{int64(1) << 31}, map[string]interface{}{"v": int64(1 << 31)}}, - {&shortPtr{int64ptr}, map[string]interface{}{"v": intvar}}, - - {&shortNonEmptyInt{1}, map[string]interface{}{"v": 1}}, - {&shortNonEmptyInt{1 << 31}, map[string]interface{}{"v": int64(1 << 31)}}, - {&shortNonEmptyInt{}, map[string]interface{}{}}, - - {&inlineInt{struct{ A, B int }{1, 2}}, map[string]interface{}{"a": 1, "b": 2}}, - {&inlineMap{A: 1, M: map[string]interface{}{"b": 2}}, map[string]interface{}{"a": 1, "b": 2}}, - {&inlineMap{A: 1, M: nil}, map[string]interface{}{"a": 1}}, - {&inlineMapInt{A: 1, M: map[string]int{"b": 2}}, map[string]int{"a": 1, "b": 2}}, - {&inlineMapInt{A: 1, M: nil}, map[string]int{"a": 1}}, - {&inlineMapMyM{A: 1, M: MyM{"b": MyM{"c": 3}}}, map[string]interface{}{"a": 1, "b": map[string]interface{}{"c": 3}}}, - - // []byte <=> MyBytes - {&struct{ B MyBytes }{[]byte("abc")}, map[string]string{"b": "abc"}}, - {&struct{ B MyBytes }{[]byte{}}, map[string]string{"b": ""}}, - {&struct{ B MyBytes }{}, map[string]bool{}}, - {&struct{ B []byte }{[]byte("abc")}, map[string]MyBytes{"b": []byte("abc")}}, - - // bool <=> MyBool - {&struct{ B MyBool }{true}, map[string]bool{"b": true}}, - {&struct{ B MyBool }{}, map[string]bool{"b": false}}, - {&struct{ B MyBool }{}, map[string]string{}}, - {&struct{ B bool }{}, map[string]MyBool{"b": false}}, - - // arrays - {&struct{ V [2]int }{[...]int{1, 2}}, map[string][2]int{"v": [2]int{1, 2}}}, - - // zero time - {&struct{ V time.Time }{}, map[string]interface{}{"v": time.Time{}}}, - - // zero time + 1 second + 1 millisecond; overflows int64 as nanoseconds - {&struct{ V time.Time }{time.Unix(-62135596799, 1e6).Local()}, - map[string]interface{}{"v": time.Unix(-62135596799, 1e6).Local()}}, - - // bson.D <=> []DocElem - {&bson.D{{"a", bson.D{{"b", 1}, {"c", 2}}}}, &bson.D{{"a", bson.D{{"b", 1}, {"c", 2}}}}}, - {&bson.D{{"a", bson.D{{"b", 1}, {"c", 2}}}}, &MyD{{"a", MyD{{"b", 1}, {"c", 2}}}}}, - - // bson.M <=> map - {bson.M{"a": bson.M{"b": 1, "c": 2}}, MyM{"a": MyM{"b": 1, "c": 2}}}, - {bson.M{"a": bson.M{"b": 1, "c": 2}}, map[string]interface{}{"a": map[string]interface{}{"b": 1, "c": 2}}}, -} - -// Same thing, but only one way (obj1 => obj2). -var oneWayCrossItems = []crossTypeItem{ - // map <=> struct - {map[string]interface{}{"a": 1, "b": "2", "c": 3}, map[string]int{"a": 1, "c": 3}}, - - // inline map elides badly typed values - {map[string]interface{}{"a": 1, "b": "2", "c": 3}, &inlineMapInt{A: 1, M: map[string]int{"c": 3}}}, - - // Can't decode int into struct. - {bson.M{"a": bson.M{"b": 2}}, &struct{ A bool }{}}, - - // Would get decoded into a int32 too in the opposite direction. - {&shortIface{int64(1) << 30}, map[string]interface{}{"v": 1 << 30}}, -} - -func testCrossPair(c *C, dump interface{}, load interface{}) { - c.Logf("Dump: %#v", dump) - c.Logf("Load: %#v", load) - zero := makeZeroDoc(load) - data, err := bson.Marshal(dump) - c.Assert(err, IsNil) - c.Logf("Dumped: %#v", string(data)) - err = bson.Unmarshal(data, zero) - c.Assert(err, IsNil) - c.Logf("Loaded: %#v", zero) - c.Assert(zero, DeepEquals, load) -} - -func (s *S) TestTwoWayCrossPairs(c *C) { - for _, item := range twoWayCrossItems { - testCrossPair(c, item.obj1, item.obj2) - testCrossPair(c, item.obj2, item.obj1) - } -} - -func (s *S) TestOneWayCrossPairs(c *C) { - for _, item := range oneWayCrossItems { - testCrossPair(c, item.obj1, item.obj2) - } -} - -// -------------------------------------------------------------------------- -// ObjectId hex representation test. - -func (s *S) TestObjectIdHex(c *C) { - id := bson.ObjectIdHex("4d88e15b60f486e428412dc9") - c.Assert(id.String(), Equals, `ObjectIdHex("4d88e15b60f486e428412dc9")`) - c.Assert(id.Hex(), Equals, "4d88e15b60f486e428412dc9") -} - -func (s *S) TestIsObjectIdHex(c *C) { - test := []struct{ id string; valid bool }{ - {"4d88e15b60f486e428412dc9", true}, - {"4d88e15b60f486e428412dc", false}, - {"4d88e15b60f486e428412dc9e", false}, - {"4d88e15b60f486e428412dcx", false}, - } - for _, t := range test { - c.Assert(bson.IsObjectIdHex(t.id), Equals, t.valid) - } -} - -// -------------------------------------------------------------------------- -// ObjectId parts extraction tests. - -type objectIdParts struct { - id bson.ObjectId - timestamp int64 - machine []byte - pid uint16 - counter int32 -} - -var objectIds = []objectIdParts{ - objectIdParts{ - bson.ObjectIdHex("4d88e15b60f486e428412dc9"), - 1300816219, - []byte{0x60, 0xf4, 0x86}, - 0xe428, - 4271561, - }, - objectIdParts{ - bson.ObjectIdHex("000000000000000000000000"), - 0, - []byte{0x00, 0x00, 0x00}, - 0x0000, - 0, - }, - objectIdParts{ - bson.ObjectIdHex("00000000aabbccddee000001"), - 0, - []byte{0xaa, 0xbb, 0xcc}, - 0xddee, - 1, - }, -} - -func (s *S) TestObjectIdPartsExtraction(c *C) { - for i, v := range objectIds { - t := time.Unix(v.timestamp, 0) - c.Assert(v.id.Time(), Equals, t, Commentf("#%d Wrong timestamp value", i)) - c.Assert(v.id.Machine(), DeepEquals, v.machine, Commentf("#%d Wrong machine id value", i)) - c.Assert(v.id.Pid(), Equals, v.pid, Commentf("#%d Wrong pid value", i)) - c.Assert(v.id.Counter(), Equals, v.counter, Commentf("#%d Wrong counter value", i)) - } -} - -func (s *S) TestNow(c *C) { - before := time.Now() - time.Sleep(1e6) - now := bson.Now() - time.Sleep(1e6) - after := time.Now() - c.Assert(now.After(before) && now.Before(after), Equals, true, Commentf("now=%s, before=%s, after=%s", now, before, after)) -} - -// -------------------------------------------------------------------------- -// ObjectId generation tests. - -func (s *S) TestNewObjectId(c *C) { - // Generate 10 ids - ids := make([]bson.ObjectId, 10) - for i := 0; i < 10; i++ { - ids[i] = bson.NewObjectId() - } - for i := 1; i < 10; i++ { - prevId := ids[i-1] - id := ids[i] - // Test for uniqueness among all other 9 generated ids - for j, tid := range ids { - if j != i { - c.Assert(id, Not(Equals), tid, Commentf("Generated ObjectId is not unique")) - } - } - // Check that timestamp was incremented and is within 30 seconds of the previous one - secs := id.Time().Sub(prevId.Time()).Seconds() - c.Assert((secs >= 0 && secs <= 30), Equals, true, Commentf("Wrong timestamp in generated ObjectId")) - // Check that machine ids are the same - c.Assert(id.Machine(), DeepEquals, prevId.Machine()) - // Check that pids are the same - c.Assert(id.Pid(), Equals, prevId.Pid()) - // Test for proper increment - delta := int(id.Counter() - prevId.Counter()) - c.Assert(delta, Equals, 1, Commentf("Wrong increment in generated ObjectId")) - } -} - -func (s *S) TestNewObjectIdWithTime(c *C) { - t := time.Unix(12345678, 0) - id := bson.NewObjectIdWithTime(t) - c.Assert(id.Time(), Equals, t) - c.Assert(id.Machine(), DeepEquals, []byte{0x00, 0x00, 0x00}) - c.Assert(int(id.Pid()), Equals, 0) - c.Assert(int(id.Counter()), Equals, 0) -} - -// -------------------------------------------------------------------------- -// ObjectId JSON marshalling. - -type jsonType struct { - Id *bson.ObjectId -} - -func (s *S) TestObjectIdJSONMarshaling(c *C) { - id := bson.ObjectIdHex("4d88e15b60f486e428412dc9") - v := jsonType{Id: &id} - data, err := json.Marshal(&v) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, `{"Id":"4d88e15b60f486e428412dc9"}`) -} - -func (s *S) TestObjectIdJSONUnmarshaling(c *C) { - data := []byte(`{"Id":"4d88e15b60f486e428412dc9"}`) - v := jsonType{} - err := json.Unmarshal(data, &v) - c.Assert(err, IsNil) - c.Assert(*v.Id, Equals, bson.ObjectIdHex("4d88e15b60f486e428412dc9")) -} - -func (s *S) TestObjectIdJSONUnmarshalingError(c *C) { - v := jsonType{} - err := json.Unmarshal([]byte(`{"Id":"4d88e15b60f486e428412dc9A"}`), &v) - c.Assert(err, ErrorMatches, `Invalid ObjectId in JSON: "4d88e15b60f486e428412dc9A"`) - err = json.Unmarshal([]byte(`{"Id":"4d88e15b60f486e428412dcZ"}`), &v) - c.Assert(err, ErrorMatches, `Invalid ObjectId in JSON: "4d88e15b60f486e428412dcZ" .*`) -} - -// -------------------------------------------------------------------------- -// Some simple benchmarks. - -type BenchT struct { - A, B, C, D, E, F string -} - -func BenchmarkUnmarhsalStruct(b *testing.B) { - v := BenchT{A: "A", D: "D", E: "E"} - data, err := bson.Marshal(&v) - if err != nil { - panic(err) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - err = bson.Unmarshal(data, &v) - } - if err != nil { - panic(err) - } -} - -func BenchmarkUnmarhsalMap(b *testing.B) { - m := bson.M{"a": "a", "d": "d", "e": "e"} - data, err := bson.Marshal(&m) - if err != nil { - panic(err) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - err = bson.Unmarshal(data, &m) - } - if err != nil { - panic(err) - } -} diff --git a/docs/fields.asciidoc b/docs/fields.asciidoc index 56087727eeb..220014eeea1 100644 --- a/docs/fields.asciidoc +++ b/docs/fields.asciidoc @@ -30,7 +30,7 @@ These fields contained data about the transaction itself. -==== timestamp +==== @timestamp type: date diff --git a/docs/new_protocol.asciidoc b/docs/new_protocol.asciidoc index 7746109f5a7..c2786d43263 100644 --- a/docs/new_protocol.asciidoc +++ b/docs/new_protocol.asciidoc @@ -429,7 +429,7 @@ As an example, here is the relevant code from the REDIS module: event["bytes_in"] = uint64(t.BytesIn) event["bytes_out"] = uint64(t.BytesOut) - event["timestamp"] = common.Time(t.ts) + event["@timestamp"] = common.Time(t.ts) event["src"] = &t.Src event["dst"] = &t.Dst @@ -439,7 +439,7 @@ As an example, here is the relevant code from the REDIS module: The following fields are required and their presence will be checked by system tests: - * `timestamp`. Set this to the timestamp of the first packet from the message + * `@timestamp`. Set this to the timestamp of the first packet from the message and cast it to `common.Time` like in the example above. * `type`. Set this to the protocol name. * `count`. This is reserved for future sampling support. Set it to 1. diff --git a/etc/fields.yml b/etc/fields.yml index d33bdd3f3c4..d3a9605f9de 100644 --- a/etc/fields.yml +++ b/etc/fields.yml @@ -101,7 +101,7 @@ event: description: > These fields contained data about the transaction itself. fields: - - name: "timestamp" + - name: "@timestamp" type: date required: true format: YYYY-MM-DDTHH:MM:SS.milliZ diff --git a/etc/packetbeat.template.json b/etc/packetbeat.template.json index 5f176e11b37..cacf9c27711 100644 --- a/etc/packetbeat.template.json +++ b/etc/packetbeat.template.json @@ -21,6 +21,9 @@ } ], "properties": { + "@timestamp": { + "type": "date" + }, "client_location": { "type": "geo_point" }, @@ -49,9 +52,6 @@ "enabled": false }, "type": "string" - }, - "timestamp": { - "type": "date" } } } diff --git a/etc/sample_outputs/dns.json b/etc/sample_outputs/dns.json index e55b6c94807..5458807aee3 100644 --- a/etc/sample_outputs/dns.json +++ b/etc/sample_outputs/dns.json @@ -146,7 +146,7 @@ "server":"", "shipper":"macbook", "status":"OK", - "timestamp":"2015-08-23T04:43:51.861Z", + "@timestamp":"2015-08-23T04:43:51.861Z", "transport":"udp", "type":"dns" } diff --git a/etc/sample_outputs/http.json b/etc/sample_outputs/http.json index 6659db8c5e2..abba940dda1 100644 --- a/etc/sample_outputs/http.json +++ b/etc/sample_outputs/http.json @@ -1,5 +1,5 @@ { - "timestamp": "2015-04-26T08:42:15.822Z", + "@timestamp": "2015-04-26T08:42:15.822Z", "agent": "vagrant", "client_ip": "10.0.2.15", "client_port": 52980, diff --git a/etc/sample_outputs/psql.json b/etc/sample_outputs/psql.json index fa48f056125..153d56c8b7c 100644 --- a/etc/sample_outputs/psql.json +++ b/etc/sample_outputs/psql.json @@ -1,5 +1,5 @@ { - "timestamp": "2015-04-26T08:44:15.704Z", + "@timestamp": "2015-04-26T08:44:15.704Z", "agent": "vagrant", "bytes_out": 517, "client_ip": "127.0.0.1", diff --git a/protos/applayer/applayer.go b/protos/applayer/applayer.go index 746461b9c8c..ad7f3db0f8d 100644 --- a/protos/applayer/applayer.go +++ b/protos/applayer/applayer.go @@ -212,7 +212,7 @@ func (t *Transaction) InitWithMsg( // Event fills common event fields. func (t *Transaction) Event(event common.MapStr) error { event["type"] = t.Type - event["timestamp"] = common.Time(t.Ts.Ts) + event["@timestamp"] = common.Time(t.Ts.Ts) event["responsetime"] = t.ResponseTime event["src"] = &t.Src event["dst"] = &t.Dst diff --git a/protos/dns/dns.go b/protos/dns/dns.go index 9d7492ea0a5..43b0a4bc1a8 100644 --- a/protos/dns/dns.go +++ b/protos/dns/dns.go @@ -386,7 +386,7 @@ func (dns *Dns) publishTransaction(t *DnsTransaction) { logp.Debug("dns", "Publishing transaction. %s", t.tuple.String()) event := common.MapStr{} - event["timestamp"] = common.Time(t.ts) + event["@timestamp"] = common.Time(t.ts) event["type"] = "dns" event["transport"] = t.Transport.String() event["src"] = &t.Src diff --git a/protos/http/http.go b/protos/http/http.go index 2aeb758bb49..0c1ec67f9a4 100644 --- a/protos/http/http.go +++ b/protos/http/http.go @@ -897,7 +897,7 @@ func (http *Http) publishTransaction(t *HttpTransaction) { event["bytes_out"] = t.BytesOut event["bytes_in"] = t.BytesIn - event["timestamp"] = common.Time(t.ts) + event["@timestamp"] = common.Time(t.ts) event["src"] = &t.Src event["dst"] = &t.Dst diff --git a/protos/mongodb/mongodb.go b/protos/mongodb/mongodb.go index 9139fbb1de0..be380680f0f 100644 --- a/protos/mongodb/mongodb.go +++ b/protos/mongodb/mongodb.go @@ -335,7 +335,7 @@ func (mongodb *Mongodb) publishTransaction(t *MongodbTransaction) { event["responsetime"] = t.ResponseTime event["bytes_in"] = uint64(t.BytesIn) event["bytes_out"] = uint64(t.BytesOut) - event["timestamp"] = common.Time(t.ts) + event["@timestamp"] = common.Time(t.ts) event["src"] = &t.Src event["dst"] = &t.Dst diff --git a/protos/mysql/mysql.go b/protos/mysql/mysql.go index 1e88b7e3b34..ed133d2e9c2 100644 --- a/protos/mysql/mysql.go +++ b/protos/mysql/mysql.go @@ -866,7 +866,7 @@ func (mysql *Mysql) publishTransaction(t *MysqlTransaction) { event["notes"] = t.Notes } - event["timestamp"] = common.Time(t.ts) + event["@timestamp"] = common.Time(t.ts) event["src"] = &t.Src event["dst"] = &t.Dst diff --git a/protos/pgsql/pgsql.go b/protos/pgsql/pgsql.go index 406c4fc06da..5ee053ed167 100644 --- a/protos/pgsql/pgsql.go +++ b/protos/pgsql/pgsql.go @@ -932,7 +932,7 @@ func (pgsql *Pgsql) publishTransaction(t *PgsqlTransaction) { event["bytes_in"] = t.BytesIn event["pgsql"] = t.Pgsql - event["timestamp"] = common.Time(t.ts) + event["@timestamp"] = common.Time(t.ts) event["src"] = &t.Src event["dst"] = &t.Dst diff --git a/protos/redis/redis.go b/protos/redis/redis.go index d4f6bf3f9da..edbbeb386d2 100644 --- a/protos/redis/redis.go +++ b/protos/redis/redis.go @@ -719,7 +719,7 @@ func (redis *Redis) publishTransaction(t *RedisTransaction) { event["bytes_in"] = uint64(t.BytesIn) event["bytes_out"] = uint64(t.BytesOut) - event["timestamp"] = common.Time(t.ts) + event["@timestamp"] = common.Time(t.ts) event["src"] = &t.Src event["dst"] = &t.Dst diff --git a/protos/thrift/thrift.go b/protos/thrift/thrift.go index 3880548f6d7..246aded9492 100644 --- a/protos/thrift/thrift.go +++ b/protos/thrift/thrift.go @@ -1126,7 +1126,7 @@ func (thrift *Thrift) publishTransactions() { } event["thrift"] = thriftmap - event["timestamp"] = common.Time(t.ts) + event["@timestamp"] = common.Time(t.ts) event["src"] = &t.Src event["dst"] = &t.Dst diff --git a/tests/pbtests/packetbeat.py b/tests/pbtests/packetbeat.py index 8f61e11d3bd..935da0b3573 100644 --- a/tests/pbtests/packetbeat.py +++ b/tests/pbtests/packetbeat.py @@ -122,7 +122,7 @@ def read_output(self, output_file="output/packetbeat"): for line in f: jsons.append(self.flatten_object(json.loads(line), self.dict_fields)) - self.all_have_fields(jsons, ["timestamp", "type", "status", + self.all_have_fields(jsons, ["@timestamp", "type", "status", "shipper", "count"]) self.all_fields_are_expected(jsons, self.expected_fields) return jsons diff --git a/tests/test_0015_udpjson.py b/tests/test_0015_udpjson.py index e735a0ea82d..ba0e844544c 100644 --- a/tests/test_0015_udpjson.py +++ b/tests/test_0015_udpjson.py @@ -68,7 +68,7 @@ def test_send_udpjson_msg(self): objs = self.read_output() - expected_fields = ["shipper", "status", "type", "timestamp", "count"] + expected_fields = ["shipper", "status", "type", "@timestamp", "count"] self.all_have_only_fields(objs, expected_fields) assert objs[0]["type"] == "http"