What are the differences between to.equal(true) and to.be.true? - unit-testing

I'm learning Mocha and Chai.
I try understand when I have to use to.equal(true) or to.be.true to know which is better in different kind of situations.
Thanks!

My understanding from the docs is that .to and .be and various other pieces of the Expect/Should syntax are just syntactical sugar, with no real functionality.
So .to.be.true === .true and .to.equal(true) === .equal(true). So the difference, if any, is between .true and .equal(true) -- and there isn't any difference; .true is just a syntactical shorthand for .equal(true).

They test the same thing. In other words, wherever .to.equal(true) fails, .to.be.true will also fail, and where .to.equal(true) succeeds, so does .to.be.true.
However, they do differ in that .to.equal takes an optional custom error message whereas .to.be.true does not take a custom error message.
var settings = {
verbose: "foo"
};
settings.verbose.should.equal(true, "verbose setting");
will show an error message like:
AssertionError: verbose setting: expected 'foo' to equal true
Same thing with expect(settings.verbose).to.equal(true, "verbose setting"). Without the custom error message, the error will be:
AssertionError: expected 'foo' to equal true
If you use expect(settings.verbose).to.be.true("verbose setting") the test will fail but the custom error message will be ignored.

it doens't look there are any differences
https://github.com/chaijs/chai/blob/master/lib/chai/core/assertions.js#L298
https://github.com/chaijs/chai/blob/master/lib/chai/core/assertions.js#L502

Related

How to testing that Bazel my_test rule fails when it should?

I have found the documentation for how to test for expected analysis phase errors, but I'm drawing a blank no mater what I try to search for on how to test for expected execution phase failures.
An example of what I'm looking for would be a test of this example line_length_test rules where the test feeds in a file with over length lines and expects the test-under-test to be run and produce a failure.
Or to put it another way; I want a test that would fail if I did something dumb like this:
def _bad_test_impl(ctx):
# No-op, never fails regardless of what you feed it.
executable = ctx.actions.declare_file(ctx.label.name + ".sh")
ctx.actions.write(output=executable, content="")
return [DefaultInfo(executable=executable)]
bad_test = rule(
implementation=_bad_test_impl,
test=True,
)
Edit:
So far, the best I've come up with is the very gross:
BUILD
# Failure
bad_test(
name = "bad_test_fail_test",
tags = ["manual"],
)
native.sh_test(
name = "bad_test_failure_test",
srcs = [":not.sh"],
args = ["$(location :bad_test_fail_test)"],
data = [":bad_test_fail_test"],
)
not.sh
! $*
This does not seem like a good idea, particularly for something I'd expect to be well supported.
EDIT:
I got annoyed and built my own. I still wish there was official implementation.
I don't think that your not.sh is a particularly bad solution. But it depends on the situation. In general the Key to good failure testing is specificity i.e. this test should fail for this specific reason. If you don't get this nailed down your going to have a lot of headaches with false positives.
I'll use a slightly more expressive example to try and illustrate why it's so difficult to create a "generic/well supported" failure testing framework.
Let's say that we are developing a compiler. To test the compilers parser we intentionally feed the compiler a malformed source file, and we expect it to fail with something like a "missed semicolon on line 55". But instead our compiler fails from a fairly nasty bug that results in a segfault. As we have just tested that the compiler fails, the test passes.
This kind of a false positive is really hard to deal with in a way that is easy to reason about, whilst also being generic.
What we really want in the above scenario, is to test that the compiler fails AND it prints "missed semicolon on line 55". At this point it becomes increasingly difficult to create a "well supported" interface for these kinds of tests.
In reality a failure test is an integration test, or in some cases an end to end test.
Here is a short excerpt of an integration test from the Bazel repository. This integration test calls Bazel with a range of different flags some combinations expecting success and others failure;
function test_explicit_sandboxfs_not_found() {
create_hello_package
bazel build \
--experimental_use_sandboxfs \
--experimental_sandboxfs_path="/non-existent/sandboxfs" \
//hello >"${TEST_log}" 2>&1 && fail "Build succeeded but should have failed"
expect_log "Failed to get sandboxfs version.*/non-existent/sandboxfs"
}
And the corresponding build definition;
sh_test(
name = "sandboxfs_test",
size = "medium",
srcs = ["sandboxfs_test.sh"],
data = [":test-deps"],
tags = ["no_windows"],
)

Setting up setCharging for Linea Pro device in Swift

I want to set up the Linea Pro to charge the phone if the phone's battery gets low and I'm having a tough time mainly because all the examples are shown in objective-C still and not in Swift.
The manual says:
#param enabled TRUE to enable charging, FALSE to disable/stop it
#param error pointer to NSError object, where error information is stored in case function fails. You can pass nil if you don't want that information
#return TRUE if function succeeded, FALSE otherwise
*/
and the code provided is the following:
-(BOOL)setCharging:(BOOL)enabled error:(NSError **)error;
So in Swift I first tried this:
self.scanner.setCharging = true
but that gives me the following error:
Cannot assign to property: 'setCharging' is a method
So I tried this:
self.scanner.setCharging(true)
which gives me this error:
Call can throw, but it is not marked with 'try' and the error is not handled
Interesting because apparently I have to build it in a function called "setCharging" I think, but I have no idea what and how it wants me to set up the try and catch to, and quite frankly where am I opposed to get this information from?
I think it should be along these lines or something, but I'm not clear on the specifics :
func setCharging(_ enabled: Bool) throws -> Bool {
do {
try
//something goes here I'm not sure what
} catch {
//and then maybe something here on that to do with error
print("some error")
}
}
The answer was provided to me by the manufacturer. It is unnecessary to create a function with the same name as the API, APIs can be called anywhere in the code with the exception of handling error. So in this case I just have this directly in my code not in a function and it just works. (Since I have my scanner.connect code inside a viewWillAppear block, the code to start charging was too early to be called in there, so I placed it inside of a viewDidAppear block).
The following is the code:
do{
try self.scanner.setCharging(true)
}catch let error as NSError{
NSLog("Operation \(error as Error)")
}

suppress wxFileName::Normalize error messages

I have the following c++ code that used to normalize user supplied file path:
wxString orig_path;
wxFileName res_path(orig_path);
res_path.Normalize(wxPATH_NORM_DOTS);
Refs:
wxFileName::Normalize
wxFileName::Normalize flags
When:
orig_path = "../../dir1/f.csv"
I get annoying error messages:
Error: The path 'f.csv' contains too many ".."!
When:
orig_path = "dir1/../dir2/f.csv"
everything works as expected.
Question
Any way I can suppress those error messages? (silent flag?).
I guess I can do some processing myself before calling Normailze but what's the point? I prefer not to do anything or know anything about orig_path before calling Normailze
Use wxLogNull. All calls to the log functions during the life time of an object of this class are just ignored.
See documentation.
wxLogNull noLogsPlease;
wxString orig_path;
wxFileName res_path(orig_path);
res_path.Normalize(wxPATH_NORM_DOTS);

Mockito - Invalid use of argument matchers

I have Junit test that is testing jms message sending. I am using Spring jmsTemplate to to do this. Here I as in the following code I want to check whether the JMS template has called send message regardless what is it in the values of actuall parameters that are passed.
my publisher method the uses the jmsTemplate to send method looks like following inside..
jmsTemplate.send(jmsQueueProperties.getProperty(key), new MessageCreator()
{
public Message createMessage(Session session) throws JMSException
{
ObjectMessage obj = session.createObjectMessage(dialogueServiceResponse);
return obj;
}
});
in My tests..
JmsTemplate mockTemplate = Mockito.mock(JmsTemplate.class);
...
publisher.publishServiceMessage(response);
....
Mockito.verify(mockTemplate,
Mockito.times(1)).send("appointment.queue",
Mockito.any(MessageCreator.class));
But when in the execution i get
org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers!
....
Cause is due to Mockito.any(MessageCreator.class) , but isn't there a way to test my send method is getting executed without creating an actual object in the MessageCreator.
Update
And is there a way to check my session.createObjectMessage(dialogueServiceResponse) is getting called as well
I think the rest of the message tells you what the problem is. When you use an argument matcher for one of the arguments, all the other arguments must also use an argument matcher:
Mockito.verify(mockTemplate, Mockito.times(1)).send(
Mockito.eq("appointment.queue"),
Mockito.any(MessageCreator.class));
For future readers. This will save you a lot of time.
We cannot use argument matcher and primitive/raw values together.
when(fooService.getResult("string",any(MyClass.class))).thenReturn(1); // will give error
when(fooService.getResult(anyString(),any(MyClass.class))).thenReturn(1); // correct
I think you cannot use argument matchers outside stubbing. I also got the same error but when I return, I had to do new string() instead of Mockito.anyString() and the error goes away.
Example:
Mockito.when(mockedBean.mockedMethod(Mockito.anyString(),
Mockito.anyInt(),
Mockito.anyInt(),
Mockito.anyInt(),
Mockito.anyBoolean())).thenReturn(new String());
I can see that this question is about Java code, but I will share this because we use Mockito in Scala as well.
I had this exception thrown from the following code that mocks Play.api configurations
"Configurations Service" should {
"return all dataset configurations" in {
val configs = mock[Configuration]
val testData = Seq("SOME VALUE")
val loader = any[ConfigLoader[Seq[String]]]
when(configs.get[Seq[String]](any[String])).thenReturn(testData) // EXCEPTIONN HERE !
val configuration: ConfigurationsService = new ConfigurationsService(configs)
assert(configuration.getSupportedDatasets() == testData)
}
}
In Scala methods can have Implicit parameters configs.get method has one explicit param and an Implicit one I passed a mock object and when an exception was thrown I was wondering what is going on as I didn't MIX params and mocks, it turned out that I had to pass mocks to implicit parameters as well, and this solved the problem.
val loader = any[ConfigLoader[Seq[String]]] // configs.get has one implicit parameter that accepts ConfigLoader[Seq[String]]
when(configs.get[Seq[String]](any[String])(loader)).thenReturn(testData)
I was seeing this error about a mismatched # of arguments, despite having the correct number...
I realized this was because method being stubbed was static. When I converted it to non-static, it worked as expected.

Modelica assert(condition, message, level=AssertionLevel.warning);

Part 8.3.7 of the Modelica Spec describes the function assert and gives two examples, but whenever I try to use one of the following commands, it does not work as expected:
assert(T > 250 and T < 400,
"Medium model outside full accuracy range",
AssertionLevel.warning);
or
assert(T > 250 and T < 400,
"Medium model outside full accuracy range",
level=AssertionLevel.warning);
What is wrong here? Did I miss something obvious?
So I checked with Dymola (2012FD01) and it looks like Dymola has not implemented the level argument:
> document("assert")
function assert "assert that a condition is true"
input Boolean _condition;
input String _error;
The given condition should be true.
If it is false an error message will be given
end assert;
Or maybe it's simply not documented. You probably should ask the DS support on that. In OpenModelica it seems they have implemented as described in the specs (see also http://build.openmodelica.org/Documentation/assert.html).
You do not state what tool you are using, but I would point out that this is a relatively new syntax for assert. You might try without the "level" indicator (i.e. just two arguments: a Boolean and a String).