@@ -149,24 +149,24 @@ mod tests {
149
149
let db_url = test_database_url ( ) ;
150
150
let mut c = sqlx:: AnyConnection :: connect ( & db_url) . await ?;
151
151
let row = sqlx:: query (
152
- "SELECT \
153
- 123.456 as one_value, \
154
- 1 as two_values, \
155
- 2 as two_values, \
156
- 'x' as three_values, \
157
- 'y' as three_values, \
158
- 'z' as three_values \
159
- ",
152
+ r# "SELECT
153
+ 123.456 as "ONE_VALUE",
154
+ 1 as "TWO_VALUES",
155
+ 2 as "TWO_VALUES",
156
+ 'x' as "THREE_VALUES",
157
+ 'y' as "THREE_VALUES",
158
+ 'z' as "THREE_VALUES"
159
+ "# ,
160
160
)
161
161
. fetch_one ( & mut c)
162
162
. await ?;
163
- assert_eq ! (
164
- row_to_json( & row) ,
165
- serde_json:: json!( {
166
- "one_value " : 123.456 ,
167
- "two_values " : [ 1 , 2 ] ,
168
- "three_values " : [ "x" , "y" , "z" ] ,
169
- } )
163
+ expect_json_object_equal (
164
+ & row_to_json ( & row) ,
165
+ & serde_json:: json!( {
166
+ "ONE_VALUE " : 123.456 ,
167
+ "TWO_VALUES " : [ 1 , 2 ] ,
168
+ "THREE_VALUES " : [ "x" , "y" , "z" ] ,
169
+ } ) ,
170
170
) ;
171
171
Ok ( ( ) )
172
172
}
@@ -466,7 +466,7 @@ mod tests {
466
466
fn expect_json_object_equal ( actual : & Value , expected : & Value ) {
467
467
use std:: fmt:: Write ;
468
468
469
- if actual == expected {
469
+ if json_values_equal ( actual, expected) {
470
470
return ;
471
471
}
472
472
let actual = actual. as_object ( ) . unwrap ( ) ;
@@ -480,7 +480,7 @@ mod tests {
480
480
for key in all_keys {
481
481
let actual_value = actual. get ( key) . unwrap_or ( & Value :: Null ) ;
482
482
let expected_value = expected. get ( key) . unwrap_or ( & Value :: Null ) ;
483
- if actual_value == expected_value {
483
+ if json_values_equal ( actual_value, expected_value) {
484
484
continue ;
485
485
}
486
486
writeln ! (
@@ -494,4 +494,33 @@ mod tests {
494
494
"JSON objects are not equal:\n \n {comparison_string}"
495
495
) ;
496
496
}
497
+
498
+ /// Compare JSON values, treating integers and floats that are numerically equal as equal
499
+ fn json_values_equal ( a : & Value , b : & Value ) -> bool {
500
+ use Value :: * ;
501
+
502
+ match ( a, b) {
503
+ ( Null , Null ) => true ,
504
+ ( Bool ( a) , Bool ( b) ) => a == b,
505
+ ( Number ( a) , Number ( b) ) => {
506
+ // Treat integers and floats as equal if they represent the same numerical value
507
+ a. as_f64 ( ) == b. as_f64 ( )
508
+ }
509
+ ( String ( a) , String ( b) ) => a == b,
510
+ ( Array ( a) , Array ( b) ) => {
511
+ a. len ( ) == b. len ( ) && a. iter ( ) . zip ( b. iter ( ) ) . all ( |( a, b) | json_values_equal ( a, b) )
512
+ }
513
+ ( Object ( a) , Object ( b) ) => {
514
+ if a. len ( ) != b. len ( ) {
515
+ return false ;
516
+ }
517
+ a. iter ( ) . all ( |( key, value) | {
518
+ b. get ( key) . map_or ( false , |expected_value| {
519
+ json_values_equal ( value, expected_value)
520
+ } )
521
+ } )
522
+ }
523
+ _ => false ,
524
+ }
525
+ }
497
526
}
0 commit comments