Idiomatic way to test the error channel of a ZIO 2 effect with ZIO Test - zio

Is this the most idiomatic way to test a failing effect?
def spec = suite("LookupPositionProviderSpec")(
suite("determinePosition")(
test("Unknown hints lead to 'NoPositionDetermined'") {
for exit <- LookupPositionProvider.determinePosition(Seq(GsmFixtures.cellHintTowerGsm1.copy(cid = 4711))).exit
yield assert(exit)(
fails(
equalTo(
ProviderError(
Lookup,
NoPositionDetermined,
Some("No position could be determined from List(CellHint(GSM,4711,Some(5891),Some(-70),None,None,None))")
)
)
)
)
}.provide(TestLayers.findsNothingLookupPositionProvider)
)
)
I saw this old question (How to test an exception case with zio-test), but I am unsure if and what has changed since then with ZIO 2.

Adam answered this on Discord (https://discord.com/channels/629491597070827530/630498701860929559?fingerprint=1007186113041006615&attemptId=31b120fc-90de-4937-af0b-46db03424f24):
"Yes the exit and then assert(exit)(fails(???)) definitely is. If you want to assert that it has that exact failure that looks great. If you just want to assert that it fails and don't care more about the failure you could do fails(anything) or you could use any other assertion there."

Related

Linear Search with Enumerate

I have started learning Python not to long ago and have decided to try making a linear search algorithim. The problem that seems to exist is that found is never = true therefore never triggering the print. The program is attached below. Any help would be greatly appreciated!
numbers = [55,37,12,13,89,47,3,24,21]
number_to_find = input("Enter a number to find:")
found = False
for index, single_num in enumerate(numbers):
if numbers[index] == number_to_find:
found = True
break
if found == True:
print(f"Found {number_to_find} at index {index}")
else:
print(f"Unable to find {number_to_find} in array")

Antlr4 saying my rule is mutually left recursive with itself

I'm working on an assignment where we make a compiler for a simple language and we are using ANTLR4 for Java. After finally getting my grammar working i had to add some Java code to the language parser to build an AST. Here's where i get confused. Antlr is supposed to throw an error if rules are mutually left recursive and as i understand it it happens when one rule references another rule and the second rule reference the first rule. What i don't understand is why antlr is telling me that my rule is mutually left recursive with itself? Here is the error message i keep getting: error(119): PrevParser.g4::: The following sets of rules are mutually left-recursive [expr]. I looked around and noone seems to be having this issue. I did find someone saying that mutually left recursive rules have in common that their first token is another rule so i tried putting a regular . token right before the rule token and now it magically compiles. Why does it do that when the rule is only referencing itself? Heres the bit of code thats causing the issue:
expr returns [AstExpr ast]
: (VOID_CONST {$ast = new AstAtomExpr(loc($VOID_CONST), AstAtomExpr.Type.VOID, $VOID_CONST.text);})
| (INT_CONST {$ast = new AstAtomExpr(loc($INT_CONST), AstAtomExpr.Type.INT, $INT_CONST.text);})
| (CHAR_CONST {$ast = new AstAtomExpr(loc($CHAR_CONST), AstAtomExpr.Type.CHAR, $CHAR_CONST.text);})
| (POINT_CONST {$ast = new AstAtomExpr(loc($POINT_CONST), AstAtomExpr.Type.POINTER, $POINT_CONST.text);})
| (STRING_CONST {$ast = new AstAtomExpr(loc($STRING_CONST), AstAtomExpr.Type.STRING, $STRING_CONST.text);})
| (BOOL_CONST {$ast = new AstAtomExpr(loc($BOOL_CONST), AstAtomExpr.Type.BOOL, $BOOL_CONST.text);})
| (IDENTIFIER {$ast = new AstNameExpr(loc($IDENTIFIER), $IDENTIFIER.text);})
| ( e1=expr O_OKLEPAJ e2=expr O_ZAKLEPAJ {$ast = new AstArrExpr(loc($e1.ast, $O_ZAKLEPAJ), $e1.ast, $e2.ast);} )
;
The error appears in the last line where the rule expr references itself as e1=expr.
If i change the rule to look like this: ( DOT e1=expr O_OKLEPAJ e2=expr O_ZAKLEPAJ {$ast = new AstArrExpr(loc($e1.ast, $O_ZAKLEPAJ), $e1.ast, $e2.ast);} ) the whole thing compiles normally. Does anyone know how i can resolve this issue? Any help is aprecciated.
I've seems this on stackoverflow before (but can't find it anymore). This seems to be a bug that is caused by the parenthesis before the left-recursive expr. Just remove the parenthesis (which are redundant anyway).
So not:
expr returns [AstExpr ast]
: ...
| ( e1=expr O_OKLEPAJ e2=expr O_ZAKLEPAJ {$ast = new AstArrExpr(loc($e1.ast, $O_ZAKLEPAJ), $e1.ast, $e2.ast);} )
;
but this instead:
expr returns [AstExpr ast]
: ...
| e1=expr O_OKLEPAJ e2=expr O_ZAKLEPAJ {$ast = new AstArrExpr(loc($e1.ast, $O_ZAKLEPAJ), $e1.ast, $e2.ast);}
;

So, a mutant escaped. Now what?

I've just managed to get mutation testing working for the first time. My usual testing framework is Codeception but as of writing, it is not compatible with mutation testing (although I believe work is being done on it and it's not far off). I'm using PHPUnit and Infection, neither of which seem easy to work out how to use.
My test suite generated ten mutants. Nine were killed and one escaped. However, I don't know what part of the code or the tests needs to be improved to kill the final mutant.
How do you get information about what code allowed the mutant to escape?
I found in this blog what I couldn't find in Infection's documentation: the results are saved in infection.log.
The log file looks like this:
Escaped mutants:
================
1) <full-path-to-source-file>.php:7 [M] ProtectedVisibility
--- Original
+++ New
## ##
use stdClass;
trait HiddenValue
{
- protected function hidden_value($name = null, $value = null)
+ private function hidden_value($name = null, $value = null)
{
static $data = [];
$keys = array_map(function ($item) {
Timed Out mutants:
==================
Not Covered mutants:
====================
It says that the mutation changed the protected visibility to private and that no tests failed as a result. If this is important, I can now either change the code or write another test to cover this case.
Now that I've found this, I've searched on the Infection website for infection.log and found --show-mutations or -s which will output escaped mutants to the console while running.

Filtering tab completion in input task implementation

I'm currently implementing a SBT plugin for Gatling.
One of its features will be to open the last generated report in a new browser tab from SBT.
As each run can have a different "simulation ID" (basically a simple string), I'd like to offer tab completion on simulation ids.
An example :
Running the Gatling SBT plugin will produce several folders (named from simulationId + date of report generaation) in target/gatling, for example mysim-20140204234534, myothersim-20140203124534 and yetanothersim-20140204234534.
Let's call the task lastReport.
If someone start typing lastReport my, I'd like to filter out tab-completion to only suggest mysim and myothersim.
Getting the simulation ID is a breeze, but how can help the parser and filter out suggestions so that it only suggest an existing simulation ID ?
To sum up, I'd like to do what testOnly do, in a way : I only want to suggest things that make sense in my context.
Thanks in advance for your answers,
Pierre
Edit : As I got a bit stuck after my latest tries, here is the code of my inputTask, in it's current state :
package io.gatling.sbt
import sbt._
import sbt.complete.{ DefaultParsers, Parser }
import io.gatling.sbt.Utils._
object GatlingTasks {
val lastReport = inputKey[Unit]("Open last report in browser")
val allSimulationIds = taskKey[Set[String]]("List of simulation ids found in reports folder")
val allReports = taskKey[List[Report]]("List of all reports by simulation id and timestamp")
def findAllReports(reportsFolder: File): List[Report] = {
val allDirectories = (reportsFolder ** DirectoryFilter.&&(new PatternFilter(reportFolderRegex.pattern))).get
allDirectories.map(file => (file, reportFolderRegex.findFirstMatchIn(file.getPath).get)).map {
case (file, regexMatch) => Report(file, regexMatch.group(1), regexMatch.group(2))
}.toList
}
def findAllSimulationIds(allReports: Seq[Report]): Set[String] = allReports.map(_.simulationId).distinct.toSet
def openLastReport(allReports: List[Report], allSimulationIds: Set[String]): Unit = {
def simulationIdParser(allSimulationIds: Set[String]): Parser[Option[String]] =
DefaultParsers.ID.examples(allSimulationIds, check = true).?
def filterReportsIfSimulationIdSelected(allReports: List[Report], simulationId: Option[String]): List[Report] =
simulationId match {
case Some(id) => allReports.filter(_.simulationId == id)
case None => allReports
}
Def.inputTaskDyn {
val selectedSimulationId = simulationIdParser(allSimulationIds).parsed
val filteredReports = filterReportsIfSimulationIdSelected(allReports, selectedSimulationId)
val reportsSortedByDate = filteredReports.sorted.map(_.path)
Def.task(reportsSortedByDate.headOption.foreach(file => openInBrowser((file / "index.html").toURI)))
}
}
}
Of course, openReport is called using the results of allReports and allSimulationIds tasks.
I think I'm close to a functioning input task but I'm still missing something...
Def.inputTaskDyn returns a value of type InputTask[T] and doesn't perform any side effects. The result needs to be bound to an InputKey, like lastReport. The return type of openLastReport is Unit, which means that openLastReport will construct a value that will be discarded, effectively doing nothing useful. Instead, have:
def openLastReport(...): InputTask[...] = ...
lastReport := openLastReport(...).evaluated
(Or, the implementation of openLastReport can be inlined into the right hand side of :=)
You probably don't need inputTaskDyn, but just inputTask. You only need inputTaskDyn if you need to return a task. Otherwise, use inputTask and drop the Def.task.

restubbing method in OCMock does not seem to work?

I am confused why this doesn't work...
[[[myObject stub] andReturnValue:#YES] isBadical];
NSLog(#"================> result: %i", [myObject isBadical]);
[[[myObject stub] andReturnValue:#NO] isBadical];
NSLog(#"================> new result: %i", [myObject isBadical]);
Result is:
2013-10-13 20:24:49.156 myApp[43197:c07] ================> result: 1
2013-10-13 20:24:49.157 myApp[43197:c07] ================> new result: 1
Is there a way to update the stubbed value without having to stop mocking and/or create a new mock object?
Use expect instead of stub. AFAIK it's not possible to stub a method twice with OCMock. You don't need to send verify after executing the code you want to test since you are not interested in verifying any expectations.

Resources