VOL-1905 added openolt-adapter unit tests for Main.go

Change-Id: I2cd1a58db1ab836fb6638a8bdc3eff346f72d98d
diff --git a/Gopkg.lock b/Gopkg.lock
index cc7c37e..9e946d7 100644
--- a/Gopkg.lock
+++ b/Gopkg.lock
@@ -281,7 +281,7 @@
 
 [[projects]]
   branch = "master"
-  digest = "1:ab16e5cb98bf2b6efcfd927e9cb737b7243014600ebcfbe8786f2e4ad2227ac1"
+  digest = "1:ba2afa449666d8b9e2310d7512af1ff5a86048cd10ce3ddddf1ca4b30bf443f9"
   name = "go.etcd.io/etcd"
   packages = [
     "auth/authpb",
@@ -294,6 +294,7 @@
     "etcdserver/etcdserverpb",
     "mvcc/mvccpb",
     "pkg/logutil",
+    "pkg/mock/mockserver",
     "pkg/systemd",
     "pkg/types",
     "raft",
@@ -550,6 +551,7 @@
     "github.com/opencord/voltha-protos/go/openolt",
     "github.com/opencord/voltha-protos/go/tech_profile",
     "github.com/opencord/voltha-protos/go/voltha",
+    "go.etcd.io/etcd/pkg/mock/mockserver",
     "google.golang.org/grpc",
     "google.golang.org/grpc/codes",
     "google.golang.org/grpc/metadata",
diff --git a/adaptercore/olt_platform_test.go b/adaptercore/olt_platform_test.go
index 6f3eb64..974d684 100644
--- a/adaptercore/olt_platform_test.go
+++ b/adaptercore/olt_platform_test.go
@@ -217,33 +217,35 @@
 		outPort uint32
 	}
 	tests := []struct {
-		name  string
-		args  args
-		want  uint32
-		want1 uint32
-		want2 uint32
-		want3 uint32
+		name   string
+		args   args
+		port   uint32
+		IntfID uint32
+		onuID  uint32
+		uniID  uint32
 	}{
 		// TODO: Add test cases.
-		{"ExtractAccessFromFlow-1", args{inPort: 10, outPort: 65536}, 10, 0, 0, 10},
+		{"ExtractAccessFromFlow-1", args{inPort: 100, outPort: 65536}, 100, 0, 6, 4},
+		{"ExtractAccessFromFlow-1", args{inPort: 65536, outPort: 10}, 10, 0, 0, 10},
 	}
 	for _, tt := range tests {
 		t.Run(tt.name, func(t *testing.T) {
 			got, got1, got2, got3 := ExtractAccessFromFlow(tt.args.inPort, tt.args.outPort)
-			if got != tt.want {
-				t.Errorf("ExtractAccessFromFlow() got = %v, want %v", got, tt.want)
+			if got != tt.port {
+				t.Errorf("ExtractAccessFromFlow() got = %v, want %v", got, tt.port)
 			}
-			if got1 != tt.want1 {
-				t.Errorf("ExtractAccessFromFlow() got1 = %v, want %v", got1, tt.want1)
+			if got1 != tt.IntfID {
+				t.Errorf("ExtractAccessFromFlow() got1 = %v, want %v", got1, tt.IntfID)
 			}
-			if got2 != tt.want2 {
-				t.Errorf("ExtractAccessFromFlow() got2 = %v, want %v", got2, tt.want2)
+			if got2 != tt.onuID {
+				t.Errorf("ExtractAccessFromFlow() got2 = %v, want %v", got2, tt.onuID)
 			}
-			if got3 != tt.want3 {
-				t.Errorf("ExtractAccessFromFlow() got3 = %v, want %v", got3, tt.want3)
+			if got3 != tt.uniID {
+				t.Errorf("ExtractAccessFromFlow() got3 = %v, want %v", got3, tt.uniID)
 			}
 		})
 	}
+	//t.Error()
 }
 
 func TestIsUpstream(t *testing.T) {
@@ -302,6 +304,7 @@
 	fa := &fu.FlowArgs{
 		MatchFields: []*ofp.OfpOxmOfbField{
 			fu.InPort(2),
+			fu.Metadata_ofp(uint64(ofp.OfpInstructionType_OFPIT_WRITE_METADATA | 2)),
 			fu.VlanVid(uint32(ofp.OfpVlanId_OFPVID_PRESENT) | 0),
 			fu.EthType(2048),
 		},
@@ -332,7 +335,7 @@
 		{"FlowExtractInfo-1", args{flow: ofpstats, flowDirection: "upstream"}, 2, 0, 0, 2, 0, 0, false},
 
 		// Negative Testcases
-		{"FlowExtractInfo-2", args{flow: ofpstats, flowDirection: "downstream"}, 0, 0, 0, 0, 0, 0, true},
+		{"FlowExtractInfo-2", args{flow: ofpstats, flowDirection: "downstream"}, 1, 0, 0, 1, 2, 2048, false},
 		{"FlowExtractInfo-3", args{flow: nil, flowDirection: "downstream"}, 0, 0, 0, 0, 0, 0, true},
 		{"FlowExtractInfo-4", args{flow: &ofp.OfpFlowStats{}, flowDirection: "downstream"}, 0, 0, 0, 0, 0, 0, true},
 	}
diff --git a/main_test.go b/main_test.go
new file mode 100644
index 0000000..a8034dd
--- /dev/null
+++ b/main_test.go
@@ -0,0 +1,215 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+
+ * 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 main
+
+import (
+	"context"
+	"errors"
+	"testing"
+
+	"github.com/opencord/voltha-go/common/log"
+	"github.com/opencord/voltha-go/kafka"
+	"github.com/opencord/voltha-openolt-adapter/config"
+	"github.com/opencord/voltha-openolt-adapter/mocks"
+	ca "github.com/opencord/voltha-protos/go/inter_container"
+	"go.etcd.io/etcd/pkg/mock/mockserver"
+)
+
+func init() {
+	log.SetDefaultLogger(log.JSON, log.DebugLevel, nil)
+}
+
+func newMockAdapter() *adapter {
+	conf := config.NewAdapterFlags()
+	conf.KVStoreType = "etcd"
+	cp := mocks.MockCoreProxy{}
+	ap := mocks.MockAdapterProxy{}
+	ad := newAdapter(conf)
+	ad.coreProxy = &cp
+	ad.adapterProxy = &ap
+	return ad
+}
+func Test_adapter_setKVClient(t *testing.T) {
+	adapt := newMockAdapter()
+	adapt1 := newMockAdapter()
+	adapt1.config.KVStoreType = "consul"
+	adapt2 := newMockAdapter()
+	adapt2.config.KVStoreType = ""
+	a, _ := mockserver.StartMockServers(1)
+	a.StartAt(0)
+	defer a.StopAt(0)
+	tests := []struct {
+		name       string
+		clienttype string
+		adapter    *adapter
+		wantErr    bool
+	}{
+		{"setKVClient", adapt.config.KVStoreType, adapt, false},
+		{"setKVClient", adapt1.config.KVStoreType, adapt1, false},
+		{"setKVClient", adapt2.config.KVStoreType, adapt2, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := tt.adapter.setKVClient(); (err != nil) != tt.wantErr {
+				t.Errorf("adapter.setKVClient() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}
+
+func Test_adapter_KVClient(t *testing.T) {
+	adapt := newMockAdapter()
+	a, _ := mockserver.StartMockServers(1)
+	a.StartAt(0)
+	defer a.StopAt(0)
+
+	if err := adapt.setKVClient(); err != nil {
+		t.Errorf("adapter.setKVClient() error = %v", err)
+	}
+}
+
+func Test_registerWithCore(t *testing.T) {
+	ad := newMockAdapter()
+	err := ad.registerWithCore(1)
+	if err != nil {
+		t.Errorf("Expected error:nil, got error: %v", err)
+	}
+}
+func Test_startInterContainerProxy(t *testing.T) {
+	ad := newMockAdapter()
+	kc := &mockKafkaClient{}
+	ad.kafkaClient = kc
+	icp, err := ad.startInterContainerProxy(1)
+	if icp != nil {
+		t.Log("Intercontainer proxy ", icp)
+	}
+	if err != nil {
+		t.Errorf("err %v", err)
+	}
+}
+
+func Test_startOpenOLT(t *testing.T) {
+	a, _ := mockserver.StartMockServers(1)
+	a.StartAt(0)
+	defer a.StopAt(0)
+
+	ad := newMockAdapter()
+	oolt, err := ad.startOpenOLT(context.TODO(), nil,
+		ad.coreProxy, ad.adapterProxy, ad.eventProxy, 1, ad.config.KVStoreHost,
+		ad.config.KVStorePort, ad.config.KVStoreType)
+	if oolt != nil {
+		t.Log("Open OLT ", oolt)
+	}
+	if err != nil {
+		t.Errorf("err %v", err)
+	}
+}
+
+func Test_newKafkaClient(t *testing.T) {
+	a, _ := mockserver.StartMockServers(1)
+	a.StartAt(0)
+	defer a.StopAt(0)
+	adapter := newMockAdapter()
+	type args struct {
+		clientType string
+		host       string
+		port       int
+	}
+	tests := []struct {
+		name    string
+		args    args
+		wantErr bool
+	}{
+		// TODO: Add test cases.
+		{"newKafkaClient", args{clientType: "sarama", host: adapter.config.KafkaAdapterHost, port: adapter.config.KafkaAdapterPort}, false},
+		{"newKafkaClient", args{clientType: "sarama", host: adapter.config.KafkaAdapterHost, port: adapter.config.KafkaAdapterPort}, false},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			_, err := newKafkaClient(tt.args.clientType, tt.args.host, tt.args.port)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("newKafkaClient() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+
+		})
+	}
+}
+
+func Test_adapter_setupRequestHandler(t *testing.T) {
+
+	ad := newMockAdapter()
+
+	kip, _ := kafka.NewInterContainerProxy(
+		kafka.InterContainerHost(ad.config.KafkaAdapterHost),
+		kafka.InterContainerPort(ad.config.KafkaAdapterPort),
+		kafka.MsgClient(&mockKafkaClient{}),
+		kafka.DefaultTopic(&kafka.Topic{Name: ad.config.Topic}))
+
+	ad.kip = kip
+	ad.kip.Start()
+
+	oolt, _ := ad.startOpenOLT(context.TODO(), nil,
+		ad.coreProxy, ad.adapterProxy, ad.eventProxy, 1, ad.config.KVStoreHost,
+		ad.config.KVStorePort, ad.config.KVStoreType)
+	printBanner()
+	printVersion()
+	if err := ad.setupRequestHandler(ad.config.InstanceID, oolt); err != nil {
+		t.Logf("adapter.setupRequestHandler() error = %v", err)
+	}
+
+}
+
+// Kafka client mocker
+type mockKafkaClient struct {
+}
+
+func (kc *mockKafkaClient) Start() error {
+	return nil
+}
+func (kc *mockKafkaClient) Stop() {
+}
+func (kc *mockKafkaClient) CreateTopic(topic *kafka.Topic, numPartition int, repFactor int) error {
+	if topic != nil {
+		return nil
+	}
+	return errors.New("invalid Topic")
+}
+func (kc *mockKafkaClient) DeleteTopic(topic *kafka.Topic) error {
+	if topic != nil {
+		return nil
+	}
+	return errors.New("invalid Topic")
+}
+func (kc *mockKafkaClient) Subscribe(topic *kafka.Topic, kvArgs ...*kafka.KVArg) (<-chan *ca.InterContainerMessage, error) {
+	if topic != nil {
+		ch := make(chan *ca.InterContainerMessage)
+		return ch, nil
+	}
+	return nil, errors.New("invalid Topic")
+}
+func (kc *mockKafkaClient) UnSubscribe(topic *kafka.Topic, ch <-chan *ca.InterContainerMessage) error {
+	if topic == nil {
+		return nil
+	}
+	return errors.New("invalid Topic")
+}
+func (kc *mockKafkaClient) Send(msg interface{}, topic *kafka.Topic, keys ...string) error {
+	if topic != nil {
+		return nil
+	}
+	return errors.New("invalid topic")
+}
diff --git a/vendor/go.etcd.io/etcd/pkg/mock/mockserver/doc.go b/vendor/go.etcd.io/etcd/pkg/mock/mockserver/doc.go
new file mode 100644
index 0000000..030b3b2
--- /dev/null
+++ b/vendor/go.etcd.io/etcd/pkg/mock/mockserver/doc.go
@@ -0,0 +1,16 @@
+// Copyright 2018 The etcd Authors
+//
+// 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 mockserver provides mock implementations for etcdserver's server interface.
+package mockserver
diff --git a/vendor/go.etcd.io/etcd/pkg/mock/mockserver/mockserver.go b/vendor/go.etcd.io/etcd/pkg/mock/mockserver/mockserver.go
new file mode 100644
index 0000000..59c543e
--- /dev/null
+++ b/vendor/go.etcd.io/etcd/pkg/mock/mockserver/mockserver.go
@@ -0,0 +1,188 @@
+// Copyright 2018 The etcd Authors
+//
+// 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 mockserver
+
+import (
+	"context"
+	"fmt"
+	"io/ioutil"
+	"net"
+	"os"
+	"sync"
+
+	pb "go.etcd.io/etcd/etcdserver/etcdserverpb"
+
+	"google.golang.org/grpc"
+	"google.golang.org/grpc/resolver"
+)
+
+// MockServer provides a mocked out grpc server of the etcdserver interface.
+type MockServer struct {
+	ln         net.Listener
+	Network    string
+	Address    string
+	GrpcServer *grpc.Server
+}
+
+func (ms *MockServer) ResolverAddress() resolver.Address {
+	switch ms.Network {
+	case "unix":
+		return resolver.Address{Addr: fmt.Sprintf("unix://%s", ms.Address)}
+	case "tcp":
+		return resolver.Address{Addr: ms.Address}
+	default:
+		panic("illegal network type: " + ms.Network)
+	}
+}
+
+// MockServers provides a cluster of mocket out gprc servers of the etcdserver interface.
+type MockServers struct {
+	mu      sync.RWMutex
+	Servers []*MockServer
+	wg      sync.WaitGroup
+}
+
+// StartMockServers creates the desired count of mock servers
+// and starts them.
+func StartMockServers(count int) (ms *MockServers, err error) {
+	return StartMockServersOnNetwork(count, "tcp")
+}
+
+// StartMockServersOnNetwork creates mock servers on either 'tcp' or 'unix' sockets.
+func StartMockServersOnNetwork(count int, network string) (ms *MockServers, err error) {
+	switch network {
+	case "tcp":
+		return startMockServersTcp(count)
+	case "unix":
+		return startMockServersUnix(count)
+	default:
+		return nil, fmt.Errorf("unsupported network type: %s", network)
+	}
+}
+
+func startMockServersTcp(count int) (ms *MockServers, err error) {
+	addrs := make([]string, 0, count)
+	for i := 0; i < count; i++ {
+		addrs = append(addrs, "localhost:0")
+	}
+	return startMockServers("tcp", addrs)
+}
+
+func startMockServersUnix(count int) (ms *MockServers, err error) {
+	dir := os.TempDir()
+	addrs := make([]string, 0, count)
+	for i := 0; i < count; i++ {
+		f, err := ioutil.TempFile(dir, "etcd-unix-so-")
+		if err != nil {
+			return nil, fmt.Errorf("failed to allocate temp file for unix socket: %v", err)
+		}
+		fn := f.Name()
+		err = os.Remove(fn)
+		if err != nil {
+			return nil, fmt.Errorf("failed to remove temp file before creating unix socket: %v", err)
+		}
+		addrs = append(addrs, fn)
+	}
+	return startMockServers("unix", addrs)
+}
+
+func startMockServers(network string, addrs []string) (ms *MockServers, err error) {
+	ms = &MockServers{
+		Servers: make([]*MockServer, len(addrs)),
+		wg:      sync.WaitGroup{},
+	}
+	defer func() {
+		if err != nil {
+			ms.Stop()
+		}
+	}()
+	for idx, addr := range addrs {
+		ln, err := net.Listen(network, addr)
+		if err != nil {
+			return nil, fmt.Errorf("failed to listen %v", err)
+		}
+		ms.Servers[idx] = &MockServer{ln: ln, Network: network, Address: ln.Addr().String()}
+		ms.StartAt(idx)
+	}
+	return ms, nil
+}
+
+// StartAt restarts mock server at given index.
+func (ms *MockServers) StartAt(idx int) (err error) {
+	ms.mu.Lock()
+	defer ms.mu.Unlock()
+
+	if ms.Servers[idx].ln == nil {
+		ms.Servers[idx].ln, err = net.Listen(ms.Servers[idx].Network, ms.Servers[idx].Address)
+		if err != nil {
+			return fmt.Errorf("failed to listen %v", err)
+		}
+	}
+
+	svr := grpc.NewServer()
+	pb.RegisterKVServer(svr, &mockKVServer{})
+	ms.Servers[idx].GrpcServer = svr
+
+	ms.wg.Add(1)
+	go func(svr *grpc.Server, l net.Listener) {
+		svr.Serve(l)
+	}(ms.Servers[idx].GrpcServer, ms.Servers[idx].ln)
+	return nil
+}
+
+// StopAt stops mock server at given index.
+func (ms *MockServers) StopAt(idx int) {
+	ms.mu.Lock()
+	defer ms.mu.Unlock()
+
+	if ms.Servers[idx].ln == nil {
+		return
+	}
+
+	ms.Servers[idx].GrpcServer.Stop()
+	ms.Servers[idx].GrpcServer = nil
+	ms.Servers[idx].ln = nil
+	ms.wg.Done()
+}
+
+// Stop stops the mock server, immediately closing all open connections and listeners.
+func (ms *MockServers) Stop() {
+	for idx := range ms.Servers {
+		ms.StopAt(idx)
+	}
+	ms.wg.Wait()
+}
+
+type mockKVServer struct{}
+
+func (m *mockKVServer) Range(context.Context, *pb.RangeRequest) (*pb.RangeResponse, error) {
+	return &pb.RangeResponse{}, nil
+}
+
+func (m *mockKVServer) Put(context.Context, *pb.PutRequest) (*pb.PutResponse, error) {
+	return &pb.PutResponse{}, nil
+}
+
+func (m *mockKVServer) DeleteRange(context.Context, *pb.DeleteRangeRequest) (*pb.DeleteRangeResponse, error) {
+	return &pb.DeleteRangeResponse{}, nil
+}
+
+func (m *mockKVServer) Txn(context.Context, *pb.TxnRequest) (*pb.TxnResponse, error) {
+	return &pb.TxnResponse{}, nil
+}
+
+func (m *mockKVServer) Compact(context.Context, *pb.CompactionRequest) (*pb.CompactionResponse, error) {
+	return &pb.CompactionResponse{}, nil
+}