Jest asymmetric matcher `expect.objectContaining`: a straight and forward example - jestjs

I have been using jest lately to train my unit-test skills. On this process, I was able to reproduce their examples on website https://jestjs.io/docs/expect. Among others, the particular use case expect.objectContaining is somewhat troublesome. The given example uses a function handler and expect matcher toHaveBeenCalledWith. Although the example is possible, it is not straight and forward enough on the objective of sub-object match using this asymmetric matcher based on given object.
The reproduction steps follow below:
Clone repository https://github.com/alloyha/experiments
Navigate to folder /web/test_expect;
Run command npm install;
Run command npm test;
The expected output is:
FAIL __test__/expect.test.js
● expect › assert asymmetric matcher existent objectContainingAsyMatch
expect(received).toEqual(expected) // deep equality
- Expected - 2
+ Received + 4
- ObjectContaining {
- "foo": Any<String>,
+ Object {
+ "bar": Object {
+ "foo": "baz",
+ },
}
8 | expectation = expect.objectContaining({ foo: expect.any(String) });
9 |
> 10 | expect(result).toEqual(expectation);
| ^
11 | }
12 | );
13 | }
at Object.toEqual (__test__/expect.test.js:10:28)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 0.163 s, estimated 1 s
Ran all test suites.

Related

Ink :: What is the right way to add the debug trace prints | ink_env::debug_println? [duplicate]

This question already has answers here:
Why doesn't println! work in Rust unit tests?
(9 answers)
Closed 2 years ago.
Ink :: What is the right way to add the debug trace prints | ink_env::debug_println ?
Was trying ERC20 sample example from https://substrate.dev/substrate-contracts-workshop/#/2/transferring-tokens
#[ink(message)]
pub fn transfer(&mut self, to: AccountId, value: Balance) -> bool {
// ACTION: Call the `transfer_from_to` with `from` as `self.env().caller()`
let source: AccountId = self.env().caller();
let dbg_msg = format!( "from {:#?} to {:#?}", source, to );
ink_env::debug_println( &dbg_msg );
self.transfer_from_to( source , to, value )
}
With trace prints, executed the test, but can't see the trace output.
$ cargo +nightly test
Compiling erc20 v0.1.0 (/tmp/tmp.MkRICOxro3/erc20)
Finished test [unoptimized + debuginfo] target(s) in 0.85s
Running target/debug/deps/erc20-ac25c678251cab02
running 3 tests
test erc20::tests::balance_works ... ok
test erc20::tests::new_works ... ok
test erc20::tests::transfer_works ... ok
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Note:: Complete code snippet is at path ...
https://gist.github.com/shamb0/aee23b7f4789b0cd57cbc1c8f3fa2538
By default, Rust hides the stdout of successful tests.
To override this, use the --nocapture flag when running your test:
cargo +nightly test -- --nocapture

Find the shortest word, in a string of words

I am doing a bit of Code-Wars Challenges again and I have a question about this particular one:
Task: " Given a string of words, return the length of the shortest word(s).
String will never be empty and you do not need to account for different data types."
I've looked up the answers available on SO and I've managed to create the program on my own based on foreign ideas.
The problem is it still does not produce the desired output.
I run- through the code and I think the problem lies with the variables, and my inability to assign to correct sections of the code.(although I may be wrong)
So below, I attach the code as well as the tests.
Hope, any of you can find the answer to the problem.
Cheers
object Shortest{
def findShort(str:String):Int ={
var smallestLength = 99
var currentLength = 0
for(word <- str.split("")) {
currentLength = 0
for(letter <- word){
currentLength +=1
}
if(currentLength < smallestLength)
smallestLength = currentLength
}
smallestLength
}
}
Here are the tests:
Test Results:
ShortestTest
findShort(bitcoin take over the world maybe who knows perhaps) should return 3
Test Failed
1 was not equal to 3
Stack Trace
Completed in 45ms
findShort(turns out random test cases are easier than writing out basic ones) should return 3
Test Failed
1 was not equal to 3
Stack Trace
Completed in 1ms
findShort(lets talk about javascript the best language) should return 3
Test Failed
1 was not equal to 3
Stack Trace
Completed in 1ms
findShort(i want to travel the world writing code one day) should return 1
findShort(Lets all go on holiday somewhere very cold) should return 2
Test Failed
1 was not equal to 2
Stack Trace
Completed in 1ms
findShort(Steem Dogecoin 21inc Dash MadeSafeCoin) should return 4
Test Failed
1 was not equal to 4
Stack Trace
Completed in 1ms
findShort(Bitcoin Lisk) should return 4
Test Failed
1 was not equal to 4
Stack Trace
Completed in 1ms
findShort(ProofOfStake Ripple) should return 6
Test Failed
1 was not equal to 6
Stack Trace
findShort(ProofOfWork Dogecoin BTC Classic Dash Ripple ProofOfWork) should return 3
Test Failed
1 was not equal to 3
Stack Trace
Completed in 1ms
findShort(LiteCoin Bitcoin LiteCoin Bitcoin Waves Waves Bitcoin Dash Ripple Ripple Ethereum Classic Factom LiteCoin Factom Waves Factom) should return 4
Test Failed
1 was not equal to 4
Stack Trace
Completed in 2ms
findShort(Bitcoin Waves MadeSafeCoin DarkCoin ProofOfStake Classic BTC) should return 3
Test Failed
1 was not equal to 3
Stack Trace
Completed in 1ms
findShort(ProofOfStake Waves Ethereum Ethereum Ripple LiteCoin Steem Classic LiteCoin Ripple ProofOfStake Steem Monero Dogecoin Factom) should return 5
Test Failed
Your solution is ok actually, all you need to change is str.split("") to str.split(" ") (note the space).
Here is a way to do it relying on built-in method:
def findShort(wordsString: String): Int = {
val wordsArray = wordsString.split(" ")
wordsArray.minBy(_.length).length
}
println(findShort("LiteCoin Bitcoin LiteCoin Bitcoin Waves Waves Bitcoin Dash Ripple Ripple Ethereum Classic Factom LiteCoin Factom Waves Factom"))
// Display 4
println(findShort("Bitcoin Waves MadeSafeCoin DarkCoin ProofOfStake Classic BTC"))
// Display 3
And here a version that use foldLeft, if you don't want to rely on built in method:
def length(word: String): Int =
word.foldLeft(0){case (acc, _) => acc + 1}
def findShort(str:String):Int = {
str.split(" ").foldLeft(99){ case (smallestLength, word) =>
val currentLength = length(word)
if(currentLength < smallestLength)
currentLength
else smallestLength
}
}

perl6 NativeCall doesn't find library on Darwin

I'm playing a bit with NativeCall to get familiar with that side of Perl6. Of course, I'm trying to load libstatgrab first (what else?).
So I start with easiest part - the host information. Since no cluster support yet, it's just one result - no worries for complication.
The code:
#!/usr/bin/env perl6
use v6;
use NativeCall;
enum sg_error (
SG_ERROR_NONE => 0,
SG_ERROR_INVALID_ARGUMENT => 1,
...
);
class sg_error_details is repr('CStruct') {
has int32 $.error;
has int32 $.errno_value;
has Str $.error_arg;
};
sub sg_init(int32 $ignore_errors) returns int32 is native('statgrab') { * };
enum sg_host_state (
sg_unknown_configuration => 0,
sg_physical_host => 1,
sg_virtual_machine => 2,
sg_paravirtual_machine => 3,
sg_hardware_virtualized => 4
);
class sg_host_info is repr('CStruct') {
has Str $.os_name;
has Str $.os_release;
has Str $.os_version;
has Str $.platform;
has Str $.hostname;
has uint32 $.bitwidth;
has int32 $.host_state;
has uint32 $.ncpus;
has uint32 $.maxcpus;
has uint64 $.uptime;
has uint64 $.systime;
};
sub sg_get_host_info(size_t is rw) returns Pointer is native('statgrab') is symbol('sg_get_host_info_r') { * };
sub sg_free_host_info(Pointer) is native('statgrab') is symbol('sg_free_stats_buf') { * };
sub MAIN() {
my int32 $ignore_errors = 0;
my $error = sg_init($ignore_errors);
if $error != SG_ERROR_NONE {
say "Maeh: $error";
exit 1;
}
my size_t $num_host_infos = 0;
my $res = sg_get_host_info($num_host_infos);
if $num_host_infos > 0 {
my $host_info = nativecast(sg_host_info, $res);
with $host_info {
say "You're using ", $_.os_name, " on ", $_.hostname;
}
}
sg_free_host_info($res);
}
Starting it (dumb) results in loading library error:
$ perl6 statgrab.p6
Cannot locate native library 'libstatgrab.dylib': dlopen(libstatgrab.dylib, 1): image not found
in method setup at /Users/sno/rakudo/share/perl6/sources/24DD121B5B4774C04A7084827BFAD92199756E03 (NativeCall) line 283
in method CALL-ME at /Users/sno/rakudo/share/perl6/sources/24DD121B5B4774C04A7084827BFAD92199756E03 (NativeCall) line 570
in sub MAIN at statgrab.p6 line 95
in block <unit> at statgrab.p6 line 93
Okay - giving it some search path:
$ LD_LIBRARY_PATH=/opt/pkg/lib:$LD_LIBRARY_PATH perl6 statgrab.p6
Cannot locate native library 'libstatgrab.dylib': dlopen(libstatgrab.dylib, 1): image not found
Same picture when using DYLD_LIBRARY_PATH - which is supported by dlopen(3) on Darwin, too.
But changing in the directory works:
$ (cd /opt/pkg/lib && perl6 /data/Projects/OSS/p6-Unix-Statgrab/statgrab.p6 )
You're using Darwin on ernie.[...]
Is there a lack of search path passthrough in the way how moarvm is called?
doug$ perl6 -v
This is Rakudo Star version 2018.10 built on MoarVM version 2018.10
implementing Perl 6.c.
On a fairly recent Rakudo Star on MacOS High Sierra, the script worked "out of the box" for me:
edited script to remove '...'.
Script failed to load the library (really missing!)
brew install libstatgrab
Script ran successfully:
vader:learning doug$ perl6 nativecall_mac_Sno.pl6
You're using Darwin on Vader.local
Homebrew installed the library as follows:
$ v /usr/local/lib
total 11904
-rw-r--r-- 1 doug admin 6080828 Sep 23 12:40 libmoar.dylib
lrwxr-xr-x 1 doug admin 51 Mar 23 11:02 libstatgrab.10.dylib# -> ../Cellar/libstatgrab/0.91/lib/libstatgrab.10.dylib
lrwxr-xr-x 1 doug admin 44 Mar 23 11:02 libstatgrab.a# -> ../Cellar/libstatgrab/0.91/lib/libstatgrab.a
lrwxr-xr-x 1 doug admin 48 Mar 23 11:02 libstatgrab.dylib# -> ../Cellar/libstatgrab/0.91/lib/libstatgrab.dylib
drwxr-xr-x 3 doug admin 102 Mar 23 11:02 pkgconfig/
For me, the perl6 executable is indeed a shell script, but it worked (there was no need to pass any extra LD_LIBRARY_PATH=...).
doug$ file `which perl6`
/Applications/Rakudo/bin/perl6: POSIX shell script text executable, ASCII text, with very long lines
doug$ set | grep LIBRARY
doug$
I have also had issues with my nativecall scripts finding the library, but have always solved them by fixing the library install and/or supplying 'LD_LIBRARY_PATH'.
Sorry this experience was Less Than Awesome for you

Puppet-lint warning when iterating over nested hash in puppet manifest

I am iterating over a hash of arrays in one of my puppet manifests
1 # class to manage needed packages
2 class profile::packages (
3 ){
4 $packages = hiera_hash('profile::packages::managed', {})
5
6 if $packages != {} {
7 $packages.each | String $package_state, Array $packages_array | {
8 $packages_array.each | Integer $idx, String $package | {
9 notify { "${package} with ${idx} should be ${package_state}": }
10 }
11 }
12 }
13 }
but I get a puppet-lint warning.
WARNING: top-scope variable being used without an explicit namespace
on line 8
Blockquote
WARNING: top-scope variable being used without an explicit
namespace on line 9
The code is running well, so it's a question of puppet-lint. Maybe there is a way to configure puppet-lint to recognize variables in the lambda blocks?
This is a known issue in puppet-lint at the time of writing. It has limited support for Puppet 4 language features.

What dtrace script output means?

I am tracing DTrace probes in my restify.js application (restify it is http server in node.js that provides dtrace support). I am using sample dtrace script from restify documentation:
#!/usr/sbin/dtrace -s
#pragma D option quiet
restify*:::route-start
{
track[arg2] = timestamp;
}
restify*:::handler-start
/track[arg3]/
{
h[arg3, copyinstr(arg2)] = timestamp;
}
restify*:::handler-done
/track[arg3] && h[arg3, copyinstr(arg2)]/
{
#[copyinstr(arg2)] = quantize((timestamp - h[arg3, copyinstr(arg2)]) / 1000000);
h[arg3, copyinstr(arg2)] = 0;
}
restify*:::route-done
/track[arg2]/
{
#[copyinstr(arg1)] = quantize((timestamp - track[arg2]) / 1000000);
track[arg2] = 0;
}
And the output is:
use_restifyRequestLogger
value ------------- Distribution ------------- count
-1 | 0
0 |######################################## 2
1 | 0
use_validate
value ------------- Distribution ------------- count
-1 | 0
0 |######################################## 2
1 | 0
pre
value ------------- Distribution ------------- count
0 | 0
1 |#################### 1
2 |#################### 1
4 | 0
handler
value ------------- Distribution ------------- count
128 | 0
256 |######################################## 2
512 | 0
route_user_read
value ------------- Distribution ------------- count
128 | 0
256 |######################################## 2
512 | 0
I was wondering what is value value field - what does it mean?
Why there is 124/256/512 for example? I guess it means the time/duration but it is in strange format - is it possible to show miliseconds for example?
The output is a histogram. You are getting a histogram because you are using the quantize function in your D script. The DTrace documentation says the following on quantize:
A power-of-two frequency distribution of the values of the specified expressions. Increments the value in the highest power-of-two bucket that is less than the specified expression.
The 'value' columns is the result of (timestamp - track[arg2]) / 1000000 where timestamp is the current time in nanoseconds. So the value shown is duration in milliseconds.
Putting this all together, the route_user_read result graph is telling you that you had 2 requests that took between 128 and 256 milliseconds.
This output is useful when you have a lot of requests and want to get a general sense of how your server is performing (you can quickly identify a bi-modal distribution for example). If you just want to see how long each request is taking, try using the printf function instead of quantize.

Resources