EzDevInfo.com

specs

Perl 6 language design documents Perl 6 Design Documents

Approaches to testing that a method is not available on a type

Given a type hierarchy for a game which strongly distinguishes whose turn is next:

trait Game
trait BlackToPlay extends Game {
  def move(p: BlackPiece, s: Square): Either[FinishedGame, WhiteToPlay]
}
trait WhiteToPlay extends Game {
  def move(p: WhitePiece, s: Square): Either[FinishedGame, BlackToPlay]
}

Can I make the following, important assertion without resorting to reflection?

"A game with white to play" should {
  "not allow black to play" in {
    // an instance of whiteToPlay should not 
    // have the `move(BlackPiece, Square)` method.
  }
}

EDIT: My attempt to implement @Martin's solution doesn't work. Any thoughts on what's wrong here? From the REPL:

scala> class B() {
     |   def b(s: String) = s
     | }
defined class B

scala> val b = new B()
b: B = B@420e44

scala> b.c("")
<console>:8: error: value c is not a member of B
       b.c("")
         ^

scala> b match {
     |   case _: { def c(s: String) } => false
     |   case _ => true
     | }
warning: there were unchecked warnings; re-run with -unchecked for details
res7: Boolean = false

res7 should have been true, because b should not match on the structural type of { def c(s: String) }


Source: (StackOverflow)

How to compose a Matcher[Iterable[A]] from a Matcher[A] with specs testing framework

If I have a Matcher[A] how do create a Matcher[Iterable[A]] that is satisfied only if each element of the Iterable satisfies the original Matcher.

class ExampleSpec extends Specification {
  def allSatisfy[A](m: => Matcher[A]): Matcher[Iterable[A]] = error("TODO")
  def notAllSatisfy[A](m: => Matcher[A]): Matcher[Iterable[A]] = allSatisfy(m).not    

   "allSatisfy" should {
     "Pass if all elements satisfy the expectation" in {
      List(1, 2, 3, 4) must allSatisfy(beLessThan(5))
    }

    "Fail if any elements do not satisfy the expectation" in {
      List(1, 2, 3, 5) must notAllSatisfy(beLessThan(5))
    }
  }
}

Source: (StackOverflow)

Advertisements

"scala is not an enclosing class"

When compiling this specification:

import org.specs.Specification
import org.specs.matcher.extension.ParserMatchers

class ParserSpec extends Specification with ParserMatchers {
  type Elem = Char

  "Vaadin DSL parser" should {
    "parse attributes in parentheses" in {
      DslParser.attributes must(
        succeedOn(stringReader("""(attr1="val1")""")).
          withResult(Map[String, AttrVal]("attr1" -> AttrVal("val1", "String"))))
    }
  }
}

I get the following error:

ParserSpec.scala:21
error: scala is not an enclosing class
withResult(Map[String, AttrVal]("attr1" -> AttrVal("val1", "String"))))
           ^

I don't understand the error message here at all. Why could it appear?

Scala version is 2.8.1, specs version is 1.6.7.2.

DslParser.attributes has type Parser[Map[String, AttrVal]] and the combinators succeedOn and withResult are defined as follows:

trait ParserMatchers extends Parsers with Matchers {
  case class SucceedOn[T](str: Input,
                          resultMatcherOpt: Option[Matcher[T]]) extends Matcher[Parser[T]] {
    def apply(parserBN: => Parser[T]) = {
      val parser = parserBN
      val parseResult = parser(str)
      parseResult match {
        case Success(result, remainingInput) =>
          val succParseMsg = "Parser "+parser+" succeeded on input "+str+" with result "+result
          val okMsgBuffer = new StringBuilder(succParseMsg)
          val koMsgBuffer = new StringBuilder(succParseMsg)
          val cond = resultMatcherOpt match {
            case None =>
              true
            case Some(resultMatcher) =>
              resultMatcher(result) match {
                case (success, okMessage, koMessage) =>
                  okMsgBuffer.append(" and ").append(okMessage)
                  koMsgBuffer.append(" but ").append(koMessage)
                  success
              }
          }
          (cond, okMsgBuffer.toString, koMsgBuffer.toString)
        case _ =>
          (false, "Parser succeeded", "Parser "+parser+": "+parseResult)
      }
    }

    def resultMust(resultMatcher: Matcher[T]) = this.copy(resultMatcherOpt = Some(resultMatcher))

    def withResult(expectedResult: T) = resultMust(beEqualTo(expectedResult))

    def ignoringResult = this.copy(resultMatcherOpt = None)
  }

  def succeedOn[T](str: Input, expectedResultOpt: Option[Matcher[T]] = None) =
    SucceedOn(str, expectedResultOpt)

  implicit def stringReader(str: String): Reader[Char] = new CharSequenceReader(str)
}

Source: (StackOverflow)

How to write a spec that is productive?

I've seen different program managers write specs in different format. Almost every one has had his/her own style of writing a spec.

On one hand are those wordy documents which given to a programmer are likely to cause him/her missing a few things. I personally dread the word documents spec...I think its because of my reading style...I am always speed reading things which I think will cause me to miss out on key points.

On the other hand, I have seen this innovative specs written in Excel by one of our clients. The way he used to write the spec was kind of create a mock application in Excel and use some VBA to mock it. He would do things like on button click where should the form go or what action should it perform (in comments).

On data form, he would display a form in cells and on each data entry cell he would comment on what valid values are, what validation should it perform etc.

I think that using this technique, it was less likely to miss out on things that needed to be done. Also, it was much easier to unit test it for the developer. The tester too had a better understanding of the system as it 'performed' before actually being written.

Visio is another tool to do screen design but I still think Excel has a better edge over it considering its VBA support and its functions.

Do you think this should become a more popular way of writing spec? I know it involves a bit of extra work on part of project manager(or whoever is writing the spec) but the payoff is huge...I myself could see a lot of productivity gain from using it. And if there are any better formats of specs that would actually help programmer.


Source: (StackOverflow)

Is there a way to match on a call-by-name argument of a Mockito mock object in Specs?

I am testing the interaction between one object, and another object with some methods that have call-by-name arguments. However, I can't figure out how to create an argument matcher for that call-by-name argument.

Let's say that this is the signature of the mocked object:

def fn(arg1: => String, arg2: Int): Any

Then what I really want to do is test if that method is called with a known second argument. I don't even care all that much about the first argument, but having a way to properly test that as well would be a bonus.

This doesn't work:

there was one(mock) fn(any[()=>String], eq(12))

nor this:

there was one(mock) fn(any[Function0[String]], eq(12))

and this doesn't even compile:

there was one(mock) fn(any[=>String], eq(12)) ... which obviously is to be expected.


Source: (StackOverflow)

What specs does one need for a good iPhone app development environment?

I'm going to buy a new mac to develop iPhone apps (previously been programming them at work on their iMac).

What do you think the minimum and recommended specs are?

Is 2 GB of RAM plenty for XCode, interface builder and the simulator to all run simultaneously? What if I'm also running a browser with 10 tabs and Photoshop with a few smallish images open?

The fact that I haven't found any recommendations elsewhere suggests that I have little to worry about, but as a student this is a large purchase for me. I need to be careful.

Thanks!
Tristan


Source: (StackOverflow)

In Scala Specs, what is the "must" function?

I'm working with some Specs tests and I'm trying to understand what the "must" function is, and what it does.

I am unable to find its declaration or implementation anywhere in the specs source, and I'm trying to understand what it does.

Here are some example usages of it:

"hello world".size must be equalTo(11)
"hello world" must be matching("h.* w.*")
stack.push(11) must throwAn[Error]

It looks to me like "must" takes a function as an argument, but I'd like to know the actual signature of "must", and what it does with its argument.

Can anyone point me in the right direction?

Thanks!


Source: (StackOverflow)

Selenium, specs and scala

I'm looking an info or some project for selenium testing with scala specs. How can I call selenium tests from my scala specs code?


Source: (StackOverflow)

Unit-testing Spring applications using Scala's Specs

We have a large infrastructure that's highly dependent on Spring Framework. Recently I began writing code in Scala and test it using Specs. This is all great but at some point I need to use Spring-dependent features (Such as a HibernateDaoSupport-based DAO).

Has anyone managed to use the SpringJUnit4ClassRunner class to run Specs tests? Does anyone have a different direction as to how to achieve this goal?

Thanks


Source: (StackOverflow)

BDD tool for Scala supporting reusable parameterized Gherkin clauses

Is there any BDD tool for Scala supporting reusable parameterized Gherkin clauses?

I would like to be able to have the ability to use specs like these:

Given number 4 is entered
When "+" is pressed
And number -1 is entered
And "*" is pressed
And number 2 is entered
And "=" is pressed
Then result is 6

And I would like to define fixtures to Gherkin clauses differing by a parameter only once, something like:

scenario("(4+(-1)) * 2 = 6") {

  given("number 4 is entered")
  when("'+' is pressed")
  and("number -1 is entered")
  and("'*' is pressed")
  and("number 2 is entered")
  and("'=' is pressed")
  then("result is 0")
}

Given definitions of clauses looking like as follows:

"number $number is entered" {
    calculator.enter(number)
}
"'$key' is pressed" {
    calculator.press(key)
}
"result is $number" {
    assert(calculator.getDisplayedNumber === number)
}

I looked through ScalaTest and Specs manuals but I didn't find such feature. ScalaTest seems to be able to reuse the defined clause in a different scenario, but looks like it is not parameterised.

Do you know some tools that does support what I want, or e.g. some extensions to ScalaTest, or a way to extend it myself with such result?


Source: (StackOverflow)

Using the "should NOT produce [exception]" syntax in ScalaTest

I'am toying with Specs2 and ScalaTest for BDD in Scala. I've written expectations in Specs2 when I am asserting that a given exception should not be thrown.

"do something" in {
 {
   ....
 } must not(throwA[MyException])
}

I was hoping to be able to write the equivalent in ScalaTest like:

"do something" in {
 evaluating {
   ....
 } should not produce[MyException]
}

But this does not compile and I could not find way of doing it. Is that even possible?

Many thanks in advance.


Source: (StackOverflow)

Is there a specs matcher that will unbox Option and Either

I've created a specs test, to validate some JSON parsing. Although the test works perfecly well, it feels rather noisy.

I wonder if there is existing code in Specifications to unbox Option and Either?

"twitter json to Scala class mapper" should {
    "parsing a tweet" in {
      TwitterJsonMapper.tweetP(tweetS) match {
        case Right(t: Tweet) => {
          implicit def unOption[T](t: Option[T]): T = t.get
          implicit def unEither[T](t: Either[T,Throwable]): T = t match {case Left(left) => left ;case Right(t) => throw t}
          "test id" in {
            true must_== (t.id.get == 228106060337135617l)
          }
          "test id_str" in {
            true must_== (t.id_str.get == "228106060337135617")
          }
          "test time" in {
            true must_== (t.created_at.getHours == 13 )
          }
        }
        case Left((pe: JsonParseException, reason: String)) => fail(reason + "\n" + pe)
      }
    }
  }

 //The Tweet is produced from JSON using Fasterxml's Jackson-Scala library. 
 //I want to use Option or Either monads over all child attributes - for the usual reasons.
case class Tweet(
  @BeanProperty contributors: Option[String],
  @BeanProperty coordinates: Option[String],

  @BeanProperty @JsonDeserialize (
      using = classOf[TwitterDateDeserializer]
  ) created_at: Either[Date,Throwable],
  @BeanProperty favorited: Boolean = false,
  //elided etc etc
  @BeanProperty id_str: Option[String]
}

Source: (StackOverflow)

How does the "specs" BDD framework for Scala work?

I'm just getting started with Scala, and I'm wondering which language feature allows you to do this:

"PersistentQueue" should {
  "add and remove one item" in {
    withTempFolder {
      val q = new PersistentQueue(folderName, "work", Config.fromMap(Map.empty))
      q.setup

      q.length mustEqual 0
      q.totalItems mustEqual 0
      q.bytes mustEqual 0
      q.journalSize mustEqual 0

      q.add("hello kitty".getBytes)

      q.length mustEqual 1
      q.totalItems mustEqual 1
      q.bytes mustEqual 11
      q.journalSize mustEqual 32

      new String(q.remove.get.data) mustEqual "hello kitty"

      q.length mustEqual 0
      q.totalItems mustEqual 1
      q.bytes mustEqual 0
      q.journalSize mustEqual 33

      q.close
      dumpJournal("work") mustEqual "add(11:0:hello kitty), remove"
    }
  }
}

That's from the unit tests for Kestrel.

What's going on here? Does "PersistentQueue" should mean that the Scala string class has been extended with a "should" method, or is something else happening here? I had a quick look through the Scala documentation but couldn't see which language features are being used for this code sample.


Source: (StackOverflow)

Exception matcher in Specs BDD library for Scala

Im using the Specs BDD library for writing Scala unit tests (http://code.google.com/p/specs) .In my code if i want to assert that a throws an exception of type ClassNotFoundException, then i can write the following code:

a must throwA[ClassNotFoundException]

However,i want to test the reverse case,i.e.i want to assert that a "does not" throw an exception of type ClassNotFoundException.

I tried using not negation matcher, as follows:

 a must throwA[ClassNotFoundException].not

But that didnt work. Im getting compilation errors. So, is there any way i can assert that an exception of type ClassNotFoundException for example, is not thrown ?

Please Help Thank You


Source: (StackOverflow)

How to use Specs2 with Scalacheck to automate testing of String arguments?

The rewritten specs2 testing framework for Scala integrates automated testing with scalacheck. The examples given in the specs2 documentation on how to use scalacheck together with specs2 either use integers or more complicated custom generators as in eric's json example.

While trying to get a slightly less complicated example working, I'm struggling because I don't know how one would use specs2 and scalacheck if I want to generate String arguments instead of Integers. How would this Quickstart example


import org.scalacheck._

object StringSpecification extends Properties("String") { property("startsWith") = Prop.forAll((a: String, b: String) => (a+b).startsWith(a))

property("endsWith") = Prop.forAll((a: String, b: String) => (a+b).endsWith(b))

// Is this really always true? property("concat") = Prop.forAll((a: String, b: String) => (a+b).length > a.length && (a+b).length > b.length )

property("substring") = Prop.forAll((a: String, b: String) => (a+b).substring(a.length) == b )

property("substring") = Prop.forAll((a: String, b: String, c: String) => (a+b+c).substring(a.length, a.length+b.length) == b ) }

taken from the scalacheck homepage look, if it was written as Specs2 specification using the scalacheck integration?


Source: (StackOverflow)