smallseo.info

specs

Perl 6 language design documents Perl 6 Design Documents

Scala testing: What's the status and relationship of SUnit, ScalaTest, ScalaCheck, Specs and ParTest?

Scala provides a choice of different testing frameworks, but I wonder if there are differences in the maturity and stability they have and which distinct features they provide.

Is there a specific one which should fit for all kinds of development?

Can the different frameworks inter-operate with each other or with test runners targeted for other languages?


Source: (StackOverflow)

Guide to writing specs in Erlang

In open source projects I see the following two ways of writing specs:

Specs in comments

@spec start_link() -> {ok, pid()}

Specs in source code

-spec start_link() -> {ok, pid()}

What's the difference? Is one preferred over the other?


Source: (StackOverflow)

Matching any parameterless function as an argument in scala Mockito

I'm trying to verify the following method gets called using Mockito:

class Notifier {
  def forward(request: ServletRequest)(onFailure: => Unit) : Unit
}

Here's the verification on a mock:

val notifier = mock[Notifier]
there was one(notifier).forward(any[ServletRequest])(any[() => Unit])

And I get the exception:

   The mock was not called as expected: 
    Invalid use of argument matchers!
    3 matchers expected, 2 recorded.
    This exception may occur if matchers are combined with raw values:
        //incorrect:
        someMethod(anyObject(), "raw String");
    When using matchers, all arguments have to be provided by matchers.
    For example:
        //correct:
        someMethod(anyObject(), eq("String by matcher"));

I know this is caused by the last parameterless function. How can I perform a verify properly here?


Source: (StackOverflow)

How to get pretty output from specs+scalacheck with maven?

When I run Specs + Scalacheck tests with IDEA, I get nice pretty output:

  Specification "CoreSpec"
    The core grammar should
    + parse any encoded string
    + fail to parse an empty encoded string
    + parse an expected empty string
    + fail on a non-empty string when expecting an empty string
    + parse well-formed coordinates

In order to get my tests to run with maven, I have the usual:

class CoreSpecTest extends JUnit4(CoreSpec)

...but then the output is not very satisfying:

Running CoreSpecTest
Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.782 sec

Results :

Tests run: 5, Failures: 0, Errors: 0, Skipped: 0

Is there a way to get the pretty output in this case?

Thanks...


Source: (StackOverflow)

Using Specs with unitils

I am trying to get scala specs and unitils-dbunit to work.

To use unitils you have to annotate your test class with @RunWith(classOf[UnitilsJUnit4TestClassRunner]) or extend from a class and you can set DataSet's to load with @DataSet(Array("DataSet.xml")). All of this works with JUnit.

But I got 2 problems when using specs:

  • I am running my specs tests with gradle and the ScalaTestAntTask, so I guess the @RunWith annotation will be ignored.
  • I can not set the @DataSet annotation to my test method as seen here:

    [...]
    @RunWith(classOf[UnitilsJUnit4TestClassRunner])
    class DaoTest extends Specification with ScalaTest {
    
        @TestDataSource
        var dataSource: DataSource = null
    
        @DataSet(Array("DataSet.xml"))
        "querying the database" should {
            "return the right data" in {
                [assertSomething]
            }
        }
    }
    

This gives me the following compiler error:

error: expected start of definition

"querying the database" should {

^

Does somebody know how I can use specs and unitils together?

UPDATE: This is the solution I came up with:

    import org.specs.runner.ScalaTest
    import org.specs.Specification
    import org.unitils.dbunit.DbUnitModule
    import java.io.File
    import java.util.Properties
    import org.unitils.core.ConfigurationLoader

    class DaoTest extends Specification with ScalaTest {

        "querying the database" should {

            doBefore {
                UnitilsDatabaseUtils.setup("DataSet.xml", "DataSet2.xml")
            }

            "return the right data" in {
                [test something]
            }
        }
    }

    object UnitilsDatabaseUtils {

        def setup(dataSetFileNames: String*) = {
            val configuration: Properties = new ConfigurationLoader().loadConfiguration
            val dbunitModule = new DbUnitModule
            dbunitModule.init(configuration)

            for (dataSetFileName <- dataSetFileNames) {
                val dataSetURL = getClass.getClassLoader.getResource(dataSetFileName)
                dbunitModule.insertDataSet(new File(dataSetURL.toURI))
            }
        }
    }

-- Christian


Source: (StackOverflow)

Specs for all android phones

Is there a central place where I can find the specs for the majority of the Android phones available on the market? I want to create avds for each of them.


Source: (StackOverflow)

Specs implicit conversion conflicts with Scala Predef

I have a type alias in my code like so:

type Time = Double

And I often in both tests and in applications pass Long values to functions that use this type. For instance:

 def at(time : Time) : T = {
     // Do Something
 }

 at(System.currentTimeMillis)

This code works fine unless run in my tests where I get the following error:

  found   : Long
  required: com.github.oetzi.echo.Echo.Time
  Note that implicit conversions are not applicable because they are ambiguous:
  both method long2double in object Predef of type (x: Long)Double
  and method longToDouble in trait NumericBaseMatchers of type (s: Long)Double
  are possible conversion functions from Long to com.github.oetzi.echo.Echo.Time

After looking up NumericBaseMatchers it seems its part of the Specs testing framework (my tests are written in Specs 1). I tried running code to get the error in the interpreter and it was fine out side of the tests.

Is there any way I can somehow remove the ambiguity so I can pass Long to values to a Double/Time function? Why does Specs try and create its own LongToDouble conversion when Scala already provides this?


Source: (StackOverflow)

Getting failure detail on failed scala/maven/specs tests

I am playing a bit with scala, using maven and scala plugin.

I can't find a way to have mvn test report failure details - in particular, whenever some function returns wrong reply, I am getting information about the failure, but I have no way to see WHICH wrong reply was reported.

For example, with test like:

object MyTestSpec extends Specification {

  "my_function" should {
      "return proper value for 3" {
           val cnt = MyCode.my_function(3)
           cnt must be_==(3)
      }
  }
}

in case my function returns something different than 3, I get only

Failed tests:
  my_function should return proper value for 3

but there is no information what value was actually returned.

Is it possible to get this info somehow (apart from injecting manual println's)?


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)

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)

"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)