<commit_before>// Copyright 2015 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package cloudstack

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"testing"
	"time"

	"github.com/tsuru/config"
	"github.com/tsuru/tsuru/iaas"
	"github.com/tsuru/tsuru/queue"
	"gopkg.in/check.v1"
)

func Test(t *testing.T) { check.TestingT(t) }

type cloudstackSuite struct{}

var _ = check.Suite(&cloudstackSuite{})

func (s *cloudstackSuite) SetUpSuite(c *check.C) {
	config.Set("iaas:cloudstack:api-key", "test")
	config.Set("iaas:cloudstack:secret-key", "test")
	config.Set("iaas:cloudstack:url", "test")
}

func (s *cloudstackSuite) SetUpTest(c *check.C) {
	config.Set("queue:mongo-database", "queue_cloudstack_iaas")
	queue.ResetQueue()
}

func (s *cloudstackSuite) TestCreateMachine(c *check.C) {
	var calls []string
	fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		cmd := r.URL.Query().Get("command")
		calls = append(calls, cmd)
		w.Header().Set("Content-type", "application/json")
		if cmd == "queryAsyncJobResult" {
			fmt.Fprintln(w, `{"queryasyncjobresultresponse": {"jobstatus": 1}}`)
		}
		if cmd == "deployVirtualMachine" {
			fmt.Fprintln(w, `{"deployvirtualmachineresponse": {"id": "0366ae09-0a77-4e2b-8595-3b749764a107", "jobid": "test"}}`)
		}
		if cmd == "listVirtualMachines" {
			json := `{ "listvirtualmachinesresponse" : { "count":1 ,"virtualmachine" : [  {"id":"0366ae09-0a77-4e2b-8595-3b749764a107","name":"vm-0366ae09-0a77-4e2b-8595-3b749764a107","projectid":"a98738c9-5acd-43e3-b1a1-972a3db5b196","project":"tsuru playground","domainid":"eec2dacf-9982-11e3-a2b8-eee0bc1594e0","domain":"ROOT","created":"2014-07-18T18:29:30-0300","state":"Stopped","haenable":false,"zoneid":"95046c6c-65b8-415f-99cb-0cff40dc5f9c","zonename":"RJOEBT0200BE","templateid":"99f66d4c-f923-46e5-aa7b-09a0b22ee747","templatename":"ubuntu-14.04-server-amd64","templatedisplaytext":"ubuntu 14.04 ( 3.13.0-24-generic )","passwordenabled":false,"serviceofferingid":"3ff651c8-a27f-4008-87d5-71636aaabbc6","serviceofferingname":"Medium","cpunumber":2,"cpuspeed":1800,"memory":8192,"guestosid":"eede1fdf-9982-11e3-a2b8-eee0bc1594e0","rootdeviceid":0,"rootdevicetype":"ROOT","securitygroup":[],"nic":[{"id":"40cd6225-9475-44a3-8288-d7a9a485d8ac","networkid":"18c20437-df18-4757-8435-1230248f955b","networkname":"PLAYGROUND_200BE","netmask":"255.255.255.0","gateway":"10.24.16.1","ipaddress":"10.24.16.241","isolationuri":"vlan://19","broadcasturi":"vlan://19","traffictype":"Guest","type":"Shared","isdefault":true,"macaddress":"06:54:7e:00:46:c6"}],"hypervisor":"XenServer","tags":[],"affinitygroup":[],"displayvm":true,"isdynamicallyscalable":true,"jobid":"82a574cc-43f2-440d-8774-e638065c37af","jobstatus":0} ] } }`
			fmt.Fprintln(w, json)
		}
	}))
	defer fakeServer.Close()
	config.Set("iaas:cloudstack:url", fakeServer.URL)
	cs := newCloudstackIaaS("cloudstack")
	err := (cs.(*CloudstackIaaS)).Initialize()
	c.Assert(err, check.IsNil)
	params := map[string]string{
		"projectid":         "val",
		"networkids":        "val",
		"templateid":        "val",
		"serviceofferingid": "val",
		"zoneid":            "val",
	}
	vm, err := cs.CreateMachine(params)
	c.Assert(err, check.IsNil)
	c.Assert(vm, check.NotNil)
	c.Assert(vm.Address, check.Equals, "10.24.16.241")
	c.Assert(vm.Id, check.Equals, "0366ae09-0a77-4e2b-8595-3b749764a107")
	c.Assert(calls, check.DeepEquals, []string{"deployVirtualMachine", "queryAsyncJobResult", "listVirtualMachines"})
}

func (s *cloudstackSuite) TestCreateMachineAsyncFailure(c *check.C) {
	var calls []string
	fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		cmd := r.URL.Query().Get("command")
		calls = append(calls, cmd)
		w.Header().Set("Content-type", "application/json")
		if cmd == "queryAsyncJobResult" {
			fmt.Fprintln(w, `{"queryasyncjobresultresponse": {"jobstatus": 2, "jobresult": "my weird error"}}`)
		}
		if cmd == "deployVirtualMachine" {
			fmt.Fprintln(w, `{"deployvirtualmachineresponse": {"id": "0366ae09-0a77-4e2b-8595-3b749764a107", "jobid": "test"}}`)
		}
	}))
	defer fakeServer.Close()
	config.Set("iaas:cloudstack:url", fakeServer.URL)
	cs := newCloudstackIaaS("cloudstack")
	err := (cs.(*CloudstackIaaS)).Initialize()
	c.Assert(err, check.IsNil)
	params := map[string]string{
		"projectid":         "val",
		"networkids":        "val",
		"templateid":        "val",
		"serviceofferingid": "val",
		"zoneid":            "val",
	}
	_, err = cs.CreateMachine(params)
	c.Assert(err, check.ErrorMatches, ".*my weird error.*")
	c.Assert(calls, check.DeepEquals, []string{"deployVirtualMachine", "queryAsyncJobResult"})
}

func (s *cloudstackSuite) TestCreateMachineValidateParams(c *check.C) {
	cs := newCloudstackIaaS("cloudstack")
	err := (cs.(*CloudstackIaaS)).Initialize()
	c.Assert(err, check.IsNil)
	params := map[string]string{
		"name": "something",
	}
	_, err = cs.CreateMachine(params)
	c.Assert(err, check.ErrorMatches, "param \"networkids\" is mandatory")
}

func (s *cloudstackSuite) TestBuildUrlToCloudstack(c *check.C) {
	cs := newCloudstackIaaS("cloudstack")
	err := (cs.(*CloudstackIaaS)).Initialize()
	c.Assert(err, check.IsNil)
	params := map[string]string{"atest": "2"}
	csIaaS, ok := cs.(*CloudstackIaaS)
	c.Assert(ok, check.Equals, true)
	urlBuilded, err := csIaaS.buildUrl("commandTest", params)<commit_msg>iaas/cloudstack: check only the two first calls in tests<commit_after>// Copyright 2015 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package cloudstack

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"testing"
	"time"

	"github.com/tsuru/config"
	"github.com/tsuru/tsuru/iaas"
	"github.com/tsuru/tsuru/queue"
	"gopkg.in/check.v1"
)

func Test(t *testing.T) { check.TestingT(t) }

type cloudstackSuite struct{}

var _ = check.Suite(&cloudstackSuite{})

func (s *cloudstackSuite) SetUpSuite(c *check.C) {
	config.Set("iaas:cloudstack:api-key", "test")
	config.Set("iaas:cloudstack:secret-key", "test")
	config.Set("iaas:cloudstack:url", "test")
}

func (s *cloudstackSuite) SetUpTest(c *check.C) {
	config.Set("queue:mongo-database", "queue_cloudstack_iaas")
	queue.ResetQueue()
}

func (s *cloudstackSuite) TestCreateMachine(c *check.C) {
	var calls []string
	fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		cmd := r.URL.Query().Get("command")
		calls = append(calls, cmd)
		w.Header().Set("Content-type", "application/json")
		if cmd == "queryAsyncJobResult" {
			fmt.Fprintln(w, `{"queryasyncjobresultresponse": {"jobstatus": 1}}`)
		}
		if cmd == "deployVirtualMachine" {
			fmt.Fprintln(w, `{"deployvirtualmachineresponse": {"id": "0366ae09-0a77-4e2b-8595-3b749764a107", "jobid": "test"}}`)
		}
		if cmd == "listVirtualMachines" {
			json := `{ "listvirtualmachinesresponse" : { "count":1 ,"virtualmachine" : [  {"id":"0366ae09-0a77-4e2b-8595-3b749764a107","name":"vm-0366ae09-0a77-4e2b-8595-3b749764a107","projectid":"a98738c9-5acd-43e3-b1a1-972a3db5b196","project":"tsuru playground","domainid":"eec2dacf-9982-11e3-a2b8-eee0bc1594e0","domain":"ROOT","created":"2014-07-18T18:29:30-0300","state":"Stopped","haenable":false,"zoneid":"95046c6c-65b8-415f-99cb-0cff40dc5f9c","zonename":"RJOEBT0200BE","templateid":"99f66d4c-f923-46e5-aa7b-09a0b22ee747","templatename":"ubuntu-14.04-server-amd64","templatedisplaytext":"ubuntu 14.04 ( 3.13.0-24-generic )","passwordenabled":false,"serviceofferingid":"3ff651c8-a27f-4008-87d5-71636aaabbc6","serviceofferingname":"Medium","cpunumber":2,"cpuspeed":1800,"memory":8192,"guestosid":"eede1fdf-9982-11e3-a2b8-eee0bc1594e0","rootdeviceid":0,"rootdevicetype":"ROOT","securitygroup":[],"nic":[{"id":"40cd6225-9475-44a3-8288-d7a9a485d8ac","networkid":"18c20437-df18-4757-8435-1230248f955b","networkname":"PLAYGROUND_200BE","netmask":"255.255.255.0","gateway":"10.24.16.1","ipaddress":"10.24.16.241","isolationuri":"vlan://19","broadcasturi":"vlan://19","traffictype":"Guest","type":"Shared","isdefault":true,"macaddress":"06:54:7e:00:46:c6"}],"hypervisor":"XenServer","tags":[],"affinitygroup":[],"displayvm":true,"isdynamicallyscalable":true,"jobid":"82a574cc-43f2-440d-8774-e638065c37af","jobstatus":0} ] } }`
			fmt.Fprintln(w, json)
		}
	}))
	defer fakeServer.Close()
	config.Set("iaas:cloudstack:url", fakeServer.URL)
	cs := newCloudstackIaaS("cloudstack")
	err := (cs.(*CloudstackIaaS)).Initialize()
	c.Assert(err, check.IsNil)
	params := map[string]string{
		"projectid":         "val",
		"networkids":        "val",
		"templateid":        "val",
		"serviceofferingid": "val",
		"zoneid":            "val",
	}
	vm, err := cs.CreateMachine(params)
	c.Assert(err, check.IsNil)
	c.Assert(vm, check.NotNil)
	c.Assert(vm.Address, check.Equals, "10.24.16.241")
	c.Assert(vm.Id, check.Equals, "0366ae09-0a77-4e2b-8595-3b749764a107")
	c.Assert(calls, check.DeepEquals, []string{"deployVirtualMachine", "queryAsyncJobResult", "listVirtualMachines"})
}

func (s *cloudstackSuite) TestCreateMachineAsyncFailure(c *check.C) {
	var calls []string
	fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		cmd := r.URL.Query().Get("command")
		calls = append(calls, cmd)
		w.Header().Set("Content-type", "application/json")
		if cmd == "queryAsyncJobResult" {
			fmt.Fprintln(w, `{"queryasyncjobresultresponse": {"jobstatus": 2, "jobresult": "my weird error"}}`)
		}
		if cmd == "deployVirtualMachine" {
			fmt.Fprintln(w, `{"deployvirtualmachineresponse": {"id": "0366ae09-0a77-4e2b-8595-3b749764a107", "jobid": "test"}}`)
		}
	}))
	defer fakeServer.Close()
	config.Set("iaas:cloudstack:url", fakeServer.URL)
	cs := newCloudstackIaaS("cloudstack")
	err := (cs.(*CloudstackIaaS)).Initialize()
	c.Assert(err, check.IsNil)
	params := map[string]string{
		"projectid":         "val",
		"networkids":        "val",
		"templateid":        "val",
		"serviceofferingid": "val",
		"zoneid":            "val",
	}
	_, err = cs.CreateMachine(params)
	c.Assert(err, check.ErrorMatches, ".*my weird error.*")
	c.Assert(calls[:2], check.DeepEquals, []string{"deployVirtualMachine", "queryAsyncJobResult"})
}

func (s *cloudstackSuite) TestCreateMachineValidateParams(c *check.C) {
	cs := newCloudstackIaaS("cloudstack")
	err := (cs.(*CloudstackIaaS)).Initialize()
	c.Assert(err, check.IsNil)
	params := map[string]string{
		"name": "something",
	}
	_, err = cs.CreateMachine(params)
	c.Assert(err, check.ErrorMatches, "param \"networkids\" is mandatory")
}

func (s *cloudstackSuite) TestBuildUrlToCloudstack(c *check.C) {
	cs := newCloudstackIaaS("cloudstack")
	err := (cs.(*CloudstackIaaS)).Initialize()
	c.Assert(err, check.IsNil)
	params := map[string]string{"atest": "2"}
	csIaaS, ok := cs.(*CloudstackIaaS)
	c.Assert(ok, check.Equals, true)
	urlBuilded, err := csIaaS.buildUrl("commandTest", params)
{'fraction_non_alphanumeric': 0.19552767930188164, 'fraction_numerical': 0.07626579401872557, 'mean_word_length': 6.098064516129032, 'pattern_counts': {'":': 136, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 8, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5421600', 'n_tokens_mistral': 4782, 'n_tokens_neox': 4276, 'n_words': 563}