~ubuntu-branches/ubuntu/trusty/libsereal-encoder-perl/trusty-proposed

« back to all changes in this revision

Viewing changes to t/020_sort_keys.t

  • Committer: Package Import Robot
  • Author(s): Alexandre Mestiashvili
  • Date: 2013-02-20 08:29:14 UTC
  • Revision ID: package-import@ubuntu.com-20130220082914-dljb6eixvtj2m1v2
Tags: upstream-0.31
ImportĀ upstreamĀ versionĀ 0.31

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!perl
 
2
use strict;
 
3
use warnings;
 
4
use Sereal::Encoder qw(encode_sereal);
 
5
use List::Util qw(shuffle);
 
6
use Test::More;
 
7
 
 
8
# Try and find 15 hash collisions in "A".."Z"
 
9
# we will use the colliding keys to produce hashes
 
10
# with the same contents, but with different key orders,
 
11
# which we will use to test the "sort_keys" logic.
 
12
 
 
13
my $max= 15;
 
14
my %hash;
 
15
my (%i, %j);
 
16
keys %i = $max;
 
17
keys %j = $max;
 
18
 
 
19
LOOP:
 
20
for my $x ("A" .. "Z") {
 
21
    for my $y ( chr(ord($x)+1) .. "Z" ) {
 
22
        %i= ();
 
23
        %j= ();
 
24
        $i{$x}= 1; $i{$y}= 1;
 
25
        $j{$y}= 1; $j{$x}= 1;
 
26
        if ("@{[keys %i]}" ne "@{[keys %j]}") {  # collission?
 
27
            $hash{$x}= 1;
 
28
            last LOOP if keys %hash == $max;
 
29
            $hash{$y}= 1;
 
30
            last LOOP if keys %hash == $max;
 
31
        }
 
32
    }
 
33
}
 
34
 
 
35
my %copy= %hash;
 
36
my $copy_keys= join "", keys %copy;
 
37
 
 
38
my %bigger= %hash;
 
39
keys(%bigger)= $max++ while scalar(%bigger) eq scalar(%hash);
 
40
 
 
41
my %shuffled;
 
42
$shuffled{$_}= $hash{$_} for shuffle keys %hash;
 
43
 
 
44
my %encoded;
 
45
my %encoded_unsorted;
 
46
for ( \%hash, \%copy, \%bigger, \%shuffled ) {
 
47
    my $keys= join "", keys %$_;
 
48
    $encoded{$keys} ||= encode_sereal($_, { sort_keys => 1 } );
 
49
    $encoded_unsorted{$keys} ||= encode_sereal($_);
 
50
}
 
51
my @keys= keys %encoded;
 
52
 
 
53
if ( @keys > 1 ) {
 
54
    plan tests => 2 * ( (@keys * (@keys-1)) / 2 );
 
55
} else {
 
56
    plan skip_all => "Could not generate test hashes";
 
57
}
 
58
 
 
59
foreach my $x ( 0 .. $#keys ) {
 
60
    foreach my $y ($x + 1 .. $#keys) {
 
61
        is($encoded{$keys[$x]}, $encoded{$keys[$y]},"$keys[$x] vs $keys[$y] (same: sort_keys)");
 
62
        isnt($encoded_unsorted{$keys[$x]}, $encoded_unsorted{$keys[$y]},"$keys[$x] vs $keys[$y] (different: no sort_keys)");
 
63
    }
 
64
}
 
65