Specs2: Ignore specification with a message? - scala

I need to put one of my test cases into a "pending" state.
I would like to assing some sort of message to it that can be displayed on the output when running the test, something like JUnit with #Ignore("Pending: issue #1234 needs to be fixed").
Is there an equivalent for that with Specs2?
class MySpec extends mutable.Specification {
args(skipAll = true) // Can I include a message here in the output somehow?
"cool MyClass feature" should {
"which is broken unfortunately" in {
failure
}
}
}
Thanks in advance!

For an individual example, I believe you can use:
class MySpec extends mutable.Specification {
"cool MyClass feature" should {
"which is broken unfortunately" in {
failure
}.pendingUntilFixed("message about the issue")
}
}
I don't know if there's a way to extend this to mark all the examples in a spec as pending with the same message, as you seem to be hoping.

Related

How to define a class that is exactly the same as another class in Dart/Flutter

I'm defining some custom Exceptions in Dart.
I want in my logic to check the type of exception and base my processing on that, so I want to create distinct classes for each, for example like this :
class FailedToLoadCriticalDataException implements Exception { } // app cannot continue
class FailedToLoadNonCriticalDataException implements Exception { } // app can continue
However I also want to pass 2 parameters when I create these types of exceptions, the type of API call, and the API url, and the definition for that would look like this :
class UrlCallFailedException implements Exception {
String _dataTypeName;
String _urlEndpoint;
UrlCallFailedException([this._dataTypeName, this._urlEndpoint]);
#override
String toString() {
return "(${this.runtimeType.toString()}) Failed to fetch $_dataTypeName ($_urlEndpoint)";
}
}
Now what I want to do is (replace the initial definitions I made earlier and re)define my FailedToLoadCriticalDataException and FailedToLoadNonCriticalDataException classes so that they are exactly the code that is in the UrlCallFailedException class.
Is there any way to simply say something like class FailedToLoadCriticalDataException **is** UrlCallFailedException; and not need to duplicate the code that defines UrlCallFailedException ?
class FailedToLoadCriticalDataException implements UrlCallFailedException{ } is wrong because it is "Missing concrete implementations of 'getter UrlCallFailedException._dataTypeName',.."
class FailedToLoadCriticalDataException extends UrlCallFailedException{ } is wrong because when I got to throw FailedToLoadNonCriticalDataException("Foo", url); it's expectation is that there are no params ("Too many positional arguments: 0 expected, but 2 found.").
Is there a way to create multiple classes that behave exactly the same as another type and differ only in their class, without duplicating all the code ?
I've come up with this as a decent compromise :
class FailedToLoadCriticalDataException extends UrlCallFailedException {
FailedToLoadCriticalDataException([dataTypeName, urlEndpoint]) {
super._dataTypeName = dataTypeName;
super._urlEndpoint = urlEndpoint;
}
}
class FailedToLoadNonCriticalDataException extends UrlCallFailedException {
FailedToLoadNonCriticalDataException([dataTypeName, urlEndpoint]) {
super._dataTypeName = dataTypeName;
super._urlEndpoint = urlEndpoint;
}
}
Some, but minimal, code duplication, and I can now call throw FailedToLoadNonCriticalDataException("Foo", url); in my code later.

When I run tests with scalaTestPlus and Play framework, I get an error "no started application"

I'm trying to make scalaTestPlus work in my play application (I'm using Play! 2.2). It works well until I need a function coming from my application. For instance, if I run this very simple test (by launching in a sbt console "test-only TestName"):
import org.scalatestplus.play._
import org.scalatest._
import Matchers._
class Test extends PlaySpec {
"This test" must {
"run this very simple test without problem" in {
1 mustEqual 1
}
}
}
There is no problem, but as soon as I call a function from my app, like in this code:
class Test extends PlaySpec {
"This test" must {
"run this very simple test without problem" in {
models.Genre.genresStringToGenresSet(Option("test")) //Here is the problem
1 mustEqual 1
}
}
}
I get an error: java.lang.ExceptionInInitializerError: at... Cause: java.lang.RuntimeException: There is no started application (even if my application is running).
I'm probably missing something simple since I'm brand new to ScalaTest, so any help abut what I'm doing wrong would be apreciated ;)
You may need an application in scope when using PlaySpec, as some operations assume that there is a Play application available via Play.current:
class Test extends PlaySpec {
implicit override lazy val app: FakeApplication = FakeApplication(...)
"This test" must {
"run this very simple test without problem" in {
models.Genre.genresStringToGenresSet(Option("test")) //Here is the problem
1 mustEqual 1
}
}
}
Check the functional testing documentation for more details on FakeApplication.
However, I don't think you need should need this for model testing. In the normal ScalaTest docs for play, it seems to just mix inMockitoSugar. But your method call chain may invoke some global state of Play that does require an Application, in which case the FakeApplication is the way to go
As asked by #akauppi, here is a method that works perfectly for me:
import org.scalatestplus.play.{OneAppPerSuite, PlaySpec}
class A extends PlaySpec with OneAppPerSuite {
"a" must {
"return true" in {
//thanks to with OneAppPerSuite, it now works
models.Genre.genresStringToGenresSet(Option("test"))
1 mustBe 1
}
"return false" in {
1 mustBe 2
}
}
}
And I simply launch the test with sbt ~testOnly a

Play2: How to do execute piece of code before each test using specs2

I have this code:
class AccountSpec extends Specification {
def fakeApp = FakeApplication(additionalConfiguration = inMemoryDatabase())
"Every account" should {
"have a user" in running(fakeApp) {
Account.create("Basic account", "username")
...
etc...
}
}
}
If i try to run this spec I will get an error, because there is no user with a username "username". So what I would like to do is:
def before = { createTestUser() }
i have tried different approaches but havent found a solution yet.
Just extend from this trait org.specs2.mutable.BeforeAfter, it comes with before and after methods, implement them, here is a link to documentation docs

Complex annotation in Scala

In order to create a message driven bean in Scala, using JBoss, I need to annotate the class as follows:
#MessageDriven(
activationConfig=Array(#ActivationConfigProperty(propertyName="destination", propertyValue="java:/queue/mail") ),
messageListenerInterface=classOf[MessageListener])
class MailService extends MessageListener {
def onMessage(m: Message) {
...
}
}
The trouble comes in that the annotation contains an attribute which itself is an annotation, and the Scala compiler doesn't seem to be able to cope with it.
The error message is: "illegal start of simple expression", highlighted around the # symbol on the second line, just after "activationConfig".
In Java I'd write the annotation as follows:
#MessageDriven(
activationConfig={#ActivationConfigProperty(propertyName="destination", propertyValue="java:/queue/mail")},
messageListenerInterface=MessageListener.class)
Is there a way in Scala to write the annotation, so that this works?
Is there any way to trick the compiler to generate the byte code in the way I want to?
Thanks,
John
try this
#MessageDriven(
activationConfig = Array[ActivationConfigProperty](
new ActivationConfigProperty(propertyName = "desctination", propertyValue = "java:/queue/mail")),
messageListenerInterface = classOf[MessageListener]
)
class MailService extends MessageListener {
def onMessage(m: Message) {
//...
}
}

is there a scalaTest mechanism similar to TestNg dependsOnMethods annotation

Can I have dependencies between scalaTest specs such that if a test fails, all tests dependent on it are skipped?
I didn't add that feature of TestNG because I didn't at the time have any compelling use cases to justify it. I have since collected some use cases, and am adding a feature to the next version of ScalaTest to address it. But it won't be dependent tests, just a way to "cancel" a test based on an unmet precondition.
In the meantime what you can do is simply use Scala if statements to only register tests if the condition is met, or to register them as ignored if you prefer to see it output. If you are using Spec, it would look something like:
if (databaseIsAvailable) {
it("should do something that requires the database") {
// ...
}
it ("should do something else that requires the database") {
}
}
This will only work if the condition will be met for sure at test construction time. If the database for example is supposed to be started up by a beforeAll method, perhaps, then you'd need to do the check inside each test. And in that case you could say it is pending. Something like:
it("should do something that requires the database") {
if (!databaseIsAvailable) pending
// ...
}
it("should do something else that requires the database") {
if (!databaseIsAvailable) pending
// ...
}
Here is a Scala trait that makes all test in the test suite fail, if any test fails.
(Thanks for the suggestion, Jens Schauder (who posted another answer to this question).)
Pros: Simple-to-understand test dependencies.
Cons: Not very customizable.
I use it for my automatic browser tests. If something fails, then usually there's no point in continuing interacting with the GUI since it's in a "messed up" state.
License: Public domain (Creative Common's CC0), or (at your option) the MIT license.
import org.scalatest.{Suite, SuiteMixin}
import scala.util.control.NonFatal
/**
* If one test fails, then this traits cancels all remaining tests.
*/
trait CancelAllOnFirstFailure extends SuiteMixin {
self: Suite =>
private var anyFailure = false
abstract override def withFixture(test: NoArgTest) {
if (anyFailure) {
cancel
}
else try {
super.withFixture(test)
}
catch {
case ex: TestPendingException =>
throw ex
case NonFatal(t: Throwable) =>
anyFailure = true
throw t
}
}
}
I don't know about a ready made solution. But you can fairly easily write your own Fixtures.
See "Composing stackable fixture traits" in the javadoc of the Suite trait
Such a fixture could for example replace all test executions after the first one with calls to pending
You can use trait org.scalatest.CancelAfterFailure to cancel remaining tests after first failure:
import org.scalatest._
class MySpec extends FunSuite with CancelAfterFailure {
test("successfull test") {
succeed
}
test("failed test") {
assert(1 == 0)
}
test("this test and all others will be cancelled") {
// ...
}
}