How to xfail off a conditional involving a parametrization? - pytest

How to xfail off a conditional involving a parametrization?
The issue is that #pytest.mark.xfail(condition=(code == 123), reason="123 is an exception case") doesn't work because code is a parametrized variable. I tried some different things including static class members, globals, and setting it in the expected_setup fixture. None of these worked (as expected)
#pytest.mark.xfail(condition=(code == 123), reason="123 is an exception case")
E NameError: name 'code' is not defined
params = [
cls1,
cls2,
cls3,
cls4
]
#pytest.mark.parametrize('code', params, ids=list(map(str, params)))
class TestContextExit(object):
#pytest.fixture(autouse=True)
def expected_setup(self, code):
self.str1 = 'JETFUEL'
self.str2 = 'OPERATIONNORTHWOODS'
self.setup = NewStore(self.str1, self.str2, code)
def test1(self, code):
assert self.root.results.result_code == expected_result_code
assert self.root.results.ta['result_code'] == expected_result_code.code
assert self.root.results.result_code == expected_result_code
#pytest.mark.xfail(condition=(code == 123), reason="123 is an exception case")
def test2(self, code):
assert self.setup.root['code'] == code
#pytest.mark.xfail(condition=(code == 123), reason="123 is an exception case")
def test3(self, code):
assert self.setup.root['setup'] == NOERROR
Any ideas or patterns? Looking at the xfail pytest docs, I don't see any examples xfailing off parametrizations, except for the as part of the params. But in this case, the class is being parametrized and only two of the class tests turn into xfails, not all the tests.

You can use pytest.param with xfail mark as a param value in parametrization to xfail a param.
#pytest.mark.parametrize(code, [1,pytest.param(0,marks=pytest.mark.xfail(reason="reasons")]
def test_a():
assert code
This is used to mark certain parametrization value. This will xfail 2nd test.

Related

Syntactic sugar explanation of Scala'a unapply method

I am getting an error in the extractor step (unapply method call).
The error message is: Wrong number of arguments for the extractors. found 2; expected 0
Can someone please help what is causing the error (where my misunderstanding is).
class ABC(val name:String, val age:Int) //class is defined.
object ABC{
def apply(age:Int, name:String) = new ABC(name, age)
def unapply(x:ABC) = (x.name, x.age)
}
val ins = ABC(25, "Joe") //here apply method is in action.
val ABC(x,y) = ins //unapply is indirectly called. As per my understanding , 25 and Joe suppose to be captured in x and y respectively. But this steps gives error.
The error I get is
an unapply result must have a member def isEmpty: Boolean
The easiest way to fix this is to make unapply return an Option:
def unapply(x: ABC) = Option((x.name, x.age))
The unapply method in an extractor which binds values must return an Option. This is because there's no intrinsic guarantee that an extractor will always succeed. For instance consider this massively oversimplified example of an extractor for an email address:
object Email {
def unapply(s: String): Option[(String, String)] =
s.indexOf('#') match {
case idx if idx >= 0 =>
val (user, maybeSite) = s.splitAt(idx)
if (maybeSite.length < 2 || maybeSite.lastIndexOf('#') > 0) None
else Some(user -> maybeSite.tail)
case _ => None
}
}
At the application site:
val Email(u, s) = "user3103957#stackoverflow.example.xyz"
Turns into code that's basically (from the description in Programming In Scala (Odersky, Spoon, Venners (3rd ed))):
val _tmpTuple2 =
"user3103957#stackoverflow.example.xyz" match {
case str: String =>
Email.unapply(str).getOrElse(throw ???)
case _ => throw ???
}
val u = _tmpTuple2._1
val s = _tmpTuple2._2
Technically, since the compiler already knows that the value is a String, the type check is elided, but I've included the type check for generality. The desugaring of extractors in a pattern match also need not throw except for the last extractor attempt.

ScalaMock: How to mock/stub a method to return different values per call?

Using ScalaMock, I want to mock/stub a class method so it will return a different value per call (order of calls matters).
I can achieve this with mock and expects, but that will force me to verify those calls.
Can I do this with a stub?
Also, how can I say something like "first time return X, and then always return Y" (both with mock and stub)?
Yes, this can be done, although the syntax is a little unintuitive:
trait Foo { def getInt: Int }
val fooStub = stub[Foo]
(fooStub.getInt _).when().returns(1).noMoreThanOnce()
(fooStub.getInt _).when().returns(2).noMoreThanOnce()
(fooStub.getInt _).when().returns(3)
(fooStub.getInt _).when().returns(4)
assert(fooStub.getInt == 1)
assert(fooStub.getInt == 2)
assert(fooStub.getInt == 3)
// Note that it's fine that we don't call it a fourth time - calls are not verified.
It's important to use .noMoreThanOnce() rather than.once(), otherwise you cause the calls to be verified. There is also a .noMoreThanTwice() method, but I don't think there is a .noMoreThanNTimes() or any equivalent.
Here is how to do "first time return X, and then always return Y" for mocks and stubs:
trait Bar { def getString: String }
val barMock = mock[Bar]
(barMock.getString _).expects().returning("X")
(barMock.getString _).expects().returning("Y").anyNumberOfTimes()
assert(barMock.getString == "X")
assert(barMock.getString == "Y")
assert(barMock.getString == "Y")
val barStub = stub[Bar]
(barStub.getString _).when().returns("x").noMoreThanOnce()
(barStub.getString _).when().returns("y")
assert(barStub.getString == "x")
assert(barStub.getString == "y")
assert(barStub.getString == "y")
For me the best way to write a mock which does not verify calls and where returning value depends on the input is to use onCall method - it takes a closure of your function. By default it will serve only the first call, so make sure to add anyNumberOfTimes or some repreted(...).
import org.scalamock.scalatest.MockFactory
trait Foo {
def getSomeValue(param1: Any, param2: Any): String
}
class Test extends MockFactory {
val fooMock = stub[Foo]
val it = Iterator.single("X") ++ Iterator.continually("Y")
(fooMock.getSomeValue _)
.expects(*, *)
.onCall((p1, p2) => it.next())
.anyNumberOfTimes
}
Now the first call to fooMock.someValue(...) will return X and each consecutive Y.

Try / Option with null

I'm searching for a possiblity in scala to call a function and get an Option as result which is "None" iff either an Exception is raised when calling the method or the method return null. Otherwise the Option should have the value of the result.
I know that Try can be used for the first part, but I don't know how to handle the second part:
val result = Try(myFunction).toOption()
If the method now returns null (because it is not a scala function but a Java function), result is Some(null) instead of None.
As I know there is only 1 method in scala standard library to convert null to None - Option.apply(x), so you have to use it manually:
val result = Try(myFunction).toOption.flatMap{Option(_)}
// or
val result = Try(Option(myFunction)).toOption.flatten
You could create your own helper method like this:
implicit class NotNullOption[T](val t: Try[T]) extends AnyVal {
def toNotNullOption = t.toOption.flatMap{Option(_)}
}
scala> Try(null: String).toNotNullOption
res0: Option[String] = None
scala> Try("a").toNotNullOption
res1: Option[String] = Some(a)
You can also do this:
val result = Try(myFunction).toOption.filter(_ != null)
which looks and feels better then .flatten or .flatMap(Option(_))
You can also do pattern matching as:
val result = myFunction() match {
case null => None
case _ => Some(_)
}
but the answer of #senia looks more "scala style"

Why doesn't the scala compiler generate a warning on if statements that always yield false inside a pattern match?

The scala compiler should generate warnings for the if statements I've commented on below, but it doesn't. Why?
sealed trait T
object A extends T
val s:Seq[T] = Seq(A)
val result = s.map {
//This if should produce a compiler warning
case a if(a == "A") =>
"First"
case a =>
//This if should produce a compiler warning
if (a == "A") {
"Second"
}
else
{
"Third"
}
}
The result will be "Third" as you'd expect, but the compiler should have generated a warning on the case a if(a == "A") and on the if (a == "A"), but alas there is no warning.
If I write the following code it behaves like I would expect:
if(A == "A"){
println("can't happen")
}
// warning: comparing values of types A.type and String using `==' will always yield false
Why is this happening?
Edit: I'm using Scala 2.10.1.
Because it can happen. If I simply kept some internal state and returned different results for == "A" on the first and second call, then I can get "Second".
You've provided a definition of A that guarantees it can't happen, but that requires examination of the whole program, and compiler warnings are only local.
May you will have inherited class with overloaded == method with string argument…

How to check for null or false in Scala concisely?

In Groovy language, it is very simple to check for null or false like:
groovy code:
def some = getSomething()
if(some) {
// do something with some as it is not null or emtpy
}
In Groovy if some is null or is empty string or is zero number etc. will evaluate to false. What is similar concise method of testing for null or false in Scala?
What is the simple answer to this part of the question assuming some is simply of Java type String?
Also another even better method in groovy is:
def str = some?.toString()
which means if some is not null then the toString method on some would be invoked instead of throwing NPE in case some was null. What is similar in Scala?
What you may be missing is that a function like getSomething in Scala probably wouldn't return null, empty string or zero number. A function that might return a meaningful value or might not would have as its return an Option - it would return Some(meaningfulvalue) or None.
You can then check for this and handle the meaningful value with something like
val some = getSomething()
some match {
case Some(theValue) => doSomethingWith(theValue)
case None => println("Whoops, didn't get anything useful back")
}
So instead of trying to encode the "failure" value in the return value, Scala has specific support for the common "return something meaningful or indicate failure" case.
Having said that, Scala's interoperable with Java, and Java returns nulls from functions all the time. If getSomething is a Java function that returns null, there's a factory object that will make Some or None out of the returned value.
So
val some = Option(getSomething())
some match {
case Some(theValue) => doSomethingWith(theValue)
case None => println("Whoops, didn't get anything useful back")
}
... which is pretty simple, I claim, and won't go NPE on you.
The other answers are doing interesting and idiomatic things, but that may be more than you need right now.
Well, Boolean cannot be null, unless passed as a type parameter. The way to handle null is to convert it into an Option, and then use all the Option stuff. For example:
Option(some) foreach { s => println(s) }
Option(some) getOrElse defaultValue
Since Scala is statically type, a thing can't be "a null or is empty string or is zero number etc". You might pass an Any which can be any of those things, but then you'd have to match on each type to be able to do anything useful with it anyway. If you find yourself in this situation, you most likely are not doing idiomatic Scala.
In Scala, the expressions you described mean that a method called ? is invoked on an object called some. Regularly, objects don't have a method called ?. You can create your own implicit conversion to an object with a ? method which checks for nullness.
implicit def conversion(x: AnyRef) = new {
def ? = x ne null
}
The above will, in essence, convert any object on which you call the method ? into the expression on the right hand side of the method conversion (which does have the ? method). For example, if you do this:
"".?
the compiler will detect that a String object has no ? method, and rewrite it into:
conversion("").?
Illustrated in an interpreter (note that you can omit . when calling methods on objects):
scala> implicit def any2hm(x: AnyRef) = new {
| def ? = x ne null
| }
any2hm: (x: AnyRef)java.lang.Object{def ?: Boolean}
scala> val x: String = "!!"
x: String = "!!"
scala> x ?
res0: Boolean = true
scala> val y: String = null
y: String = null
scala> y ?
res1: Boolean = false
So you could write:
if (some ?) {
// ...
}
Or you could create an implicit conversion into an object with a ? method which invokes the specified method on the object if the argument is not null - do this:
scala> implicit def any2hm[T <: AnyRef](x: T) = new {
| def ?(f: T => Unit) = if (x ne null) f(x)
| }
any2hm: [T <: AnyRef](x: T)java.lang.Object{def ?(f: (T) => Unit): Unit}
scala> x ? { println }
!!
scala> y ? { println }
so that you could then write:
some ? { _.toString }
Building (recursively) on soc's answer, you can pattern match on x in the examples above to refine what ? does depending on the type of x. :D
If you use extempore's null-safe coalescing operator, then you could write your str example as
val str = ?:(some)(_.toString)()
It also allows you to chain without worrying about nulls (thus "coalescing"):
val c = ?:(some)(_.toString)(_.length)()
Of course, this answer only addresses the second part of your question.
You could write some wrapper yourself or use an Option type.
I really wouldn't check for null though. If there is a null somewhere, you should fix it and not build checks around it.
Building on top of axel22's answer:
implicit def any2hm(x: Any) = new {
def ? = x match {
case null => false
case false => false
case 0 => false
case s: String if s.isEmpty => false
case _ => true
}
}
Edit: This seems to either crash the compiler or doesn't work. I'll investigate.
What you ask for is something in the line of Safe Navigation Operator (?.) of Groovy, andand gem of Ruby, or accessor variant of the existential operator (?.) of CoffeeScript. For such cases, I generally use ? method of my RichOption[T], which is defined as follows
class RichOption[T](option: Option[T]) {
def ?[V](f: T => Option[V]): Option[V] = option match {
case Some(v) => f(v)
case _ => None
}
}
implicit def option2RichOption[T](option: Option[T]): RichOption[T] =
new RichOption[T](option)
and used as follows
scala> val xs = None
xs: None.type = None
scala> xs.?(_ => Option("gotcha"))
res1: Option[java.lang.String] = None
scala> val ys = Some(1)
ys: Some[Int] = Some(1)
scala> ys.?(x => Some(x * 2))
res2: Option[Int] = Some(2)
Using pattern matching as suggested in a couple of answers here is a nice approach:
val some = Option(getSomething())
some match {
case Some(theValue) => doSomethingWith(theValue)
case None => println("Whoops, didn't get anything useful back")
}
But, a bit verbose.
I prefer to map an Option in the following way:
Option(getSomething()) map (something -> doSomethingWith(something))
One liner, short, clear.
The reason to that is Option can be viewed as some kind of collection – some special snowflake of a collection that contains either zero elements or exactly one element of a type and as as you can map a List[A] to a List[B], you can map an Option[A] to an Option[B]. This means that if your instance of Option[A] is defined, i.e. it is Some[A], the result is Some[B], otherwise it is None. It's really powerful!