<commit_before>/*
 * Copyright (C) 2011-2017 Interfaculty Department of Geoinformatics, University of
 * Salzburg (Z_GIS) & Institute of Geological and Nuclear Sciences Limited (GNS Science)
 * in the SMART Aquifer Characterisation (SAC) programme funded by the New Zealand
 * Ministry of Business, Innovation and Employment (MBIE)
 *
 * 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.
 */

import java.time.{ZoneId, ZonedDateTime}

import akka.stream.Materializer
import com.google.inject.AbstractModule
import com.typesafe.config.ConfigFactory
import controllers.security.{AuthenticationAction, OptionalAuthenticationAction, UserAction}
import controllers.{CollectionsController, routes}
import info.smart.models.owc100.OwcContext
import models.users.UserSession
import org.scalatest.TestData
import org.scalatestplus.play.OneAppPerTest
import org.specs2.mock._
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.json.Json
import play.api.mvc._
import play.api.test.Helpers._
import play.api.test._
import play.api.{Application, Configuration}
import services.{EmailService, OwcCollectionsService, UserService}
import utils.PasswordHashing


class CollectionsControllerSpec extends WithDefaultTest with OneAppPerTest with Results with Mockito {

  // creating mock instances for underlying required services for this controller
  private lazy val mockCollectionsService = mock[OwcCollectionsService].defaultReturn(Seq[OwcContext]())
  private lazy val mockEmailService = mock[EmailService]
  private lazy val mockUserService = mock[UserService].defaultReturn(None)
  private lazy val mockAuthenticationAction = mock[AuthenticationAction]
  private lazy val mockOptionalAuthenticationAction = mock[OptionalAuthenticationAction]
  private lazy val mockUserAction = mock[UserAction]

  // creating "fake" Guice Module to inject mock service instances into test application, with the required dependencies
  class FakeModule extends AbstractModule {
    def configure(): Unit = {
      bind(classOf[PasswordHashing]).asEagerSingleton()
      bind(classOf[UserService]).toInstance(mockUserService)
      bind(classOf[EmailService]).toInstance(mockEmailService)
      bind(classOf[OwcCollectionsService]).toInstance(mockCollectionsService)
    }
  }

  // Override newAppForTest if you need a FakeApplication with other than non-default parameters, incl. fake guice module
  import scala.language.implicitConversions

  implicit override def newAppForTest(testData: TestData): Application = new GuiceApplicationBuilder()
    .overrides(new FakeModule)
    .loadConfig(new Configuration(ConfigFactory.load("application.test.conf")))
    .build()

  // needed for routes execution on tested controller
  implicit lazy val materializer: Materializer = app.materializer

  val demodata = new DemoData

  "CollectionsController" when {

    "request to getCollections(None)" in {
      (pending)

      Then("create mock components, particular mocked CollectionsServive")

      // behaviour for mocked underlying collections service when controller calls injected service functions
      mockCollectionsService.getOwcContextsForUserAndId(None, None) returns Seq[OwcContext]()
      mockUserService.getUserSessionByToken("<PASSWORD>.", "<PASSWORD>,mnbtvrchvbn.,bmvn.", "Default UA!1.0") returns None

      Then("create the Controller with mock components")

      // explicitely instatiating tested controller
      val controller = new CollectionsController(
        userService = mockUserService,
        emailService = mockEmailService,
        collectionsService = mockCollectionsService,
        authenticationAction = mockAuthenticationAction,
        optionalAuthenticationAction = mockOptionalAuthenticationAction,
        userAction = mockUserAction
      )

      Then("call request on the Controller")

      // behaviour for mocked underlying collections service when controller calls injected service functions
      mockCollectionsService.getOwcContextsForUserAndId(None, Some("fakeContextId")) returns Seq[OwcContext]()


      val fakeRequest = FakeRequest(routes.CollectionsController.getCollections(Some("fakeContextId")))
        .withHeaders("Content-Type" -> "application/json")
        .withHeaders("X-XSRF-TOKEN" -> "<KEY>

      val result = controller.getCollections(None).apply(FakeRequest())
      val otherResult = controller.getCollections(None).apply(fakeRequest)

      Then("response status must be ok and contain zero collections")
      status(otherResult.run) must be(OK)
      status(result.run) must be(OK)
      val jsbody = contentAsJson(result.run)
      println(Json.stringify(jsbody))
      jsbody mustEqual Json.parse("""{"count":0,"collections":[]}""")
      (jsbody \ "count").toOption mustBe defined
      (jsbody \ "count").as[Int] mustBe 0
      (jsbody \ "collections").asOpt[List[OwcContext]] must contain(List())


      // TODO now should be evaluated if big FakeModule thing, or explicit controller instances
    }

    // GET  /api/v1/collections controllers.CollectionsController.getCollections(id: Option[String])
    "request to getCollections(fakeContextId)" in {

      // behaviour for mocked underlying collections service when controller calls injected service functions
      mockCollectionsService.getOwcContextsForUserAndId(None, Some("fakeContextId")) returns Seq[OwcContext]()
      mockCollectionsService.getOwcContextsForUserAndId(Some(demodata.testUser1("xxx")), Some("fakeContextId")) returns Seq(demodata.owcContext1)
      mockUserService.getUserSessionByToken(anyString, anyString, anyString) returns Some(
        UserSession("sv56fb7n8m90pü,mnbtvrchvbn.,bmvn.",
          "Default UA/1.0",
          demodata.testUser1("xxx").email.value,
          "ACTIVE",
          ZonedDateTime.now(ZoneId.of("UTC"))))

      mockUserService.getUserSessionByToken("<PASSWORD>.", "<PASSWORD>,mnbtvrchvbn.,bmvn.", "Default UA/1.0") returns None<commit_msg>API support for frontend usergroups WIP updates (test fixes) #24<commit_after>/*
 * Copyright (C) 2011-2017 Interfaculty Department of Geoinformatics, University of
 * Salzburg (Z_GIS) & Institute of Geological and Nuclear Sciences Limited (GNS Science)
 * in the SMART Aquifer Characterisation (SAC) programme funded by the New Zealand
 * Ministry of Business, Innovation and Employment (MBIE)
 *
 * 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.
 */

import java.time.{ZoneId, ZonedDateTime}

import akka.stream.Materializer
import com.google.inject.AbstractModule
import com.typesafe.config.ConfigFactory
import controllers.security.{AuthenticationAction, OptionalAuthenticationAction, UserAction}
import controllers.{CollectionsController, routes}
import info.smart.models.owc100.OwcContext
import models.users.UserSession
import org.scalatest.TestData
import org.scalatestplus.play.OneAppPerTest
import org.specs2.mock._
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.json.Json
import play.api.mvc._
import play.api.test.Helpers._
import play.api.test._
import play.api.{Application, Configuration}
import services.{EmailService, OwcCollectionsService, UserService}
import utils.PasswordHashing


class CollectionsControllerSpec extends WithDefaultTest with OneAppPerTest with Results with Mockito {

  // creating mock instances for underlying required services for this controller
  private lazy val mockCollectionsService = mock[OwcCollectionsService].defaultReturn(Seq[OwcContext]())
  private lazy val mockEmailService = mock[EmailService]
  private lazy val mockUserService = mock[UserService].defaultReturn(None)
  private lazy val mockAuthenticationAction = mock[AuthenticationAction]
  private lazy val mockOptionalAuthenticationAction = mock[OptionalAuthenticationAction]
  private lazy val mockUserAction = mock[UserAction]

  // creating "fake" Guice Module to inject mock service instances into test application, with the required dependencies
  class FakeModule extends AbstractModule {
    def configure(): Unit = {
      bind(classOf[PasswordHashing]).asEagerSingleton()
      bind(classOf[UserService]).toInstance(mockUserService)
      bind(classOf[EmailService]).toInstance(mockEmailService)
      bind(classOf[OwcCollectionsService]).toInstance(mockCollectionsService)
    }
  }

  // Override newAppForTest if you need a FakeApplication with other than non-default parameters, incl. fake guice module
  import scala.language.implicitConversions

  implicit override def newAppForTest(testData: TestData): Application = new GuiceApplicationBuilder()
    .overrides(new FakeModule)
    .loadConfig(new Configuration(ConfigFactory.load("application.test.conf")))
    .build()

  // needed for routes execution on tested controller
  implicit lazy val materializer: Materializer = app.materializer

  val demodata = new DemoData

  "CollectionsController" when {

    "request to getCollections(None)" in {
      (pending)

      Then("create mock components, particular mocked CollectionsServive")

      // behaviour for mocked underlying collections service when controller calls injected service functions
      mockCollectionsService.queryOwcContextsForUserAndIdForViewing(None, None) returns Seq[OwcContext]()
      mockUserService.getUserSessionByToken("<KEY> "<PASSWORD>.,b<PASSWORD>.", "Default UA!1.0") returns None

      Then("create the Controller with mock components")

      // explicitely instatiating tested controller
      val controller = new CollectionsController(
        userService = mockUserService,
        emailService = mockEmailService,
        collectionsService = mockCollectionsService,
        authenticationAction = mockAuthenticationAction,
        optionalAuthenticationAction = mockOptionalAuthenticationAction,
        userAction = mockUserAction
      )

      Then("call request on the Controller")

      // behaviour for mocked underlying collections service when controller calls injected service functions
      mockCollectionsService.queryOwcContextsForUserAndIdForViewing(None, Some("fakeContextId")) returns Seq[OwcContext]()


      val fakeRequest = FakeRequest(routes.CollectionsController.getCollections(Some("fakeContextId")))
        .withHeaders("Content-Type" -> "application/json")
        .withHeaders("X-XSRF-TOKEN" -> "<PASSWORD>.")

      val result = controller.getCollections(None).apply(FakeRequest())
      val otherResult = controller.getCollections(None).apply(fakeRequest)

      Then("response status must be ok and contain zero collections")
      status(otherResult.run) must be(OK)
      status(result.run) must be(OK)
      val jsbody = contentAsJson(result.run)
      println(Json.stringify(jsbody))
      jsbody mustEqual Json.parse("""{"count":0,"collections":[]}""")
      (jsbody \ "count").toOption mustBe defined
      (jsbody \ "count").as[Int] mustBe 0
      (jsbody \ "collections").asOpt[List[OwcContext]] must contain(List())


      // TODO now should be evaluated if big FakeModule thing, or explicit controller instances
    }

    // GET  /api/v1/collections controllers.CollectionsController.getCollections(id: Option[String])
    "request to getCollections(fakeContextId)" in {

      // behaviour for mocked underlying collections service when controller calls injected service functions
      mockCollectionsService.queryOwcContextsForUserAndIdForViewing(None, Some("fakeContextId")) returns Seq[OwcContext]()
      mockCollectionsService.getOwcContextsForUserAndId(demodata.testUser1("xxx"), Some("fakeContextId")) returns Seq(demodata.owcContext1)
      mockUserService.getUserSessionByToken(anyString, anyString, anyString) returns Some(
        UserSession("sv56fb7n8m90pü,mnbtvrchvbn.,bmvn.",
          "Default UA/1.0",
          demodata.testUser1("xxx").email.value,
          "ACTIVE",
          ZonedDateTime.now(ZoneId.of("UTC"))))

      mockUserService.getUserSessionByToken("<PASSWORD>.", "sv56fb7n8m90pü,mnbtvrchvbn.,bmvn.", "Default UA/1.0") returns None
{'fraction_non_alphanumeric': 0.08602316602316602, 'fraction_numerical': 0.005868725868725869, 'mean_word_length': 4.7103174603174605, 'pattern_counts': {'":': 4, '<': 13, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, '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': '6067283', 'n_tokens_mistral': 3418, 'n_tokens_neox': 3326, 'n_words': 958}