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