func TestMemPlugin(t *testing.T) {
	Convey("getMemstat Should return memory amount value", t, func() {

		httpmock.Activate()
		defer httpmock.DeactivateAndReset()
		httpmock.RegisterResponder("GET", "http://192.168.192.200:8000/os/memory/free",
			func(req *http.Request) (*http.Response, error) {
				resp := httpmock.NewStringResponse(200, "20000")
				return resp, nil

			},
		)
		httpmock.RegisterResponder("GET", "http://192.168.192.200:8000/os/memory/total",
			func(req *http.Request) (*http.Response, error) {
				resp := httpmock.NewStringResponse(200, "10000")
				return resp, nil

			},
		)

		memFree, err := getMemStat("http://192.168.192.200:8000", "free")
		So(err, ShouldBeNil)
		So(strconv.FormatUint(memFree, 10), ShouldResemble, "20000")
		memTotal, err := getMemStat("http://192.168.192.200:8000", "total")
		So(err, ShouldBeNil)
		So(strconv.FormatUint(memTotal, 10), ShouldResemble, "10000")

	})
	Convey("MemStat Should return pluginMetricType Data", t, func() {

		httpmock.Activate()
		defer httpmock.DeactivateAndReset()
		httpmock.RegisterResponder("GET", "http://192.168.192.200:8000/os/memory/free",
			func(req *http.Request) (*http.Response, error) {
				resp := httpmock.NewStringResponse(200, "20000")
				return resp, nil

			},
		)
		httpmock.RegisterResponder("GET", "http://192.168.192.200:8000/os/memory/total",
			func(req *http.Request) (*http.Response, error) {
				resp := httpmock.NewStringResponse(200, "10000")
				return resp, nil

			},
		)

		ns := []string{"osv", "memory", "free"}
		ns2 := []string{"osv", "memory", "total"}
		memFree, err := memStat(ns, "http://192.168.192.200:8000")
		So(err, ShouldBeNil)
		So(memFree.Namespace_, ShouldResemble, ns)
		So(memFree.Data_, ShouldResemble, "20000")
		memTotal, err := memStat(ns2, "http://192.168.192.200:8000")
		So(err, ShouldBeNil)
		So(memTotal.Namespace_, ShouldResemble, ns2)
		So(memTotal.Data_, ShouldResemble, "10000")

	})
}
예제 #2
0
func RegisterEntityMocks() {
	// *******************************************************
	// GET ENTITY
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/entity/user/email/[email protected]",
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if queries.Get("fields") == "score_intensity" {
				return httpmock.NewStringResponse(200, readJsonFile("get_entity_fields")), nil
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_entity")), nil
		},
	)
}
예제 #3
0
func TestGetOrders(t *testing.T) {

	httpmock.Activate()
	defer httpmock.DeactivateAndReset()

	httpmock.RegisterResponder("GET", TICTAIL_TEST_URL+"/v1/stores/x1234/orders",
		func(req *http.Request) (*http.Response, error) {
			if req.Header.Get("Authorization") == "Bearer "+TICTAIL_TEST_KEY {
				return httpmock.NewStringResponse(200, TICTAIL_MOCK_GET_ORDERS_200_RESPONSE), nil
			}
			return httpmock.NewStringResponse(401, "{}"), nil
		},
	)

	tt := NewTictail(TICTAIL_TEST_KEY)

	response, err := tt.GetAllOrders("x1234")
	if err != nil {
		t.Error(err.Error())
	}
	t.Logf("response: %#v", response)

	var expectedData []spec.OrdersResponse
	err = json.Unmarshal([]byte(TICTAIL_MOCK_GET_ORDERS_200_RESPONSE), &expectedData)
	if err != nil {
		t.Error(err.Error())
	}

	if !reflect.DeepEqual(expectedData, response) {
		t.Error("Response and mock data didn't match")
	}

}
예제 #4
0
func RegisterUserMocks() {
	// *******************************************************
	// GET SINGLE USER
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/user/"+MockUserID,
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_user")), nil
		},
	)

	// *******************************************************
	// GET ALL USERS FOR API KEY
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/user",
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_users")), nil
		},
	)
}
예제 #5
0
func RegisterAccountMocks() {
	// *******************************************************
	// GET SINGLE ACCOUNT
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/account/"+MockAccountID,
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_account")), nil
		},
	)

	// *******************************************************
	// GET ALL ACCOUNTS FOR API KEY
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/account",
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_accounts")), nil
		},
	)
}
예제 #6
0
func RegisterWorkMocks() {
	// *******************************************************
	// GET SINGLE WORK
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/work/"+MockWorkID,
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_work")), nil
		},
	)

	// *******************************************************
	// GET ALL AVAILABLE WORKS FOR API KEY
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/work",
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_works")), nil
		},
	)
}
예제 #7
0
func RegisterSegmentMLMocks() {
	// *******************************************************
	// GET SINGLE SEGMENTML MODEL
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/segmentml/"+MockSegmentMLID,
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_segmentml")), nil
		},
	)

	// *******************************************************
	// GET ALL SEGMENTML MODELS
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/segmentml",
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_segmentml_models")), nil
		},
	)
}
예제 #8
0
func TestGetMe(t *testing.T) {

	httpmock.Activate()
	defer httpmock.DeactivateAndReset()

	httpmock.RegisterResponder("GET", TICTAIL_TEST_URL+"/v1/me",
		func(req *http.Request) (*http.Response, error) {
			if req.Header.Get("Authorization") == "Bearer "+TICTAIL_TEST_KEY {
				return httpmock.NewStringResponse(200, TICTAIL_MOCK_GET_ME_200_RESPONSE), nil
			}
			return httpmock.NewStringResponse(401, "{}"), nil
		},
	)
	tt := NewTictail("WRONGKEY")

	response, err := tt.GetMe()
	if err == nil {
		t.Error(err.Error())
	}

	tt = NewTictail(TICTAIL_TEST_KEY)

	response, err = tt.GetMe()
	if err != nil {
		t.Error(err.Error())
	} else if response == nil {
		t.Error("Nil response")
	}

	expectedData := &spec.MeResponse{}
	err = json.Unmarshal([]byte(TICTAIL_MOCK_GET_ME_200_RESPONSE), expectedData)
	if err != nil {
		t.Error(err.Error())
	}

	if fmt.Sprintf("%#v", response) != fmt.Sprintf("%#v", expectedData) {
		t.Error("Response and expected data don't match")
	}
}
예제 #9
0
func RegisterCatalogMocks() {
	// *******************************************************
	// GET SCHEMA FOR TABLE
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/schema/user",
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_catalog_user")), nil
		},
	)
}
func TestCpuPlugin(t *testing.T) {
	Convey("getcpuTime Should return cputime value", t, func() {

		httpmock.Activate()
		defer httpmock.DeactivateAndReset()
		httpmock.RegisterResponder("GET", "http://192.168.192.200:8000/trace/count",
			func(req *http.Request) (*http.Response, error) {
				resp := httpmock.NewStringResponse(200, `{"time_ms": 144123232, "list": []}`)
				return resp, nil

			},
		)

		cpuTime, err := getCPUTime("http://192.168.192.200:8000")
		So(err, ShouldBeNil)
		So(strconv.FormatUint(cpuTime, 10), ShouldResemble, "144123232")

	})
	Convey("CpuStat Should return pluginMetricType Data", t, func() {

		httpmock.Activate()
		defer httpmock.DeactivateAndReset()
		httpmock.RegisterResponder("GET", "http://192.168.192.200:8000/trace/count",
			func(req *http.Request) (*http.Response, error) {
				resp := httpmock.NewStringResponse(200, `{"time_ms": 144123232, "list": []}`)
				return resp, nil

			},
		)

		ns := []string{"osv", "cpu", "cputime"}
		cpuTime, err := cpuStat(ns, "http://192.168.192.200:8000")
		So(err, ShouldBeNil)
		So(cpuTime.Namespace_, ShouldResemble, ns)
		So(cpuTime.Data_, ShouldResemble, "144123232")

	})
}
예제 #11
0
// TestTransactionRun runs tests on the Transaction Run method.
func TestTransactionRun(t *testing.T) {
	a := assert.New(t)
	r := require.New(t)
	db := New().LoggerOptions(false, false, false)
	db.Connect("http://arangodb:8000", "dbName", "foo", "bar")

	httpmock.Activate()
	defer httpmock.DeactivateAndReset()

	result, err := db.Run(NewTransaction([]string{"foo"}, []string{"bar"}).
		AddQuery("var1", "FOR c IN customer RETURN c"))
	r.Error(err)
	a.Nil(result)

	httpmock.RegisterResponder("POST", "http://arangodb:8000/_db/dbName/_api/transaction",
		func(r *http.Request) (*http.Response, error) {
			buffer, _ := ioutil.ReadAll(r.Body)
			return httpmock.NewStringResponse(200, string(buffer)), nil
		})

	result, err = db.Run(NewTransaction(nil, nil))
	r.NoError(err)
	a.Equal("{\"collections\":{\"read\":[],\"write\":[]},\"action\":\"function () {var db = require(`internal`).db; }\"}", string(result))

	result, err = db.Run(NewTransaction([]string{"foo"}, []string{"bar"}).
		AddQuery("", "FOR c IN customer RETURN c"))
	r.NoError(err)
	a.Equal("{\"collections\":{\"read\":[\"foo\"],\"write\":[\"bar\"]},\"action\":\"function () {var db = require(`internal`).db; db._query(aqlQuery`FOR c IN customer RETURN c`).toArray(); }\"}", string(result))

	result, err = db.Run(NewTransaction([]string{"foo"}, []string{"bar"}).
		AddQuery("var1", "FOR c IN customer RETURN c").
		AddQuery("var2", "FOR c IN {{.var1}} RETURN c").
		Return("var1"))
	r.NoError(err)
	a.Equal("{\"collections\":{\"read\":[\"foo\"],\"write\":[\"bar\"]},\"action\":\"function () {var db = require(`internal`).db; var var1 = db._query(aqlQuery`FOR c IN customer RETURN c`).toArray(); var var2 = db._query(aqlQuery`FOR c IN ${var1} RETURN c`).toArray(); return var1;}\"}", string(result))

	httpmock.RegisterResponder("POST", "http://arangodb:8000/_db/dbName/_api/transaction",
		httpmock.NewStringResponder(500, `{"error": true, "errorMessage": "error !"}`))

	result, err = db.Run(NewTransaction([]string{"foo"}, []string{"bar"}).
		AddQuery("var1", "FOR c IN customer RETURN c"))
	r.Error(err)
	a.Nil(result)
}
예제 #12
0
func TestCheckResponseError(t *testing.T) {
	cases := []struct {
		resp     *http.Response
		expected error
	}{
		{
			httpmock.NewStringResponse(200, `{"foo": "bar"}`),
			nil,
		},
		{
			httpmock.NewStringResponse(299, `{"foo": "bar"}`),
			nil,
		},
		{
			httpmock.NewStringResponse(400, `{"error": "bad request"}`),
			ResponseError{Status: 400, Message: "bad request"},
		},
		{
			httpmock.NewStringResponse(500, `{"error": "terrible error"}`),
			ResponseError{Status: 500, Message: "terrible error"},
		},
		{
			httpmock.NewStringResponse(500, `{"errors": "This action requires read_customers scope"}`),
			ResponseError{Status: 500, Message: "This action requires read_customers scope"},
		},
		{
			httpmock.NewStringResponse(500, `{"errors": ["not", "very good"]}`),
			ResponseError{Status: 500, Message: "not, very good", Errors: []string{"not", "very good"}},
		},
		{
			httpmock.NewStringResponse(400, `{"errors": { "order": ["order is wrong"] }}`),
			ResponseError{Status: 400, Message: "order is wrong", Errors: []string{"order: order is wrong"}},
		},
	}

	for _, c := range cases {
		actual := CheckResponseError(c.resp)
		if !reflect.DeepEqual(actual, c.expected) {
			t.Errorf("CheckResponseError(): expected %#v, actual %#v", c.expected, actual)
		}
	}
}
func TestLibirtPlugin(t *testing.T) {
	Convey("Meta should return metadata for the plugin", t, func() {
		meta := Meta()
		So(meta.Name, ShouldResemble, Name)
		So(meta.Version, ShouldResemble, Version)
		So(meta.Type, ShouldResemble, plugin.CollectorPluginType)
	})

	Convey("Create Osv Collector", t, func() {
		osvCol := NewOsvCollector()
		Convey("So psCol should not be nil", func() {
			So(osvCol, ShouldNotBeNil)
		})
		Convey("So psCol should be of Osv type", func() {
			So(osvCol, ShouldHaveSameTypeAs, &Osv{})
		})
		Convey("osvCol.GetConfigPolicy() should return a config policy", func() {
			configPolicy, _ := osvCol.GetConfigPolicy()
			Convey("So config policy should not be nil", func() {
				So(configPolicy, ShouldNotBeNil)
			})
			Convey("So config policy should be a cpolicy.ConfigPolicy", func() {
				So(configPolicy, ShouldHaveSameTypeAs, &cpolicy.ConfigPolicy{})
			})
		})
	})
	Convey("Join namespace ", t, func() {
		namespace1 := []string{"intel", "osv", "one"}
		namespace2 := []string{}
		Convey("So namespace should equal intel/osv/one", func() {
			So("/intel/osv/one", ShouldResemble, joinNamespace(namespace1))
		})
		Convey("So namespace should equal slash", func() {
			So("/", ShouldResemble, joinNamespace(namespace2))
		})

	})
	Convey("Get URI ", t, func() {
		Convey("So should return 10.1.0.1:8000", func() {
			swagIP := "10.1.0.1"
			swagPort := 8000
			uri := osvRestURL(swagIP, swagPort)
			So("http://10.1.0.1:8000", ShouldResemble, uri)
		})
	})
	Convey("Get Metrics ", t, func() {
		osvCol := NewOsvCollector()
		cfgNode := cdata.NewNode()
		var cfg = plugin.PluginConfigType{
			ConfigDataNode: cfgNode,
		}
		Convey("So should return 187 types of metrics", func() {
			metrics, err := osvCol.GetMetricTypes(cfg)
			So(187, ShouldResemble, len(metrics))
			So(err, ShouldBeNil)
		})
		Convey("So should check namespace", func() {
			metrics, err := osvCol.GetMetricTypes(cfg)
			waitNamespace := joinNamespace(metrics[0].Namespace())
			wait := regexp.MustCompile(`^/osv/trace/virtio/virtio_wait_for_queue`)
			So(true, ShouldEqual, wait.MatchString(waitNamespace))
			So(err, ShouldBeNil)

		})

	})
	Convey("Get Metrics ", t, func() {
		osvCol := NewOsvCollector()
		cfgNode := cdata.NewNode()
		cfgNode.AddItem("swagIP", ctypes.ConfigValueStr{Value: "192.168.192.200"})
		cfgNode.AddItem("swagPort", ctypes.ConfigValueInt{Value: 8000})

		httpmock.Activate()
		defer httpmock.DeactivateAndReset()
		httpmock.RegisterResponder("GET", "http://192.168.192.200:8000/os/memory/free",
			func(req *http.Request) (*http.Response, error) {
				resp := httpmock.NewStringResponse(200, "20000")
				return resp, nil

			},
		)
		httpmock.RegisterResponder("GET", "http://192.168.192.200:8000/trace/count",
			func(req *http.Request) (*http.Response, error) {
				resp := httpmock.NewStringResponse(200, `{"time_ms": 144123232, "list": []}`)
				return resp, nil

			},
		)
		defer httpmock.DeactivateAndReset()
		httpmock.RegisterResponder("GET", "http://192.168.192.200:8000/trace/count",
			func(req *http.Request) (*http.Response, error) {
				resp := httpmock.NewStringResponse(200, `{"time_ms": 144123232, "list": [{"name": "waitqueue_wake_one", "count": 1000}]}`)
				return resp, nil

			},
		)
		Convey("So should get memory metrics", func() {
			metrics := []plugin.PluginMetricType{{
				Namespace_: []string{"osv", "memory", "free"},
				Config_:    cfgNode,
			}}
			collect, err := osvCol.CollectMetrics(metrics)
			So(err, ShouldBeNil)
			So(collect[0].Data_, ShouldNotBeNil)
			So(len(collect), ShouldResemble, 1)

		})
		Convey("So should get cpu metrics", func() {
			metrics := []plugin.PluginMetricType{{
				Namespace_: []string{"osv", "cpu", "cputime"},
				Config_:    cfgNode,
			}}
			collect, err := osvCol.CollectMetrics(metrics)
			So(err, ShouldBeNil)
			So(collect[0].Data_, ShouldNotBeNil)
			So(collect[0].Data_, ShouldResemble, "144123232")
			So(len(collect), ShouldResemble, 1)

		})
		Convey("So should get trace metrics", func() {
			metrics := []plugin.PluginMetricType{{
				Namespace_: []string{"osv", "trace", "wait", "waitqueue_wake_one"},
				Config_:    cfgNode,
			}}
			collect, err := osvCol.CollectMetrics(metrics)
			So(err, ShouldBeNil)
			So(collect[0].Data_, ShouldNotBeNil)
			So(collect[0].Data_, ShouldResemble, "1000")
			So(len(collect), ShouldResemble, 1)

		})

	})
}
예제 #14
0
func RegisterSegmentMocks() {
	// *******************************************************
	// GET SINGLE SEGMENT
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/segment/"+MockSegmentID1,
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_segment")), nil
		},
	)

	// *******************************************************
	// GET ALL SEGMENTS FOR API KEY
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/segment",
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if queries.Get("table") == "content" {
				return httpmock.NewStringResponse(200, readJsonFile("get_content_segments")), nil
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_segments")), nil
		},
	)

	// *******************************************************
	// GET SEGMENT SIZES
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/segment/"+MockSegmentID1+"/sizes",
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_segment_size")), nil
		},
	)

	// *******************************************************
	// GET ALL SEGMENT SIZES FOR API KEY
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/segment/sizes",
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_segment_sizes")), nil
		},
	)

	// *******************************************************
	// GET SEGMENT ATTRIBUTION FOR 2 SEGMENTS
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/segment/attribution",
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			// make sure we have the correct segment ids in the request
			if queries.Get("ids") != MockSegmentID1+","+MockSegmentID2 {
				fmt.Println("Ids Query Failed in Segment Attribution Mock")
				fail = true
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_segment_attribution")), nil
		},
	)

	// *******************************************************
	// GET SEGMENT COLLECTION
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/segmentcollection/"+MockSegmentCollection,
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_segment_collection")), nil
		},
	)

	// *******************************************************
	// GET SEGMENT COLLECTION List
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/segmentcollection",
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_segment_collection_list")), nil
		},
	)

	// *******************************************************
	// GET SEGMENT SCAN
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/segment/f186a334ad7109bbe08880/scan",
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			// make sure we have the correct segment ids in the request
			if queries.Get("start") == "number2" {
				return httpmock.NewStringResponse(200, readJsonFile("get_segment_scan_2")), nil
			}
			if queries.Get("start") == "number3" {
				return httpmock.NewStringResponse(200, readJsonFile("get_segment_scan_3")), nil
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_segment_scan_1")), nil
		},
	)

	// *******************************************************
	// POST CREATE SEGMENT
	// *******************************************************
	httpmock.RegisterResponder("POST", "https://api.lytics.io/api/segment",
		func(req *http.Request) (*http.Response, error) {

			body := make(map[string]interface{})
			json.NewDecoder(req.Body).Decode(&body)

			if _, ok := body["segment_ql"]; !ok {
				return httpmock.NewStringResponse(400, readJsonFile("post_segment_create_error")), nil
			}

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("post_segment_create")), nil
		},
	)

	// *******************************************************
	// POST SEGMENT VALIDATE
	// *******************************************************
	httpmock.RegisterResponder("POST", "https://api.lytics.io/api/segment/validate",
		func(req *http.Request) (*http.Response, error) {

			buf := new(bytes.Buffer)
			buf.ReadFrom(req.Body)

			if buf.String() == "" {
				return httpmock.NewStringResponse(400, readJsonFile("post_segment_validate_error")), nil
			}

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("post_segment_validate")), nil
		},
	)
}
예제 #15
0
func testSuccess(t *testing.T, apiEndpoint string, fixture Fixture) {
	httpmock.Activate()
	defer httpmock.DeactivateAndReset()

	for _, source := range fixture.Sources {
		weatherApiJson, wErr := ioutil.ReadFile(source.Data)

		if wErr != nil {
			t.Log("File error")
			t.Fail()
		}

		httpmock.RegisterResponder("GET", source.Url,
			func(req *http.Request) (*http.Response, error) {
				resp := httpmock.NewStringResponse(source.Status, string(weatherApiJson))
				return resp, nil
			},
		)

	}

	r := gin.New()

	Router(r)
	r.Use(ValidCityMiddleware())

	req, _ := http.NewRequest("GET", apiEndpoint, nil)
	resp := httptest.NewRecorder()
	r.ServeHTTP(resp, req)

	var data gin.H

	decoder := json.NewDecoder(resp.Body)

	jsonErr := decoder.Decode(&data)

	if jsonErr != nil {
		t.Log("JSON error")
		t.Fail()
	}

	var expectedJsonData gin.H

	expectedJson, expectedJsonFileErr := ioutil.ReadFile(fixture.ExpectedJson)

	if expectedJsonFileErr != nil {
		t.Log("File error")
		t.Fail()
	}

	expectedJsonParseErr := json.Unmarshal(expectedJson, &expectedJsonData)

	if expectedJsonParseErr != nil {
		t.Log("JSON error")
		t.Fail()
	}

	diffResults := pretty.Diff(data, expectedJsonData)

	for _, delta := range diffResults {
		t.Logf("Difference found: %+v", delta)
	}

	assert.Equal(t, len(diffResults), 0, "Response Body and Expected JSON should have no differences")

	assert.Equal(t, resp.Code, 200)
}
예제 #16
0
func setupMock() {

	testUser := User{
		EventsURL:         "https://api.github.com/users/octocat/events{/privacy}",
		Followers:         20,
		FollowersURL:      "https://api.github.com/users/octocat/followers",
		Following:         0,
		FollowingURL:      "https://api.github.com/users/octocat/following{/other_user}",
		GistsURL:          "https://api.github.com/users/octocat/gists{/gist_id}",
		Hireable:          false,
		HTMLURL:           "https://github.com/octocat",
		Location:          "San Francisco",
		Login:             "******",
		Name:              "monalisa octocat",
		OrganizationsURL:  "https://api.github.com/users/octocat/orgs",
		PublicRepos:       2,
		ReceivedEventsURL: "https://api.github.com/users/octocat/received_events",
		ReposURL:          "https://api.github.com/users/octocat/repos",
		StarredURL:        "https://api.github.com/users/octocat/starred{/owner}{/repo}",
		SubscriptionsURL:  "https://api.github.com/users/octocat/subscriptions",
		Type:              "User",
		URL:               "https://api.github.com/users/octocat",
	}

	httpmock.RegisterResponder("GET", "http://testapi.my/hello",
		func(req *http.Request) (*http.Response, error) {
			resp := httpmock.NewStringResponse(200, "Hello World!")
			return resp, nil
		},
	)

	httpmock.RegisterResponder("GET", "http://testapi.my/user/octocat",
		func(req *http.Request) (*http.Response, error) {
			return httpmock.NewJsonResponse(200, testUser)
		},
	)

	httpmock.RegisterResponder("GET", "http://testapi.my/user/someveryunknown",
		func(req *http.Request) (*http.Response, error) {
			resp := httpmock.NewStringResponse(404, "user someveryunknown not found")
			return resp, nil
		},
	)

	httpmock.RegisterResponder("GET", "http://testapi.my/user/BadGuy",
		func(req *http.Request) (*http.Response, error) {
			resp := httpmock.NewStringResponse(500, "BadGuy failed me :(")
			return resp, nil
		},
	)

	httpmock.RegisterResponder("POST", "http://testapi.my/user",
		func(req *http.Request) (*http.Response, error) {
			return httpmock.NewJsonResponse(201, testUser)
		},
	)

	httpmock.RegisterResponder("PATCH", "http://testapi.my/user/octocat",
		func(req *http.Request) (*http.Response, error) {
			patchedUser := testUser
			patchedUser.Name = "I Am Updated!"
			return httpmock.NewJsonResponse(200, patchedUser)
		},
	)

	httpmock.RegisterResponder("DELETE", "http://testapi.my/user/octocat",
		func(req *http.Request) (*http.Response, error) {
			resp := httpmock.NewBytesResponse(204, nil)
			return resp, nil
		},
	)

	httpmock.RegisterResponder("DELETE", "http://testapi.my/user/someveryunknown",
		func(req *http.Request) (*http.Response, error) {
			resp := httpmock.NewStringResponse(404, "user someveryunknown not found")
			return resp, nil
		},
	)

	httpmock.RegisterResponder("DELETE", "http://testapi.my/user/BadGuy",
		func(req *http.Request) (*http.Response, error) {
			resp := httpmock.NewStringResponse(500, "BadGuy failed me :(")
			return resp, nil
		},
	)
}
예제 #17
0
func RegisterContentMocks() {
	// *******************************************************
	// GET USER CONTENT RECOMMENDATION
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/content/recommend/user/user_id/"+MockUserID,
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if queries.Get("topics[]") != "mock" || len(queries["topics[]"]) != 2 {
				fail = true
			}

			if queries.Get("visited") != "false" {
				fail = true
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_user_content_recommendation")), nil
		},
	)

	// *******************************************************
	// GET SEGMENT CONTENT RECOMMENDATION
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/content/recommend/segment/"+MockSegmentID1,
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if queries.Get("rank") != "popular" {
				fail = true
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_user_content_recommendation")), nil
		},
	)

	// *******************************************************
	// GET CONTENT DOCUMENTS
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/content/doc",
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			if queries.Get("limit") == "1" {
				return httpmock.NewStringResponse(200, readJsonFile("get_document")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_documents")), nil
		},
	)

	// *******************************************************
	// GET TOPIC SUMMARY
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/content/topic/"+MockTopicID,
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_topic")), nil
		},
	)

	// *******************************************************
	// GET CONTENT TAXONOMY
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/content/taxonomy",
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_content_taxonomy")), nil
		},
	)

	// *******************************************************
	// GET TOPIC ROLLUPS
	// *******************************************************
	httpmock.RegisterResponder("GET", "https://api.lytics.io/api/content/topicrollup",
		func(req *http.Request) (*http.Response, error) {
			var fail bool

			queries := req.URL.Query()

			if queries.Get("key") != MockApiKey {
				fail = true
			}

			if fail {
				return httpmock.NewStringResponse(401, readJsonFile("get_error")), nil
			}

			return httpmock.NewStringResponse(200, readJsonFile("get_topic_rollups")), nil
		},
	)
}
func TestTracePlugin(t *testing.T) {
	Convey("getMemstat Should return memory amount value", t, func() {

		httpmock.Activate()
		defer httpmock.DeactivateAndReset()
		httpmock.RegisterResponder("GET", "http://192.168.192.200:8000/trace/count",
			func(req *http.Request) (*http.Response, error) {
				resp := httpmock.NewStringResponse(200, `{"time_ms": 144123232, "list": [{"name": "waitqueue_wake_one", "count": 1000}]}`)
				return resp, nil

			},
		)
		httpmock.RegisterResponder("POST", "http://192.168.192.200:8000/trace/count/waitqueue_wake_one?enabled=True",
			func(req *http.Request) (*http.Response, error) {
				resp := httpmock.NewStringResponse(200, "")
				return resp, nil

			},
		)

		trace, err := getTrace("waitqueue_wake_one", "http://192.168.192.200:8000")
		So(err, ShouldBeNil)
		So(strconv.FormatUint(trace, 10), ShouldResemble, "1000")

	})
	Convey("MemStat Should return pluginMetricType Data", t, func() {

		httpmock.Activate()
		defer httpmock.DeactivateAndReset()
		httpmock.RegisterResponder("GET", "http://192.168.192.200:8000/trace/count",
			func(req *http.Request) (*http.Response, error) {
				resp := httpmock.NewStringResponse(200, `{"time_ms": 144123232, "list": [{"name": "waitqueue_wake_one", "count": 1000}]}`)
				return resp, nil

			},
		)

		ns := []string{"osv", "trace", "wait", "waitqueue_wake_one"}
		memFree, err := traceStat(ns, "http://192.168.192.200:8000")
		So(err, ShouldBeNil)
		So(memFree.Namespace_, ShouldResemble, ns)
		So(memFree.Data_, ShouldResemble, "1000")

	})
	Convey("osvCallRest should return nil", t, func() {

		httpmock.Activate()
		defer httpmock.DeactivateAndReset()
		httpmock.RegisterResponder("POST", "http://192.168.192.200:8000/trace/count/waitqueue_wake_one?enabled=True",
			func(req *http.Request) (*http.Response, error) {
				resp := httpmock.NewStringResponse(200, "")
				return resp, nil

			},
		)

		resp := osvRestPost("http://192.168.192.200:8000", "trace/count/waitqueue_wake_one?enabled=True")
		So(resp, ShouldBeNil)

	})
}