org.specs2.specification.Scope Scala Examples

The following examples show how to use org.specs2.specification.Scope. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: JsonJacksonMarshallerTest.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.json

import java.time.LocalDateTime
import java.util.Optional

import com.fasterxml.jackson.databind.ObjectMapper
import com.wix.e2e.http.api.Marshaller
import com.wix.e2e.http.json.MarshallingTestObjects.SomeCaseClass
import com.wix.test.random._
import org.joda.time.DateTimeZone.UTC
import org.joda.time.{DateTime, DateTimeZone}
import org.specs2.mutable.Spec
import org.specs2.specification.Scope

class JsonJacksonMarshallerTest extends Spec {

  trait ctx extends Scope {
    val someStr = randomStr
    val javaDateTime = LocalDateTime.now()
    val someCaseClass = SomeCaseClass(randomStr, randomInt)
    val dateTime = new DateTime
    val dateTimeUTC = new DateTime(UTC)

    val marshaller: Marshaller = new JsonJacksonMarshaller
  }


  "JsonJacksonMarshaller" should {

    "marshall scala option properly" in new ctx {
      marshaller.unmarshall[Option[String]](
        marshaller.marshall( Some(someStr) )
      ) must beSome(someStr)
    }

    "marshall scala case classes properly" in new ctx {
      marshaller.unmarshall[SomeCaseClass](
        marshaller.marshall( someCaseClass )
      ) must_=== someCaseClass
    }

    "marshall datetime without zone" in new ctx {
      marshaller.unmarshall[DateTime](
        marshaller.marshall( dateTime.withZone(DateTimeZone.getDefault) )
      ) must_=== dateTime.withZone(UTC)
    }

    "marshall date time to textual format in UTC" in new ctx {
      marshaller.marshall( dateTime ) must contain(dateTime.withZone(UTC).toString)
    }


    "marshall java.time objects" in new ctx {
      marshaller.unmarshall[LocalDateTime](
        marshaller.marshall( javaDateTime )
      ) must_=== javaDateTime

    }

    "marshall java 8 Optional" in new ctx {
      marshaller.unmarshall[Optional[DateTime]](
        marshaller.marshall( dateTimeUTC )
      ) must_=== Optional.of(dateTimeUTC)

      marshaller.unmarshall[Optional[SomeCaseClass]](
        marshaller.marshall( someCaseClass )
      ) must_=== Optional.of(someCaseClass)
    }

    "expose jackson object mapper to allow external configuration" in new ctx {
      marshaller.asInstanceOf[JsonJacksonMarshaller].configure must beAnInstanceOf[ObjectMapper]
    }
  }
}

object MarshallingTestObjects {
  case class SomeCaseClass(s: String, i: Int)
} 
Example 2
Source File: ResponseHeadersMatchersTest.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.matchers.internal

import com.wix.e2e.http.matchers.ResponseMatchers._
import com.wix.e2e.http.matchers.drivers.HttpResponseFactory._
import com.wix.e2e.http.matchers.drivers.{HttpMessageTestSupport, MatchersTestSupport}
import org.specs2.matcher.AlwaysMatcher
import org.specs2.mutable.Spec
import org.specs2.specification.Scope


class ResponseHeadersMatchersTest extends Spec with MatchersTestSupport {

  trait ctx extends Scope with HttpMessageTestSupport

  "ResponseHeadersMatchers" should {

    "contain header will check if any header is present" in new ctx {
      aResponseWithHeaders(header, anotherHeader) must haveAnyHeadersOf(header)
    }

    "return detailed message on hasAnyOf match failure" in new ctx {
      failureMessageFor(haveAnyHeadersOf(header, anotherHeader), matchedOn = aResponseWithHeaders(yetAnotherHeader, andAnotherHeader)) must_===
        s"Could not find header [${header._1}, ${anotherHeader._1}] but found those: [${yetAnotherHeader._1}, ${andAnotherHeader._1}]"
    }

    "contain header will check if all headers are present" in new ctx {
      aResponseWithHeaders(header, anotherHeader, yetAnotherHeader) must haveAllHeadersOf(header, anotherHeader)
    }

    "allOf matcher will return a message stating what was found, and what is missing from header list" in new ctx {
      failureMessageFor(haveAllHeadersOf(header, anotherHeader), matchedOn = aResponseWithHeaders(yetAnotherHeader, header)) must_===
        s"Could not find header [${anotherHeader._1}] but found those: [${header._1}]."
    }

    "same header as will check if the same headers is present" in new ctx {
      aResponseWithHeaders(header, anotherHeader) must haveTheSameHeadersAs(header, anotherHeader)
      aResponseWithHeaders(header, anotherHeader) must not( haveTheSameHeadersAs(header) )
      aResponseWithHeaders(header) must not( haveTheSameHeadersAs(header, anotherHeader) )
    }

    "haveTheSameHeadersAs matcher will return a message stating what was found, and what is missing from header list" in new ctx {
      failureMessageFor(haveTheSameHeadersAs(header, anotherHeader), matchedOn = aResponseWithHeaders(yetAnotherHeader, header)) must_===
        s"Response header is not identical, missing headers from response: [${anotherHeader._1}], response contained extra headers: [${yetAnotherHeader._1}]."
    }

    "header name compare should be case insensitive" in new ctx {
      aResponseWithHeaders(header) must haveAnyHeadersOf(header.copy(_1 = header._1.toUpperCase))
      aResponseWithHeaders(header) must not( haveAnyHeadersOf(header.copy(_2 = header._2.toUpperCase)) )

      aResponseWithHeaders(header) must haveAllHeadersOf(header.copy(_1 = header._1.toUpperCase))
      aResponseWithHeaders(header) must not( haveAllHeadersOf(header.copy(_2 = header._2.toUpperCase)) )

      aResponseWithHeaders(header) must haveTheSameHeadersAs(header.copy(_1 = header._1.toUpperCase))
      aResponseWithHeaders(header) must not( haveTheSameHeadersAs(header.copy(_2 = header._2.toUpperCase)) )
    }
    
    "response with no headers will show a 'no headers' message" in new ctx {
      failureMessageFor(haveAnyHeadersOf(header), matchedOn = aResponseWithNoHeaders ) must_===
        "Response did not contain any headers."

      failureMessageFor(haveAllHeadersOf(header), matchedOn = aResponseWithNoHeaders ) must_===
        "Response did not contain any headers."

      failureMessageFor(haveTheSameHeadersAs(header), matchedOn = aResponseWithNoHeaders ) must_===
        "Response did not contain any headers."
    }

    "ignore cookies and set cookies from headers comparison" in new ctx {
      aResponseWithCookies(cookie) must not( haveAnyHeadersOf("Set-Cookie" -> s"${cookie.name}=${cookie.value}") )
      aResponseWithCookies(cookie) must not( haveAllHeadersOf("Set-Cookie" -> s"${cookie.name}=${cookie.value}") )
      aResponseWithCookies(cookie) must not( haveTheSameHeadersAs("Set-Cookie" -> s"${cookie.name}=${cookie.value}") )
    }

    "match if any header satisfy the composed matcher" in new ctx {
      aResponseWithHeaders(header) must haveAnyHeaderThat(must = be_===(header._2), withHeaderName = header._1)
      aResponseWithHeaders(header) must not( haveAnyHeaderThat(must = be_===(anotherHeader._2), withHeaderName = header._1) )
    }

    "return informative error messages" in new ctx {
      failureMessageFor(haveAnyHeaderThat(must = AlwaysMatcher(), withHeaderName = nonExistingHeaderName), matchedOn = aResponseWithHeaders(header)) must_===
        s"Response contain header names: [${header._1}] which did not contain: [$nonExistingHeaderName]"
      failureMessageFor(haveAnyHeaderThat(must = AlwaysMatcher(), withHeaderName = nonExistingHeaderName), matchedOn = aResponseWithNoHeaders) must_===
        "Response did not contain any headers."
      failureMessageFor(haveAnyHeaderThat(must = be_===(anotherHeader._2), withHeaderName = header._1), matchedOn = aResponseWithHeaders(header)) must_===
        s"Response header [${header._1}], did not match { ${be_===(anotherHeader._2).apply(header._2).message} }"
    }
  }
} 
Example 3
Source File: ResponseCookiesMatchersTest.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.matchers.internal

import com.wix.e2e.http.matchers.ResponseMatchers._
import com.wix.e2e.http.matchers.drivers.HttpResponseFactory._
import com.wix.e2e.http.matchers.drivers.HttpResponseMatchers._
import com.wix.e2e.http.matchers.drivers.{HttpMessageTestSupport, MatchersTestSupport}
import org.specs2.matcher.Matchers._
import org.specs2.mutable.Spec
import org.specs2.specification.Scope


class ResponseCookiesMatchersTest extends Spec with MatchersTestSupport {

  trait ctx extends Scope with HttpMessageTestSupport

  "ResponseCookiesMatchers" should {

    "match if cookie with name is found" in new ctx {
      aResponseWithCookies(cookie) must receivedCookieWith(cookie.name)
    }

    "failure message should describe which cookies are present and which did not match" in new ctx {
      failureMessageFor(receivedCookieWith(cookie.name), matchedOn = aResponseWithCookies(anotherCookie, yetAnotherCookie)) must
        contain(cookie.name) and contain(anotherCookie.name) and contain(yetAnotherCookie.name)
    }

    "failure message for response withoout cookies will print that the response did not contain any cookies" in new ctx {
      receivedCookieWith(cookie.name).apply( aResponseWithNoCookies ).message must
        contain("Response did not contain any `Set-Cookie` headers.")
    }

    "allow to compose matcher with custom cookie matcher" in new ctx {
      aResponseWithCookies(cookie) must receivedCookieThat(must = cookieWith(cookie.value))
    }
  }
} 
Example 4
Source File: RequestBodyMatchersTest.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.matchers.internal

import com.wix.e2e.http.matchers.RequestMatchers._
import com.wix.e2e.http.matchers.drivers.HttpRequestFactory._
import com.wix.e2e.http.matchers.drivers.MarshallingTestObjects.SomeCaseClass
import com.wix.e2e.http.matchers.drivers.{CustomMarshallerProvider, HttpMessageTestSupport, MarshallerTestSupport, MatchersTestSupport}
import org.specs2.matcher.CaseClassDiffs._
import org.specs2.matcher.ResultMatchers._
import org.specs2.mutable.Spec
import org.specs2.specification.Scope

class RequestBodyMatchersTest extends Spec with MatchersTestSupport {

  trait ctx extends Scope with HttpMessageTestSupport with MarshallerTestSupport with CustomMarshallerProvider

  "ResponseBodyMatchers" should {

    "exact match on response body" in new ctx {
      aRequestWith(content) must haveBodyWith(content)
      aRequestWith(content) must not( haveBodyWith(anotherContent) )
    }

    "match underlying matcher with body content" in new ctx {
      aRequestWith(content) must haveBodyThat(must = be_===( content ))
      aRequestWith(content) must not( haveBodyThat(must = be_===( anotherContent )) )
    }

    "exact match on response binary body" in new ctx {
      aRequestWith(binaryContent) must haveBodyWith(binaryContent)
      aRequestWith(binaryContent) must not( haveBodyWith(anotherBinaryContent) )
    }

    "match underlying matcher with binary body content" in new ctx {
      aRequestWith(binaryContent) must haveBodyDataThat(must = be_===( binaryContent ))
      aRequestWith(binaryContent) must not( haveBodyDataThat(must = be_===( anotherBinaryContent )) )
    }

    "handle empty body" in new ctx {
      aRequestWithoutBody must not( haveBodyWith(content))
    }

    "support unmarshalling body content with user custom unmarshaller" in new ctx {
      givenUnmarshallerWith[SomeCaseClass](someObject, forContent = content)

      aRequestWith(content) must haveBodyWith(entity = someObject)
      aRequestWith(content) must not( haveBodyWith(entity = anotherObject) )
    }

    "provide a meaningful explanation why match failed" in new ctx {
      givenUnmarshallerWith[SomeCaseClass](someObject, forContent = content)

      failureMessageFor(haveBodyEntityThat(must = be_===(anotherObject)), matchedOn = aRequestWith(content)) must_===
        s"Failed to match: [SomeCaseClass(s: '${someObject.s}' != '${anotherObject.s}',              i: ${someObject.i} != ${anotherObject.i})] with content: [$content]"
    }

    "provide a proper message to user sent a matcher to an entity matcher" in new ctx {
      failureMessageFor(haveBodyWith(entity = be_===(someObject)), matchedOn = aRequestWith(content)) must_===
        "Matcher misuse: `haveBodyWith` received a matcher to match against, please use `haveBodyThat` instead."
    }

    "provide a proper message to user in case of a badly behaving marshaller" in new ctx {
      givenBadlyBehavingUnmarshallerFor[SomeCaseClass](withContent = content)

      haveBodyWith(entity = someObject).apply( aRequestWith(content) ) must beError(s"Failed to unmarshall: \\[$content\\]")
    }

    "support custom matcher for user object" in new ctx {
      givenUnmarshallerWith[SomeCaseClass](someObject, forContent = content)

      aRequestWith(content) must haveBodyEntityThat(must = be_===(someObject))
      aRequestWith(content) must not( haveBodyEntityThat(must = be_===(anotherObject)) )
    }
  }
} 
Example 5
Source File: ResponseBodyAndStatusMatchersTest.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.matchers.internal

import com.wix.e2e.http.api.Marshaller.Implicits.marshaller
import com.wix.e2e.http.matchers.ResponseMatchers._
import com.wix.e2e.http.matchers.drivers.HttpResponseFactory._
import com.wix.e2e.http.matchers.drivers.HttpResponseMatchers._
import com.wix.e2e.http.matchers.drivers.{HttpMessageTestSupport, MatchersTestSupport}
import org.specs2.mutable.Spec
import org.specs2.specification.Scope


class ResponseBodyAndStatusMatchersTest extends Spec with MatchersTestSupport {

  trait ctx extends Scope with HttpMessageTestSupport


  "ResponseBodyAndStatusMatchers" should {

    "match successful response with body content" in new ctx {
      aSuccessfulResponseWith(content) must beSuccessfulWith(content)
      aSuccessfulResponseWith(content) must not( beSuccessfulWith(anotherContent) )
    }

    "provide a proper message to user sent a matcher to an entity matcher" in new ctx {
      failureMessageFor(beSuccessfulWith(entity = be_===(content)), matchedOn = aResponseWith(content)) must_===
        s"Matcher misuse: `beSuccessfulWith` received a matcher to match against, please use `beSuccessfulWithEntityThat` instead."
    }

    "match successful response with body content matcher" in new ctx {
      aSuccessfulResponseWith(content) must beSuccessfulWithBodyThat(must = be_===( content ))
      aSuccessfulResponseWith(content) must not( beSuccessfulWithBodyThat(must = be_===( anotherContent )) )
    }

    "match invalid response with body content" in new ctx {
      anInvalidResponseWith(content) must beInvalidWith(content)
      anInvalidResponseWith(content) must not( beInvalidWith(anotherContent) )
    }

    "match invalid response with body content matcher" in new ctx {
      anInvalidResponseWith(content) must beInvalidWithBodyThat(must = be_===( content ))
      anInvalidResponseWith(content) must not( beInvalidWithBodyThat(must = be_===( anotherContent )) )
    }

    "match successful response with binary body content" in new ctx {
      aSuccessfulResponseWith(binaryContent) must beSuccessfulWith(binaryContent)
      aSuccessfulResponseWith(binaryContent) must not( beSuccessfulWith(anotherBinaryContent) )
    }

    "match successful response with binary body content matcher" in new ctx {
      aSuccessfulResponseWith(binaryContent) must beSuccessfulWithBodyDataThat(must = be_===( binaryContent ))
      aSuccessfulResponseWith(binaryContent) must not( beSuccessfulWithBodyDataThat(must = be_===( anotherBinaryContent )) )
    }

    "match successful response with entity" in new ctx {
      aSuccessfulResponseWith(marshaller.marshall(someObject)) must beSuccessfulWith( someObject )
      aSuccessfulResponseWith(marshaller.marshall(someObject)) must not( beSuccessfulWith( anotherObject ) )
    }

    "match successful response with entity with custom marshaller" in new ctx {
      aSuccessfulResponseWith(marshaller.marshall(someObject)) must beSuccessfulWith( someObject )
      aSuccessfulResponseWith(marshaller.marshall(someObject)) must not( beSuccessfulWith( anotherObject ) )
    }

    "match successful response with entity matcher" in new ctx {
      aSuccessfulResponseWith(marshaller.marshall(someObject)) must beSuccessfulWithEntityThat( must = be_===( someObject ) )
      aSuccessfulResponseWith(marshaller.marshall(someObject)) must not( beSuccessfulWithEntityThat( must = be_===( anotherObject ) ) )
    }

    "match successful response with headers" in new ctx {
      aSuccessfulResponseWith(header, anotherHeader) must beSuccessfulWithHeaders(header, anotherHeader)
      aSuccessfulResponseWith(header) must not( beSuccessfulWithHeaders(anotherHeader) )
    }

    "match successful response with header matcher" in new ctx {
      aSuccessfulResponseWith(header) must beSuccessfulWithHeaderThat(must = be_===(header._2), withHeaderName = header._1)
      aSuccessfulResponseWith(header) must not( beSuccessfulWithHeaderThat(must = be_===(anotherHeader._2), withHeaderName = header._1) )
    }

    "match successful response with cookies" in new ctx {
      aSuccessfulResponseWithCookies(cookie, anotherCookie) must beSuccessfulWithCookie(cookie.name)
      aSuccessfulResponseWithCookies(cookie) must not( beSuccessfulWithCookie(anotherCookie.name) )
    }

    "match successful response with cookie matcher" in new ctx {
      aSuccessfulResponseWithCookies(cookie) must beSuccessfulWithCookieThat(must = cookieWith(cookie.value))
      aSuccessfulResponseWithCookies(cookie) must not( beSuccessfulWithCookieThat(must = cookieWith(anotherCookie.value)) )
    }

    "provide a proper message to user sent a matcher to an entity matcher" in new ctx {
      failureMessageFor(haveBodyWith(entity = be_===(someObject)), matchedOn = aResponseWith(content)) must_===
        s"Matcher misuse: `haveBodyWith` received a matcher to match against, please use `haveBodyWithEntityThat` instead."
    }
  }
} 
Example 6
Source File: ResponseStatusMatchersTest.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.matchers.internal


import akka.http.scaladsl.model.StatusCodes._
import com.wix.e2e.http.matchers.ResponseMatchers._
import com.wix.e2e.http.matchers.drivers.HttpResponseFactory._
import com.wix.e2e.http.matchers.drivers.HttpMessageTestSupport
import org.specs2.mutable.Spec
import org.specs2.specification.Scope


class ResponseStatusMatchersTest extends Spec {

  trait ctx extends Scope with HttpMessageTestSupport


  "ResponseStatusMatchers" should {
      Seq(OK -> beSuccessful, NoContent -> beNoContent, Created -> beSuccessfullyCreated, Accepted -> beAccepted, // 2xx

          Found -> beRedirect, MovedPermanently -> bePermanentlyRedirect, //3xx

          // 4xx
          Forbidden -> beRejected, NotFound -> beNotFound, BadRequest -> beInvalid, RequestEntityTooLarge -> beRejectedTooLarge,
          Unauthorized -> beUnauthorized, MethodNotAllowed -> beNotSupported, Conflict -> beConflict, PreconditionFailed -> bePreconditionFailed,
          UnprocessableEntity -> beUnprocessableEntity, PreconditionRequired -> bePreconditionRequired, TooManyRequests -> beTooManyRequests,

          ServiceUnavailable -> beUnavailable, InternalServerError -> beInternalServerError, NotImplemented -> beNotImplemented // 5xx
         ).foreach { case (status, matcherForStatus) =>

        s"match against status ${status.value}" in new ctx {
          aResponseWith( status ) must matcherForStatus
          aResponseWith( randomStatusThatIsNot(status) ) must not( matcherForStatus )
        }
      }

    "allow matching against status code" in new ctx {
      val status = randomStatus
      aResponseWith( status ) must haveStatus(code = status.intValue )
      aResponseWith( status ) must not( haveStatus(code = randomStatusThatIsNot(status).intValue ) )
    }
  }
} 
Example 7
Source File: RequestUrlMatchersTest.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.matchers.internal

import com.wix.e2e.http.matchers.RequestMatchers._
import com.wix.e2e.http.matchers.drivers.HttpRequestFactory._
import com.wix.e2e.http.matchers.drivers.{HttpMessageTestSupport, MatchersTestSupport}
import org.specs2.matcher.AlwaysMatcher
import org.specs2.mutable.Spec
import org.specs2.specification.Scope


class RequestUrlMatchersTest extends Spec with MatchersTestSupport {

  trait ctx extends Scope with HttpMessageTestSupport

  "RequestUrlMatchers" should {

    "match exact path" in new ctx {
      aRequestWithPath(somePath) must havePath(somePath)
      aRequestWithPath(somePath) must not( havePath(anotherPath) )
    }

    "match exact path matcher" in new ctx {
      aRequestWithPath(somePath) must havePathThat(must = be_===( somePath ))
      aRequestWithPath(somePath) must not( havePathThat(must = be_===( anotherPath )) )
    }
    // if first ignore first slash ???

    "contain parameter will check if any parameter is present" in new ctx {
      aRequestWithParameters(parameter, anotherParameter) must haveAnyParamOf(parameter)
      aRequestWithParameters(parameter) must not( haveAnyParamOf(anotherParameter) )
    }

    "return detailed message on hasAnyOf match failure" in new ctx {
      failureMessageFor(haveAnyParamOf(parameter, anotherParameter), matchedOn = aRequestWithParameters(yetAnotherParameter, andAnotherParameter)) must_===
        s"Could not find parameter [${parameter._1}, ${anotherParameter._1}] but found those: [${yetAnotherParameter._1}, ${andAnotherParameter._1}]"
    }

    "contain parameter will check if all parameters are present" in new ctx {
      aRequestWithParameters(parameter, anotherParameter, yetAnotherParameter) must haveAllParamFrom(parameter, anotherParameter)
      aRequestWithParameters(parameter, yetAnotherParameter) must not( haveAllParamFrom(parameter, anotherParameter) )
    }

    "allOf matcher will return a message stating what was found, and what is missing from parameter list" in new ctx {
      failureMessageFor(haveAllParamFrom(parameter, anotherParameter), matchedOn = aRequestWithParameters(parameter, yetAnotherParameter)) must_===
        s"Could not find parameter [${anotherParameter._1}] but found those: [${parameter._1}]."
    }

    "same parameter as will check if the same parameters is present" in new ctx {
      aRequestWithParameters(parameter, anotherParameter) must haveTheSameParamsAs(parameter, anotherParameter)
      aRequestWithParameters(parameter, anotherParameter) must not( haveTheSameParamsAs(parameter) )
      aRequestWithParameters(parameter) must not( haveTheSameParamsAs(parameter, anotherParameter) )
    }

    "haveTheSameParametersAs matcher will return a message stating what was found, and what is missing from parameter list" in new ctx {
      failureMessageFor(haveTheSameParamsAs(parameter, anotherParameter), matchedOn = aRequestWithParameters(parameter, yetAnotherParameter)) must_===
        s"Request parameters are not identical, missing parameters from request: [${anotherParameter._1}], request contained extra parameters: [${yetAnotherParameter._1}]."
    }

    "request with no parameters will show a 'no parameters' message" in new ctx {
      failureMessageFor(haveAnyParamOf(parameter), matchedOn = aRequestWithNoParameters ) must_===
        "Request did not contain any request parameters."

      failureMessageFor(haveAllParamFrom(parameter), matchedOn = aRequestWithNoParameters ) must_===
        "Request did not contain any request parameters."

      failureMessageFor(haveTheSameParamsAs(parameter), matchedOn = aRequestWithNoParameters ) must_===
        "Request did not contain any request parameters."
    }

    "match if any parameter satisfy the composed matcher" in new ctx {
      aRequestWithParameters(parameter) must haveAnyParamThat(must = be_===(parameter._2), withParamName = parameter._1)
      aRequestWithParameters(parameter) must not( haveAnyParamThat(must = be_===(anotherParameter._2), withParamName = anotherParameter._1) )
    }

    "return informative error messages" in new ctx {
      failureMessageFor(haveAnyParamThat(must = AlwaysMatcher(), withParamName = nonExistingParamName), matchedOn = aRequestWithParameters(parameter)) must_===
        s"Request contain parameter names: [${parameter._1}] which did not contain: [$nonExistingParamName]"
      failureMessageFor(haveAnyParamThat(must = AlwaysMatcher(), withParamName = nonExistingParamName), matchedOn = aRequestWithNoParameters) must_===
        "Request did not contain any parameters."
      failureMessageFor(haveAnyParamThat(must = be_===(anotherParameter._2), withParamName = parameter._1), matchedOn = aRequestWithParameters(parameter)) must_===
        s"Request parameter [${parameter._1}], did not match { ${be_===(anotherParameter._2).apply(parameter._2).message} }"
    }
  }
} 
Example 8
Source File: RequestHeadersMatchersTest.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.matchers.internal

import com.wix.e2e.http.matchers.RequestMatchers._
import com.wix.e2e.http.matchers.drivers.HttpRequestFactory._
import com.wix.e2e.http.matchers.drivers.{HttpMessageTestSupport, MatchersTestSupport}
import org.specs2.matcher.AlwaysMatcher
import org.specs2.mutable.Spec
import org.specs2.specification.Scope


class RequestHeadersMatchersTest extends Spec with MatchersTestSupport {

  trait ctx extends Scope with HttpMessageTestSupport

  "RequestHeadersMatchers" should {

    "contain header will check if any header is present" in new ctx {
      aRequestWithHeaders(header, anotherHeader) must haveAnyHeadersOf(header)
    }

    "return detailed message on hasAnyOf match failure" in new ctx {
      failureMessageFor(haveAnyHeadersOf(header, anotherHeader), matchedOn = aRequestWithHeaders(yetAnotherHeader, andAnotherHeader)) must_===
        s"Could not find header [${header._1}, ${anotherHeader._1}] but found those: [${yetAnotherHeader._1}, ${andAnotherHeader._1}]"
    }

    "contain header will check if all headers are present" in new ctx {
      aRequestWithHeaders(header, anotherHeader, yetAnotherHeader) must haveAllHeadersOf(header, anotherHeader)
    }

    "allOf matcher will return a message stating what was found, and what is missing from header list" in new ctx {
      failureMessageFor(haveAllHeadersOf(header, anotherHeader), matchedOn = aRequestWithHeaders(yetAnotherHeader, header)) must_===
        s"Could not find header [${anotherHeader._1}] but found those: [${header._1}]."
    }

    "same header as will check if the same headers is present" in new ctx {
      aRequestWithHeaders(header, anotherHeader) must haveTheSameHeadersAs(header, anotherHeader)
      aRequestWithHeaders(header, anotherHeader) must not( haveTheSameHeadersAs(header) )
      aRequestWithHeaders(header) must not( haveTheSameHeadersAs(header, anotherHeader) )
    }

    "haveTheSameHeadersAs matcher will return a message stating what was found, and what is missing from header list" in new ctx {
      failureMessageFor(haveTheSameHeadersAs(header, anotherHeader), matchedOn = aRequestWithHeaders(yetAnotherHeader, header)) must_===
        s"Request header is not identical, missing headers from request: [${anotherHeader._1}], request contained extra headers: [${yetAnotherHeader._1}]."
    }

    "header name compare should be case insensitive" in new ctx {
      aRequestWithHeaders(header) must haveAnyHeadersOf(header.copy(_1 = header._1.toUpperCase))
      aRequestWithHeaders(header) must not( haveAnyHeadersOf(header.copy(_2 = header._2.toUpperCase)) )

      aRequestWithHeaders(header) must haveAllHeadersOf(header.copy(_1 = header._1.toUpperCase))
      aRequestWithHeaders(header) must not( haveAllHeadersOf(header.copy(_2 = header._2.toUpperCase)) )

      aRequestWithHeaders(header) must haveTheSameHeadersAs(header.copy(_1 = header._1.toUpperCase))
      aRequestWithHeaders(header) must not( haveTheSameHeadersAs(header.copy(_2 = header._2.toUpperCase)) )
    }

    "request with no headers will show a 'no headers' message" in new ctx {
      failureMessageFor(haveAnyHeadersOf(header), matchedOn = aRequestWithNoHeaders ) must_===
        "Request did not contain any headers."

      failureMessageFor(haveAllHeadersOf(header), matchedOn = aRequestWithNoHeaders ) must_===
        "Request did not contain any headers."

      failureMessageFor(haveTheSameHeadersAs(header), matchedOn = aRequestWithNoHeaders ) must_===
        "Request did not contain any headers."
    }

    "ignore cookies and set cookies from headers comparison" in new ctx {
      aRequestWithCookies(cookiePair) must not( haveAnyHeadersOf("Cookie" -> s"${cookiePair._1}=${cookiePair._2}") )
      aRequestWithCookies(cookiePair) must not( haveAllHeadersOf("Cookie" -> s"${cookiePair._1}=${cookiePair._2}") )
      aRequestWithCookies(cookiePair) must not( haveTheSameHeadersAs("Cookie" -> s"${cookiePair._1}=${cookiePair._2}") )
      aRequestWithCookies(cookiePair) must not( haveAnyHeaderThat(must = be_===(s"${cookiePair._1}=${cookiePair._2}"), withHeaderName = "Cookie") )
    }

    "match if any header satisfy the composed matcher" in new ctx {
      aRequestWithHeaders(header) must haveAnyHeaderThat(must = be_===(header._2), withHeaderName = header._1)
      aRequestWithHeaders(header) must not( haveAnyHeaderThat(must = be_===(anotherHeader._2), withHeaderName = header._1) )
    }

    "return informative error messages" in new ctx {
      failureMessageFor(haveAnyHeaderThat(must = AlwaysMatcher(), withHeaderName = nonExistingHeaderName), matchedOn = aRequestWithHeaders(header)) must_===
        s"Request contain header names: [${header._1}] which did not contain: [$nonExistingHeaderName]"
      failureMessageFor(haveAnyHeaderThat(must = AlwaysMatcher(), withHeaderName = nonExistingHeaderName), matchedOn = aRequestWithNoHeaders) must_===
        "Request did not contain any headers."
      failureMessageFor(haveAnyHeaderThat(must = be_===(anotherHeader._2), withHeaderName = header._1), matchedOn = aRequestWithHeaders(header)) must_===
        s"Request header [${header._1}], did not match { ${be_===(anotherHeader._2).apply(header._2).message} }"
    }
  }
} 
Example 9
Source File: ResponseContentTypeMatchersTest.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.matchers.internal

import com.wix.e2e.http.matchers.ResponseMatchers._
import com.wix.e2e.http.matchers.drivers.HttpResponseFactory._
import com.wix.e2e.http.matchers.drivers.{HttpMessageTestSupport, MatchersTestSupport}
import org.specs2.mutable.Spec
import org.specs2.specification.Scope


class ResponseContentTypeMatchersTest extends Spec with MatchersTestSupport {

  trait ctx extends Scope with HttpMessageTestSupport


  "ResponseContentTypeMatchers" should {

    "support matching against json content type" in new ctx {
      aResponseWithContentType("application/json") must beJsonResponse
      aResponseWithContentType("text/plain") must not( beJsonResponse )
    }

    "support matching against text plain content type" in new ctx {
      aResponseWithContentType("text/plain") must beTextPlainResponse
      aResponseWithContentType("application/json") must not( beTextPlainResponse )
    }

    "support matching against form url encoded content type" in new ctx {
      aResponseWithContentType("application/x-www-form-urlencoded") must beFormUrlEncodedResponse
      aResponseWithContentType("application/json") must not( beFormUrlEncodedResponse )
    }

    "show proper error in case matching against a malformed content type" in new ctx {
      failureMessageFor(haveContentType(malformedContentType), matchedOn = aResponseWithContentType(anotherContentType)) must
        contain(s"Cannot match against a malformed content type: $malformedContentType")
    }

    "support matching against content type" in new ctx {
      aResponseWithContentType(contentType) must haveContentType(contentType)
    }

    "failure message should describe what was the expected content type and what was found" in new ctx {
      failureMessageFor(haveContentType(contentType), matchedOn = aResponseWithContentType(anotherContentType)) must_===
        s"Expected content type [$contentType] does not match actual content type [$anotherContentType]"
    }

    "failure message in case no content type for body should be handled" in new ctx {
      failureMessageFor(haveContentType(contentType), matchedOn = aResponseWithoutBody) must_===
        "Response body does not have a set content type"
    }

    "failure message if someone tries to match content-type in headers matchers" in new ctx {
      failureMessageFor(haveAllHeadersOf(contentTypeHeader), matchedOn = aResponseWithContentType(contentType)) must_===
        """`Content-Type` is a special header and cannot be used in `haveAnyHeadersOf`, `haveAllHeadersOf`, `haveTheSameHeadersAs` matchers.
          |Use `haveContentType` matcher instead (or `beJsonResponse`, `beTextPlainResponse`, `beFormUrlEncodedResponse`).""".stripMargin
      failureMessageFor(haveAnyHeadersOf(contentTypeHeader), matchedOn = aResponseWithContentType(contentType)) must_===
        """`Content-Type` is a special header and cannot be used in `haveAnyHeadersOf`, `haveAllHeadersOf`, `haveTheSameHeadersAs` matchers.
          |Use `haveContentType` matcher instead (or `beJsonResponse`, `beTextPlainResponse`, `beFormUrlEncodedResponse`).""".stripMargin
      failureMessageFor(haveTheSameHeadersAs(contentTypeHeader), matchedOn = aResponseWithContentType(contentType)) must_===
        """`Content-Type` is a special header and cannot be used in `haveAnyHeadersOf`, `haveAllHeadersOf`, `haveTheSameHeadersAs` matchers.
          |Use `haveContentType` matcher instead (or `beJsonResponse`, `beTextPlainResponse`, `beFormUrlEncodedResponse`).""".stripMargin
    }
  }
} 
Example 10
Source File: RequestRecorderMatchersTest.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.matchers.internal

import com.wix.e2e.http.matchers.RequestMatchers._
import com.wix.e2e.http.matchers.drivers.RequestRecorderFactory._
import com.wix.e2e.http.matchers.drivers.{MatchersTestSupport, RequestRecorderTestSupport}
import org.specs2.matcher.AlwaysMatcher
import org.specs2.mutable.Spec
import org.specs2.specification.Scope

class RequestRecorderMatchersTest extends Spec with MatchersTestSupport {

  trait ctx extends Scope with RequestRecorderTestSupport

  "RequestRecorderMatchers" should {

    "check that request recorder has any of the given requests" in new ctx {
      aRequestRecorderWith(request, anotherRequest) must receivedAnyOf(request)
      aRequestRecorderWith(request) must not( receivedAnyOf(anotherRequest) )
    }

    "return detailed message on hasAnyOf match failure" in new ctx {
      failureMessageFor(receivedAnyOf(request, anotherRequest), matchedOn = aRequestRecorderWith(yetAnotherRequest, yetAnotherRequest)) must_===
        s"""Could not find requests:
           |1: $request,
           |2: $anotherRequest
           |
           |but found those:
           |1: $yetAnotherRequest,
           |2: $yetAnotherRequest""".stripMargin
    }

    "contain header will check if all requests are present" in new ctx {
      aRequestRecorderWith(request, anotherRequest, yetAnotherRequest) must receivedAllOf(request, anotherRequest)
      aRequestRecorderWith(request) must not( receivedAllOf(request, anotherRequest) )
    }

    "allOf matcher will return a message stating what was found, and what is missing from recorded requests list" in new ctx {
      failureMessageFor(receivedAllOf(request, anotherRequest), matchedOn = aRequestRecorderWith(request, yetAnotherRequest)) must_===
        s"""Could not find requests:
            |1: $anotherRequest
            |
            |but found those:
            |1: $request""".stripMargin
    }

    "same request as will check if the same requests is present" in new ctx {
      aRequestRecorderWith(request, anotherRequest) must receivedTheSameRequestsAs(request, anotherRequest)
      aRequestRecorderWith(request, anotherRequest) must not( receivedTheSameRequestsAs(request) )
      aRequestRecorderWith(request) must not( receivedTheSameRequestsAs(request, anotherRequest) )
    }

    "receivedTheSameRequestsAs matcher will return a message stating what was found, and what is missing from header list" in new ctx {
      failureMessageFor(receivedTheSameRequestsAs(request, anotherRequest), matchedOn = aRequestRecorderWith(request, yetAnotherRequest)) must_===
        s"""Requests are not identical, missing requests are:
            |1: $anotherRequest
            |
            |added requests found:
            |1: $yetAnotherRequest""".stripMargin
    }

    "if no recorded requests were found, error message returned will be 'no requests' message" in new ctx {
      failureMessageFor(receivedAnyOf(request), matchedOn = anEmptyRequestRecorder ) must_===
        "Server did not receive any requests."

      failureMessageFor(receivedAllOf(request), matchedOn = anEmptyRequestRecorder ) must_===
        "Server did not receive any requests."

      failureMessageFor(receivedTheSameRequestsAs(request), matchedOn = anEmptyRequestRecorder ) must_===
        "Server did not receive any requests."
    }

    "match if any request satisfy the composed matcher" in new ctx {
      aRequestRecorderWith(request) must receivedAnyRequestThat(must = be_===(request))
      aRequestRecorderWith(request) must not( receivedAnyRequestThat(must = be_===(anotherRequest)) )
    }

    "return informative error messages" in new ctx {
      failureMessageFor(receivedAnyRequestThat(must = be_===(anotherRequest)), matchedOn = aRequestRecorderWith(request)) must_===
        s"""Could not find any request that matches:
           |1: ${ be_===(anotherRequest).apply(request).message.replaceAll("\n", "") }""".stripMargin
      failureMessageFor(receivedAnyRequestThat(must = AlwaysMatcher()), matchedOn = anEmptyRequestRecorder) must_===
        "Server did not receive any requests."
    }
  }
} 
Example 11
Source File: ResponseStatusAndHeaderMatchersTest.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.matchers.internal

import akka.http.scaladsl.model.StatusCodes.{Found, MovedPermanently}
import com.wix.e2e.http.matchers.ResponseMatchers._
import com.wix.e2e.http.matchers.drivers.HttpResponseFactory._
import com.wix.e2e.http.matchers.drivers.{HttpMessageTestSupport, MatchersTestSupport}
import org.specs2.mutable.Spec
import org.specs2.specification.Scope

class ResponseStatusAndHeaderMatchersTest extends Spec with MatchersTestSupport {

  trait ctx extends Scope with HttpMessageTestSupport

  "ResponseStatusAndHeaderMatchers" should {

    "match against a response that is temporarily redirected to url" in new ctx {
      aRedirectResponseTo(url) must beRedirectedTo(url)
      aRedirectResponseTo(url) must not( beRedirectedTo(anotherUrl) )
      aRedirectResponseTo(url).copy(status = randomStatusThatIsNot(Found)) must not( beRedirectedTo(url) )
    }

    "match against a response that is permanently redirected to url" in new ctx {
      aPermanentlyRedirectResponseTo(url) must bePermanentlyRedirectedTo(url)
      aPermanentlyRedirectResponseTo(url) must not( bePermanentlyRedirectedTo(anotherUrl) )
      aPermanentlyRedirectResponseTo(url).copy(status = randomStatusThatIsNot(MovedPermanently)) must not( bePermanentlyRedirectedTo(url) )
    }

    "match against url params even if params has a different order" in new ctx {
      aRedirectResponseTo(s"$url?param1=val1&param2=val2") must beRedirectedTo(s"$url?param2=val2&param1=val1")
      aPermanentlyRedirectResponseTo(s"$url?param1=val1&param2=val2") must bePermanentlyRedirectedTo(s"$url?param2=val2&param1=val1")
    }

    "match will fail for different protocol" in new ctx {
      aRedirectResponseTo(s"http://example.com") must not( beRedirectedTo(s"https://example.com") )
      aPermanentlyRedirectResponseTo(s"http://example.com") must not( bePermanentlyRedirectedTo(s"https://example.com") )
    }

    "match will fail for different host and port" in new ctx {
      aRedirectResponseTo(s"http://example.com") must not( beRedirectedTo(s"http://example.org") )
      aRedirectResponseTo(s"http://example.com:99") must not( beRedirectedTo(s"http://example.com:81") )
      aPermanentlyRedirectResponseTo(s"http://example.com") must not( bePermanentlyRedirectedTo(s"http://example.org") )
      aPermanentlyRedirectResponseTo(s"http://example.com:99") must not( bePermanentlyRedirectedTo(s"http://example.com:81") )
    }

    "port 80 is removed by akka http" in new ctx {
      aRedirectResponseTo(s"http://example.com:80") must beRedirectedTo(s"http://example.com")
      aPermanentlyRedirectResponseTo(s"http://example.com:80") must bePermanentlyRedirectedTo(s"http://example.com")
    }

    "match will fail for different path" in new ctx {
      aRedirectResponseTo(s"http://example.com/path1") must not( beRedirectedTo(s"http://example.com/path2") )
      aPermanentlyRedirectResponseTo(s"http://example.com/path1") must not( bePermanentlyRedirectedTo(s"http://example.org/path2") )
    }

    "match will fail for different hash fragment" in new ctx {
      aRedirectResponseTo(s"http://example.com/path#fragment") must not( beRedirectedTo(s"http://example.com/path#anotherFxragment") )
      aPermanentlyRedirectResponseTo(s"http://example.com/path#fragment") must not( bePermanentlyRedirectedTo(s"http://example.com/path#anotherFxragment") )
    }

    "failure message in case response does not have location header" in new ctx {
      failureMessageFor(beRedirectedTo(url), matchedOn = aRedirectResponseWithoutLocationHeader) must_===
        "Response does not contain Location header."
      failureMessageFor(bePermanentlyRedirectedTo(url), matchedOn = aPermanentlyRedirectResponseWithoutLocationHeader) must_===
        "Response does not contain Location header."
    }

    "failure message in case trying to match against a malformed url" in new ctx {
      failureMessageFor(beRedirectedTo(malformedUrl), matchedOn = aRedirectResponseTo(url)) must_===
        s"Matching against a malformed url: [$malformedUrl]."
      failureMessageFor(bePermanentlyRedirectedTo(malformedUrl), matchedOn = aPermanentlyRedirectResponseTo(url)) must_===
        s"Matching against a malformed url: [$malformedUrl]."
    }

    "failure message in case response have different urls should show the actual url and the expected url" in new ctx {
      failureMessageFor(beRedirectedTo(url), matchedOn = aRedirectResponseTo(s"$url?param1=val1")) must_===
        s"""Response is redirected to a different url:
           |actual:   $url?param1=val1
           |expected: $url
           |""".stripMargin
      failureMessageFor(bePermanentlyRedirectedTo(url), matchedOn = aPermanentlyRedirectResponseTo(s"$url?param1=val1")) must_===
        s"""Response is redirected to a different url:
           |actual:   $url?param1=val1
           |expected: $url
           |""".stripMargin
    }
  }
} 
Example 12
Source File: RequestCookiesMatchersTest.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.matchers.internal

import com.wix.e2e.http.matchers.RequestMatchers._
import com.wix.e2e.http.matchers.drivers.CommonTestMatchers._
import com.wix.e2e.http.matchers.drivers.HttpRequestFactory._
import com.wix.e2e.http.matchers.drivers.{HttpMessageTestSupport, MatchersTestSupport}
import org.specs2.matcher.Matchers._
import org.specs2.mutable.Spec
import org.specs2.specification.Scope


class RequestCookiesMatchersTest extends Spec with MatchersTestSupport {

  trait ctx extends Scope with HttpMessageTestSupport

  "ResponseCookiesMatchers" should {

    "match if cookie with name is found" in new ctx {
      aRequestWithCookies(cookiePair) must receivedCookieWith(cookiePair._1)
    }

    "failure message should describe which cookies are present and which did not match" in new ctx {
      failureMessageFor(receivedCookieWith(cookiePair._1), matchedOn = aRequestWithCookies(anotherCookiePair, yetAnotherCookiePair)) must
        contain(cookiePair._1) and contain(anotherCookiePair._1) and contain(yetAnotherCookiePair._1)
    }

    "failure message for response withoout cookies will print that the response did not contain any cookies" in new ctx {
      receivedCookieWith(cookiePair._1).apply( aRequestWithNoCookies ).message must
        contain("Request did not contain any Cookie headers.")
    }

    "allow to compose matcher with custom cookie matcher" in new ctx {
      aRequestWithCookies(cookiePair) must receivedCookieThat(must = cookieWith(cookiePair._2))
    }
  }
} 
Example 13
Source File: ResponseContentLengthMatchersTest.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.matchers.internal

import com.wix.e2e.http.matchers.ResponseMatchers._
import com.wix.e2e.http.matchers.drivers.HttpResponseFactory._
import com.wix.e2e.http.matchers.drivers.{HttpMessageTestSupport, MatchersTestSupport}
import org.specs2.mutable.Spec
import org.specs2.specification.Scope


class ResponseContentLengthMatchersTest extends Spec with MatchersTestSupport {

  trait ctx extends Scope with HttpMessageTestSupport

  "ResponseContentLengthMatchers" should {

    "support matching against specific content length" in new ctx {
      aResponseWith(contentWith(length = length)) must haveContentLength(length = length)
      aResponseWith(contentWith(length = anotherLength)) must not( haveContentLength(length = length) )
    }

    "support matching content length against response without content length" in new ctx {
      aResponseWithoutContentLength must not( haveContentLength(length = length) )
    }

    "support matching against response without content length" in new ctx {
      aResponseWithoutContentLength must haveNoContentLength
      aResponseWith(contentWith(length = length)) must not( haveNoContentLength )
    }

    "failure message should describe what was the expected content length and what was found" in new ctx {
      failureMessageFor(haveContentLength(length = length), matchedOn = aResponseWith(contentWith(length = anotherLength))) must_===
        s"Expected content length [$length] does not match actual content length [$anotherLength]"
    }

    "failure message should reflect that content length header was not found" in new ctx {
      failureMessageFor(haveContentLength(length = length), matchedOn = aResponseWithoutContentLength) must_===
        s"Expected content length [$length] but response did not contain `content-length` header."
    }

    "failure message should reflect that content length header exists while trying to match against a content length that doesn't exists" in new ctx {
      failureMessageFor(haveNoContentLength, matchedOn = aResponseWith(contentWith(length = length))) must_===
        s"Expected no `content-length` header but response did contain `content-length` header with size [$length]."
    }

    "failure message if someone tries to match content-length in headers matchers" in new ctx {
      failureMessageFor(haveAllHeadersOf(contentLengthHeader), matchedOn = aResponseWithContentType(contentType)) must_===
        """`Content-Length` is a special header and cannot be used in `haveAnyHeadersOf`, `haveAllHeadersOf`, `haveTheSameHeadersAs` matchers.
          |Use `haveContentLength` matcher instead.""".stripMargin
      failureMessageFor(haveAnyHeadersOf(contentLengthHeader), matchedOn = aResponseWithContentType(contentType)) must_===
        """`Content-Length` is a special header and cannot be used in `haveAnyHeadersOf`, `haveAllHeadersOf`, `haveTheSameHeadersAs` matchers.
          |Use `haveContentLength` matcher instead.""".stripMargin
      failureMessageFor(haveTheSameHeadersAs(contentLengthHeader), matchedOn = aResponseWithContentType(contentType)) must_===
        """`Content-Length` is a special header and cannot be used in `haveAnyHeadersOf`, `haveAllHeadersOf`, `haveTheSameHeadersAs` matchers.
          |Use `haveContentLength` matcher instead.""".stripMargin
    }
  }
} 
Example 14
Source File: HttpClientNoCustomMarshallerContractTest.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.marshaller

import com.wix.e2e.http.api.Marshaller.Implicits.marshaller
import com.wix.e2e.http.client.extractors.HttpMessageExtractors
import com.wix.e2e.http.client.transformers.HttpClientTransformers
import com.wix.e2e.http.drivers.MarshallerMatchers._
import com.wix.e2e.http.drivers.MarshallerTestSupport
import com.wix.e2e.http.drivers.MarshallingTestObjects.SomeCaseClass
import com.wix.e2e.http.exceptions.MissingMarshallerException
import com.wix.e2e.http.matchers.{RequestMatchers, ResponseMatchers}
import org.specs2.mutable.Spec
import org.specs2.specification.Scope

class HttpClientNoCustomMarshallerContractTest extends Spec with HttpClientTransformers with HttpMessageExtractors {

  trait ctx extends Scope with MarshallerTestSupport

  "Response Transformers without custom marshaller" should {

    "detect custom marshaller and use it to marshall body payload" in new ctx {
      withPayload(someObject).apply(request) must throwA[MissingMarshallerException]
    }


    "print informative error message when marshaller is not included" in new ctx {
      aResponseWith(content).extractAs[SomeCaseClass] must throwA[MissingMarshallerException]
    }
  }

  "RequestBodyMatchers without custom marshaller" should {

    "print informative error message when marshaller is not included" in new ctx {
      RequestMatchers.haveBodyWith(entity = someObject).apply(aRequestWith(content)) must beMissingMarshallerMatcherError
    }

    "print informative error message when marshaller is not included2" in new ctx {
      RequestMatchers.haveBodyEntityThat(must = be_===(someObject)).apply(aRequestWith(content)) must beMissingMarshallerMatcherError
    }
  }

  "ResponseBodyMatchers without custom marshaller" should {
    "in haveBodyWith matcher, print informative error message when marshaller is not included" in new ctx {
      ResponseMatchers.haveBodyWith(entity = someObject).apply(aResponseWith(content)) must beMissingMarshallerMatcherError
    }

    "in haveBodyThat matcher, print informative error message when marshaller is not included2" in new ctx {
      ResponseMatchers.haveBodyWithEntityThat(must = be_===(someObject)).apply(aResponseWith(content)) must beMissingMarshallerMatcherError
    }
  }
} 
Example 15
Source File: ResponseTransferEncodingMatchersTest.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.matchers.internal

import akka.http.scaladsl.model.TransferEncodings
import akka.http.scaladsl.model.TransferEncodings._
import com.wix.e2e.http.matchers.ResponseMatchers._
import com.wix.e2e.http.matchers.drivers.HttpResponseFactory._
import com.wix.e2e.http.matchers.drivers.{HttpMessageTestSupport, MatchersTestSupport}
import org.specs2.mutable.Spec
import org.specs2.specification.Scope


class ResponseTransferEncodingMatchersTest extends Spec with MatchersTestSupport {

  trait ctx extends Scope with HttpMessageTestSupport


  "ResponseTransferEncodingMatchersTest" should {

    "support matching against chunked transfer encoding" in new ctx {
      aChunkedResponse must beChunkedResponse
      aResponseWithoutTransferEncoding must not( beChunkedResponse )
      aResponseWithTransferEncodings(compress) must not( beChunkedResponse )
      aResponseWithTransferEncodings(chunked) must beChunkedResponse
    }

    "failure message in case no transfer encoding header should state that response did not have the proper header" in new ctx {
      failureMessageFor(beChunkedResponse, matchedOn = aResponseWithoutTransferEncoding) must_===
        "Expected Chunked response while response did not contain `Transfer-Encoding` header"
    }

    "failure message in case transfer encoding header exists should state that transfer encoding has a different value" in new ctx {
      failureMessageFor(beChunkedResponse, matchedOn = aResponseWithTransferEncodings(compress, TransferEncodings.deflate)) must_===
        "Expected Chunked response while response has `Transfer-Encoding` header with values ['compress', 'deflate']"
    }

    "support matching against transfer encoding header values" in new ctx {
      aResponseWithTransferEncodings(compress) must haveTransferEncodings("compress")
      aResponseWithTransferEncodings(compress) must not( haveTransferEncodings("deflate") )
    }

    "support matching against transfer encoding header with multiple values, matcher will validate that response has all of the expected values" in new ctx {
      aResponseWithTransferEncodings(compress, deflate) must haveTransferEncodings("deflate", "compress")
      aResponseWithTransferEncodings(compress, deflate) must haveTransferEncodings("compress")
    }

    "properly match chunked encoding" in new ctx {
      aChunkedResponse must haveTransferEncodings("chunked")
      aChunkedResponseWith(compress) must haveTransferEncodings("compress", "chunked")
      aChunkedResponseWith(compress) must haveTransferEncodings("chunked")
    }

    "failure message should describe what was the expected transfer encodings and what was found" in new ctx {
      failureMessageFor(haveTransferEncodings("deflate", "compress"), matchedOn = aChunkedResponseWith(gzip)) must_===
        s"Expected transfer encodings ['deflate', 'compress'] does not match actual transfer encoding ['chunked', 'gzip']"
    }

    "failure message in case no Transfer-Encoding for response should be handled" in new ctx {
      failureMessageFor(haveTransferEncodings("chunked"), matchedOn = aResponseWithoutTransferEncoding) must_===
        "Response did not contain `Transfer-Encoding` header."
    }

    "failure message if someone tries to match content-type in headers matchers" in new ctx {
      failureMessageFor(haveAllHeadersOf(transferEncodingHeader), matchedOn = aResponseWithContentType(contentType)) must_===
        """`Transfer-Encoding` is a special header and cannot be used in `haveAnyHeadersOf`, `haveAllHeadersOf`, `haveTheSameHeadersAs` matchers.
          |Use `beChunkedResponse` or `haveTransferEncodings` matcher instead.""".stripMargin
      failureMessageFor(haveAnyHeadersOf(transferEncodingHeader), matchedOn = aResponseWithContentType(contentType)) must_===
        """`Transfer-Encoding` is a special header and cannot be used in `haveAnyHeadersOf`, `haveAllHeadersOf`, `haveTheSameHeadersAs` matchers.
          |Use `beChunkedResponse` or `haveTransferEncodings` matcher instead.""".stripMargin
      failureMessageFor(haveTheSameHeadersAs(transferEncodingHeader), matchedOn = aResponseWithContentType(contentType)) must_===
        """`Transfer-Encoding` is a special header and cannot be used in `haveAnyHeadersOf`, `haveAllHeadersOf`, `haveTheSameHeadersAs` matchers.
          |Use `beChunkedResponse` or `haveTransferEncodings` matcher instead.""".stripMargin
    }
  }
} 
Example 16
Source File: PathBuilderTest.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.client.internals

import java.net.URLEncoder

import com.wix.e2e.http.client.drivers.PathBuilderTestSupport
import com.wix.e2e.http.client.drivers.UrlBuilderMatchers._
import org.specs2.mutable.SpecWithJUnit
import org.specs2.specification.Scope

class PathBuilderTest extends SpecWithJUnit {

  trait ctx extends Scope
  with PathBuilderTestSupport

  "Url building" should {

    "handle context path with single path" in new ctx {
      baseUri.copy(contextRoot = Some(contextRoot)).asUri must beUrl(s"http://${baseUri.host}:${baseUri.port}$contextRoot")
    }

    "handle empty context root" in new ctx {
      baseUri.copy(contextRoot = None).asUri must beUrl(s"http://${baseUri.host}:${baseUri.port}")
      baseUri.copy(contextRoot = Some("")).asUri must beUrl(s"http://${baseUri.host}:${baseUri.port}")
      baseUri.copy(contextRoot = Some("   ")).asUri must beUrl(s"http://${baseUri.host}:${baseUri.port}")
    }

    "handle context path with more than one path" in new ctx {
      baseUri.copy(contextRoot = Some(contextRootWithMultiplePaths)).asUri must beUrl(s"http://${baseUri.host}:${baseUri.port}$contextRootWithMultiplePaths")
    }

    "handle no context and empty relative path" in new ctx {
      baseUri.copy(contextRoot = None).asUriWith("/") must beUrl(s"http://${baseUri.host}:${baseUri.port}")
      baseUri.copy(contextRoot = None).asUriWith("") must beUrl(s"http://${baseUri.host}:${baseUri.port}")
      baseUri.copy(contextRoot = None).asUriWith("    ") must beUrl(s"http://${baseUri.host}:${baseUri.port}")
    }

    "ignore cases in which path and context root are single slash" in new ctx {
      baseUri.copy(contextRoot = Some("/")).asUriWith("/") must beUrl(s"http://${baseUri.host}:${baseUri.port}")
      baseUri.copy(contextRoot = None).asUriWith("/") must beUrl(s"http://${baseUri.host}:${baseUri.port}")
    }

    "allow to append relative path" in new ctx {
      baseUri.copy(contextRoot = None).asUriWith(relativePath) must beUrl(s"http://${baseUri.host}:${baseUri.port}$relativePath")
      baseUri.copy(contextRoot = Some("")).asUriWith(relativePath) must beUrl(s"http://${baseUri.host}:${baseUri.port}$relativePath")
      baseUri.copy(contextRoot = Some("/")).asUriWith(relativePath) must beUrl(s"http://${baseUri.host}:${baseUri.port}$relativePath")
    }

    "allow to append relative path with multiple parts" in new ctx {
      baseUri.copy(contextRoot = None).asUriWith(relativePathWithMultipleParts) must beUrl(s"http://${baseUri.host}:${baseUri.port}$relativePathWithMultipleParts")
    }

    "properly combine context root and relative path" in new ctx {
      baseUri.copy(contextRoot = Some(contextRoot)).asUriWith(relativePath) must beUrl(s"http://${baseUri.host}:${baseUri.port}$contextRoot$relativePath")
      baseUri.copy(contextRoot = Some(contextRootWithMultiplePaths)).asUriWith(relativePathWithMultipleParts) must beUrl(s"http://${baseUri.host}:${baseUri.port}$contextRootWithMultiplePaths$relativePathWithMultipleParts")
    }

    "support context root that doesn't start with /" in new ctx {
      baseUri.copy(contextRoot = Some(contextRoot.stripPrefix("/"))).asUri must beUrl(s"http://${baseUri.host}:${baseUri.port}$contextRoot")
      baseUri.copy(contextRoot = None).asUriWith(relativePath.stripPrefix("/")) must beUrl(s"http://${baseUri.host}:${baseUri.port}$relativePath")
    }

    "support relative path with explicit request params" in new ctx {
      baseUri.copy(contextRoot = None).asUriWith(s"$relativePath?key=val") must beUrl(s"http://${baseUri.host}:${baseUri.port}$relativePath?key=val")
    }

    "support relative path with explicit request escaped params" in new ctx {
      baseUri.copy(contextRoot = None).asUriWith(s"$relativePath?key=val&encoded=$escapedCharacters") must beUrl(s"http://${baseUri.host}:${baseUri.port}$relativePath?key=val&encoded=${URLEncoder.encode(escapedCharacters, "UTF-8")}")
    }

    "support relative path with explicit request params without value" in new ctx {
      baseUri.copy(contextRoot = None).asUriWith(s"$relativePath?key") must beUrl(s"http://${baseUri.host}:${baseUri.port}$relativePath?key")
    }
  }
} 
Example 17
Source File: HttpMessageExtractorsTest.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.client.extractors

import akka.http.scaladsl.model._
import com.wix.e2e.http.api.Marshaller.Implicits._
import com.wix.e2e.http.drivers.{HttpClientTransformersTestSupport, SomePayload}
import org.specs2.mutable.Spec
import org.specs2.specification.Scope

class HttpMessageExtractorsTest extends Spec with HttpMessageExtractors {

  trait ctx extends Scope with HttpClientTransformersTestSupport

  "Message Extractors" should {
    "extract response body" should {
      "as unmarshalled JSON" in new ctx {
        HttpResponse(entity = marshaller.marshall(payload)).extractAs[SomePayload] must_=== payload
      }

      "as string" in new ctx {
        HttpResponse(entity = HttpEntity(strBody)).extractAsString must_=== strBody
      }

      "as array of bytes" in new ctx {
        HttpResponse(entity = HttpEntity(someBytes)).extractAsBytes must_=== someBytes
      }
    }

    "extract response entity" should {
      "as unmarshalled JSON" in new ctx {
        HttpEntity(marshaller.marshall(payload)).extractAs[SomePayload] must_=== payload
      }

      "as string" in new ctx {
        HttpEntity(strBody).extractAsString must_=== strBody
      }

      "as array of bytes" in new ctx {
        HttpEntity(someBytes).extractAsBytes must_=== someBytes
      }
    }

    "extract request body" should {
      "as unmarshalled JSON" in new ctx {
        HttpRequest(entity = marshaller.marshall(payload)).extractAs[SomePayload] must_=== payload
      }

      "as string" in new ctx {
        HttpRequest(entity = HttpEntity(strBody)).extractAsString must_=== strBody
      }

      "as array of bytes" in new ctx {
        HttpRequest(entity = HttpEntity(someBytes)).extractAsBytes must_=== someBytes
      }
    }
  }
} 
Example 18
Source File: MetricsServiceSpec.scala    From finagle-prometheus   with MIT License 5 votes vote down vote up
package com.samstarling.prometheusfinagle.metrics

import com.samstarling.prometheusfinagle.UnitTest
import com.twitter.finagle.http.{Method, Request}
import com.twitter.util.Await
import io.prometheus.client.CollectorRegistry
import org.specs2.specification.Scope

class MetricsServiceSpec extends UnitTest {

  trait Context extends Scope {
    val registry = new CollectorRegistry(true)
    val telemetry = new Telemetry(registry, "unit_test")
    val service = new MetricsService(registry)
  }

  "it renders metrics correctly" in new Context {
    telemetry.counter("foo").inc()
    val request = Request(Method.Get, "/")
    val response = Await.result(service.apply(request))

    response.getContentString.trim ====
      "# HELP unit_test_foo No help provided\n" +
        "# TYPE unit_test_foo counter\n" +
        "unit_test_foo 1.0"
  }
} 
Example 19
Source File: HttpLatencyMonitoringFilterSpec.scala    From finagle-prometheus   with MIT License 5 votes vote down vote up
package com.samstarling.prometheusfinagle.filter

import com.samstarling.prometheusfinagle.UnitTest
import com.samstarling.prometheusfinagle.helper.{CollectorHelper, CollectorRegistryHelper}
import com.samstarling.prometheusfinagle.metrics.Telemetry
import com.twitter.finagle.Service
import com.twitter.finagle.http.{Method, Request, Response, Status}
import com.twitter.finagle.util.DefaultTimer
import com.twitter.util.{Await, Duration, Future, Timer}
import io.prometheus.client.CollectorRegistry
import org.specs2.specification.Scope

class HttpLatencyMonitoringFilterSpec extends UnitTest {

  class SlowService extends Service[Request, Response] {
    implicit val timer = DefaultTimer.twitter

    override def apply(request: Request): Future[Response] = {
      Future
        .value(Response(request.version, Status.Ok))
        .delayed(Duration.fromMilliseconds(1500))
    }
  }

  trait Context extends Scope {
    val registry = new CollectorRegistry(true)
    val registryHelper = CollectorRegistryHelper(registry)
    val telemetry = new Telemetry(registry, "test")
    val buckets = Seq(1.0, 2.0)
    val labeller = new TestLabeller
    val filter = new HttpLatencyMonitoringFilter(telemetry, buckets, labeller)
    val service = mock[Service[Request, Response]]
    val slowService = new SlowService
    val request = Request(Method.Get, "/foo/bar")
    val serviceResponse = Response(Status.Created)
    val histogram =
      telemetry.histogram(name = "incoming_http_request_latency_seconds")
    service.apply(request) returns Future.value(serviceResponse)
  }

  "HttpLatencyMonitoringFilter" >> {
    "passes requests on to the next service" in new Context {
      Await.result(filter.apply(request, service))
      there was one(service).apply(request)
    }

    "returns the Response from the next service" in new Context {
      val actualResponse = Await.result(filter.apply(request, service))
      actualResponse ==== serviceResponse
    }

    "counts the request" in new Context {
      Await.result(filter.apply(request, slowService))

      registryHelper.samples
        .get("test_incoming_http_request_latency_seconds_count")
        .map(_.map(_.value).sum) must beSome(1.0).eventually
    }

    "increments the counter with the labels from the labeller" in new Context {
      Await.result(filter.apply(request, service))

      registryHelper.samples
        .get("test_incoming_http_request_latency_seconds_count")
        .map(_.head.dimensions.get("foo").get) must beSome("bar").eventually
    }

    "categorises requests into the correct bucket" in new Context {
      Await.result(filter.apply(request, slowService))

      // Our request takes ~1500ms, so it should NOT fall into the "less than or equal to 1 second" bucket (le=0.5)
      registryHelper.samples
        .get("test_incoming_http_request_latency_seconds_bucket")
        .flatMap(_.find(_.dimensions.get("le").contains("1.0")))
        .map(_.value) must beSome(0.0).eventually

      // However, it should fall into the "less than or equal to 2 seconds" bucket (le=0.5)
      registryHelper.samples
        .get("test_incoming_http_request_latency_seconds_bucket")
        .flatMap(_.find(_.dimensions.get("le").contains("2.0")))
        .map(_.value) must beSome(1.0).eventually

      // It should also fall into the "+Inf" bucket
      registryHelper.samples
        .get("test_incoming_http_request_latency_seconds_bucket")
        .flatMap(_.find(_.dimensions.get("le").contains("+Inf")))
        .map(_.value) must beSome(1.0).eventually
    }
  }
} 
Example 20
Source File: HttpServiceLabellerSpec.scala    From finagle-prometheus   with MIT License 5 votes vote down vote up
package com.samstarling.prometheusfinagle.filter

import com.samstarling.prometheusfinagle.UnitTest
import com.twitter.finagle.http.{Method, Request, Response, Status}
import org.specs2.specification.Scope

class HttpServiceLabellerSpec extends UnitTest {

  trait Context extends Scope {
    val request = Request(Method.Get, "/foo/bar")
    val response = Response(Status.Ok)
    val labeller = new HttpServiceLabeller()
    val labels = labeller.labelsFor(request, response)
  }

  "keys" >> {
    "returns the keys in the correct order" in new Context {
      labeller.keys ==== Seq("status", "statusClass", "method")
    }
  }

  "labelsFor" >> {
    "returns the status code of the response" in new Context {
      labels(0) ==== "200"
    }

    "returns the status class of the request" in new Context {
      labels(1) ==== "2xx"
    }

    "returns the method of the request" in new Context {
      labels(2) ==== "GET"
    }
  }
} 
Example 21
Source File: HttpMonitoringFilterSpec.scala    From finagle-prometheus   with MIT License 5 votes vote down vote up
package com.samstarling.prometheusfinagle.filter

import com.samstarling.prometheusfinagle.UnitTest
import com.samstarling.prometheusfinagle.helper.CollectorHelper
import com.samstarling.prometheusfinagle.metrics.Telemetry
import com.twitter.finagle.Service
import com.twitter.finagle.http.{Method, Request, Response, Status}
import com.twitter.util.{Await, Future}
import io.prometheus.client.CollectorRegistry
import org.specs2.specification.Scope

import scala.collection.JavaConverters._

class HttpMonitoringFilterSpec extends UnitTest {

  trait Context extends Scope {
    val registry = new CollectorRegistry(true)
    val telemetry = new Telemetry(registry, "test")
    val labeller = new TestLabeller
    val filter = new HttpMonitoringFilter(telemetry, labeller)
    val service = mock[Service[Request, Response]]
    val request = Request(Method.Get, "/foo/bar")
    val serviceResponse = Response(Status.Created)
    val counter = telemetry.counter(name = "incoming_http_requests_total")
    service.apply(request) returns Future.value(serviceResponse)
  }

  "HttpMonitoringFilter" >> {
    "passes requests on to the next service" in new Context {
      Await.result(filter.apply(request, service))
      there was one(service).apply(request)
    }

    "returns the Response from the next service" in new Context {
      val actualResponse = Await.result(filter.apply(request, service))
      actualResponse ==== serviceResponse
    }

    "increments the incoming_http_requests_total counter" in new Context {
      Await.result(filter.apply(request, service))
      Await.result(filter.apply(request, service))
      CollectorHelper.firstSampleFor(counter).map { sample =>
        sample.value ==== 2.0
      }
    }

    "adds the correct help label" in new Context {
      Await.result(filter.apply(request, service))
      CollectorHelper.firstMetricFor(counter).map { metric =>
        metric.help ==== "The number of incoming HTTP requests"
      }
    }

    "increments the counter with the labels from the labeller" in new Context {
      Await.result(filter.apply(request, service))
      CollectorHelper.firstSampleFor(counter).map { sample =>
        sample.labelNames.asScala(0) ==== "foo"
        sample.labelValues.asScala(0) ==== "bar"
      }
    }
  }
} 
Example 22
Source File: HatDataStatsProcessorSpec.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.api.service.monitoring

import java.util.UUID

import akka.stream.Materializer
import com.google.inject.AbstractModule
import net.codingwell.scalaguice.ScalaModule
import org.hatdex.hat.api.models.{ EndpointData, Owner }
import org.hatdex.hat.api.service.applications.{ TestApplicationProvider, TrustedApplicationProvider }
import org.hatdex.hat.api.service.monitoring.HatDataEventBus.DataCreatedEvent
import org.hatdex.hat.authentication.models.HatUser
import org.hatdex.hat.dal.ModelTranslation
import org.hatdex.hat.resourceManagement.FakeHatConfiguration
import org.joda.time.DateTime
import org.specs2.mock.Mockito
import org.specs2.specification.Scope
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.json.{ JsValue, Json }
import play.api.test.PlaySpecification
import play.api.{ Application, Logger }

class HatDataStatsProcessorSpec extends PlaySpecification with Mockito with HatDataStatsProcessorContext {

  val logger = Logger(this.getClass)

  sequential

  "The `computeInboundStats` method" should {
    "Correctly count numbers of values for simple objects" in {
      val service = application.injector.instanceOf[HatDataStatsProcessor]
      val stats = service.computeInboundStats(simpleDataCreatedEvent)

      import org.hatdex.hat.api.json.DataStatsFormat._
      logger.debug(s"Got back stats: ${Json.prettyPrint(Json.toJson(stats))}")

      stats.logEntry must be equalTo "test item"
      stats.statsType must be equalTo "inbound"
      stats.stats.length must be equalTo 1
      val endpointStats = stats.stats.head
      endpointStats.endpoint must be equalTo "testendpoint"

      endpointStats.propertyStats("field") must equalTo(1)
      endpointStats.propertyStats("date") must equalTo(1)
      endpointStats.propertyStats("date_iso") must equalTo(1)
      endpointStats.propertyStats("anotherField") must equalTo(1)
      endpointStats.propertyStats("object.objectField") must equalTo(1)
      endpointStats.propertyStats("object.objectFieldArray[]") must equalTo(3)
      endpointStats.propertyStats("object.objectFieldObjectArray[].subObjectName") must equalTo(2)
      endpointStats.propertyStats("object.objectFieldObjectArray[].subObjectName2") must equalTo(2)
    }
  }

}

trait HatDataStatsProcessorContext extends Scope {
  import scala.concurrent.ExecutionContext.Implicits.global
  // Setup default users for testing
  val owner = HatUser(UUID.randomUUID(), "hatuser", Some("pa55w0rd"), "hatuser", Seq(Owner()), enabled = true)

  class ExtrasModule extends AbstractModule with ScalaModule {
    override def configure(): Unit = {
      bind[TrustedApplicationProvider].toInstance(new TestApplicationProvider(Seq()))
    }
  }

  lazy val application: Application = new GuiceApplicationBuilder()
    .configure(FakeHatConfiguration.config)
    .overrides(new ExtrasModule)
    .build()

  implicit lazy val materializer: Materializer = application.materializer

  val simpleJson: JsValue = Json.parse(
    """
      | {
      |   "field": "value",
      |   "date": 1492699047,
      |   "date_iso": "2017-04-20T14:37:27+00:00",
      |   "anotherField": "anotherFieldValue",
      |   "object": {
      |     "objectField": "objectFieldValue",
      |     "objectFieldArray": ["objectFieldArray1", "objectFieldArray2", "objectFieldArray3"],
      |     "objectFieldObjectArray": [
      |       {"subObjectName": "subObject1", "subObjectName2": "subObject1-2"},
      |       {"subObjectName": "subObject2", "subObjectName2": "subObject2-2"}
      |     ]
      |   }
      | }
    """.stripMargin)

  val simpleDataCreatedEvent = DataCreatedEvent(
    "testhat.hubofallthings.net",
    ModelTranslation.fromInternalModel(owner).clean,
    DateTime.now(), "test item",
    Seq(
      EndpointData("testendpoint", Option(UUID.randomUUID()), None, None, simpleJson, None)))
} 
Example 23
Source File: TwoSumTest.scala    From coding-interview-questions-scala   with Apache License 2.0 5 votes vote down vote up
package org.questions.arrays

import org.specs2.matcher.Matcher
import org.specs2.mutable.Specification
import org.specs2.specification.Scope


class TwoSumTest extends Specification {

  class Context extends Scope {
    val arrayUtils = new TwoSum

    def sumTo(sum: Int): Matcher[(Int, Int)] = (_: (Int, Int)) match {
      case (a, b) => a + b must be_===(sum)
    }
  }

  "under 2 elements in seq" should {
    "be none" in new Context {
      arrayUtils.findPairSum(Seq(1), 8) must beNone
    }
  }

  "two elements that sum" should {
    "return these elements" in new Context {
      arrayUtils.findPairSum(Seq(2, 3), 5) must beSome(sumTo(5))
    }
  }

  "two elements that doesn't sum" should {
    "return these none" in new Context {
      arrayUtils.findPairSum(Seq(2, 3), 4) must beNone
    }
  }

  "more elements that sum" should {
    "return the sum" in new Context {
      arrayUtils.findPairSum(Seq(1, 2, 3), 5) must beSome(sumTo(5))
    }
  }
} 
Example 24
Source File: CanvasTest.scala    From coding-interview-questions-scala   with Apache License 2.0 5 votes vote down vote up
package org.questions.fill

import org.specs2.mutable.Specification
import org.specs2.specification.Scope


class CanvasTest extends Specification {

  class Context extends Scope {
    private val sample =
      """............
        |.*******....
        |.*....***...
        |.**.....*...
        |..*....**...
        |...*****....""".stripMargin

    private def toCharsCanvas(s: String) =
      new CharsCanvas(s.lines.map(_.toCharArray).toArray)

    val canvas = toCharsCanvas(sample)
    val drawUtils = new DrawUtils(canvas)

    def >(canvas: Canvas) = {
      val (rows, cols) = canvas.getSize

      for {r <- 0 until rows} {
        for {c <- 0 until cols} {
          Predef.print(canvas.getColor(r, c))
        }
        println()
      }
    }
  }

  Seq((1, 100), (100, 1), (-1, 1), (1, -1)) foreach { case (x, y) =>
    "outside of the canvas" should {
      "result in error" in new Context {
        drawUtils.fill(x, y, 'X') must throwA[IndexOutOfBoundsException]
      }
    }
  }

  "adjacent fields with same color" should {
    "be filled" in new Context {
      drawUtils.fill(3, 4, '#')

      Seq((3, 5), (3, 3), (2, 4), (4, 4)) foreach { case (x, y) =>
        canvas.getColor(x, y) must be_===('#')
      }
    }
  }

  "adjacent fields with different color" should {
    "stay with previous color" in new Context {
      drawUtils.fill(0, 1, '#')
      canvas.getColor(1, 1) must be_===('*')
    }
  }

  "selected field" should {
    "be colored" in new Context {
      drawUtils.fill(0, 0, '#')
      canvas.getColor(0, 0) must be_===('#')
    }
  }

  "far fields that in same shape" should {
    "be colored" in new Context {
      drawUtils.fill(0, 0, '#')
      canvas.getColor(5, 11) must be_===('#')
    }
  }
} 
Example 25
Source File: TextFileSpec.scala    From duometer   with Apache License 2.0 5 votes vote down vote up
package com.pawelmandera.io

import scala.util.Success

import org.specs2.mutable._
import org.specs2.mock._
import org.specs2.specification.Scope


class TextFileSpec extends Specification {
  trait TestData extends Scope {
    val mockedFile = new TextFile("test/path") with HasTextLines {
      val lines = Success(Vector(
        "This is a first line",
        "This is a second line",
        "This is a third line"
      ))
    }
  }

  "A TextFile object " should {
    "return the text" in new TestData {
      val text = mockedFile.text
      text.get must_== mockedFile.lines.get.mkString("\n")
    }
  }
} 
Example 26
Source File: FormSupportSpec.scala    From twitter4s   with Apache License 2.0 5 votes vote down vote up
package com.danielasfregola.twitter4s.http.serializers

import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpResponse}
import com.danielasfregola.twitter4s.exceptions.TwitterException
import com.danielasfregola.twitter4s.helpers.{AwaitableFuture, TestActorSystem, TestExecutionContext}
import org.specs2.mutable.SpecificationLike
import org.specs2.specification.Scope

import scala.concurrent.Future

class FormSupportSpec extends TestActorSystem with SpecificationLike with AwaitableFuture with TestExecutionContext {

  case class MyTest(a: String, b: String, c: String, d: Boolean)

  implicit object MyTestFromMap extends FromMap[MyTest] {
    def apply(m: Map[String, String]) =
      for {
        a <- m.get("a")
        b <- m.get("b")
        c <- m.get("c")
        d <- m.get("d")
      } yield MyTest(a, b, c, toBoolean(d))
  }

  abstract class FormSupportContext extends Scope

  def buildResponse(text: String): HttpResponse =
    HttpResponse(entity = HttpEntity.apply(ContentTypes.`text/html(UTF-8)`, text))

  "FormSupport" should {

    "unmarshall a well-formed text into a case class" in new FormSupportContext {
      val text = "a=hello&c=test&b=foobar&d=true"
      val result: Future[MyTest] = FormSupport.unmarshallText[MyTest](buildResponse(text))
      result.await === MyTest(a = "hello", b = "foobar", c = "test", d = true)
    }

    "throw TwitterException if text is not well formed" in new FormSupportContext {
      val text = "non-well-formed-string"
      val result: Future[MyTest] = FormSupport.unmarshallText[MyTest](buildResponse(text))
      result.await should throwA[TwitterException]
    }
  }
} 
Example 27
Source File: ConfigurationDetectorSpec.scala    From twitter4s   with Apache License 2.0 5 votes vote down vote up
package com.danielasfregola.twitter4s.util

import com.typesafe.config.{Config, ConfigException}
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.specs2.specification.Scope

class ConfigurationDetectorSpec extends Specification with Mockito {

  val myConfigFromEnvVar = "my-configuration-from-env-var"
  val myConfigFromFile = "my-configuration-from-file"

  abstract class ConfigurationDetectorSpecContext extends Scope {
    def config = mock[Config]

    val variableName = "MY-CONFIG"
    val configName = "my.config"
  }

  trait NoEnvVariable extends ConfigurationDetector {
    override protected def environmentVariable(name: String) = None
  }

  trait WithEnvVariable extends ConfigurationDetector {
    override protected def environmentVariable(name: String) = Some(myConfigFromEnvVar)
  }

  trait NoConfigFromFile extends ConfigurationDetector {
    override protected def configuration(path: String) = throw new ConfigException.Missing(path)
  }

  trait WithConfigFromFile extends ConfigurationDetector {
    override protected def configuration(path: String) = myConfigFromFile
  }

  "ConfigurationDetector" should {

    "if environment variable exists" in {

      "if configuration from file does not exists" in {
        "detect the configuration from the environment variable" in
          new ConfigurationDetectorSpecContext with WithEnvVariable with NoConfigFromFile {
            envVarOrConfig(variableName, configName) === myConfigFromEnvVar
          }
      }

      "if configuration from file exists" in {
        "detect the configuration from the environment variable" in
          new ConfigurationDetectorSpecContext with WithEnvVariable with WithConfigFromFile {
            envVarOrConfig(variableName, configName) === myConfigFromEnvVar
          }
      }
    }

    "if environment variable does not exist" in {

      "if configuration from file exists" in {
        "detect the configuration from the configuration file" in
          new ConfigurationDetectorSpecContext with NoEnvVariable with WithConfigFromFile {
            envVarOrConfig(variableName, configName) === myConfigFromFile
          }
      }

      "if configuration from file does not exist" in {
        "throw an exception" in
          new ConfigurationDetectorSpecContext with NoEnvVariable with NoConfigFromFile {
            envVarOrConfig(variableName, configName) must throwA[RuntimeException]
          }
      }
    }
  }
} 
Example 28
Source File: ZincAnalysisParserTest.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wix.build.zinc.analysis

import java.io.InputStream
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Paths}
import java.util.UUID

import com.github.marschall.memoryfilesystem.MemoryFileSystemBuilder
import com.wixpress.build.maven.Coordinates
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope

class ZincAnalysisParserTest extends SpecificationWithJUnit {
  "ZincAnalysisParser" should {
    "parse repo with zinc analysis" in new baseCtx {
      private val parser = new ZincAnalysisParser(repoRoot)
      private val coordinatesToAnalyses: Map[Coordinates, List[ZincModuleAnalysis]] = parser.readModules()
      coordinatesToAnalyses must haveLength(greaterThan(0))
      private val analysisList: List[ZincModuleAnalysis] = coordinatesToAnalyses.head._2
      analysisList must haveLength(greaterThan(0))
    }
  }

  abstract class baseCtx extends Scope {
    val fileSystem = MemoryFileSystemBuilder.newLinux().build()
    val repoRoot = fileSystem.getPath("repoRoot")
    Files.createDirectories(repoRoot)
    writeResourceAsFileToPath("/pom.xml", "pom.xml", "java-junit-sample/")
    writeResourceAsFileToPath("/aggregate-pom.xml", "pom.xml", "")
    writeResourceAsFileToPath("/compile.relations", "compile.relations","java-junit-sample/target/analysis/")
    writeResourceAsFileToPath("/test-compile.relations", "test-compile.relations","java-junit-sample/target/analysis/")

    private def writeResourceAsFileToPath(resource: String, fileName: String, path: String) = {
      if (path.nonEmpty)
        Files.createDirectories(repoRoot.resolve(path))
      val stream: InputStream = getClass.getResourceAsStream(s"$resource")
      val compileRelations = scala.io.Source.fromInputStream(stream).mkString
      Files.write(repoRoot.resolve(s"$path$fileName"), compileRelations.getBytes(StandardCharsets.UTF_8))
    }

    def path(withName: String) = repoRoot.resolve(withName)
    def random = UUID.randomUUID().toString
  }
} 
Example 29
Source File: RomaniaIterativeDeepeningSearchSpec.scala    From aima-scala   with MIT License 5 votes vote down vote up
package aima.core.search.uninformed

import aima.core.search.StateNode
import aima.core.search.problems.Romania._
import org.specs2.mutable.Specification
import org.specs2.specification.Scope

import scala.reflect.ClassTag


class RomaniaIterativeDeepeningSearchSpec extends Specification {

  "going from Arad to Arad must return no actions" in new context {
    search(new RomaniaRoadProblem(In(Arad), In(Arad)), NoAction) must beSuccessfulTry.like {
      case Solution(Nil) => ok
    }
  }

  "going from Arad to Bucharest must return a list of actions" in new context {
    search(new RomaniaRoadProblem(In(Arad), In(Bucharest)), NoAction) must beSuccessfulTry.like {
      case Solution(GoTo(Sibiu) :: GoTo(Fagaras) :: GoTo(Bucharest) :: Nil) => ok
    }
  }

  trait context extends Scope with IterativeDeepeningSearch[RomaniaState, RomaniaAction] {

    val depthLimitedTreeSearch = new DepthLimitedTreeSearch[RomaniaState, RomaniaAction] {
      override implicit val nCT: ClassTag[StateNode[RomaniaState, RomaniaAction]] = snCTag
    }
  }

} 
Example 30
Source File: RomaniaUniformCostSearchSpec.scala    From aima-scala   with MIT License 5 votes vote down vote up
package aima.core.search.uninformed

import aima.core.search.CostNode
import aima.core.search.problems.Romania._
import org.specs2.mutable.Specification
import org.specs2.specification.Scope

import scala.reflect.ClassTag


class RomaniaUniformCostSearchSpec extends Specification {

  "going from Arad to Arad must return no actions" in new context {
    search(new RomaniaRoadProblem(In(Arad), In(Arad)), NoAction) must beEmpty
  }

  "going from Arad to Bucharest must return a list of actions" in new context {
    search(new RomaniaRoadProblem(In(Arad), In(Bucharest)), NoAction) must_== List(
      GoTo(Sibiu),
      GoTo(RimnicuVilcea),
      GoTo(Pitesti),
      GoTo(Bucharest)
    )
  }

  trait context extends Scope with UniformCostSearch[RomaniaState, RomaniaAction] {
    override implicit val nCT: ClassTag[CostNode[RomaniaState, RomaniaAction]] = cnCTag
  }

} 
Example 31
Source File: RomaniaDepthLimitedTreeSearchSpec.scala    From aima-scala   with MIT License 5 votes vote down vote up
package aima.core.search.uninformed

import aima.core.search.StateNode
import aima.core.search.problems.Romania._
import org.specs2.mutable.Specification
import org.specs2.specification.Scope

import scala.reflect.ClassTag


class RomaniaDepthLimitedTreeSearchSpec extends Specification {

  "going from Arad to Arad must return no actions" in new context {
    search(new RomaniaRoadProblem(In(Arad), In(Arad)), 1, NoAction) must beSuccessfulTry.like {
      case Solution(Nil) => ok
    }
  }

  "going from Arad to Bucharest must return a list of actions with depth 19" in new context {
    search(new RomaniaRoadProblem(In(Arad), In(Bucharest)), 19, NoAction) must beSuccessfulTry.like {
      case Solution(GoTo(Sibiu) :: GoTo(RimnicuVilcea) :: GoTo(Pitesti) :: GoTo(Bucharest) :: Nil) => ok
    }
  }

  "going from Arad to Bucharest must return a list of actions with depth 9" in new context {
    search(new RomaniaRoadProblem(In(Arad), In(Bucharest)), 9, NoAction) must beSuccessfulTry.like {
      case Solution(GoTo(Sibiu) :: GoTo(RimnicuVilcea) :: GoTo(Pitesti) :: GoTo(Bucharest) :: Nil) => ok
    }
  }

  "going from Arad to Bucharest must return a Cuttoff with depth 1" in new context {
    search(new RomaniaRoadProblem(In(Arad), In(Bucharest)), 1, NoAction) must beSuccessfulTry.like {
      case CutOff(GoTo(Zerind) :: Nil) => ok
    }
  }

  trait context extends Scope with DepthLimitedTreeSearch[RomaniaState, RomaniaAction] {
    override implicit val nCT: ClassTag[StateNode[RomaniaState, RomaniaAction]] = snCTag
  }

} 
Example 32
Source File: TableDrivenVacuumAgentSpec.scala    From aima-scala   with MIT License 5 votes vote down vote up
package aima.core.environment.vacuum

import org.specs2.mutable.Specification
import org.specs2.specification.Scope

import scala.util.Random


class TableDrivenVacuumAgentSpec extends Specification {

  "first level dirty sucks" in new context {
    invokeAgent(List(LocationAPercept, DirtyPercept)) must_== List(NoAction, Suck)
  }

  "first level A and Clean moves Right" in new context {
    invokeAgent(List(LocationAPercept, CleanPercept)) must_== List(NoAction, RightMoveAction)
  }

  "first level B and Clean moves Right" in new context {
    invokeAgent(List(LocationBPercept, CleanPercept)) must_== List(NoAction, LeftMoveAction)
  }

  "second level dirty sucks" in new context {
    val givenPercepts   = List.fill(2)(LocationAPercept) ++ List(LocationAPercept, DirtyPercept)
    val expectedActions = List.fill(2)(NoAction) ++ List(NoAction, Suck)
    invokeAgent(givenPercepts) must_== expectedActions
  }

  "second level A and Clean moves Right" in new context {
    val givenPercepts   = List.fill(2)(LocationAPercept) ++ List(LocationAPercept, CleanPercept)
    val expectedActions = List.fill(2)(NoAction) ++ List(NoAction, RightMoveAction)
    invokeAgent(givenPercepts) must_== expectedActions
  }

  "second level B and Clean moves Right" in new context {
    val givenPercepts   = List.fill(2)(LocationAPercept) ++ List(LocationBPercept, CleanPercept)
    val expectedActions = List.fill(2)(NoAction) ++ List(NoAction, LeftMoveAction)
    invokeAgent(givenPercepts) must_== expectedActions
  }

  "fourth level dirty sucks" in new context {
    val givenPercepts   = List.fill(6)(LocationAPercept) ++ List(LocationAPercept, DirtyPercept)
    val expectedActions = List.fill(6)(NoAction) ++ List(NoAction, Suck)
    invokeAgent(givenPercepts) must_== expectedActions
  }

  "fourth level A and Clean moves Right" in new context {
    val givenPercepts   = List.fill(6)(LocationAPercept) ++ List(LocationAPercept, CleanPercept)
    val expectedActions = List.fill(6)(NoAction) ++ List(NoAction, RightMoveAction)
    invokeAgent(givenPercepts) must_== expectedActions
  }

  "fourth level B and Clean moves Right" in new context {
    val givenPercepts   = List.fill(6)(LocationAPercept) ++ List(LocationBPercept, CleanPercept)
    val expectedActions = List.fill(6)(NoAction) ++ List(NoAction, LeftMoveAction)
    invokeAgent(givenPercepts) must_== expectedActions
  }

  "twenty dirty percepts is undefined because out of table definition range" in new context {
    val givenPercepts   = List.fill(20)(LocationAPercept)
    val expectedActions = List.fill(20)(NoAction)
    invokeAgent(givenPercepts) must_== expectedActions
  }

  "table driven agent must persist all percepts" in new context {
    val rnd = new Random()
    val randomPerceptStream: LazyList[VacuumPercept] = LazyList.continually {
      val selector = rnd.nextInt(3)
      if (selector == 0)
        LocationPercept.randomValue
      else
        DirtPercept.randomValue
    }

    val givenPercepts = randomPerceptStream.take(100).toList

    invokeAgent(givenPercepts)

    agent.percepts.toList must_== givenPercepts
  }

  trait context extends Scope {
    val agent = new TableDrivenVacuumAgentProgram
    def invokeAgent(percepts: List[VacuumPercept]): List[VacuumAction] = {
      percepts.map(agent.agentFunction)
    }
  }
} 
Example 33
Source File: ModelBasedReflexVacuumAgentSpec.scala    From aima-scala   with MIT License 5 votes vote down vote up
package aima.core.environment.vacuum

import org.specs2.mutable.Specification
import org.specs2.specification.Scope


class ModelBasedReflexVacuumAgentSpec extends Specification {

  "should suck if location A" in new context {
    agent.agentFunction.apply(LocationAPercept) must beLike {
      case Suck => ok
    }
  }

  "should move if location A is clean" in new context {
    agent.agentFunction.apply(LocationAPercept)
    agent.agentFunction.apply(CleanPercept) must beLike {
      case RightMoveAction => ok
    }
  }

  "should assume dirty after moving to location B" in new context {
    agent.agentFunction.apply(LocationAPercept)
    agent.agentFunction.apply(CleanPercept)
    agent.agentFunction.apply(LocationBPercept) must beLike {
      case Suck => ok
    }
  }

  "should suck if location B" in new context {
    agent.agentFunction.apply(LocationBPercept) must beLike {
      case Suck => ok
    }
  }

  "should move if location B is clean" in new context {
    agent.agentFunction.apply(LocationBPercept)
    agent.agentFunction.apply(CleanPercept) must beLike {
      case LeftMoveAction => ok
    }
  }

  "should assume dirty after moving to location A" in new context {
    agent.agentFunction.apply(LocationBPercept)
    agent.agentFunction.apply(CleanPercept)
    agent.agentFunction.apply(LocationAPercept) must beLike {
      case Suck => ok
    }
  }

  "should suck if dirty" in new context {
    agent.agentFunction.apply(DirtyPercept) must beLike {
      case Suck => ok
    }
  }

  "should do nothing if low on power" in new context {
    val resultStream = LazyList.continually(agent.agentFunction.apply(DirtyPercept))
    resultStream.take(100).last must beLike {
      case NoAction => ok
    }
  }

  trait context extends Scope {
    val agent = new ModelBasedReflexVacuumAgentProgram
  }
} 
Example 34
Source File: SimpleReflexVacuumAgentSpec.scala    From aima-scala   with MIT License 5 votes vote down vote up
package aima.core.environment.vacuum

import org.specs2.mutable.Specification
import org.specs2.specification.Scope


class SimpleReflexVacuumAgentSpec extends Specification {

  "should move right if location A" in new context {
    agent.agentFunction.apply(LocationAPercept) must beLike {
      case RightMoveAction => ok
    }
  }

  "should move left if location B" in new context {
    agent.agentFunction.apply(LocationBPercept) must beLike {
      case LeftMoveAction => ok
    }
  }

  "should suck if dirty" in new context {
    agent.agentFunction.apply(DirtyPercept) must beLike {
      case Suck => ok
    }
  }

  trait context extends Scope {
    val agent = new SimpleReflexVacuumAgentProgram

  }
} 
Example 35
Source File: PrettyPrinterSpec.scala    From random-data-generator   with Apache License 2.0 5 votes vote down vote up
package com.danielasfregola.randomdatagenerator.utils

import org.specs2.mock.Mockito
import org.specs2.mutable._
import org.specs2.specification.Scope
import scala.collection.mutable.ListBuffer

class PrettyPrinterSpec extends SpecificationLike with Mockito {

  abstract class PrettyPrinterSpecContext extends Scope {
    val logs: ListBuffer[String] = new ListBuffer
    private def append(log: String): Unit = synchronized { logs += log; () }

    val printer = {
      val mockPrintF = (log: String) => append(log)
      new PrettyPrinter(mockPrintF)
    }
  }

  "PrettyPrinter" should {

    "print an info message" in new PrettyPrinterSpecContext {
      val msg = "This is my info message"
      printer.info(msg)
      logs must haveSize(1)
      logs must_== ListBuffer(s"[info] [RandomDataGenerator] $msg")
    }

    "print an warning message" in new PrettyPrinterSpecContext {
      val msg = "This is my warning message"
      printer.warning(msg)
      logs must haveSize(1)
      logs must_== ListBuffer(s"[warn] [RandomDataGenerator] $msg")
    }

    "print an error message" in new PrettyPrinterSpecContext {
      val msg = "This is my error message"
      printer.error(msg)
      logs must haveSize(1)
      logs must_== ListBuffer(s"[error] [RandomDataGenerator] $msg")
    }

    "print an debug message" in new PrettyPrinterSpecContext {
      val msg = "This is my debug message"
      printer.debug(msg)
      logs must haveSize(1)
      logs must_== ListBuffer(s"[debug] [RandomDataGenerator] $msg")
    }
  }

} 
Example 36
Source File: SeedDetectorSpec.scala    From random-data-generator   with Apache License 2.0 5 votes vote down vote up
package com.danielasfregola.randomdatagenerator.utils

import org.scalacheck.rng.Seed
import org.specs2.mock.Mockito
import org.specs2.mutable._
import org.specs2.specification.Scope

class SeedDetectorSpec extends SpecificationLike with Mockito {

  abstract class SeedDetectorSpecContext extends Scope {
    val myRandomLong = scala.util.Random.nextLong

    def buildSeedDetector(myEnvVariable: Option[String]) = new SeedDetector {
      override protected lazy val envVariable = myEnvVariable
      override protected def randomLong = myRandomLong
    }
  }

  "SeedDetector" should {

    "when RANDOM_DATA_GENERATOR_SEED is not defined" should {
      "randomly select a seed value" in new SeedDetectorSpecContext {
        val seedDetector = buildSeedDetector(myEnvVariable = None)
        seedDetector.seed === Seed(myRandomLong)
      }
    }

    "when RANDOM_DATA_GENERATOR_SEED is defined" should {
      "set seed to the variable value" in new SeedDetectorSpecContext {
        val mySeed = "1234567"
        val seedDetector = buildSeedDetector(myEnvVariable = Some(mySeed))
        seedDetector.seed === Seed(mySeed.toLong)
      }

      "throw exception if the variable value is not numeric" in new SeedDetectorSpecContext {
        val mySeed = "not-a-valid-value"
        val seedDetector = buildSeedDetector(myEnvVariable = Some(mySeed))
        seedDetector.seed should throwA[RuntimeException]
      }
    }
  }

} 
Example 37
Source File: ConversionsUtilsTest.scala    From scala-serialization   with MIT License 5 votes vote down vote up
package com.komanov.serialization.converters

import java.time.Instant
import java.util.UUID

import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope

class ConversionsUtilsTest extends SpecificationWithJUnit {

  "UUID" should {
    "be serialized-parsed" in new ctx {
      val zero = new UUID(0, 0)
      val rnd = UUID.randomUUID()
      ConversionUtils.bytesToUuid(ConversionUtils.uuidToBytes(null)) must beNull
      ConversionUtils.bytesToUuid(ConversionUtils.uuidToBytes(zero)) must be_===(zero)
      ConversionUtils.bytesToUuid(ConversionUtils.uuidToBytes(rnd)) must be_===(rnd)

      ConversionUtils.bytesToUuid(ConversionUtils.uuidToByteBuffer(null)) must beNull
      ConversionUtils.bytesToUuid(ConversionUtils.uuidToByteBuffer(zero)) must be_===(zero)
      ConversionUtils.bytesToUuid(ConversionUtils.uuidToByteBuffer(rnd)) must be_===(rnd)
    }
  }

  "Instant" should {
    "be serialized-parsed" in new ctx {
      val zero = Instant.ofEpochMilli(0)
      val now = Instant.now()
      ConversionUtils.longToInstance(ConversionUtils.instantToLong(zero)) must be_===(zero)
      ConversionUtils.longToInstance(ConversionUtils.instantToLong(now)) must be_===(now)
    }
  }

  class ctx extends Scope {
  }

} 
Example 38
Source File: SerializationTest.scala    From scala-serialization   with MIT License 5 votes vote down vote up
package com.komanov.serialization.converters

import java.io.ByteArrayOutputStream

import com.komanov.serialization.domain.SiteEventData
import org.apache.commons.io.HexDump
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope
import org.specs2.specification.core.Fragments

class SerializationTest extends SpecificationWithJUnit {

  sequential

  doTest("JSON", JsonConverter)
  doTest("ScalaPB", ScalaPbConverter)
  doTest("Java Protobuf", JavaPbConverter)
  doTest("Java Thrift", JavaThriftConverter)
  doTest("Scrooge", ScroogeConverter)
  doTest("Serializable", JavaSerializationConverter)
  doTest("Pickling", PicklingConverter)
  doTest("BooPickle", BoopickleConverter)
  doTest("Chill", ChillConverter)

  "ScalaPB and Java Protobuf" should {
    Fragments.foreach(TestData.sites) { case (name, site) =>
      s"be interoperable for site of $name" in new ctx {
        val javaMessage = JavaPbConverter.toByteArray(site)
        val scalaMessage = ScalaPbConverter.toByteArray(site)
        toHexDump(javaMessage) must be_===(toHexDump(scalaMessage))
      }
    }

    Fragments.foreach(TestData.events) { case (name, events) =>
      s"be interoperable events of $name" in new ctx {
        for (SiteEventData(_, event, _) <- events) {
          val javaMessage = JavaPbConverter.toByteArray(event)
          val scalaMessage = ScalaPbConverter.toByteArray(event)
          toHexDump(javaMessage) must be_===(toHexDump(scalaMessage))
        }
      }
    }
  }

  "Scrooge and Java Thrift" should {
    Fragments.foreach(TestData.sites) { case (name, site) =>
      s"be interoperable for site of $name" in new ctx {
        val javaMessage = JavaThriftConverter.toByteArray(site)
        val scalaMessage = ScroogeConverter.toByteArray(site)
        toHexDump(javaMessage) must be_===(toHexDump(scalaMessage))
      }
    }

    Fragments.foreach(TestData.events) { case (name, events) =>
      s"be interoperable events of $name" in new ctx {
        for (SiteEventData(_, event, _) <- events) {
          val javaMessage = JavaThriftConverter.toByteArray(event)
          val scalaMessage = ScroogeConverter.toByteArray(event)
          toHexDump(javaMessage) must be_===(toHexDump(scalaMessage))
        }
      }
    }
  }

  class ctx extends Scope

  def toHexDump(arr: Array[Byte]): String = {
    if (arr.isEmpty) {
      ""
    } else {
      val baos = new ByteArrayOutputStream
      HexDump.dump(arr, 0, baos, 0)
      new String(baos.toByteArray)
    }
  }

  def doTest(converterName: String, converter: MyConverter) = {
    converterName should {
      Fragments.foreach(TestData.sites) { case (name, site) =>
        s"serialize-parse site of $name" in new ctx {
          val bytes = converter.toByteArray(site)
          val parsed = converter.fromByteArray(bytes)
          parsed must be_===(site)
        }
      }

      Fragments.foreach(TestData.events) { case (name, events) =>
        s"serialize-parse site events of $name" in new ctx {
          for (SiteEventData(_, event, _) <- events) {
            val bytes = converter.toByteArray(event)
            val parsed = converter.siteEventFromByteArray(event.getClass, bytes)
            parsed must be_===(event)
          }
        }
      }
    }
  }

} 
Example 39
Source File: ThirdPartyOverridesReaderTest.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wixpress.build.bazel

import com.fasterxml.jackson.core.JsonProcessingException
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope

//noinspection TypeAnnotation
class ThirdPartyOverridesReaderTest extends SpecificationWithJUnit {
  "ThirdPartyOverridesReader" should {
    trait ctx extends Scope{
      def someRuntimeOverrides = someOverrides("runtime")
      def someCompileTimeOverrides = someOverrides("compile")
      def someOverrides(classifier: String) = Some({
        {1 to 10}
          .map(index => OverrideCoordinates("com.example", s"some-artifact$index-$classifier") -> Set(s"label$index-$classifier"))
          .toMap
      })
    }

    "throw parse exception given invalid overrides json string" in {
      ThirdPartyOverridesReader.from("{invalid") must throwA[JsonProcessingException]
    }

    "read third party overrides from generated json" in new ctx {
      val originalOverrides = ThirdPartyOverrides(someRuntimeOverrides, someCompileTimeOverrides)
      val json = {
        val objectMapper = ThirdPartyOverridesReader.mapper
        objectMapper.writeValueAsString(originalOverrides)
      }

      val readOverrides = ThirdPartyOverridesReader.from(json)

      readOverrides mustEqual originalOverrides
    }

    "read third party overrides from manual json" in {
      val overrides = ThirdPartyOverridesReader.from(
        """{
          |  "runtimeOverrides" : {
          |  "com.example:an-artifact" :
          |   ["some-label"],
          |  "other.example:other-artifact" :
          |   ["other-label"]
          |  },
          |  "compileTimeOverrides" : {
          |  "com.example:an-artifact" :
          |   ["some-label"],
          |  "other.example:other-artifact" :
          |   ["other-label"]
          |  }
          |}""".stripMargin)

      overrides.runtimeDependenciesOverridesOf(OverrideCoordinates("com.example","an-artifact")) must contain("some-label")
      overrides.runtimeDependenciesOverridesOf(OverrideCoordinates("other.example","other-artifact")) must contain("other-label")

      overrides.compileTimeDependenciesOverridesOf(OverrideCoordinates("com.example","an-artifact")) must contain("some-label")
      overrides.compileTimeDependenciesOverridesOf(OverrideCoordinates("other.example","other-artifact")) must contain("other-label")
    }

    "fail when OverrideCoordinates key is in bad format" in {
      ThirdPartyOverridesReader.from(
        """{
          |  "runtimeOverrides" : {
          |  "com" :
          |   ["some-label"],
          |}""".stripMargin) must throwA[JsonProcessingException]("OverrideCoordinates.*groupId:artifactId")
    }

    "have sensible defaults when reading an empty json object to support specifying either compile/runtime on their own" in {
      val partialOverrides = ThirdPartyOverridesReader.from("{}")

      (partialOverrides.compileTimeDependenciesOverridesOf(OverrideCoordinates("foo","bar")) must beEmpty) and
      (partialOverrides.runtimeDependenciesOverridesOf(OverrideCoordinates("foo","bar")) must beEmpty)
    }

  }

} 
Example 40
Source File: DiffSynchronizerIT.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wixpress.build.bazel

import com.wixpress.build.BazelWorkspaceDriver
import com.wixpress.build.BazelWorkspaceDriver._
import com.wixpress.build.maven.MavenMakers._
import com.wixpress.build.maven._
import com.wixpress.build.sync.DiffSynchronizer
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope

//noinspection TypeAnnotation
class DiffSynchronizerIT extends SpecificationWithJUnit {
  sequential

  val fakeMavenRepository = new FakeMavenRepository()

  "DiffSynchronizer" should {

    "reflect scope (Runtime) of aether resolved transitive dependency in scala_import target" in new baseCtx {
      val transitiveDependencyRuntimeScope = transitiveDependency.withScope(MavenScope.Runtime)
      val transitiveDependencyCompileScope = transitiveDependencyRuntimeScope.withScope(MavenScope.Compile)

      givenBazelWorkspaceWithManagedDependencies(
        DependencyNode(managedDependency, Set(transitiveDependencyRuntimeScope)),
        aRootDependencyNode(transitiveDependencyRuntimeScope))

      val resolver = givenAetherResolverForDependency(SingleDependency(managedDependency, transitiveDependencyRuntimeScope))
      val synchronizer = givenSynchornizerFor(resolver)


      val resolvedNodes = resolver.dependencyClosureOf(List(managedDependency, transitiveDependencyCompileScope), List.empty)

      synchronizer.sync(resolvedNodes)

      bazelWorkspace must includeImportExternalTargetWith(artifact = managedDependency.coordinates,
          runtimeDependencies = Set(transitiveDependency.coordinates))

      bazelWorkspace must notIncludeImportExternalRulesInWorkspace(transitiveDependency.coordinates)
    }
  }

  trait baseCtx extends Scope {
    private val externalFakeLocalWorkspace = new FakeLocalBazelWorkspace(localWorkspaceName = "some_external_workspace_name")
    val externalFakeBazelRepository = new InMemoryBazelRepository(externalFakeLocalWorkspace)
    private val targetFakeLocalWorkspace = new FakeLocalBazelWorkspace(localWorkspaceName = "some_local_workspace_name")
    val targetFakeBazelRepository = new InMemoryBazelRepository(targetFakeLocalWorkspace)
    val importExternalLoadStatement = ImportExternalLoadStatement(importExternalRulePath = "@some_workspace//:import_external.bzl", importExternalMacroName = "some_import_external")

    val bazelWorkspace = new BazelWorkspaceDriver(targetFakeLocalWorkspace)

    val managedDependency = aDependency("base")
    val transitiveDependency = aDependency("transitive")

    def givenBazelWorkspaceWithManagedDependencies(managedDeps: DependencyNode*) = {
      writerFor(externalFakeLocalWorkspace).writeDependencies(managedDeps.map(_.toBazelNode).toSet)
    }

    private def writerFor(localWorkspace: BazelLocalWorkspace, neverLinkResolver: NeverLinkResolver = NeverLinkResolver()) = {
      new BazelDependenciesWriter(localWorkspace, neverLinkResolver, importExternalLoadStatement = importExternalLoadStatement)
    }

    def givenAetherResolverForDependency(node: SingleDependency) = {
      val dependantDescriptor = ArtifactDescriptor.withSingleDependency(node.dependant.coordinates, node.dependency)
      val dependencyDescriptor = ArtifactDescriptor.rootFor(node.dependency.coordinates)

      fakeMavenRepository.addArtifacts(Set(dependantDescriptor,dependencyDescriptor))
      fakeMavenRepository.start()
      new AetherMavenDependencyResolver(List(fakeMavenRepository.url))
    }

    def givenSynchornizerFor(resolver: MavenDependencyResolver) = {
      DiffSynchronizer(Some(externalFakeBazelRepository), targetFakeBazelRepository, resolver, _ => None, NeverLinkResolver(), importExternalLoadStatement)
    }

  }
} 
Example 41
Source File: BazelDependenciesPersisterTest.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wixpress.build.bazel

import com.wixpress.build.maven.MavenMakers
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope

//noinspection TypeAnnotation
class BazelDependenciesPersisterTest extends SpecificationWithJUnit {
  "BazelDependenciesPersister should persist files with appropriate message" >> {
    trait ctx extends Scope {
      val branch = "master"
      val header = "some header"
      val bazelRepository = new FakeBazelRepository()
      val persister = new BazelDependenciesPersister(header, bazelRepository)
    }

    "given a single dependency and a single file path" in new ctx {
      val changedFiles = Set("some-file")
      val coordinates = MavenMakers.someCoordinates("artifact")
      val dependenciesSet = Set(coordinates)

      persister.persistWithMessage(changedFiles, dependenciesSet)

      bazelRepository.lastCommit should beEqualTo(DummyCommit(
        branchName = branch,
        changedFilePaths = changedFiles,
        message =
          s"""$header
             | - ${coordinates.serialized}
             |""".stripMargin))
    }

    "given multiple files and dependencies" in new ctx {
      val changedFiles = Set("file1", "file2")
      val someDependencies = {
        1 to 5
      }.map(index => MavenMakers.someCoordinates(s"artifact-$index")).reverse.toSet

      persister.persistWithMessage(changedFiles, someDependencies)

      bazelRepository.lastCommit should beEqualTo(DummyCommit(
        branchName = branch,
        changedFilePaths = changedFiles,
        message =
          s"""$header
             |${someDependencies.map(_.serialized).toSeq.sorted.map(c => s" - $c").mkString("\n")}
             |""".stripMargin))
    }

    "given asPr = true add #pr" in new ctx {
      val changedFiles = Set("some-file")
      val coordinates = MavenMakers.someCoordinates("artifact")
      val dependenciesSet = Set(coordinates)

      persister.persistWithMessage(changedFiles, dependenciesSet, asPr = true)

      bazelRepository.lastCommit should beEqualTo(DummyCommit(
        branchName = branch,
        changedFilePaths = changedFiles,
        message =
          s"""$header
             | - ${coordinates.serialized}
             |#pr""".stripMargin))
    }
  }
}

class FakeBazelRepository() extends BazelRepository {
  private val commits = collection.mutable.ListBuffer.empty[DummyCommit]

  def lastCommit: DummyCommit = commits.last

  override def resetAndCheckoutMaster(): BazelLocalWorkspace = {
    throw new RuntimeException("this class is only for dummy commits purpose")
  }

  override def persist(branchName: String, changedFilePaths: Set[String], message: String): Unit = {
    commits.append(DummyCommit(branchName, changedFilePaths, message))
  }

}

case class DummyCommit(branchName: String, changedFilePaths: Set[String], message: String) 
Example 42
Source File: RomaniaBreadthFirstSearchSpec.scala    From aima-scala   with MIT License 5 votes vote down vote up
package aima.core.search.uninformed

import aima.core.search.StateNode
import aima.core.search.problems.Romania._
import org.specs2.mutable.Specification
import org.specs2.specification.Scope

import scala.reflect.ClassTag


class RomaniaBreadthFirstSearchSpec extends Specification {

  "going from Arad to Arad must return no actions" in new context {
    search(new RomaniaRoadProblem(In(Arad), In(Arad)), NoAction) must beEmpty
  }

  "going from Arad to Bucharest must return a list of actions" in new context {
    search(new RomaniaRoadProblem(In(Arad), In(Bucharest)), NoAction) must_== List(
      GoTo(Sibiu),
      GoTo(Fagaras),
      GoTo(Bucharest)
    )
  }

  trait context extends Scope with BreadthFirstSearch[RomaniaState, RomaniaAction] {

    override implicit val sCT: ClassTag[RomaniaState]                           = sCTag
    override implicit val aCT: ClassTag[RomaniaAction]                          = aCTag
    override implicit val nCT: ClassTag[StateNode[RomaniaState, RomaniaAction]] = snCTag
  }

} 
Example 43
Source File: MavenScopeTest.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wixpress.build.maven

import com.wix.bazel.migrator.Persister
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope
import org.specs2.specification.core.{Fragment, Fragments}

class MavenScopeTest extends SpecificationWithJUnit {
  val ScopesToNames = List(
    ScopeToName(MavenScope.Compile,"compile"),
    ScopeToName(MavenScope.Test,"test"),
    ScopeToName(MavenScope.Runtime,"runtime"),
    ScopeToName(MavenScope.Provided,"provided"),
    ScopeToName(MavenScope.System,"system")
  )

  private def aNewInstanceOf(scope: MavenScope): MavenScope = {
    mapper.readValue(mapper.writeValueAsString(scope), classOf[MavenScope])
  }

  private def extractTest(scopeToName:ScopeToName):Fragment ={
    s"parse ${scopeToName.scope} from string '${scopeToName.name}'" in {
      MavenScope.of(scopeToName.name) mustEqual scopeToName.scope
    }

    s"have equals working on different instances(!) of the same ${scopeToName.scope} value " +
      "(different instances can be created by jackson deserialization)" in {
      val differentInstance = aNewInstanceOf(scopeToName.scope)
      differentInstance.eq(scopeToName.scope) must beFalse
      differentInstance mustEqual scopeToName.scope
    }

    s"have hash working on different instances(!) of the same ${scopeToName.scope} value " +
      "(different instances can be created by jackson deserialization)" in {
      val differentInstance = aNewInstanceOf(scopeToName.scope)
      differentInstance.eq(scopeToName.scope) must beFalse
      differentInstance.hashCode() mustEqual scopeToName.scope.hashCode()
    }
  }

  val mapper = Persister.objectMapper

  def allTests:Fragments = Fragments(ScopesToNames.map(extractTest): _*)

  "MavenScope" should {
    allTests
  }

  "equals" should {
    "return 'false' for two different scopes" in new Context {
      MavenScope.Compile mustNotEqual MavenScope.Provided
    }

    "return 'false' when comparing to an object which is not an instance of MavenScope" in new Context {
      MavenScope.System mustNotEqual 3
    }
  }

  "hashCode" should {
    "return different hash for differnt scopes" in new Context {
      MavenScope.Runtime.hashCode() mustNotEqual MavenScope.Test.hashCode()
    }
  }

  abstract class Context extends Scope {

  }
}

case class ScopeToName(scope:MavenScope, name:String) 
Example 44
Source File: DependencyCollectorTest.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wixpress.build.maven

import com.wixpress.build.maven.MavenMakers.aDependency
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope

//noinspection TypeAnnotation
class DependencyCollectorTest extends SpecificationWithJUnit {

  trait ctx extends Scope {

  }

  "DependencyCollector" >> {
    "when no new dependencies were added after initialization" should {
      "return empty dependency set" in new ctx {
        val collector = new DependencyCollector()
        collector.dependencySet() mustEqual Set.empty[Dependency]
      }

      "return a set with dependencies after they were added using the addOrOverrideDependencies call" in new ctx {
        val collector = new DependencyCollector()
        val newDependencies = Set(aDependency("a"))

        collector
          .addOrOverrideDependencies(newDependencies)
          .dependencySet() must contain(allOf(newDependencies))
      }


      "merge all exclusions for each dependency" in new ctx {
        val otherDependency = aDependency("guava", exclusions = Set(MavenMakers.anExclusion("a")))
        val newDependencies = Set(
          aDependency("b", exclusions = Set(MavenMakers.anExclusion("a"))),
          aDependency("b", exclusions = Set(MavenMakers.anExclusion("c"))),
          aDependency("b", exclusions = Set(MavenMakers.anExclusion("d"))),
          otherDependency)
        val collector = new DependencyCollector(newDependencies)

        collector.mergeExclusionsOfSameCoordinates().dependencySet() mustEqual Set(
          aDependency("b", exclusions = Set(
            MavenMakers.anExclusion("a"),
            MavenMakers.anExclusion("c"),
            MavenMakers.anExclusion("d"))),
          otherDependency)
      }
    }

    "after already collect dependency A," should {
      trait oneCollectedDependencyCtx extends ctx {
        val existingDependency: Dependency = aDependency("existing")
        def collector = new DependencyCollector(Set(existingDependency))
      }

      "return a set with both A and new dependencies after they were added using the with dependencies call" in new oneCollectedDependencyCtx {
        val newDependency = aDependency("new")
        collector
          .addOrOverrideDependencies(Set(newDependency))
          .dependencySet() mustEqual Set(existingDependency, newDependency)
      }

      "allow overriding the version of A by adding a set with a different version of A" in new oneCollectedDependencyCtx {
        val newDependency = existingDependency.withVersion("different-version")

        collector
          .addOrOverrideDependencies(Set(newDependency))
          .dependencySet() mustEqual Set(newDependency)
      }

    }

  }
} 
Example 45
Source File: MavenCoordinatesListReaderIT.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wix.bazel.migrator.utils

import java.nio.charset.StandardCharsets
import java.nio.file.{Files, NoSuchFileException, Path}

import com.github.marschall.memoryfilesystem.MemoryFileSystemBuilder
import com.wixpress.build.maven.MavenCoordinatesListReader
import com.wixpress.build.maven.MavenMakers.someCoordinates
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope

//noinspection TypeAnnotation
class MavenCoordinatesListReaderIT extends SpecificationWithJUnit{
  "MavenCoordinatesListReader" should {
    "read file with coordinates" in new Ctx{
      val coordinatesA = someCoordinates("a")
      val coordinatesB = someCoordinates("b")
      val fileContent = s"""${coordinatesA.serialized}
                            |${coordinatesB.serialized}""".stripMargin
      val filePath:Path = fileWithContent(fileContent)

      MavenCoordinatesListReader.coordinatesIn(filePath) mustEqual Set(coordinatesA,coordinatesB)
    }

    "ignore empty line" in new Ctx{
      val coordinatesA = someCoordinates("a")
      val coordinatesB = someCoordinates("b")
      val fileContent = s"""${coordinatesA.serialized}
                           |
                           |${coordinatesB.serialized}""".stripMargin
      val filePath:Path = fileWithContent(fileContent)

      MavenCoordinatesListReader.coordinatesIn(filePath) mustEqual Set(coordinatesA,coordinatesB)
    }

    "ignore preceding and trailing spaces" in new Ctx{
      val coordinatesA = someCoordinates("a")
      val coordinatesB = someCoordinates("b")
      val fileContent = s"    ${coordinatesA.serialized}   "
      val filePath:Path = fileWithContent(fileContent)

      MavenCoordinatesListReader.coordinatesIn(filePath) mustEqual Set(coordinatesA)
    }

    "ignore lines that starts with #" in new Ctx{
      val coordinatesA = someCoordinates("a")
      val coordinatesB = someCoordinates("b")
      val fileContent = s"""${coordinatesA.serialized}
                            |#${coordinatesB.serialized}""".stripMargin
      val filePath:Path = fileWithContent(fileContent)

      MavenCoordinatesListReader.coordinatesIn(filePath) mustEqual Set(coordinatesA)
    }

    "throw exception in case file is missing" in new Ctx{
      MavenCoordinatesListReader.coordinatesIn(fs.getPath("non-existing-file")) must throwA[NoSuchFileException]
    }
  }

  trait Ctx extends Scope{
    val fs = MemoryFileSystemBuilder.newLinux().build()
    def fileWithContent(content:String):Path = {
      val path = Files.createTempFile(fs.getPath("/"),"",".txt")
      Files.write(path, content.getBytes(StandardCharsets.UTF_8))
    }
  }

} 
Example 46
Source File: InternalTargetOverridesReaderIT.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wix.bazel.migrator.overrides

import java.nio.file.Path

import com.fasterxml.jackson.core.JsonProcessingException
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope

class InternalTargetOverridesReaderIT extends SpecificationWithJUnit {
  "read" should {
    "throw parse exception given invalid overrides json string" in new Context {
      writeOverrides("invl:")

      InternalTargetOverridesReader.from(repoRoot) must throwA[JsonProcessingException]
    }
    "default to no overrides when trying to read an non existent overrides file" in new Context {
      InternalTargetOverridesReader.from(repoRoot).targetOverrides must beEmpty
    }

    "read empty overrides" in new Context {
      val label = "//some/path/to/target:target"

      writeOverrides(
        s"""|{
            |  "targetOverrides" : [ {
            |      "label" : "$label"
            |  } ]
            |}""".stripMargin
      )

      InternalTargetOverridesReader.from(repoRoot) must beEqualTo(
        InternalTargetsOverrides(Set(InternalTargetOverride(label)))
      )
    }

    "read docker image dep from manual json" in new Context {
      val label = "//some/path/to/target:target"
      val dockerImage = "docker-repo/docker-image:t.a.g"

      writeOverrides(
        s"""{
           |  "targetOverrides" : [ {
           |      "label" : "$label",
           |      "dockerImagesDeps" : [ "$dockerImage" ]
           |  } ]
           |}""".stripMargin)

      InternalTargetOverridesReader.from(repoRoot) must beEqualTo(
        InternalTargetsOverrides(Set(InternalTargetOverride(label, dockerImagesDeps = Option(List(dockerImage))))))
    }

    "read block network from manual json" in new Context {
      val label = "//some/path/to/target:target"
      val blockNetwork = false

      writeOverrides(
        s"""{
           |  "targetOverrides" : [ {
           |      "label" : "$label",
           |      "blockNetwork" : $blockNetwork
           |  } ]
           |}""".stripMargin)

      InternalTargetOverridesReader.from(repoRoot) must beEqualTo(
        InternalTargetsOverrides(Set(InternalTargetOverride(label, blockNetwork = Some(blockNetwork)))))
    }
  }

  abstract class Context extends Scope with OverridesReaderITSupport {
    override val overridesPath: Path = setupOverridesPath(repoRoot, "internal_targets.overrides")
  }

} 
Example 47
Source File: AdditionalDepsByMavenDepsOverridesReaderIT.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wix.bazel.migrator.overrides

import java.nio.file.Path

import org.specs2.matcher.Matcher
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope

//noinspection TypeAnnotation
class AdditionalDepsByMavenDepsOverridesReaderIT extends SpecificationWithJUnit {
  "read" should {
    "throw parse exception given invalid overrides json string" in new Context {
      writeOverrides("invl:")

      AdditionalDepsByMavenDepsOverridesReader.from(overridesPath) must throwA[OverrideParsingException]
    }

    "read overrides from manual json" in new Context {

      writeOverrides(
        s"""{ "overrides" : [{
           |   "groupId" : "$groupId",
           |   "artifactId" : "$artifactId",
           |   "additionalDeps": {
           |      "deps" : ["$dependency"],
           |      "runtimeDeps" : ["$runtimeDependency"]
           |    }
           |  }
           |]}""".stripMargin)
      private val expectedOverride = AdditionalDepsByMavenDepsOverride(
        groupId,
        artifactId,
        AdditionalDeps(
          deps = Set(dependency),
          runtimeDeps = Set(runtimeDependency)))
      AdditionalDepsByMavenDepsOverridesReader.from(overridesPath) must containExactly(expectedOverride)
    }

    "read overrides from manual json with only runtime deps" in new Context {
      writeOverrides(
        s"""{ "overrides" : [{
           |   "groupId" : "$groupId",
           |   "artifactId" : "$artifactId",
           |   "additionalDeps": {
           |      "runtimeDeps" : ["$runtimeDependency"]
           |    }
           |  }
           |]}""".stripMargin)
      private val expectedOverride = AdditionalDepsByMavenDepsOverride(
        groupId,
        artifactId,
        AdditionalDeps(
          deps = Set.empty,
          runtimeDeps = Set(runtimeDependency)))
      AdditionalDepsByMavenDepsOverridesReader.from(overridesPath) must containExactly(expectedOverride)
    }.pendingUntilFixed("currently it reads 'deps' field as null, must specify empty array")

    "read overrides from generated json" in new Context {
      val overrides = AdditionalDepsByMavenDepsOverrides(List(AdditionalDepsByMavenDepsOverride(
        groupId,
        artifactId,
        AdditionalDeps(
          deps = Set(dependency),
          runtimeDeps = Set(runtimeDependency)))))
      writeOverrides(objectMapper.writeValueAsString(overrides))

      AdditionalDepsByMavenDepsOverridesReader.from(overridesPath) must beEqualTo(overrides)
    }

    "default to no overrides when trying to read an non existent overrides file" in new Context {
      AdditionalDepsByMavenDepsOverridesReader.from(overridesPath) must haveNoOverrides
    }

  }

  abstract class Context extends Scope with OverridesReaderITSupport {
    val groupId = "some.group"
    val artifactId = "some-artifact"
    val dependency = "//some:dependency"
    val runtimeDependency = "//some/runtime:dependency"
    override val overridesPath: Path = setupOverridesPath(repoRoot, "additional_deps_by_maven.overrides")
  }

  def containExactly(expectedOverride:AdditionalDepsByMavenDepsOverride): Matcher[AdditionalDepsByMavenDepsOverrides] =
    {(_:AdditionalDepsByMavenDepsOverrides).overrides} ^^ contain(exactly(expectedOverride))

  def haveNoOverrides: Matcher[AdditionalDepsByMavenDepsOverrides] =
    {(_:AdditionalDepsByMavenDepsOverrides).overrides} ^^ beEmpty


} 
Example 48
Source File: GeneratedCodeLinksOverridesReaderIT.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wix.bazel.migrator.overrides

import java.nio.file.Path

import com.fasterxml.jackson.core.JsonProcessingException
import com.wix.bazel.migrator
import com.wixpress.build.maven.{Coordinates, MavenMakers}
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope

//noinspection TypeAnnotation
class GeneratedCodeLinksOverridesReaderIT extends SpecificationWithJUnit {
  "read" should {
    "throw parse exception given invalid overrides json string" in new Context {
      writeOverrides("invl:")

      GeneratedCodeOverridesReader.from(repoRoot) must throwA[JsonProcessingException]
    }

    "read overrides from manual json" in new Context {
      val generatedFile = "com/wixpress/Foo.scala"
      val sourceFile = "com/wixpress/foo.proto"
      writeOverrides(
        s"""{
           |  "links" : [ {
           |      "groupId" : "${module.groupId}",
           |      "artifactId" : "${module.artifactId}",
           |      "generatedFile" : "$generatedFile",
           |      "sourceFile" : "$sourceFile"
           |  } ]
           |}""".stripMargin)

      GeneratedCodeOverridesReader.from(repoRoot) must beEqualTo(GeneratedCodeLinksOverrides(Seq(
        GeneratedCodeLink(module.groupId, module.artifactId, generatedFile, sourceFile))))
    }

    "read overrides from generated json" in new Context {
      val overrides = multipleOverrides
      writeOverrides(objectMapper.writeValueAsString(overrides))

      GeneratedCodeOverridesReader.from(repoRoot) must beEqualTo(overrides)
    }

    "default to no overrides when trying to read an non existent overrides file" in new Context {
      GeneratedCodeOverridesReader.from(repoRoot).links must beEmpty
    }

  }

  abstract class Context extends Scope with OverridesReaderITSupport {
    val module: Coordinates = MavenMakers.someCoordinates("some-module")
    override val overridesPath: Path = setupOverridesPath(repoRoot, "code_paths.overrides")

    def multipleOverrides: GeneratedCodeLinksOverrides = {
      val overrides = (1 to 20).map { index =>
        GeneratedCodeLink(
          groupId = module.groupId,
          artifactId = module.artifactId,
          generatedFile = s"com/wixpress/Foo$index.scala",
          sourceFile = s"com/wixpress/foo$index.proto"
        )
      }
      migrator.overrides.GeneratedCodeLinksOverrides(overrides)
    }
  }

} 
Example 49
Source File: SourceModulesOverridesReaderIT.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wix.bazel.migrator.overrides

import com.fasterxml.jackson.core.JsonProcessingException
import com.wix.build.maven.analysis.SourceModulesOverrides
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope

//noinspection TypeAnnotation
class SourceModulesOverridesReaderIT extends SpecificationWithJUnit {
  "SourceModulesOverridesReader" should {

    "throw parse exception given invalid overrides json string" in new Context {
      writeOverrides("{invalid")

      SourceModulesOverridesReader.from(repoRoot) must throwA[JsonProcessingException]
    }

    "read overrides from generated json" in new Context {
      val originalOverrides = SourceModulesOverrides(mutedModules)
      writeOverrides(objectMapper.writeValueAsString(originalOverrides))

      SourceModulesOverridesReader.from(repoRoot) mustEqual originalOverrides
    }

    "read overrides from manual json" in new Context {
      writeOverrides("""{
          |  "modulesToMute" : [
          |   "some/path/to/module/one",
          |   "other/path"
          |  ]
          |}""".stripMargin)

      val overrides = SourceModulesOverridesReader.from(repoRoot)

      overrides.modulesToMute must contain("some/path/to/module/one", "other/path")
    }

    "default to no overrides when trying to read an non existent overrides file" in new Context {
      val partialOverrides = SourceModulesOverridesReader.from(repoRoot)

      partialOverrides.modulesToMute must beEmpty
    }

  }

  abstract class Context extends Scope with OverridesReaderITSupport {
    override val overridesPath = setupOverridesPath(repoRoot, "source_modules.overrides")

    def mutedModules: Set[String] =
      { 1 to 10 }
        .map {
          index =>
            s"module$index"
        }.toSet

  }

} 
Example 50
Source File: MavenArchiveTargetsOverridesReaderIT.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wix.bazel.migrator.overrides

import java.nio.file.Path

import com.fasterxml.jackson.core.JsonProcessingException
import com.github.marschall.memoryfilesystem.MemoryFileSystemBuilder
import com.wixpress.build.bazel.OverrideCoordinates
import org.specs2.mutable.SpecificationWithJUnit
import org.specs2.specification.Scope


class MavenArchiveTargetsOverridesReaderIT extends SpecificationWithJUnit {
  "MavenArchiveTargetsOverridesReader" should {

    "return empty set in case override file does not exists" in {
      lazy val fileSystem = MemoryFileSystemBuilder.newLinux().build()
      val repoRoot: Path = fileSystem.getPath("repoRoot")
      MavenArchiveTargetsOverridesReader.from(repoRoot) mustEqual MavenArchiveTargetsOverrides(Set.empty)
    }

    "throw exception in case of invalid json" in new ctx {
      val overridesPath = setupOverridesPath(repoRoot, "maven_archive_targets.overrides")
      writeOverrides("blabla")

      MavenArchiveTargetsOverridesReader.from(repoRoot) must throwA[JsonProcessingException]
    }

    "return empty set in case of empty array in the json" in new ctx {
      val overridesPath = setupOverridesPath(repoRoot, "maven_archive_targets.overrides")
      val json = s"""|{
                     |  "unpackedOverridesToArchive" : []
                     |}""".stripMargin
      writeOverrides(json)
      MavenArchiveTargetsOverridesReader.from(repoRoot) mustEqual MavenArchiveTargetsOverrides(Set.empty)
    }

    "return set of maven archive coordinates to override" in new ctx {
      val overridesPath = setupOverridesPath(repoRoot, "maven_archive_targets.overrides")
      val json = s"""{
                     |  "unpackedOverridesToArchive": [
                     |    {
                     |      "groupId": "some-group",
                     |      "artifactId": "some-artifact-id"
                     |    },
                     |    {
                     |      "groupId": "another-group",
                     |      "artifactId": "another-artifact-id"
                     |    }
                     |  ]
                     |}""".stripMargin

      writeOverrides(json)
      MavenArchiveTargetsOverridesReader.from(repoRoot) mustEqual MavenArchiveTargetsOverrides(Set(
        OverrideCoordinates("some-group", "some-artifact-id"),
        OverrideCoordinates("another-group", "another-artifact-id")))
    }
  }
  trait ctx extends Scope with OverridesReaderITSupport
} 
Example 51
Source File: HighestVersionConflictResolutionTest.scala    From exodus   with MIT License 5 votes vote down vote up
package com.wixpress.build.sync

import com.wixpress.build.maven.MavenMakers.{aDependency, randomCoordinates}
import com.wixpress.build.maven.{Coordinates, Dependency, Exclusion, MavenScope}
import org.specs2.mutable.SpecWithJUnit
import org.specs2.specification.Scope

//noinspection TypeAnnotation
class HighestVersionConflictResolutionTest extends SpecWithJUnit {

  "HighestVersionConflictResolution" should {
    "retain highest version given same groupId, artifactId, classifier" in new Context {
      val higherVersion = dependency(coordinates.copy(version = "2"))
      val lowerVersion = dependency(coordinates.copy(version = "1"))

      resolution.resolve(Set(lowerVersion, higherVersion)) must be_==(Set(higherVersion))
    }
  }

  "ConflictResolution" should {
    "retain both artifacts when they differ in groupId" in new Context {
      val dependencies = Set(
        dependency(coordinates.copy(groupId = "foo")),
        dependency(coordinates.copy(groupId = "bar"))
      )

      resolution.resolve(dependencies) must be_==(dependencies)
    }

    "retain both artifacts when they differ in artifactId" in new Context {
      val dependencies = Set(
        dependency(coordinates.copy(artifactId = "foo")),
        dependency(coordinates.copy(artifactId = "bar"))
      )

      resolution.resolve(dependencies) must be_==(dependencies)
    }

    "retain both artifacts when they differ in classifier" in new Context {
      val dependencies = Set(
        dependency(coordinates.copy(classifier = Some("foo"))),
        dependency(coordinates.copy(classifier = Some("bar")))
      )

      resolution.resolve(dependencies) must be_==(dependencies)
    }

    "collect exclusions from all dependencies of the same groupId and artifactId" in new Context {
      val dep = aDependency("mygroup").withVersion("1.0.2")
      val exclusion1 = Exclusion("ex-group", "ex-artifact")
      val exclusion2 = Exclusion("ex-group", "ex-artifact2")
      val depWithExclusion1 = dep.withExclusions(Set(exclusion1))
      val depWithExclusion2 = dep.withVersion("1.0.1").withExclusions(Set(exclusion2))
      val dependencies = Set(dep, depWithExclusion1, depWithExclusion2)

      resolution.resolve(dependencies) must contain(exactly(dep.withExclusions(Set(exclusion1, exclusion2))))
    }
  }

  abstract class Context extends Scope {
    val resolution = new HighestVersionConflictResolution()
    val coordinates = randomCoordinates()
  }

  protected def dependency(coordinates: Coordinates) = Dependency(coordinates, MavenScope.Compile)
} 
Example 52
Source File: ResponseBodyMatchersTest.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.matchers.internal

import com.wix.e2e.http.matchers.ResponseMatchers._
import com.wix.e2e.http.matchers.drivers.HttpResponseFactory._
import com.wix.e2e.http.matchers.drivers.MarshallingTestObjects.SomeCaseClass
import com.wix.e2e.http.matchers.drivers.{CustomMarshallerProvider, HttpMessageTestSupport, MarshallerTestSupport, MatchersTestSupport}
import org.specs2.matcher.CaseClassDiffs._
import org.specs2.matcher.ResultMatchers._
import org.specs2.mutable.Spec
import org.specs2.specification.Scope

class ResponseBodyMatchersTest extends Spec with MatchersTestSupport {

  trait ctx extends Scope with HttpMessageTestSupport with MarshallerTestSupport with CustomMarshallerProvider

  "ResponseBodyMatchers" should {

    "exact match on response body" in new ctx {
      aResponseWith(content) must haveBodyWith(content)
      aResponseWith(content) must not( haveBodyWith(anotherContent) )
    }

    "match underlying matcher with body content" in new ctx {
      aResponseWith(content) must haveBodyThat(must = be_===( content ))
      aResponseWith(content) must not( haveBodyThat(must = be_===( anotherContent )) )
    }

    "exact match on response binary body" in new ctx {
      aResponseWith(binaryContent) must haveBodyWith(binaryContent)
      aResponseWith(binaryContent) must not( haveBodyWith(anotherBinaryContent) )
    }

    "match underlying matcher with binary body content" in new ctx {
      aResponseWith(binaryContent) must haveBodyDataThat(must = be_===( binaryContent ))
      aResponseWith(binaryContent) must not( haveBodyDataThat(must = be_===( anotherBinaryContent )) )
    }

    "handle empty body" in new ctx {
      aResponseWithoutBody must not( haveBodyWith(content))
    }

    "support unmarshalling body content with user custom unmarshaller" in new ctx {
      givenUnmarshallerWith[SomeCaseClass](someObject, forContent = content)

      aResponseWith(content) must haveBodyWith(entity = someObject)
      aResponseWith(content) must not( haveBodyWith(entity = anotherObject) )
    }

    "provide a meaningful explanation why match failed" in new ctx {
      givenUnmarshallerWith[SomeCaseClass](someObject, forContent = content)

      failureMessageFor(haveBodyWithEntityThat(must = be_===(anotherObject)), matchedOn = aResponseWith(content)) must_===
        s"Failed to match: [SomeCaseClass(s: '${someObject.s}' != '${anotherObject.s}',              i: ${someObject.i} != ${anotherObject.i})] with content: [$content]"
    }

    "provide a proper message to user in case of a badly behaving marshaller" in new ctx {
      givenBadlyBehavingUnmarshallerFor[SomeCaseClass](withContent = content)

      haveBodyWith(entity = someObject).apply( aResponseWith(content) ) must beError(s"Failed to unmarshall: \\[$content\\]")
    }

    "provide a proper message to user sent a matcher to an entity matcher" in new ctx {
      failureMessageFor(haveBodyWith(entity = be_===(someObject)), matchedOn = aResponseWith(content)) must_===
        s"Matcher misuse: `haveBodyWith` received a matcher to match against, please use `haveBodyWithEntityThat` instead."
    }

    "support custom matcher for user object" in new ctx {
      givenUnmarshallerWith[SomeCaseClass](someObject, forContent = content)

      aResponseWith(content) must haveBodyWithEntityThat(must = be_===(someObject))
      aResponseWith(content) must not( haveBodyWithEntityThat(must = be_===(anotherObject)) )
    }
  }
} 
Example 53
Source File: RequestContentTypeMatchersTest.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.matchers.internal

import akka.http.scaladsl.model.ContentTypes._
import com.wix.e2e.http.matchers.RequestMatchers._
import com.wix.e2e.http.matchers.drivers.HttpRequestFactory._
import com.wix.e2e.http.matchers.drivers.{HttpMessageTestSupport, MatchersTestSupport}
import org.specs2.mutable.Spec
import org.specs2.specification.Scope

class RequestContentTypeMatchersTest extends Spec with MatchersTestSupport {

  trait ctx extends Scope with HttpMessageTestSupport

  "RequestContentTypeMatchers" should {

    "exact match on request json content type" in new ctx {
      aRequestWith(`application/json`) must haveJsonBody
      aRequestWith(`text/csv(UTF-8)`) must not( haveJsonBody )
    }

    "exact match on request text plain content type" in new ctx {
      aRequestWith(`text/plain(UTF-8)`) must haveTextPlainBody
      aRequestWith(`text/csv(UTF-8)`) must not( haveTextPlainBody )
    }

    "exact match on request form url encoded content type" in new ctx {
      aRequestWith(`application/x-www-form-urlencoded`) must haveFormUrlEncodedBody
      aRequestWith(`text/csv(UTF-8)`) must not( haveFormUrlEncodedBody )
    }

    "exact match on multipart request content type" in new ctx {
      aRequestWith(`multipart/form-data`) must haveMultipartFormBody
      aRequestWith(`text/csv(UTF-8)`) must not( haveMultipartFormBody )
    }
  }
} 
Example 54
Source File: RequestMethodMatchersTest.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.matchers.internal

import akka.http.scaladsl.model.HttpMethods._
import com.wix.e2e.http.matchers.RequestMatchers._
import com.wix.e2e.http.matchers.drivers.HttpRequestFactory._
import com.wix.e2e.http.matchers.drivers.HttpMessageTestSupport
import org.specs2.mutable.Spec
import org.specs2.specification.Scope


class RequestMethodMatchersTest extends Spec {

  trait ctx extends Scope with HttpMessageTestSupport

  "RequestMethodMatchers" should {

    "match all request methods" in new ctx {
      Seq(POST -> bePost, GET -> beGet, PUT -> bePut, DELETE -> beDelete,
          HEAD -> beHead, OPTIONS -> beOptions,
          PATCH -> bePatch, TRACE -> beTrace, CONNECT -> beConnect)
        .foreach { case (method, matcherForMethod) =>

          aRequestWith( method ) must matcherForMethod
          aRequestWith( randomMethodThatIsNot( method )) must not( matcherForMethod )
        }
    }
  }
}