mchung / mchung-code

Bits of code from around the world

This URL has Read+Write access

mchung-code / hacks / rb / hash_test.rb
4737175f » Marc Chung 2008-05-14 Amusing Hash lookup style 1 require 'test/unit'
2 require 'hash'
3 require 'rubygems'
4 require 'xmlsimple'
5
6 class HashTest < Test::Unit::TestCase
7
8 def test_should_lookup_when_key_is_symbol
9 a = {:foo => "42"}
10 assert_equal "42", a.fetch(:foo)
11 assert_equal "42", a[:foo]
12 assert_equal "42", a.foo
13 assert_equal nil, a.foo_no_aqui
14 end
15
16 def test_should_lookup_when_key_is_string
17 a = {"foo" => "fnord"}
18 assert_equal "fnord", a["foo"]
19 assert_equal "fnord", a.foo
20 assert_equal nil, a.foo_no_aqui_tambien
21 end
22
23 def test_should_query_flat_hash
24 a = {:foo => "salsa"}
25 assert_equal nil, a.foo?.bar
26 assert_equal nil, a.samba?.chacha?.rumba?.salsa
27 assert_equal "salsa", a.foo
28 end
29
30 def test_should_query_nested_hash
31 a = {:foo => "jazz", :bar => {:baz => "blues"}}
32 b = {:baz => "blues"}
33 assert_equal "jazz", a.foo
34 assert_equal b, a.bar
35 assert_equal "blues", a.bar.baz
36 assert_equal "blues", a.bar?.baz
37 assert_equal({}, a.bar?.baz?)
38 assert_equal nil, a.bar?.baz?.tienes_ganas_una_taza_de_cafe
39 end
40
41 def test_hash_from_xml
42 xml =<<XML
43 <SyncHdr>
44 <VerDTD>1.2</VerDTD>
45 <VerProto>OMA/1.2</VerProto>
46 <SessionID>1</SessionID>
47 <MsgID>1</MsgID>
48 <Target>
49 <LocURI>https://oma.example.com</LocURI>
50 </Target>
51 <Source>
52 <LocURI>OMA123456</LocURI>
53 </Source>
54 <Cred>
55 <Meta>
56 <Type>syncml:auth-basic</Type>
57 <Format>b64</Format>
58 </Meta>
59 <Data>ssh_the_pass</Data>
60 </Cred>
61 <Meta>
62 <MaxMsgSize>10700</MaxMsgSize>
63 </Meta>
64 </SyncHdr>
65 XML
66 hash = XmlSimple.xml_in(xml, {"forcearray" => false, "keeproot" => true})
67 assert_equal "1.2", hash.SyncHdr?.VerDTD
68 assert_equal "ssh_the_pass", hash.SyncHdr?.Cred?.Data
69 assert_equal nil, hash.SyncHdr?.Cred?.Meta?.MoreData
70 assert_equal "OMA123456", hash.SyncHdr?.Source?.LocURI
71 end
72
73
74 end