]> git.openstreetmap.org Git - rails.git/blob - test/lib/short_link_test.rb
Merge remote-tracking branch 'upstream/pull/1948'
[rails.git] / test / lib / short_link_test.rb
1 require "test_helper"
2
3 class ShortLinkTest < ActiveSupport::TestCase
4   ##
5   # tests that encoding and decoding are working to within
6   # the acceptable quantisation range.
7   def test_encode_decode
8     cases = []
9     1000.times do
10       cases << [180.0 * rand - 90.0, 360.0 * rand - 180.0, (18 * rand).to_i]
11     end
12
13     cases.each do |lat, lon, zoom|
14       lon2, lat2, zoom2 = ShortLink.decode(ShortLink.encode(lon, lat, zoom))
15       # zooms should be identical
16       assert_equal zoom, zoom2, "Decoding a encoded short link gives different zoom for (#{lat}, #{lon}, #{zoom})."
17       # but the location has a quantisation error introduced at roughly
18       # one pixel (i.e: zoom + 8). the sqrt(5) is because each position
19       # has an extra bit of accuracy in the lat coordinate, due to the
20       # smaller range.
21       distance = Math.sqrt((lat - lat2)**2 + (lon - lon2)**2)
22       max_distance = 360.0 / (1 << (zoom + 8)) * 0.5 * Math.sqrt(5)
23       assert max_distance > distance, "Maximum expected error exceeded: #{max_distance} <= #{distance} for (#{lat}, #{lon}, #{zoom})."
24     end
25   end
26
27   ##
28   # test that links are backwards-compatible, so any old links with
29   # the deprecated @ characters in them still work properly.
30   def test_deprecated_at_sign
31     cases = [["~v2juONc--", "@v2juONc--"],
32              ["as3I3GpG~-", "as3I3GpG@-"],
33              ["D~hV--",     "D@hV--"],
34              ["CO0O~m8--",  "CO0O@m8--"]]
35
36     cases.each do |new_code, old_code|
37       assert_equal ShortLink.decode(old_code), ShortLink.decode(new_code),
38                    "old (#{old_code}) and new (#{new_code}) should decode to the same location."
39     end
40   end
41 end