Commit 5e44d699 authored by Leonardo Menezes's avatar Leonardo Menezes
Browse files

tests to template module

parent c58854c4
Loading
Loading
Loading
Loading
+2 −2
Original line number Diff line number Diff line
@@ -17,7 +17,7 @@ class TemplatesController extends BaseController {
  def delete = process { (request, client) =>
    val name = request.get("name")
    client.deleteTemplate(name, ElasticServer(request.host, request.authentication)).map { response =>
      Status(response.status)(Templates(response.body))
      Status(response.status)(response.body)
    }
  }

@@ -25,7 +25,7 @@ class TemplatesController extends BaseController {
    val name = request.get("name")
    val template = request.getObj("template")
    client.createTemplate(name, template, ElasticServer(request.host, request.authentication)).map { response =>
      Status(response.status)(Templates(response.body))
      Status(response.status)(response.body)
    }
  }

+11 −14
Original line number Diff line number Diff line
@@ -748,7 +748,6 @@ angular.module('cerebro').controller('TemplatesController', ['$scope',
    $scope.create = function(name) {
      try {
        var template = $scope.editor.getValue();
        try {
        var success = function(response) {
          AlertService.info('Template successfully created');
          $scope.loadTemplates();
@@ -757,11 +756,9 @@ angular.module('cerebro').controller('TemplatesController', ['$scope',
          AlertService.error('Error creating template', response);
        };
        TemplatesDataService.create(name, template, success, errorCallback);
        } catch (error) {
          console.log(error);
          AlertService.error(error);
      }
      } catch (error) {
      catch
        (error) {
        AlertService.error('Malformed template', error);
      }
    };
+11 −14
Original line number Diff line number Diff line
@@ -45,7 +45,6 @@ angular.module('cerebro').controller('TemplatesController', ['$scope',
    $scope.create = function(name) {
      try {
        var template = $scope.editor.getValue();
        try {
        var success = function(response) {
          AlertService.info('Template successfully created');
          $scope.loadTemplates();
@@ -54,11 +53,9 @@ angular.module('cerebro').controller('TemplatesController', ['$scope',
          AlertService.error('Error creating template', response);
        };
        TemplatesDataService.create(name, template, success, errorCallback);
        } catch (error) {
          console.log(error);
          AlertService.error(error);
      }
      } catch (error) {
      catch
        (error) {
        AlertService.error('Malformed template', error);
      }
    };
+137 −0
Original line number Diff line number Diff line
package controllers

import elastic.{ElasticClient, ElasticResponse}
import models.ElasticServer
import org.specs2.Specification
import org.specs2.mock.Mockito
import play.api.libs.json.Json
import play.api.test.Helpers._
import play.api.test.{FakeApplication, FakeRequest}

import scala.concurrent.Future

object TemplatesControllerSpec extends Specification with Mockito {

  def is =
    s2"""
    TemplatesController should                           ${step(play.api.Play.start(FakeApplication()))}
      return all templates                               $templates
      delete template                                    $delete
      require template name to delete                    $requireNameDelete
      create template                                    $create
      require template name to create                    $requireNameCreate
                                                         ${step(play.api.Play.stop(FakeApplication()))}
      """

  def templates = {
    val mockedClient = mock[ElasticClient]
    val mockedResponse = Json.parse(
      """
        |{
        |  "template_1": {
        |    "order": 0,
        |    "template": "somePattern_1*",
        |    "settings": {},
        |    "mappings": {},
        |    "aliases": {}
        |  },
        |  "template_2": {
        |    "order": 0,
        |    "template": "somePattern_2*",
        |    "settings": {},
        |    "mappings": {},
        |    "aliases": {}
        |  }
        |}
      """.stripMargin
    )
    val expectedResponse = Json.parse(
      """
        |[
        |  {
        |    "name": "template_1",
        |    "template": {
        |      "order": 0,
        |      "template": "somePattern_1*",
        |      "settings": {},
        |      "mappings": {},
        |      "aliases": {}
        |    }
        |  },
        |  {
        |    "name": "template_2",
        |    "template": {
        |      "order": 0,
        |      "template": "somePattern_2*",
        |      "settings": {},
        |      "mappings": {},
        |      "aliases": {}
        |    }
        |  }
        |]
      """.stripMargin
    )
    mockedClient.getTemplates(ElasticServer("somehost", None)) returns Future.successful(ElasticResponse(200, mockedResponse))
    val controller = new TemplatesController {
      override val client: ElasticClient = mockedClient
    }
    val response = controller.templates()(FakeRequest().withBody(Json.obj("host" -> "somehost")))
    (status(response) mustEqual 200) and (contentAsJson(response) mustEqual expectedResponse)
  }

  def delete = {
    val mockedClient = mock[ElasticClient]
    val expectedResponse = Json.parse(
      """
        |{"acknowledged":true}
      """.stripMargin
    )
    mockedClient.deleteTemplate("someTemplate", ElasticServer("somehost", None)) returns Future.successful(ElasticResponse(200, expectedResponse))
    val controller = new TemplatesController {
      override val client: ElasticClient = mockedClient
    }
    val response = controller.delete()(FakeRequest().withBody(Json.obj("host" -> "somehost", "name" -> "someTemplate")))
    (status(response) mustEqual 200) and (contentAsJson(response) mustEqual expectedResponse)
  }

  def requireNameDelete = {
    val controller = new TemplatesController
    val response = controller.delete()(FakeRequest().withBody(Json.obj("host" -> "somehost")))
    (status(response) mustEqual 400) and (contentAsJson(response) mustEqual Json.parse("{\"error\":\"Missing required parameter name\"}"))
  }

  def create = {
    val template = Json.parse(
      """
        |{
        |  "whatever": {}
        |}
      """.stripMargin)
    val mockedClient = mock[ElasticClient]
    val expectedResponse = Json.parse(
      """
        |{"acknowledged":true}
      """.stripMargin
    )
    mockedClient.createTemplate("someTemplate", template, ElasticServer("somehost", None)) returns Future.successful(ElasticResponse(200, expectedResponse))
    val controller = new TemplatesController {
      override val client: ElasticClient = mockedClient
    }
    val response = controller.create()(FakeRequest().withBody(Json.obj("host" -> "somehost", "name" -> "someTemplate", "template" -> template)))
    (status(response) mustEqual 200) and (contentAsJson(response) mustEqual expectedResponse)
  }

  def requireNameCreate = {
    val controller = new TemplatesController
    val response = controller.create()(FakeRequest().withBody(Json.obj("host" -> "somehost")))
    (status(response) mustEqual 400) and (contentAsJson(response) mustEqual Json.parse("{\"error\":\"Missing required parameter name\"}"))
  }

  def requireNameTemplate = {
    val controller = new TemplatesController
    val response = controller.create()(FakeRequest().withBody(Json.obj("host" -> "somehost", "name" -> "any")))
    (status(response) mustEqual 400) and (contentAsJson(response) mustEqual Json.parse("{\"error\":\"Missing required parameter template\"}"))
  }


}
+128 −0
Original line number Diff line number Diff line
describe('TemplatesController', function() {

  beforeEach(angular.mock.module('cerebro'));

  beforeEach(angular.mock.inject(function($rootScope, $controller, $injector) {
    this.scope = $rootScope.$new();
    this.AlertService = $injector.get('AlertService');
    this.AceEditorService = $injector.get('AceEditorService');
    this.TemplatesDataService = $injector.get('TemplatesDataService');
    this.ModalService = $injector.get('ModalService');

    this.createController = function() {
      return $controller('TemplatesController',
        {$scope: this.scope}, this.AlertService, this.AceEditorService, this.TemplatesDataService, this.ModalService);
    };
    this._controller = this.createController();
  }));

  describe('setup', function() {
    it('loads aliases and indices, and initializes ace editor', function() {
      spyOn(this.scope, 'loadTemplates').andReturn();
      spyOn(this.scope, 'initEditor').andReturn();
      this.scope.setup();
      expect(this.scope.loadTemplates).toHaveBeenCalled();
      expect(this.scope.initEditor).toHaveBeenCalled();
    });
  });

  describe('loadTemplates', function() {
    it('load templates', function() {
      var templates = [{name: 'a'}, {name: 'b'}];
      this.TemplatesDataService.getTemplates = function(success, error) {
        success(templates);
      };
      spyOn(this.TemplatesDataService, 'getTemplates').andCallThrough();
      spyOn(this.scope.paginator, 'setCollection').andCallThrough();
      spyOn(this.scope.paginator, 'getPage').andReturn('page!');
      this.scope.loadTemplates();
      expect(this.TemplatesDataService.getTemplates).toHaveBeenCalledWith(jasmine.any(Function), jasmine.any(Function));
      expect(this.scope.paginator.setCollection).toHaveBeenCalledWith(templates);
      expect(this.scope.paginator.getPage).toHaveBeenCalled();
      expect(this.scope.page).toEqual('page!');
    });
    it('alert on failure loading templates', function() {
      this.TemplatesDataService.getTemplates = function(success, error) {
        error('failed!');
      };
      spyOn(this.AlertService, 'error').andReturn();
      spyOn(this.TemplatesDataService, 'getTemplates').andCallThrough();
      this.scope.loadTemplates();
      expect(this.TemplatesDataService.getTemplates).toHaveBeenCalledWith(jasmine.any(Function), jasmine.any(Function));
      expect(this.AlertService.error).toHaveBeenCalledWith('Error while loading templates', 'failed!');
    });
  });

  describe('create', function() {
    it('create template', function() {
      this.TemplatesDataService.create = function(name, template, success, error) {
        success('ok');
      };
      this.scope.editor = {
        getValue: function() {
        }
      };
      spyOn(this.TemplatesDataService, 'create').andCallThrough();
      spyOn(this.scope.editor, 'getValue').andReturn({key: 'value'});
      spyOn(this.AlertService, 'info').andReturn();
      this.scope.create('someTemplate');
      expect(this.TemplatesDataService.create).toHaveBeenCalledWith('someTemplate', {key: 'value'}, jasmine.any(Function), jasmine.any(Function));
      expect(this.AlertService.info).toHaveBeenCalledWith('Template successfully created');
    });
    it('alerts about malformed template', function() {
      this.scope.editor = {
        getValue: function() {
          throw 'pffff';
        }
      };
      spyOn(this.TemplatesDataService, 'create').andCallThrough();
      spyOn(this.AlertService, 'error').andReturn();
      this.scope.create('someTemplate');
      expect(this.TemplatesDataService.create).not.toHaveBeenCalled();
      expect(this.AlertService.error).toHaveBeenCalledWith('Malformed template', 'pffff');
    });
    it('alerts on error while creation', function() {
      this.TemplatesDataService.create = function(name, template, success, error) {
        error('ko');
      };
      this.scope.editor = {
        getValue: function() {
        }
      };
      spyOn(this.TemplatesDataService, 'create').andCallThrough();
      spyOn(this.scope.editor, 'getValue').andReturn({key: 'value'});
      spyOn(this.AlertService, 'error').andReturn();
      this.scope.create('someTemplate');
      expect(this.TemplatesDataService.create).toHaveBeenCalledWith('someTemplate', {key: 'value'}, jasmine.any(Function), jasmine.any(Function));
      expect(this.AlertService.error).toHaveBeenCalledWith('Error creating template', 'ko');
    });
  });

  describe('pagination', function() {
    it('refreshes page when paginator/filter information changes', function() {
      var elements = [8, 9, 1];
      spyOn(this.scope.paginator, 'getPage').andReturn(elements);
      this.scope.$digest();
      expect(this.scope.page).toEqual([8, 9, 1]);
      this.scope.page = []; // resets value
      this.scope.$digest(); // nothing changed
      expect(this.scope.page).toEqual([]);
      this.scope.paginator.filter.name = 'a';
      this.scope.$digest();
      expect(this.scope.page).toEqual([8, 9, 1]);
      this.scope.page = []; // resets value
      this.scope.$digest(); // nothing changed
      expect(this.scope.page).toEqual([]);
      this.scope.paginator.filter.template = 'a';
      this.scope.$digest();
      expect(this.scope.page).toEqual([8, 9, 1]);
      this.scope.page = []; // resets value
      this.scope.$digest(); // nothing changed
      expect(this.scope.page).toEqual([]);
      this.scope.paginator.nextPage();
      this.scope.$digest();
      expect(this.scope.page).toEqual([8, 9, 1]);
    });
  });

});