Swift 5 Result: XCTAssertEqual is ambiguous without more context - unit-testing

XCTAssertEqual produces an error: Expression type '()' is ambiguous without more context when comparing two result values(see below):
let success = Result<String, Error>.success("Value")
let failure = Result<String, Error>.failure(NSError.createError("Error"))
XCTAssertEqual(success, failure)

The problem is that the type of success and failure you're trying to compare is not Equatable.
Result<Success, Failure> only conforms to Equatable when both Success and Failure conform to Equatable. From the definition of Result:
extension Result : Equatable where Success : Equatable, Failure : Equatable {}
Thus, you'll need to use a custom Error type that conforms to Equatable or use a different way to compare the two values by first extracting the success (or failure) value:
switch (a, b) {
case let (.success(x), .success(y)):
XCTAssertEqual(x, y)
default:
XCTFail()
}

Related

assertEquals fails for Error implementation but pass for Success one

I have these sealed interface
sealed interface Result<out T> {
data class Success<T>(val data: T) : Result<T>
data class Error(val exception: Throwable? = null) : Result<Nothing>
}
when i tried to assertEquals the Success one, it pass. But when it comes to Error one, it will fail even though the content is identical. Here is simple example:
#Test
fun testSucess() = runTest {
whenever(repository.login("email", "password"))
.thenReturn(someValue)
val expected = Result.Success(data = someValue)
val actual = loginUseCase(LoginRequest("email", "password"))
verify(repository).login("email", "password")
assertEquals(expected, actual) // this will pass
}
#Test
fun testError() = runTest {
val exception = RuntimeException("HTTP Error")
whenever(repository.login("", ""))
.thenThrow(exception)
val expected = Result.Error(exception = exception)
val actual = loginUseCase(LoginRequest("", ""))
verify(repository).login("", "")
assertEquals(expected, actual) // this will fail
assertEquals(expected.toString(), actual.toString()) // this will pass
}
What is causing this and what is possible solution to this? I have read some info that it needs equals() to be overriden, but i still confused as to why it only happens in Error case only and how to properly override the equals method.
Data classes in Kotlin have an implicitly generated equals function automatically derived from all their properties.
The problem you are facing is probably due to the fact that the type of your someValue has a proper equals function, so the equals works for your Success and its property value. But Throwable does not have an equals function which means that two Throwables are only equal if they are the same instance, which is obviously not the case for expected and actual in your test assertion. I can only guess that in loginUseCase, the exception is wrapped inside another exception, or a new exception is created based on the one thrown by the repository?
Kotlin already has a built-in Result type, and I strongly recommend using that one instead of defining your own.
Nonetheless, if you use the built-in type, you will probably face the same problem, since the equals check still fails for the different exception instances.
There are several ways to solve that:
Define your own exception type and override the equals function to return true if they are both of the same type and have the same message.
Check for expected is Error (or with the default Result type that expected.isFailure), and then check that the messages are the same.
Make sure that loginUseCase throws exactly the same exception instance as is thrown by the repository.

How to compare/match closures in mocks?

TL;DR: mocked method accepts closure. I wonder how to create custom matcher (https://godoc.org/github.com/golang/mock/gomock#Matcher): closure itself in turn is working with private structure - meaning I can't even call the closure in my test to check it against expectations.
I'm working on a small app using Slack API with help of nlopes/slack (https://github.com/nlopes/slack).
For testing, I'm mocking nlopes/slack with gomock. For that I've created interface
type slackAPI interface {
OpenConversation(*slack.OpenConversationParameters) (*slack.Channel, bool, bool, error)
PostMessage(channelID string, options ...slack.MsgOption) (string, string, error)
GetUserByEmail(email string) (*slack.User, error)
}
I have no problem testing OpenConversation or GetUserByEmail, e.g.
slackAPIClient.
EXPECT().
GetUserByEmail("some#email.com").
Return(slackUserJohndoe, nil).
Times(1)
Things get more complicated when it comes to PostMessage. In main code the call looks like
_, _, err := slackAPIClient.PostMessage(channel.ID, slack.MsgOptionText(message, false))
And slack.MsgOptionText (from nlopes/slack) is actually returning closure:
func MsgOptionText(text string, escape bool) MsgOption {
return func(config *sendConfig) error {
if escape {
text = slackutilsx.EscapeMessage(text)
}
config.values.Add("text", text)
return nil
}
}
Since method is accepting closure, I need to create custom gomock matcher (https://godoc.org/github.com/golang/mock/gomock#Matcher). Custom matcher itself is not a problem, it would look something like
type higherOrderFunctionEqMatcher struct {
x interface{}
}
func (e hofEqMatcher) Matches(x interface{}) bool {
//return m.x == x
return true
}
func (e hofEqMatcher) String(x interface{}) string {
return fmt.Sprintf("is equal %v", e.x)
}
However, since MsgOptionText uses nlopes/slack private structure sendConfig, I wonder how can I even work with that in scope of my test to check equality to expectations.
How should I tackle such problem?
Bearing in mind that
in Golang you can't compare functions
in this precise case I can't do indirect test by calling closure itself (since it's using private 3rd party lib's structure as an argument)
the solution I've found is to mock slack.MsgOptionText(message, false), which in turn returns closure for PostMessage(channelID string, options ...slack.MsgOption):
type slackMsgCreator interface {
MsgOptionText(string, bool) slack.MsgOption
}
type slackMsgCreatorInst struct{}
func (s slackMsgCreatorInst) MsgOptionText(text string, escape bool) slack.MsgOption {
return slack.MsgOptionText(text, escape)
}
...
slackMsgCreator.
EXPECT().
MsgOptionText("Dear John Doe, message goes here", false).
Return(slack.MsgOptionText("Dear John Doe, message goes here", false)).
Times(1)
And, as for PostMessage - as was advised in comments, the only thing that I could check is that closure is not nil:
slackAPIClient.
EXPECT().
PostMessage("ABCDE", Not(Nil())).
AnyTimes()

How to unit-test a deserialization function used in serde(deserialize_with)?

I have a struct which implements Deserialize and uses the serde(deserialize_with) on a field:
#[derive(Debug, Deserialize)]
struct Record {
name: String,
#[serde(deserialize_with = "deserialize_numeric_bool")]
is_active: bool,
}
The implementation of deserialize_numeric_bool deserializes a string "0" or "1" to the corresponding boolean value:
pub fn deserialize_numeric_bool<'de, D>(deserializer: D) -> Result<bool, D::Error>
where D: Deserializer<'de>
{
struct NumericBoolVisitor;
impl<'de> Visitor<'de> for NumericBoolVisitor {
type Value = bool;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("either 0 or 1")
}
fn visit_u64<E>(self, value: u64) -> Result<bool, E>
where E: DeserializeError
{
match value {
0 => Ok(false),
1 => Ok(true),
_ => Err(E::custom(format!("invalid bool: {}", value))),
}
}
}
deserializer.deserialize_u64(NumericBoolVisitor)
}
(I appreciate comments about code improvements)
I'd like to write unit tests for deserialization functions like deserialize_numeric_bool. Of course, my friendly search box revealed the serde_test crate and a documentation page about unit-testing.
But these resources couldn't help me in my case, as the crate tests a structure directly implementing Deserialize.
One idea I had was to create a newtype which only contains the output of my deserialize functions and test it with it. But this looks like a unnecessary indirection to me.
#[derive(Deserialize)]
NumericBool {
#[serde(deserialize_with = "deserialize_numeric_bool")]
value: bool
};
How do I write idiomatic tests for it?
My current solution uses only structures already provided by serde.
In my use case, I only wanted to test that a given string will deserialize successfully into a bool or has a certain error. The serde::de::value provides simple deserializers for fundamental data types, for example U64Deserializer which holds a u64. It also has an Error struct which provides a minimal representation for the Error traits – ready to be used for mocking errors.
My tests look currently like that: I mock the input with a deserializer and pass it to my function under test. I like that I don't need an indirection there and that I have no additional dependencies. It is not as nice as the assert_tokens* provided serde_test, as it needs the error struct and feels less polished. But for my case, where only a single value is deserialized, it fulfills my needs.
use serde::de::IntoDeserializer;
use serde::de::value::{U64Deserializer, StrDeserializer, Error as ValueError};
#[test]
fn test_numeric_true() {
let deserializer: U64Deserializer<ValueError> = 1u64.into_deserializer();
assert_eq!(numeric_bool(deserializer), Ok(true));
}
#[test]
fn test_numeric_false() {
let deserializer: U64Deserializer<ValueError> = 0u64.into_deserializer();
assert_eq!(numeric_bool(deserializer), Ok(false));
}
#[test]
fn test_numeric_invalid_number() {
let deserializer: U64Deserializer<ValueError> = 2u64.into_deserializer();
let error = numeric_bool(deserializer).unwrap_err();
assert_eq!(error.description(), "invalid bool: 2");
}
#[test]
fn test_numeric_empty() {
let deserializer: StrDeserializer<ValueError> = "".into_deserializer();
let error = numeric_bool(deserializer).unwrap_err();
assert_eq!(error.description(), "invalid type: string \"\", expected either 0 or 1");
}
I hope that it helps other folks too or inspire other people to find a more polished version.
I've come across this question several times while trying to solve a similar problem recently. For future readers, pixunil's answer is nice, straightforward, and works well. However, I'd like to provide a solution using serde_test as the unit testing documentation mentions.
I researched how serde_test is used across a few crates that I found via its reverse dependencies on lib.rs. Several of them define small structs or enums for testing deserialization or serialization as you mentioned in your original post. I suppose doing so is idiomatic when testing would be too verbose otherwise.
Here's a few examples; this is a non-exhaustive list:
Example from time
Another example from time
Example from slab (tokio)
Example from bitcoin_hashes
Example from uuid
Example from euclid
Anyway, let's say I have a function to deserialize a bool from a u8 and another function that serializes a bool to a u8.
use serde::{
de::{Error as DeError, Unexpected},
Deserialize, Deserializer, Serialize, Serializer,
};
fn bool_from_int<'de, D>(deserializer: D) -> Result<bool, D::Error>
where
D: Deserializer<'de>,
{
match u8::deserialize(deserializer)? {
0 => Ok(false),
1 => Ok(true),
wrong => Err(DeError::invalid_value(
Unexpected::Unsigned(wrong.into()),
&"zero or one",
)),
}
}
#[inline]
fn bool_to_int<S>(a_bool: &bool, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if *a_bool {
serializer.serialize_u8(1)
} else {
serializer.serialize_u8(0)
}
}
I can test those functions by defining a struct in my test module. This allows constraining the tests to those functions specifically instead of ser/deserializing a larger object.
#[cfg(test)]
mod tests {
use super::{bool_from_int, bool_to_int};
use serde::{Deserialize, Serialize};
use serde_test::{assert_de_tokens_error, assert_tokens, Token};
#[derive(Debug, PartialEq, Deserialize, Serialize)]
#[serde(transparent)]
struct BoolTest {
#[serde(deserialize_with = "bool_from_int", serialize_with = "bool_to_int")]
a_bool: bool,
}
const TEST_TRUE: BoolTest = BoolTest { a_bool: true };
const TEST_FALSE: BoolTest = BoolTest { a_bool: false };
#[test]
fn test_true() {
assert_tokens(&TEST_TRUE, &[Token::U8(1)])
}
#[test]
fn test_false() {
assert_tokens(&TEST_FALSE, &[Token::U8(0)])
}
#[test]
fn test_de_error() {
assert_de_tokens_error::<BoolTest>(
&[Token::U8(14)],
"invalid value: integer `14`, expected zero or one",
)
}
}
BoolTest is within the tests module which is gated by #[cfg(test)] as per usual. This means that BoolTest is only compiled for tests rather than adding bloat. I'm not a Rust expert, but I think this is a good alternative if a programmer wishes to use serde_test as a harness.

How to write reasonml binding for a union type

I am trying to write bindings for https://github.com/oblador/react-native-keychain/blob/master/typings/react-native-keychain.d.ts#L76
getGenericPassword returns false if an error, else an object (credentials). I am not sure this union type can be represented in reason, but a better API would be the result an option (option(credentials)). But, how can I convert Promise<boolean | credentials> -> Js.Promise.t(option(credentials)) in the binding file. Below is a template.
Thanks for your help.
[#bs.deriving abstract]
type credentials = {
service: string,
username: string,
password: string,
};
/* TODO convert the actual return value
Js.Promise.t(option(credentials)) to more reason type
Js.Promise.t(option(credentials)) */
[#bs.module "react-native-keychain"] [#bs.scope "default"]
external getGenericPassword: unit => Js.Promise.t(option(credentials)) = "";
You can use Js.Types.classify to get the runtime type of a value.
type maybeCredentials;
[#bs.module "react-native-keychain"] [#bs.scope "default"]
external getGenericPassword: unit => Js.Promise.t(maybeCredentials) = "";
let getGenericPassword: unit => Js.Promise.t(option(credentials)) =
() =>
Js.Promise.(
getGenericPassword()
|> then_(maybeCredentials =>
switch (Js.Types.classify(maybeCredentials)) {
| JSObject(obj) => resolve(Some(obj |> Obj.magic))
| _ => resolve(None)
}
)
);
Here maybeCredentials is defined and used as an intermediate type.
We then define a function with the same name as the binding, which will "shadow" the name and prevent the binding from being used directly in favour of our "override". However, within the override we're still able to use the binding.
We then call Js.Types.classify to get the runtime type of the returned value. If it is an object we use Obj.magic to cast the abstract obj_type to our credentials type (inferred from the return type of the function), and wrap it in an option. For any other type we return None.
By the way, this kind of "type" is called an untagged union. I've written down a few examples using different strategies for dealing with these, as both a producer and a consumer, in bucklescript-cookbook.

Swift: RxSwift's asObservable() method and type erasure

I am having problem understanding the rationale and purpose for asObservable method in RxSwift's Observable class.
/// A type-erased `ObservableType`.
///
/// It represents a push style sequence.
public class Observable<Element> : ObservableType {
/// Type of elements in sequence.
public typealias E = Element
public func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E {
abstractMethod()
}
public func asObservable() -> Observable<E> {
return self
}
}
What's the purpose of asObservable when it's returning self?
Surely if you can run this method, you already have access to the object. Also, what does the "type-erased ObservableType" in the comment means?
I believe the answer is apparent if you look at the ObservableType protocol and what objects conform to it (namely things like subjects, etc.).
The only guarantee is that the object will return an Observable in response to a call to asObservable. While conformance is trivial for an Observable, it may be less so for subjects and other units. But this guarantee allows you to use all type that can provide an Observable together in the same operator chain.
In essence this is similar to Strings conformance to CustomStringConvertible.
You asked two questions:
1. What's the purpose of asObservable when it's returning self?
You almost don't need to ever use asObservable(). The only time I think you'd need is when you're assigning casting a Subject/Relay to an Observable.
Suppose you have a variable that is a BehaviorRelay. It can both, observe and be an observable.
ViewModel.swift
let deviceOrientation = BehaviorRelay<UIInterfaceOrientation>(value: UIApplication.shared.statusBarOrientation)
And then you have a variable that is not both but only an observable like below.
ViewController.swift
lazy var incorrect : Observable<UIInterfaceOrientation> = {
return self.viewModel.deviceOrientation // ERROR
}()
lazy var correct : Observable<UIInterfaceOrientation> = {
return self.viewModel.deviceOrientation.asObservable()
}()
Then you'd need to cast so you'd have the correct type.
The incorrect variable would give the following error:
Cannot convert value of type BehaviorRelay<UIInterfaceOrientation>
to closure result type Observable<UIInterfaceOrientation>
2. What does the "type-erased ObservableType" in the comment means?
I suspect Scott's comment is semi-correct. I mean for sure it's confusing. You can flatten the type of a BehvaiorRelay, PublishSubject to a Observable and then assign one Observable to another. Otherwise still they all require the associatedType to be given ie no type erasure happening.
let x : AnyHashable = 10
let y : AnyHashable = "Alex"
if x == y { print("equal" } // compiles!
var i = PublishSubject<Int>().asObservable()
var s = PublishSubject<String>().asObservable()
if i == s { print("equal" } // does NOT compile. Gives following error:
Binary operator == cannot be applied to operands of type
Observable<Int> and Observable<String>