]> git.openstreetmap.org Git - rails.git/commitdiff
Merge remote-tracking branch 'upstream/pull/2161'
authorTom Hughes <tom@compton.nu>
Thu, 28 Feb 2019 19:17:40 +0000 (19:17 +0000)
committerTom Hughes <tom@compton.nu>
Thu, 28 Feb 2019 19:17:40 +0000 (19:17 +0000)
88 files changed:
.rubocop_todo.yml
app/controllers/amf_controller.rb [deleted file]
app/controllers/api/amf_controller.rb [new file with mode: 0644]
app/controllers/api/changeset_comments_controller.rb [new file with mode: 0644]
app/controllers/api/changesets_controller.rb [new file with mode: 0644]
app/controllers/api/nodes_controller.rb [new file with mode: 0644]
app/controllers/api/notes_controller.rb [new file with mode: 0644]
app/controllers/api/old_controller.rb [new file with mode: 0644]
app/controllers/api/old_nodes_controller.rb [new file with mode: 0644]
app/controllers/api/old_relations_controller.rb [new file with mode: 0644]
app/controllers/api/old_ways_controller.rb [new file with mode: 0644]
app/controllers/api/relations_controller.rb [new file with mode: 0644]
app/controllers/api/search_controller.rb [new file with mode: 0644]
app/controllers/api/swf_controller.rb [new file with mode: 0644]
app/controllers/api/traces_controller.rb [new file with mode: 0644]
app/controllers/api/user_preferences_controller.rb [new file with mode: 0644]
app/controllers/api/users_controller.rb [new file with mode: 0644]
app/controllers/api/ways_controller.rb [new file with mode: 0644]
app/controllers/changeset_comments_controller.rb
app/controllers/changesets_controller.rb
app/controllers/nodes_controller.rb [deleted file]
app/controllers/notes_controller.rb
app/controllers/old_controller.rb [deleted file]
app/controllers/old_nodes_controller.rb [deleted file]
app/controllers/old_relations_controller.rb [deleted file]
app/controllers/old_ways_controller.rb [deleted file]
app/controllers/relations_controller.rb [deleted file]
app/controllers/search_controller.rb [deleted file]
app/controllers/swf_controller.rb [deleted file]
app/controllers/traces_controller.rb
app/controllers/user_preferences_controller.rb [deleted file]
app/controllers/users_controller.rb
app/controllers/ways_controller.rb [deleted file]
app/helpers/note_helper.rb
app/views/api/notes/_comment.html.erb [moved from app/views/notes/_comment.html.erb with 100% similarity]
app/views/api/notes/_description.html.erb [moved from app/views/notes/_description.html.erb with 100% similarity]
app/views/api/notes/_entry.html.erb [moved from app/views/notes/_entry.html.erb with 100% similarity]
app/views/api/notes/_note.gpx.builder [moved from app/views/notes/_note.gpx.builder with 100% similarity]
app/views/api/notes/_note.json.jsonify [moved from app/views/notes/_note.json.jsonify with 100% similarity]
app/views/api/notes/_note.rss.builder [moved from app/views/notes/_note.rss.builder with 73% similarity]
app/views/api/notes/_note.xml.builder [moved from app/views/notes/_note.xml.builder with 100% similarity]
app/views/api/notes/feed.rss.builder [moved from app/views/notes/feed.rss.builder with 56% similarity]
app/views/api/notes/index.gpx.builder [moved from app/views/notes/index.gpx.builder with 100% similarity]
app/views/api/notes/index.json.jsonify [moved from app/views/notes/index.json.jsonify with 100% similarity]
app/views/api/notes/index.rss.builder [moved from app/views/notes/index.rss.builder with 54% similarity]
app/views/api/notes/index.xml.builder [moved from app/views/notes/index.xml.builder with 100% similarity]
app/views/api/notes/show.gpx.builder [moved from app/views/notes/show.gpx.builder with 100% similarity]
app/views/api/notes/show.json.jsonify [moved from app/views/notes/show.json.jsonify with 100% similarity]
app/views/api/notes/show.rss.builder [moved from app/views/notes/show.rss.builder with 56% similarity]
app/views/api/notes/show.xml.builder [moved from app/views/notes/show.xml.builder with 100% similarity]
app/views/api/users/_api_user.builder [moved from app/views/users/_api_user.builder with 100% similarity]
app/views/api/users/api_read.builder [moved from app/views/users/api_read.builder with 100% similarity]
app/views/api/users/api_users.builder [moved from app/views/users/api_users.builder with 100% similarity]
app/views/browse/changeset.html.erb
app/views/browse/feature.html.erb
app/views/browse/history.html.erb
config/locales/en.yml
config/routes.rb
test/controllers/amf_controller_test.rb [deleted file]
test/controllers/api/amf_controller_test.rb [new file with mode: 0644]
test/controllers/api/changeset_comments_controller_test.rb [new file with mode: 0644]
test/controllers/api/changesets_controller_test.rb [new file with mode: 0644]
test/controllers/api/nodes_controller_test.rb [new file with mode: 0644]
test/controllers/api/notes_controller_test.rb [new file with mode: 0644]
test/controllers/api/old_nodes_controller_test.rb [new file with mode: 0644]
test/controllers/api/old_relations_controller_test.rb [new file with mode: 0644]
test/controllers/api/old_ways_controller_test.rb [new file with mode: 0644]
test/controllers/api/relations_controller_test.rb [new file with mode: 0644]
test/controllers/api/search_controller_test.rb [new file with mode: 0644]
test/controllers/api/swf_controller_test.rb [new file with mode: 0644]
test/controllers/api/traces_controller_test.rb [new file with mode: 0644]
test/controllers/api/user_preferences_controller_test.rb [new file with mode: 0644]
test/controllers/api/users_controller_test.rb [new file with mode: 0644]
test/controllers/api/ways_controller_test.rb [new file with mode: 0644]
test/controllers/changeset_comments_controller_test.rb
test/controllers/changesets_controller_test.rb
test/controllers/nodes_controller_test.rb [deleted file]
test/controllers/notes_controller_test.rb
test/controllers/old_nodes_controller_test.rb [deleted file]
test/controllers/old_relations_controller_test.rb [deleted file]
test/controllers/old_ways_controller_test.rb [deleted file]
test/controllers/relations_controller_test.rb [deleted file]
test/controllers/search_controller_test.rb [deleted file]
test/controllers/swf_controller_test.rb [deleted file]
test/controllers/traces_controller_test.rb
test/controllers/user_preferences_controller_test.rb [deleted file]
test/controllers/users_controller_test.rb
test/controllers/ways_controller_test.rb [deleted file]

index 35107e9b9b2ea961b3949d10ec50b4caef6ba16d..25a30bf40099b15ac1326ca0bcccd3568322472c 100644 (file)
@@ -13,9 +13,10 @@ Lint/AssignmentInCondition:
     - 'app/controllers/application_controller.rb'
     - 'app/controllers/geocoder_controller.rb'
     - 'app/controllers/notes_controller.rb'
+    - 'app/controllers/api/traces_controller.rb'
     - 'app/controllers/traces_controller.rb'
     - 'app/controllers/users_controller.rb'
-    - 'app/controllers/user_preferences_controller.rb'
+    - 'app/controllers/api/user_preferences_controller.rb'
     - 'app/helpers/application_helper.rb'
     - 'app/helpers/browse_helper.rb'
     - 'app/helpers/browse_tags_helper.rb'
@@ -28,7 +29,7 @@ Lint/AssignmentInCondition:
 # Offense count: 4
 Lint/HandleExceptions:
   Exclude:
-    - 'app/controllers/amf_controller.rb'
+    - 'app/controllers/api/amf_controller.rb'
     - 'app/controllers/users_controller.rb'
 
 # Offense count: 692
@@ -178,7 +179,7 @@ Style/FrozenStringLiteralComment:
 # Cop supports --auto-correct.
 Style/IfUnlessModifier:
   Exclude:
-    - 'app/controllers/ways_controller.rb'
+    - 'app/controllers/api/ways_controller.rb'
 
 # Offense count: 70
 # Cop supports --auto-correct.
diff --git a/app/controllers/amf_controller.rb b/app/controllers/amf_controller.rb
deleted file mode 100644 (file)
index 2ad0fe6..0000000
+++ /dev/null
@@ -1,1000 +0,0 @@
-# amf_controller is a semi-standalone API for Flash clients, particularly
-# Potlatch. All interaction between Potlatch (as a .SWF application) and the
-# OSM database takes place using this controller. Messages are
-# encoded in the Actionscript Message Format (AMF).
-#
-# Helper functions are in /lib/potlatch.rb
-#
-# Author::  editions Systeme D / Richard Fairhurst 2004-2008
-# Licence:: public domain.
-#
-# == General structure
-#
-# Apart from the amf_read and amf_write methods (which distribute the requests
-# from the AMF message), each method generally takes arguments in the order
-# they were sent by the Potlatch SWF. Do not assume typing has been preserved.
-# Methods all return an array to the SWF.
-#
-# == API 0.6
-#
-# Note that this requires a patched version of composite_primary_keys 1.1.0
-# (see http://groups.google.com/group/compositekeys/t/a00e7562b677e193)
-# if you are to run with POTLATCH_USE_SQL=false .
-#
-# == Debugging
-#
-# Any method that returns a status code (0 for ok) can also send:
-# return(-1,"message")        <-- just puts up a dialogue
-# return(-2,"message")        <-- also asks the user to e-mail me
-# return(-3,["type",v],id)    <-- version conflict
-# return(-4,"type",id)        <-- object not found
-# -5 indicates the method wasn't called (due to a previous error)
-#
-# To write to the Rails log, use logger.info("message").
-
-# Remaining issues:
-# * version conflict when POIs and ways are reverted
-
-class AmfController < ApplicationController
-  include Potlatch
-
-  skip_before_action :verify_authenticity_token
-  before_action :check_api_writable
-
-  # AMF Controller implements its own authentication and authorization checks
-  # completely independently of the rest of the codebase, so best just to let
-  # it keep doing its own thing.
-  skip_authorization_check
-
-  # Main AMF handlers: process the raw AMF string (using AMF library) and
-  # calls each action (private method) accordingly.
-
-  def amf_read
-    self.status = :ok
-    self.content_type = Mime[:amf]
-    self.response_body = Dispatcher.new(request.raw_post) do |message, *args|
-      logger.info("Executing AMF #{message}(#{args.join(',')})")
-
-      case message
-      when "getpresets" then        result = getpresets(*args)
-      when "whichways" then         result = whichways(*args)
-      when "whichways_deleted" then result = whichways_deleted(*args)
-      when "getway" then            result = getway(args[0].to_i)
-      when "getrelation" then       result = getrelation(args[0].to_i)
-      when "getway_old" then        result = getway_old(args[0].to_i, args[1])
-      when "getway_history" then    result = getway_history(args[0].to_i)
-      when "getnode_history" then   result = getnode_history(args[0].to_i)
-      when "findgpx" then           result = findgpx(*args)
-      when "findrelations" then     result = findrelations(*args)
-      when "getpoi" then            result = getpoi(*args)
-      end
-
-      result
-    end
-  end
-
-  def amf_write
-    renumberednodes = {}              # Shared across repeated putways
-    renumberedways = {}               # Shared across repeated putways
-    err = false                       # Abort batch on error
-
-    self.status = :ok
-    self.content_type = Mime[:amf]
-    self.response_body = Dispatcher.new(request.raw_post) do |message, *args|
-      logger.info("Executing AMF #{message}")
-
-      if err
-        result = [-5, nil]
-      else
-        case message
-        when "putway" then
-          orn = renumberednodes.dup
-          result = putway(renumberednodes, *args)
-          result[4] = renumberednodes.reject { |k, _v| orn.key?(k) }
-          renumberedways[result[2]] = result[3] if result[0].zero? && result[2] != result[3]
-        when "putrelation" then
-          result = putrelation(renumberednodes, renumberedways, *args)
-        when "deleteway" then
-          result = deleteway(*args)
-        when "putpoi" then
-          result = putpoi(*args)
-          renumberednodes[result[2]] = result[3] if result[0].zero? && result[2] != result[3]
-        when "startchangeset" then
-          result = startchangeset(*args)
-        end
-
-        err = true if result[0] == -3 # If a conflict is detected, don't execute any more writes
-      end
-
-      result
-    end
-  end
-
-  private
-
-  def amf_handle_error(call, rootobj, rootid)
-    yield
-  rescue OSM::APIAlreadyDeletedError => ex
-    [-4, ex.object, ex.object_id]
-  rescue OSM::APIVersionMismatchError => ex
-    [-3, [rootobj, rootid], [ex.type.downcase, ex.id, ex.latest]]
-  rescue OSM::APIUserChangesetMismatchError => ex
-    [-2, ex.to_s]
-  rescue OSM::APIBadBoundingBox => ex
-    [-2, "Sorry - I can't get the map for that area. The server said: #{ex}"]
-  rescue OSM::APIError => ex
-    [-1, ex.to_s]
-  rescue StandardError => ex
-    [-2, "An unusual error happened (in #{call}). The server said: #{ex}"]
-  end
-
-  def amf_handle_error_with_timeout(call, rootobj, rootid)
-    amf_handle_error(call, rootobj, rootid) do
-      OSM::Timer.timeout(API_TIMEOUT, OSM::APITimeoutError) do
-        yield
-      end
-    end
-  end
-
-  # Start new changeset
-  # Returns success_code,success_message,changeset id
-
-  def startchangeset(usertoken, cstags, closeid, closecomment, opennew)
-    amf_handle_error("'startchangeset'", nil, nil) do
-      user = getuser(usertoken)
-      return -1, "You are not logged in, so Potlatch can't write any changes to the database." unless user
-      return -1, t("application.setup_user_auth.blocked") if user.blocks.active.exists?
-      return -1, "You must accept the contributor terms before you can edit." if user.terms_agreed.nil?
-
-      if cstags
-        return -1, "One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1." unless tags_ok(cstags)
-
-        cstags = strip_non_xml_chars cstags
-      end
-
-      # close previous changeset and add comment
-      if closeid
-        cs = Changeset.find(closeid.to_i)
-        cs.set_closed_time_now
-        if cs.user_id != user.id
-          raise OSM::APIUserChangesetMismatchError
-        elsif closecomment.empty?
-          cs.save!
-        else
-          cs.tags["comment"] = closecomment
-          # in case closecomment has chars not allowed in xml
-          cs.tags = strip_non_xml_chars cs.tags
-          cs.save_with_tags!
-        end
-      end
-
-      # open a new changeset
-      if opennew.nonzero?
-        cs = Changeset.new
-        cs.tags = cstags
-        cs.user_id = user.id
-        unless closecomment.empty?
-          cs.tags["comment"] = closecomment
-          # in case closecomment has chars not allowed in xml
-          cs.tags = strip_non_xml_chars cs.tags
-        end
-        # smsm1 doesn't like the next two lines and thinks they need to be abstracted to the model more/better
-        cs.created_at = Time.now.getutc
-        cs.closed_at = cs.created_at + Changeset::IDLE_TIMEOUT
-        cs.save_with_tags!
-        return [0, "", cs.id]
-      else
-        return [0, "", nil]
-      end
-    end
-  end
-
-  # Return presets (default tags, localisation etc.):
-  # uses POTLATCH_PRESETS global, set up in OSM::Potlatch.
-
-  def getpresets(usertoken, _lang)
-    user = getuser(usertoken)
-
-    langs = if user && !user.languages.empty?
-              Locale.list(user.languages)
-            else
-              Locale.list(http_accept_language.user_preferred_languages)
-            end
-
-    lang = getlocales.preferred(langs)
-    (real_lang, localised) = getlocalized(lang.to_s)
-
-    # Tell Potlatch what language it's using
-    localised["__potlatch_locale"] = real_lang
-
-    # Get help from i18n but delete it so we won't pass it around
-    # twice for nothing
-    help = localised["help_html"]
-    localised.delete("help_html")
-
-    # Populate icon names
-    POTLATCH_PRESETS[10].each do |id|
-      POTLATCH_PRESETS[11][id] = localised["preset_icon_#{id}"]
-      localised.delete("preset_icon_#{id}")
-    end
-
-    POTLATCH_PRESETS + [localised, help]
-  end
-
-  def getlocalized(lang)
-    # What we end up actually using. Reported in Potlatch's created_by=* string
-    loaded_lang = "en"
-
-    # Load English defaults
-    en = YAML.safe_load(File.open(Rails.root.join("config", "potlatch", "locales", "en.yml")))["en"]
-
-    if lang == "en"
-      return [loaded_lang, en]
-    else
-      # Use English as a fallback
-      begin
-        other = YAML.safe_load(File.open(Rails.root.join("config", "potlatch", "locales", "#{lang}.yml")))[lang]
-        loaded_lang = lang
-      rescue StandardError
-        other = en
-      end
-
-      # We have to return a flat list and some of the keys won't be
-      # translated (probably)
-      return [loaded_lang, en.merge(other)]
-    end
-  end
-
-  ##
-  # Find all the ways, POI nodes (i.e. not part of ways), and relations
-  # in a given bounding box. Nodes are returned in full; ways and relations
-  # are IDs only.
-  #
-  # return is of the form:
-  # [success_code, success_message,
-  #  [[way_id, way_version], ...],
-  #  [[node_id, lat, lon, [tags, ...], node_version], ...],
-  #  [[rel_id, rel_version], ...]]
-  # where the ways are any visible ways which refer to any visible
-  # nodes in the bbox, nodes are any visible nodes in the bbox but not
-  # used in any way, rel is any relation which refers to either a way
-  # or node that we're returning.
-  def whichways(xmin, ymin, xmax, ymax)
-    amf_handle_error_with_timeout("'whichways'", nil, nil) do
-      enlarge = [(xmax - xmin) / 8, 0.01].min
-      xmin -= enlarge
-      ymin -= enlarge
-      xmax += enlarge
-      ymax += enlarge
-
-      # check boundary is sane and area within defined
-      # see /config/application.yml
-      bbox = BoundingBox.new(xmin, ymin, xmax, ymax)
-      bbox.check_boundaries
-      bbox.check_size
-
-      if POTLATCH_USE_SQL
-        ways = sql_find_ways_in_area(bbox)
-        points = sql_find_pois_in_area(bbox)
-        relations = sql_find_relations_in_area_and_ways(bbox, ways.collect { |x| x[0] })
-      else
-        # find the way ids in an area
-        nodes_in_area = Node.bbox(bbox).visible.includes(:ways)
-        ways = nodes_in_area.inject([]) do |sum, node|
-          visible_ways = node.ways.select(&:visible?)
-          sum + visible_ways.collect { |w| [w.id, w.version] }
-        end.uniq
-        ways.delete([])
-
-        # find the node ids in an area that aren't part of ways
-        nodes_not_used_in_area = nodes_in_area.select { |node| node.ways.empty? }
-        points = nodes_not_used_in_area.collect { |n| [n.id, n.lon, n.lat, n.tags, n.version] }.uniq
-
-        # find the relations used by those nodes and ways
-        relations = Relation.nodes(nodes_in_area.collect(&:id)).visible +
-                    Relation.ways(ways.collect { |w| w[0] }).visible
-        relations = relations.collect { |relation| [relation.id, relation.version] }.uniq
-      end
-
-      [0, "", ways, points, relations]
-    end
-  end
-
-  # Find deleted ways in current bounding box (similar to whichways, but ways
-  # with a deleted node only - not POIs or relations).
-
-  def whichways_deleted(xmin, ymin, xmax, ymax)
-    amf_handle_error_with_timeout("'whichways_deleted'", nil, nil) do
-      enlarge = [(xmax - xmin) / 8, 0.01].min
-      xmin -= enlarge
-      ymin -= enlarge
-      xmax += enlarge
-      ymax += enlarge
-
-      # check boundary is sane and area within defined
-      # see /config/application.yml
-      bbox = BoundingBox.new(xmin, ymin, xmax, ymax)
-      bbox.check_boundaries
-      bbox.check_size
-
-      nodes_in_area = Node.bbox(bbox).joins(:ways_via_history).where(:current_ways => { :visible => false })
-      way_ids = nodes_in_area.collect { |node| node.ways_via_history.invisible.collect(&:id) }.flatten.uniq
-
-      [0, "", way_ids]
-    end
-  end
-
-  # Get a way including nodes and tags.
-  # Returns the way id, a Potlatch-style array of points, a hash of tags, the version number, and the user ID.
-
-  def getway(wayid)
-    amf_handle_error_with_timeout("'getway' #{wayid}", "way", wayid) do
-      if POTLATCH_USE_SQL
-        points = sql_get_nodes_in_way(wayid)
-        tags = sql_get_tags_in_way(wayid)
-        version = sql_get_way_version(wayid)
-        uid = sql_get_way_user(wayid)
-      else
-        # Ideally we would do ":include => :nodes" here but if we do that
-        # then rails only seems to return the first copy of a node when a
-        # way includes a node more than once
-        way = Way.where(:id => wayid).first
-
-        # check case where way has been deleted or doesn't exist
-        return [-4, "way", wayid] if way.nil? || !way.visible
-
-        points = way.nodes.preload(:node_tags).collect do |node|
-          nodetags = node.tags
-          nodetags.delete("created_by")
-          [node.lon, node.lat, node.id, nodetags, node.version]
-        end
-        tags = way.tags
-        version = way.version
-        uid = way.changeset.user.id
-      end
-
-      [0, "", wayid, points, tags, version, uid]
-    end
-  end
-
-  # Get an old version of a way, and all constituent nodes.
-  #
-  # For undelete (version<0), always uses the most recent version of each node,
-  # even if it's moved.  For revert (version >= 0), uses the node in existence
-  # at the time, generating a new id if it's still visible and has been moved/
-  # retagged.
-  #
-  # Returns:
-  # 0. success code,
-  # 1. id,
-  # 2. array of points,
-  # 3. hash of tags,
-  # 4. version,
-  # 5. is this the current, visible version? (boolean)
-
-  def getway_old(id, timestamp)
-    amf_handle_error_with_timeout("'getway_old' #{id}, #{timestamp}", "way", id) do
-      if timestamp == ""
-        # undelete
-        old_way = OldWay.where(:visible => true, :way_id => id).unredacted.order("version DESC").first
-        points = old_way.get_nodes_undelete unless old_way.nil?
-      else
-        begin
-          # revert
-          timestamp = Time.zone.strptime(timestamp.to_s, "%d %b %Y, %H:%M:%S")
-          old_way = OldWay.where("way_id = ? AND timestamp <= ?", id, timestamp).unredacted.order("timestamp DESC").first
-          unless old_way.nil?
-            if old_way.visible
-              points = old_way.get_nodes_revert(timestamp)
-            else
-              return [-1, "Sorry, the way was deleted at that time - please revert to a previous version.", id]
-            end
-          end
-        rescue ArgumentError
-          # thrown by date parsing method. leave old_way as nil for
-          # the error handler below.
-          old_way = nil
-        end
-      end
-
-      if old_way.nil?
-        return [-1, "Sorry, the server could not find a way at that time.", id]
-      else
-        curway = Way.find(id)
-        old_way.tags["history"] = "Retrieved from v#{old_way.version}"
-        return [0, "", id, points, old_way.tags, curway.version, (curway.version == old_way.version && curway.visible)]
-      end
-    end
-  end
-
-  # Find history of a way.
-  # Returns 'way', id, and an array of previous versions:
-  # - formerly [old_way.version, old_way.timestamp.strftime("%d %b %Y, %H:%M"), old_way.visible ? 1 : 0, user, uid]
-  # - now [timestamp,user,uid]
-  #
-  # Heuristic: Find all nodes that have ever been part of the way;
-  # get a list of their revision dates; add revision dates of the way;
-  # sort and collapse list (to within 2 seconds); trim all dates before the
-  # start date of the way.
-
-  def getway_history(wayid)
-    revdates = []
-    revusers = {}
-    Way.find(wayid).old_ways.unredacted.collect do |a|
-      revdates.push(a.timestamp)
-      revusers[a.timestamp.to_i] = change_user(a) unless revusers.key?(a.timestamp.to_i)
-      a.nds.each do |n|
-        Node.find(n).old_nodes.unredacted.collect do |o|
-          revdates.push(o.timestamp)
-          revusers[o.timestamp.to_i] = change_user(o) unless revusers.key?(o.timestamp.to_i)
-        end
-      end
-    end
-    waycreated = revdates[0]
-    revdates.uniq!
-    revdates.sort!
-    revdates.reverse!
-
-    # Remove any dates (from nodes) before first revision date of way
-    revdates.delete_if { |d| d < waycreated }
-    # Remove any elements where 2 seconds doesn't elapse before next one
-    revdates.delete_if { |d| revdates.include?(d + 1) || revdates.include?(d + 2) }
-    # Collect all in one nested array
-    revdates.collect! { |d| [(d + 1).strftime("%d %b %Y, %H:%M:%S")] + revusers[d.to_i] }
-    revdates.uniq!
-
-    ["way", wayid, revdates]
-  rescue ActiveRecord::RecordNotFound
-    ["way", wayid, []]
-  end
-
-  # Find history of a node. Returns 'node', id, and an array of previous versions as above.
-
-  def getnode_history(nodeid)
-    history = Node.find(nodeid).old_nodes.unredacted.reverse.collect do |old_node|
-      [(old_node.timestamp + 1).strftime("%d %b %Y, %H:%M:%S")] + change_user(old_node)
-    end
-    ["node", nodeid, history]
-  rescue ActiveRecord::RecordNotFound
-    ["node", nodeid, []]
-  end
-
-  def change_user(obj)
-    user_object = obj.changeset.user
-    user = user_object.data_public? ? user_object.display_name : "anonymous"
-    uid  = user_object.data_public? ? user_object.id : 0
-    [user, uid]
-  end
-
-  # Find GPS traces with specified name/id.
-  # Returns array listing GPXs, each one comprising id, name and description.
-
-  def findgpx(searchterm, usertoken)
-    amf_handle_error_with_timeout("'findgpx'", nil, nil) do
-      user = getuser(usertoken)
-
-      return -1, "You must be logged in to search for GPX traces." unless user
-      return -1, t("application.setup_user_auth.blocked") if user.blocks.active.exists?
-
-      query = Trace.visible_to(user)
-      query = if searchterm.to_i.positive?
-                query.where(:id => searchterm.to_i)
-              else
-                query.where("MATCH(name) AGAINST (?)", searchterm).limit(21)
-              end
-      gpxs = query.collect do |gpx|
-        [gpx.id, gpx.name, gpx.description]
-      end
-      [0, "", gpxs]
-    end
-  end
-
-  # Get a relation with all tags and members.
-  # Returns:
-  # 0. success code?
-  # 1. object type?
-  # 2. relation id,
-  # 3. hash of tags,
-  # 4. list of members,
-  # 5. version.
-
-  def getrelation(relid)
-    amf_handle_error("'getrelation' #{relid}", "relation", relid) do
-      rel = Relation.where(:id => relid).first
-
-      return [-4, "relation", relid] if rel.nil? || !rel.visible
-
-      [0, "", relid, rel.tags, rel.members, rel.version]
-    end
-  end
-
-  # Find relations with specified name/id.
-  # Returns array of relations, each in same form as getrelation.
-
-  def findrelations(searchterm)
-    rels = []
-    if searchterm.to_i.positive?
-      rel = Relation.where(:id => searchterm.to_i).first
-      rels.push([rel.id, rel.tags, rel.members, rel.version]) if rel&.visible
-    else
-      RelationTag.where("v like ?", "%#{searchterm}%").limit(11).each do |t|
-        rels.push([t.relation.id, t.relation.tags, t.relation.members, t.relation.version]) if t.relation.visible
-      end
-    end
-    rels
-  end
-
-  # Save a relation.
-  # Returns
-  # 0. 0 (success),
-  # 1. original relation id (unchanged),
-  # 2. new relation id,
-  # 3. version.
-
-  def putrelation(renumberednodes, renumberedways, usertoken, changeset_id, version, relid, tags, members, visible)
-    amf_handle_error("'putrelation' #{relid}", "relation", relid) do
-      user = getuser(usertoken)
-
-      return -1, "You are not logged in, so the relation could not be saved." unless user
-      return -1, t("application.setup_user_auth.blocked") if user.blocks.active.exists?
-      return -1, "You must accept the contributor terms before you can edit." if user.terms_agreed.nil?
-
-      return -1, "One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1." unless tags_ok(tags)
-
-      tags = strip_non_xml_chars tags
-
-      relid = relid.to_i
-      visible = visible.to_i.nonzero?
-
-      new_relation = nil
-      relation = nil
-      Relation.transaction do
-        # create a new relation, or find the existing one
-        relation = Relation.find(relid) if relid.positive?
-        # We always need a new node, based on the data that has been sent to us
-        new_relation = Relation.new
-
-        # check the members are all positive, and correctly type
-        typedmembers = []
-        members.each do |m|
-          mid = m[1].to_i
-          if mid.negative?
-            mid = renumberednodes[mid] if m[0] == "Node"
-            mid = renumberedways[mid] if m[0] == "Way"
-          end
-          typedmembers << [m[0], mid, m[2].delete("\000-\037\ufffe\uffff", "^\011\012\015")] if mid
-        end
-
-        # assign new contents
-        new_relation.members = typedmembers
-        new_relation.tags = tags
-        new_relation.visible = visible
-        new_relation.changeset_id = changeset_id
-        new_relation.version = version
-
-        if relid <= 0
-          # We're creating the relation
-          new_relation.create_with_history(user)
-        elsif visible
-          # We're updating the relation
-          new_relation.id = relid
-          relation.update_from(new_relation, user)
-        else
-          # We're deleting the relation
-          new_relation.id = relid
-          relation.delete_with_history!(new_relation, user)
-        end
-      end
-
-      if relid <= 0
-        return [0, "", relid, new_relation.id, new_relation.version]
-      else
-        return [0, "", relid, relid, relation.version]
-      end
-    end
-  end
-
-  # Save a way to the database, including all nodes. Any nodes in the previous
-  # version and no longer used are deleted.
-  #
-  # Parameters:
-  # 0. hash of renumbered nodes (added by amf_controller)
-  # 1. current user token (for authentication)
-  # 2. current changeset
-  # 3. new way version
-  # 4. way ID
-  # 5. list of nodes in way
-  # 6. hash of way tags
-  # 7. array of nodes to change (each one is [lon,lat,id,version,tags]),
-  # 8. hash of nodes to delete (id->version).
-  #
-  # Returns:
-  # 0. '0' (code for success),
-  # 1. message,
-  # 2. original way id (unchanged),
-  # 3. new way id,
-  # 4. hash of renumbered nodes (old id=>new id),
-  # 5. way version,
-  # 6. hash of changed node versions (node=>version)
-  # 7. hash of deleted node versions (node=>version)
-
-  def putway(renumberednodes, usertoken, changeset_id, wayversion, originalway, pointlist, attributes, nodes, deletednodes)
-    amf_handle_error("'putway' #{originalway}", "way", originalway) do
-      # -- Initialise
-
-      user = getuser(usertoken)
-      return -1, "You are not logged in, so the way could not be saved." unless user
-      return -1, t("application.setup_user_auth.blocked") if user.blocks.active.exists?
-      return -1, "You must accept the contributor terms before you can edit." if user.terms_agreed.nil?
-
-      return -2, "Server error - way is only #{pointlist.length} points long." if pointlist.length < 2
-
-      return -1, "One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1." unless tags_ok(attributes)
-
-      attributes = strip_non_xml_chars attributes
-
-      originalway = originalway.to_i
-      pointlist.collect!(&:to_i)
-
-      way = nil # this is returned, so scope it outside the transaction
-      nodeversions = {}
-      Way.transaction do
-        # -- Update each changed node
-
-        nodes.each do |a|
-          lon = a[0].to_f
-          lat = a[1].to_f
-          id = a[2].to_i
-          version = a[3].to_i
-
-          return -2, "Server error - node with id 0 found in way #{originalway}." if id.zero?
-          return -2, "Server error - node with latitude -90 found in way #{originalway}." if lat == 90
-
-          id = renumberednodes[id] if renumberednodes[id]
-
-          node = Node.new
-          node.changeset_id = changeset_id
-          node.lat = lat
-          node.lon = lon
-          node.tags = a[4]
-
-          # fixup node tags in a way as well
-          return -1, "One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1." unless tags_ok(node.tags)
-
-          node.tags = strip_non_xml_chars node.tags
-
-          node.tags.delete("created_by")
-          node.version = version
-          if id <= 0
-            # We're creating the node
-            node.create_with_history(user)
-            renumberednodes[id] = node.id
-            nodeversions[node.id] = node.version
-          else
-            # We're updating an existing node
-            previous = Node.find(id)
-            node.id = id
-            previous.update_from(node, user)
-            nodeversions[previous.id] = previous.version
-          end
-        end
-
-        # -- Save revised way
-
-        pointlist.collect! do |a|
-          renumberednodes[a] || a
-        end
-        new_way = Way.new
-        new_way.tags = attributes
-        new_way.nds = pointlist
-        new_way.changeset_id = changeset_id
-        new_way.version = wayversion
-        if originalway <= 0
-          new_way.create_with_history(user)
-          way = new_way # so we can get way.id and way.version
-        else
-          way = Way.find(originalway)
-          if way.tags != attributes || way.nds != pointlist || !way.visible?
-            new_way.id = originalway
-            way.update_from(new_way, user)
-          end
-        end
-
-        # -- Delete unwanted nodes
-
-        deletednodes.each do |id, v|
-          node = Node.find(id.to_i)
-          new_node = Node.new
-          new_node.changeset_id = changeset_id
-          new_node.version = v.to_i
-          new_node.id = id.to_i
-          begin
-            node.delete_with_history!(new_node, user)
-          rescue OSM::APIPreconditionFailedError
-            # We don't do anything here as the node is being used elsewhere
-            # and we don't want to delete it
-          end
-        end
-      end
-
-      [0, "", originalway, way.id, renumberednodes, way.version, nodeversions, deletednodes]
-    end
-  end
-
-  # Save POI to the database.
-  # Refuses save if the node has since become part of a way.
-  # Returns array with:
-  # 0. 0 (success),
-  # 1. success message,
-  # 2. original node id (unchanged),
-  # 3. new node id,
-  # 4. version.
-
-  def putpoi(usertoken, changeset_id, version, id, lon, lat, tags, visible)
-    amf_handle_error("'putpoi' #{id}", "node", id) do
-      user = getuser(usertoken)
-      return -1, "You are not logged in, so the point could not be saved." unless user
-      return -1, t("application.setup_user_auth.blocked") if user.blocks.active.exists?
-      return -1, "You must accept the contributor terms before you can edit." if user.terms_agreed.nil?
-
-      return -1, "One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1." unless tags_ok(tags)
-
-      tags = strip_non_xml_chars tags
-
-      id = id.to_i
-      visible = (visible.to_i == 1)
-      node = nil
-      new_node = nil
-      Node.transaction do
-        if id.positive?
-          begin
-            node = Node.find(id)
-          rescue ActiveRecord::RecordNotFound
-            return [-4, "node", id]
-          end
-
-          return -1, "Point #{id} has since become part of a way, so you cannot save it as a POI.", id, id, version unless visible || node.ways.empty?
-        end
-        # We always need a new node, based on the data that has been sent to us
-        new_node = Node.new
-
-        new_node.changeset_id = changeset_id
-        new_node.version = version
-        new_node.lat = lat
-        new_node.lon = lon
-        new_node.tags = tags
-        if id <= 0
-          # We're creating the node
-          new_node.create_with_history(user)
-        elsif visible
-          # We're updating the node
-          new_node.id = id
-          node.update_from(new_node, user)
-        else
-          # We're deleting the node
-          new_node.id = id
-          node.delete_with_history!(new_node, user)
-        end
-      end
-
-      if id <= 0
-        return [0, "", id, new_node.id, new_node.version]
-      else
-        return [0, "", id, node.id, node.version]
-      end
-    end
-  end
-
-  # Read POI from database
-  # (only called on revert: POIs are usually read by whichways).
-  #
-  # Returns array of id, long, lat, hash of tags, (current) version.
-
-  def getpoi(id, timestamp)
-    amf_handle_error("'getpoi' #{id}", "node", id) do
-      id = id.to_i
-      n = Node.where(:id => id).first
-      if n
-        v = n.version
-        n = OldNode.where("node_id = ? AND timestamp <= ?", id, timestamp).unredacted.order("timestamp DESC").first unless timestamp == ""
-      end
-
-      if n
-        return [0, "", id, n.lon, n.lat, n.tags, v]
-      else
-        return [-4, "node", id]
-      end
-    end
-  end
-
-  # Delete way and all constituent nodes.
-  # Params:
-  # * The user token
-  # * the changeset id
-  # * the id of the way to change
-  # * the version of the way that was downloaded
-  # * a hash of the id and versions of all the nodes that are in the way, if any
-  # of the nodes have been changed by someone else then, there is a problem!
-  # Returns 0 (success), unchanged way id, new way version, new node versions.
-
-  def deleteway(usertoken, changeset_id, way_id, way_version, deletednodes)
-    amf_handle_error("'deleteway' #{way_id}", "way", way_id) do
-      user = getuser(usertoken)
-      return -1, "You are not logged in, so the way could not be deleted." unless user
-      return -1, t("application.setup_user_auth.blocked") if user.blocks.active.exists?
-      return -1, "You must accept the contributor terms before you can edit." if user.terms_agreed.nil?
-
-      way_id = way_id.to_i
-      nodeversions = {}
-      old_way = nil # returned, so scope it outside the transaction
-      # Need a transaction so that if one item fails to delete, the whole delete fails.
-      Way.transaction do
-        # -- Delete the way
-
-        old_way = Way.find(way_id)
-        delete_way = Way.new
-        delete_way.version = way_version
-        delete_way.changeset_id = changeset_id
-        delete_way.id = way_id
-        old_way.delete_with_history!(delete_way, user)
-
-        # -- Delete unwanted nodes
-
-        deletednodes.each do |id, v|
-          node = Node.find(id.to_i)
-          new_node = Node.new
-          new_node.changeset_id = changeset_id
-          new_node.version = v.to_i
-          new_node.id = id.to_i
-          begin
-            node.delete_with_history!(new_node, user)
-            nodeversions[node.id] = node.version
-          rescue OSM::APIPreconditionFailedError
-            # We don't do anything with the exception as the node is in use
-            # elsewhere and we don't want to delete it
-          end
-        end
-      end
-      [0, "", way_id, old_way.version, nodeversions]
-    end
-  end
-
-  # ====================================================================
-  # Support functions
-
-  # Authenticate token
-  # (can also be of form user:pass)
-  # When we are writing to the api, we need the actual user model,
-  # not just the id, hence this abstraction
-
-  def getuser(token)
-    if token =~ /^(.+)\:(.+)$/
-      User.authenticate(:username => Regexp.last_match(1), :password => Regexp.last_match(2))
-    else
-      User.authenticate(:token => token)
-    end
-  end
-
-  def getlocales
-    @getlocales ||= Locale.list(Dir.glob(Rails.root.join("config", "potlatch", "locales", "*")).collect { |f| File.basename(f, ".yml") })
-  end
-
-  ##
-  # check that all key-value pairs are valid UTF-8.
-  def tags_ok(tags)
-    tags.each do |k, v|
-      return false unless UTF8.valid? k
-      return false unless UTF8.valid? v
-    end
-    true
-  end
-
-  ##
-  # strip characters which are invalid in XML documents from the strings
-  # in the +tags+ hash.
-  def strip_non_xml_chars(tags)
-    new_tags = {}
-    tags&.each do |k, v|
-      new_k = k.delete "\000-\037\ufffe\uffff", "^\011\012\015"
-      new_v = v.delete "\000-\037\ufffe\uffff", "^\011\012\015"
-      new_tags[new_k] = new_v
-    end
-    new_tags
-  end
-
-  # ====================================================================
-  # Alternative SQL queries for getway/whichways
-
-  def sql_find_ways_in_area(bbox)
-    sql = <<-SQL
-    SELECT DISTINCT current_ways.id AS wayid,current_ways.version AS version
-      FROM current_way_nodes
-    INNER JOIN current_nodes ON current_nodes.id=current_way_nodes.node_id
-    INNER JOIN current_ways  ON current_ways.id =current_way_nodes.id
-       WHERE current_nodes.visible=TRUE
-       AND current_ways.visible=TRUE
-       AND #{OSM.sql_for_area(bbox, 'current_nodes.')}
-    SQL
-    ActiveRecord::Base.connection.select_all(sql).collect { |a| [a["wayid"].to_i, a["version"].to_i] }
-  end
-
-  def sql_find_pois_in_area(bbox)
-    pois = []
-    sql = <<-SQL
-      SELECT current_nodes.id,current_nodes.latitude*0.0000001 AS lat,current_nodes.longitude*0.0000001 AS lon,current_nodes.version
-      FROM current_nodes
-       LEFT OUTER JOIN current_way_nodes cwn ON cwn.node_id=current_nodes.id
-       WHERE current_nodes.visible=TRUE
-       AND cwn.id IS NULL
-       AND #{OSM.sql_for_area(bbox, 'current_nodes.')}
-    SQL
-    ActiveRecord::Base.connection.select_all(sql).each do |row|
-      poitags = {}
-      ActiveRecord::Base.connection.select_all("SELECT k,v FROM current_node_tags WHERE id=#{row['id']}").each do |n|
-        poitags[n["k"]] = n["v"]
-      end
-      pois << [row["id"].to_i, row["lon"].to_f, row["lat"].to_f, poitags, row["version"].to_i]
-    end
-    pois
-  end
-
-  def sql_find_relations_in_area_and_ways(bbox, way_ids)
-    # ** It would be more Potlatchy to get relations for nodes within ways
-    #    during 'getway', not here
-    sql = <<-SQL
-      SELECT DISTINCT cr.id AS relid,cr.version AS version
-      FROM current_relations cr
-      INNER JOIN current_relation_members crm ON crm.id=cr.id
-      INNER JOIN current_nodes cn ON crm.member_id=cn.id AND crm.member_type='Node'
-       WHERE #{OSM.sql_for_area(bbox, 'cn.')}
-    SQL
-    unless way_ids.empty?
-      sql += <<-SQL
-       UNION
-        SELECT DISTINCT cr.id AS relid,cr.version AS version
-        FROM current_relations cr
-        INNER JOIN current_relation_members crm ON crm.id=cr.id
-         WHERE crm.member_type='Way'
-         AND crm.member_id IN (#{way_ids.join(',')})
-      SQL
-    end
-    ActiveRecord::Base.connection.select_all(sql).collect { |a| [a["relid"].to_i, a["version"].to_i] }
-  end
-
-  def sql_get_nodes_in_way(wayid)
-    points = []
-    sql = <<-SQL
-      SELECT latitude*0.0000001 AS lat,longitude*0.0000001 AS lon,current_nodes.id,current_nodes.version
-      FROM current_way_nodes,current_nodes
-       WHERE current_way_nodes.id=#{wayid.to_i}
-       AND current_way_nodes.node_id=current_nodes.id
-       AND current_nodes.visible=TRUE
-      ORDER BY sequence_id
-    SQL
-    ActiveRecord::Base.connection.select_all(sql).each do |row|
-      nodetags = {}
-      ActiveRecord::Base.connection.select_all("SELECT k,v FROM current_node_tags WHERE id=#{row['id']}").each do |n|
-        nodetags[n["k"]] = n["v"]
-      end
-      nodetags.delete("created_by")
-      points << [row["lon"].to_f, row["lat"].to_f, row["id"].to_i, nodetags, row["version"].to_i]
-    end
-    points
-  end
-
-  def sql_get_tags_in_way(wayid)
-    tags = {}
-    ActiveRecord::Base.connection.select_all("SELECT k,v FROM current_way_tags WHERE id=#{wayid.to_i}").each do |row|
-      tags[row["k"]] = row["v"]
-    end
-    tags
-  end
-
-  def sql_get_way_version(wayid)
-    ActiveRecord::Base.connection.select_one("SELECT version FROM current_ways WHERE id=#{wayid.to_i}")["version"]
-  end
-
-  def sql_get_way_user(wayid)
-    ActiveRecord::Base.connection.select_one("SELECT user FROM current_ways,changesets WHERE current_ways.id=#{wayid.to_i} AND current_ways.changeset=changesets.id")["user"]
-  end
-end
diff --git a/app/controllers/api/amf_controller.rb b/app/controllers/api/amf_controller.rb
new file mode 100644 (file)
index 0000000..2a878d2
--- /dev/null
@@ -0,0 +1,1002 @@
+# amf_controller is a semi-standalone API for Flash clients, particularly
+# Potlatch. All interaction between Potlatch (as a .SWF application) and the
+# OSM database takes place using this controller. Messages are
+# encoded in the Actionscript Message Format (AMF).
+#
+# Helper functions are in /lib/potlatch.rb
+#
+# Author::  editions Systeme D / Richard Fairhurst 2004-2008
+# Licence:: public domain.
+#
+# == General structure
+#
+# Apart from the amf_read and amf_write methods (which distribute the requests
+# from the AMF message), each method generally takes arguments in the order
+# they were sent by the Potlatch SWF. Do not assume typing has been preserved.
+# Methods all return an array to the SWF.
+#
+# == API 0.6
+#
+# Note that this requires a patched version of composite_primary_keys 1.1.0
+# (see http://groups.google.com/group/compositekeys/t/a00e7562b677e193)
+# if you are to run with POTLATCH_USE_SQL=false .
+#
+# == Debugging
+#
+# Any method that returns a status code (0 for ok) can also send:
+# return(-1,"message")        <-- just puts up a dialogue
+# return(-2,"message")        <-- also asks the user to e-mail me
+# return(-3,["type",v],id)    <-- version conflict
+# return(-4,"type",id)        <-- object not found
+# -5 indicates the method wasn't called (due to a previous error)
+#
+# To write to the Rails log, use logger.info("message").
+
+# Remaining issues:
+# * version conflict when POIs and ways are reverted
+
+module Api
+  class AmfController < ApplicationController
+    include Potlatch
+
+    skip_before_action :verify_authenticity_token
+    before_action :check_api_writable
+
+    # AMF Controller implements its own authentication and authorization checks
+    # completely independently of the rest of the codebase, so best just to let
+    # it keep doing its own thing.
+    skip_authorization_check
+
+    # Main AMF handlers: process the raw AMF string (using AMF library) and
+    # calls each action (private method) accordingly.
+
+    def amf_read
+      self.status = :ok
+      self.content_type = Mime[:amf]
+      self.response_body = Dispatcher.new(request.raw_post) do |message, *args|
+        logger.info("Executing AMF #{message}(#{args.join(',')})")
+
+        case message
+        when "getpresets" then        result = getpresets(*args)
+        when "whichways" then         result = whichways(*args)
+        when "whichways_deleted" then result = whichways_deleted(*args)
+        when "getway" then            result = getway(args[0].to_i)
+        when "getrelation" then       result = getrelation(args[0].to_i)
+        when "getway_old" then        result = getway_old(args[0].to_i, args[1])
+        when "getway_history" then    result = getway_history(args[0].to_i)
+        when "getnode_history" then   result = getnode_history(args[0].to_i)
+        when "findgpx" then           result = findgpx(*args)
+        when "findrelations" then     result = findrelations(*args)
+        when "getpoi" then            result = getpoi(*args)
+        end
+
+        result
+      end
+    end
+
+    def amf_write
+      renumberednodes = {}              # Shared across repeated putways
+      renumberedways = {}               # Shared across repeated putways
+      err = false                       # Abort batch on error
+
+      self.status = :ok
+      self.content_type = Mime[:amf]
+      self.response_body = Dispatcher.new(request.raw_post) do |message, *args|
+        logger.info("Executing AMF #{message}")
+
+        if err
+          result = [-5, nil]
+        else
+          case message
+          when "putway" then
+            orn = renumberednodes.dup
+            result = putway(renumberednodes, *args)
+            result[4] = renumberednodes.reject { |k, _v| orn.key?(k) }
+            renumberedways[result[2]] = result[3] if result[0].zero? && result[2] != result[3]
+          when "putrelation" then
+            result = putrelation(renumberednodes, renumberedways, *args)
+          when "deleteway" then
+            result = deleteway(*args)
+          when "putpoi" then
+            result = putpoi(*args)
+            renumberednodes[result[2]] = result[3] if result[0].zero? && result[2] != result[3]
+          when "startchangeset" then
+            result = startchangeset(*args)
+          end
+
+          err = true if result[0] == -3 # If a conflict is detected, don't execute any more writes
+        end
+
+        result
+      end
+    end
+
+    private
+
+    def amf_handle_error(call, rootobj, rootid)
+      yield
+    rescue OSM::APIAlreadyDeletedError => ex
+      [-4, ex.object, ex.object_id]
+    rescue OSM::APIVersionMismatchError => ex
+      [-3, [rootobj, rootid], [ex.type.downcase, ex.id, ex.latest]]
+    rescue OSM::APIUserChangesetMismatchError => ex
+      [-2, ex.to_s]
+    rescue OSM::APIBadBoundingBox => ex
+      [-2, "Sorry - I can't get the map for that area. The server said: #{ex}"]
+    rescue OSM::APIError => ex
+      [-1, ex.to_s]
+    rescue StandardError => ex
+      [-2, "An unusual error happened (in #{call}). The server said: #{ex}"]
+    end
+
+    def amf_handle_error_with_timeout(call, rootobj, rootid)
+      amf_handle_error(call, rootobj, rootid) do
+        OSM::Timer.timeout(API_TIMEOUT, OSM::APITimeoutError) do
+          yield
+        end
+      end
+    end
+
+    # Start new changeset
+    # Returns success_code,success_message,changeset id
+
+    def startchangeset(usertoken, cstags, closeid, closecomment, opennew)
+      amf_handle_error("'startchangeset'", nil, nil) do
+        user = getuser(usertoken)
+        return -1, "You are not logged in, so Potlatch can't write any changes to the database." unless user
+        return -1, t("application.setup_user_auth.blocked") if user.blocks.active.exists?
+        return -1, "You must accept the contributor terms before you can edit." if user.terms_agreed.nil?
+
+        if cstags
+          return -1, "One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1." unless tags_ok(cstags)
+
+          cstags = strip_non_xml_chars cstags
+        end
+
+        # close previous changeset and add comment
+        if closeid
+          cs = Changeset.find(closeid.to_i)
+          cs.set_closed_time_now
+          if cs.user_id != user.id
+            raise OSM::APIUserChangesetMismatchError
+          elsif closecomment.empty?
+            cs.save!
+          else
+            cs.tags["comment"] = closecomment
+            # in case closecomment has chars not allowed in xml
+            cs.tags = strip_non_xml_chars cs.tags
+            cs.save_with_tags!
+          end
+        end
+
+        # open a new changeset
+        if opennew.nonzero?
+          cs = Changeset.new
+          cs.tags = cstags
+          cs.user_id = user.id
+          unless closecomment.empty?
+            cs.tags["comment"] = closecomment
+            # in case closecomment has chars not allowed in xml
+            cs.tags = strip_non_xml_chars cs.tags
+          end
+          # smsm1 doesn't like the next two lines and thinks they need to be abstracted to the model more/better
+          cs.created_at = Time.now.getutc
+          cs.closed_at = cs.created_at + Changeset::IDLE_TIMEOUT
+          cs.save_with_tags!
+          return [0, "", cs.id]
+        else
+          return [0, "", nil]
+        end
+      end
+    end
+
+    # Return presets (default tags, localisation etc.):
+    # uses POTLATCH_PRESETS global, set up in OSM::Potlatch.
+
+    def getpresets(usertoken, _lang)
+      user = getuser(usertoken)
+
+      langs = if user && !user.languages.empty?
+                Locale.list(user.languages)
+              else
+                Locale.list(http_accept_language.user_preferred_languages)
+              end
+
+      lang = getlocales.preferred(langs)
+      (real_lang, localised) = getlocalized(lang.to_s)
+
+      # Tell Potlatch what language it's using
+      localised["__potlatch_locale"] = real_lang
+
+      # Get help from i18n but delete it so we won't pass it around
+      # twice for nothing
+      help = localised["help_html"]
+      localised.delete("help_html")
+
+      # Populate icon names
+      POTLATCH_PRESETS[10].each do |id|
+        POTLATCH_PRESETS[11][id] = localised["preset_icon_#{id}"]
+        localised.delete("preset_icon_#{id}")
+      end
+
+      POTLATCH_PRESETS + [localised, help]
+    end
+
+    def getlocalized(lang)
+      # What we end up actually using. Reported in Potlatch's created_by=* string
+      loaded_lang = "en"
+
+      # Load English defaults
+      en = YAML.safe_load(File.open(Rails.root.join("config", "potlatch", "locales", "en.yml")))["en"]
+
+      if lang == "en"
+        return [loaded_lang, en]
+      else
+        # Use English as a fallback
+        begin
+          other = YAML.safe_load(File.open(Rails.root.join("config", "potlatch", "locales", "#{lang}.yml")))[lang]
+          loaded_lang = lang
+        rescue StandardError
+          other = en
+        end
+
+        # We have to return a flat list and some of the keys won't be
+        # translated (probably)
+        return [loaded_lang, en.merge(other)]
+      end
+    end
+
+    ##
+    # Find all the ways, POI nodes (i.e. not part of ways), and relations
+    # in a given bounding box. Nodes are returned in full; ways and relations
+    # are IDs only.
+    #
+    # return is of the form:
+    # [success_code, success_message,
+    #  [[way_id, way_version], ...],
+    #  [[node_id, lat, lon, [tags, ...], node_version], ...],
+    #  [[rel_id, rel_version], ...]]
+    # where the ways are any visible ways which refer to any visible
+    # nodes in the bbox, nodes are any visible nodes in the bbox but not
+    # used in any way, rel is any relation which refers to either a way
+    # or node that we're returning.
+    def whichways(xmin, ymin, xmax, ymax)
+      amf_handle_error_with_timeout("'whichways'", nil, nil) do
+        enlarge = [(xmax - xmin) / 8, 0.01].min
+        xmin -= enlarge
+        ymin -= enlarge
+        xmax += enlarge
+        ymax += enlarge
+
+        # check boundary is sane and area within defined
+        # see /config/application.yml
+        bbox = BoundingBox.new(xmin, ymin, xmax, ymax)
+        bbox.check_boundaries
+        bbox.check_size
+
+        if POTLATCH_USE_SQL
+          ways = sql_find_ways_in_area(bbox)
+          points = sql_find_pois_in_area(bbox)
+          relations = sql_find_relations_in_area_and_ways(bbox, ways.collect { |x| x[0] })
+        else
+          # find the way ids in an area
+          nodes_in_area = Node.bbox(bbox).visible.includes(:ways)
+          ways = nodes_in_area.inject([]) do |sum, node|
+            visible_ways = node.ways.select(&:visible?)
+            sum + visible_ways.collect { |w| [w.id, w.version] }
+          end.uniq
+          ways.delete([])
+
+          # find the node ids in an area that aren't part of ways
+          nodes_not_used_in_area = nodes_in_area.select { |node| node.ways.empty? }
+          points = nodes_not_used_in_area.collect { |n| [n.id, n.lon, n.lat, n.tags, n.version] }.uniq
+
+          # find the relations used by those nodes and ways
+          relations = Relation.nodes(nodes_in_area.collect(&:id)).visible +
+                      Relation.ways(ways.collect { |w| w[0] }).visible
+          relations = relations.collect { |relation| [relation.id, relation.version] }.uniq
+        end
+
+        [0, "", ways, points, relations]
+      end
+    end
+
+    # Find deleted ways in current bounding box (similar to whichways, but ways
+    # with a deleted node only - not POIs or relations).
+
+    def whichways_deleted(xmin, ymin, xmax, ymax)
+      amf_handle_error_with_timeout("'whichways_deleted'", nil, nil) do
+        enlarge = [(xmax - xmin) / 8, 0.01].min
+        xmin -= enlarge
+        ymin -= enlarge
+        xmax += enlarge
+        ymax += enlarge
+
+        # check boundary is sane and area within defined
+        # see /config/application.yml
+        bbox = BoundingBox.new(xmin, ymin, xmax, ymax)
+        bbox.check_boundaries
+        bbox.check_size
+
+        nodes_in_area = Node.bbox(bbox).joins(:ways_via_history).where(:current_ways => { :visible => false })
+        way_ids = nodes_in_area.collect { |node| node.ways_via_history.invisible.collect(&:id) }.flatten.uniq
+
+        [0, "", way_ids]
+      end
+    end
+
+    # Get a way including nodes and tags.
+    # Returns the way id, a Potlatch-style array of points, a hash of tags, the version number, and the user ID.
+
+    def getway(wayid)
+      amf_handle_error_with_timeout("'getway' #{wayid}", "way", wayid) do
+        if POTLATCH_USE_SQL
+          points = sql_get_nodes_in_way(wayid)
+          tags = sql_get_tags_in_way(wayid)
+          version = sql_get_way_version(wayid)
+          uid = sql_get_way_user(wayid)
+        else
+          # Ideally we would do ":include => :nodes" here but if we do that
+          # then rails only seems to return the first copy of a node when a
+          # way includes a node more than once
+          way = Way.where(:id => wayid).first
+
+          # check case where way has been deleted or doesn't exist
+          return [-4, "way", wayid] if way.nil? || !way.visible
+
+          points = way.nodes.preload(:node_tags).collect do |node|
+            nodetags = node.tags
+            nodetags.delete("created_by")
+            [node.lon, node.lat, node.id, nodetags, node.version]
+          end
+          tags = way.tags
+          version = way.version
+          uid = way.changeset.user.id
+        end
+
+        [0, "", wayid, points, tags, version, uid]
+      end
+    end
+
+    # Get an old version of a way, and all constituent nodes.
+    #
+    # For undelete (version<0), always uses the most recent version of each node,
+    # even if it's moved.  For revert (version >= 0), uses the node in existence
+    # at the time, generating a new id if it's still visible and has been moved/
+    # retagged.
+    #
+    # Returns:
+    # 0. success code,
+    # 1. id,
+    # 2. array of points,
+    # 3. hash of tags,
+    # 4. version,
+    # 5. is this the current, visible version? (boolean)
+
+    def getway_old(id, timestamp)
+      amf_handle_error_with_timeout("'getway_old' #{id}, #{timestamp}", "way", id) do
+        if timestamp == ""
+          # undelete
+          old_way = OldWay.where(:visible => true, :way_id => id).unredacted.order("version DESC").first
+          points = old_way.get_nodes_undelete unless old_way.nil?
+        else
+          begin
+            # revert
+            timestamp = Time.zone.strptime(timestamp.to_s, "%d %b %Y, %H:%M:%S")
+            old_way = OldWay.where("way_id = ? AND timestamp <= ?", id, timestamp).unredacted.order("timestamp DESC").first
+            unless old_way.nil?
+              if old_way.visible
+                points = old_way.get_nodes_revert(timestamp)
+              else
+                return [-1, "Sorry, the way was deleted at that time - please revert to a previous version.", id]
+              end
+            end
+          rescue ArgumentError
+            # thrown by date parsing method. leave old_way as nil for
+            # the error handler below.
+            old_way = nil
+          end
+        end
+
+        if old_way.nil?
+          return [-1, "Sorry, the server could not find a way at that time.", id]
+        else
+          curway = Way.find(id)
+          old_way.tags["history"] = "Retrieved from v#{old_way.version}"
+          return [0, "", id, points, old_way.tags, curway.version, (curway.version == old_way.version && curway.visible)]
+        end
+      end
+    end
+
+    # Find history of a way.
+    # Returns 'way', id, and an array of previous versions:
+    # - formerly [old_way.version, old_way.timestamp.strftime("%d %b %Y, %H:%M"), old_way.visible ? 1 : 0, user, uid]
+    # - now [timestamp,user,uid]
+    #
+    # Heuristic: Find all nodes that have ever been part of the way;
+    # get a list of their revision dates; add revision dates of the way;
+    # sort and collapse list (to within 2 seconds); trim all dates before the
+    # start date of the way.
+
+    def getway_history(wayid)
+      revdates = []
+      revusers = {}
+      Way.find(wayid).old_ways.unredacted.collect do |a|
+        revdates.push(a.timestamp)
+        revusers[a.timestamp.to_i] = change_user(a) unless revusers.key?(a.timestamp.to_i)
+        a.nds.each do |n|
+          Node.find(n).old_nodes.unredacted.collect do |o|
+            revdates.push(o.timestamp)
+            revusers[o.timestamp.to_i] = change_user(o) unless revusers.key?(o.timestamp.to_i)
+          end
+        end
+      end
+      waycreated = revdates[0]
+      revdates.uniq!
+      revdates.sort!
+      revdates.reverse!
+
+      # Remove any dates (from nodes) before first revision date of way
+      revdates.delete_if { |d| d < waycreated }
+      # Remove any elements where 2 seconds doesn't elapse before next one
+      revdates.delete_if { |d| revdates.include?(d + 1) || revdates.include?(d + 2) }
+      # Collect all in one nested array
+      revdates.collect! { |d| [(d + 1).strftime("%d %b %Y, %H:%M:%S")] + revusers[d.to_i] }
+      revdates.uniq!
+
+      ["way", wayid, revdates]
+    rescue ActiveRecord::RecordNotFound
+      ["way", wayid, []]
+    end
+
+    # Find history of a node. Returns 'node', id, and an array of previous versions as above.
+
+    def getnode_history(nodeid)
+      history = Node.find(nodeid).old_nodes.unredacted.reverse.collect do |old_node|
+        [(old_node.timestamp + 1).strftime("%d %b %Y, %H:%M:%S")] + change_user(old_node)
+      end
+      ["node", nodeid, history]
+    rescue ActiveRecord::RecordNotFound
+      ["node", nodeid, []]
+    end
+
+    def change_user(obj)
+      user_object = obj.changeset.user
+      user = user_object.data_public? ? user_object.display_name : "anonymous"
+      uid  = user_object.data_public? ? user_object.id : 0
+      [user, uid]
+    end
+
+    # Find GPS traces with specified name/id.
+    # Returns array listing GPXs, each one comprising id, name and description.
+
+    def findgpx(searchterm, usertoken)
+      amf_handle_error_with_timeout("'findgpx'", nil, nil) do
+        user = getuser(usertoken)
+
+        return -1, "You must be logged in to search for GPX traces." unless user
+        return -1, t("application.setup_user_auth.blocked") if user.blocks.active.exists?
+
+        query = Trace.visible_to(user)
+        query = if searchterm.to_i.positive?
+                  query.where(:id => searchterm.to_i)
+                else
+                  query.where("MATCH(name) AGAINST (?)", searchterm).limit(21)
+                end
+        gpxs = query.collect do |gpx|
+          [gpx.id, gpx.name, gpx.description]
+        end
+        [0, "", gpxs]
+      end
+    end
+
+    # Get a relation with all tags and members.
+    # Returns:
+    # 0. success code?
+    # 1. object type?
+    # 2. relation id,
+    # 3. hash of tags,
+    # 4. list of members,
+    # 5. version.
+
+    def getrelation(relid)
+      amf_handle_error("'getrelation' #{relid}", "relation", relid) do
+        rel = Relation.where(:id => relid).first
+
+        return [-4, "relation", relid] if rel.nil? || !rel.visible
+
+        [0, "", relid, rel.tags, rel.members, rel.version]
+      end
+    end
+
+    # Find relations with specified name/id.
+    # Returns array of relations, each in same form as getrelation.
+
+    def findrelations(searchterm)
+      rels = []
+      if searchterm.to_i.positive?
+        rel = Relation.where(:id => searchterm.to_i).first
+        rels.push([rel.id, rel.tags, rel.members, rel.version]) if rel&.visible
+      else
+        RelationTag.where("v like ?", "%#{searchterm}%").limit(11).each do |t|
+          rels.push([t.relation.id, t.relation.tags, t.relation.members, t.relation.version]) if t.relation.visible
+        end
+      end
+      rels
+    end
+
+    # Save a relation.
+    # Returns
+    # 0. 0 (success),
+    # 1. original relation id (unchanged),
+    # 2. new relation id,
+    # 3. version.
+
+    def putrelation(renumberednodes, renumberedways, usertoken, changeset_id, version, relid, tags, members, visible)
+      amf_handle_error("'putrelation' #{relid}", "relation", relid) do
+        user = getuser(usertoken)
+
+        return -1, "You are not logged in, so the relation could not be saved." unless user
+        return -1, t("application.setup_user_auth.blocked") if user.blocks.active.exists?
+        return -1, "You must accept the contributor terms before you can edit." if user.terms_agreed.nil?
+
+        return -1, "One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1." unless tags_ok(tags)
+
+        tags = strip_non_xml_chars tags
+
+        relid = relid.to_i
+        visible = visible.to_i.nonzero?
+
+        new_relation = nil
+        relation = nil
+        Relation.transaction do
+          # create a new relation, or find the existing one
+          relation = Relation.find(relid) if relid.positive?
+          # We always need a new node, based on the data that has been sent to us
+          new_relation = Relation.new
+
+          # check the members are all positive, and correctly type
+          typedmembers = []
+          members.each do |m|
+            mid = m[1].to_i
+            if mid.negative?
+              mid = renumberednodes[mid] if m[0] == "Node"
+              mid = renumberedways[mid] if m[0] == "Way"
+            end
+            typedmembers << [m[0], mid, m[2].delete("\000-\037\ufffe\uffff", "^\011\012\015")] if mid
+          end
+
+          # assign new contents
+          new_relation.members = typedmembers
+          new_relation.tags = tags
+          new_relation.visible = visible
+          new_relation.changeset_id = changeset_id
+          new_relation.version = version
+
+          if relid <= 0
+            # We're creating the relation
+            new_relation.create_with_history(user)
+          elsif visible
+            # We're updating the relation
+            new_relation.id = relid
+            relation.update_from(new_relation, user)
+          else
+            # We're deleting the relation
+            new_relation.id = relid
+            relation.delete_with_history!(new_relation, user)
+          end
+        end
+
+        if relid <= 0
+          return [0, "", relid, new_relation.id, new_relation.version]
+        else
+          return [0, "", relid, relid, relation.version]
+        end
+      end
+    end
+
+    # Save a way to the database, including all nodes. Any nodes in the previous
+    # version and no longer used are deleted.
+    #
+    # Parameters:
+    # 0. hash of renumbered nodes (added by amf_controller)
+    # 1. current user token (for authentication)
+    # 2. current changeset
+    # 3. new way version
+    # 4. way ID
+    # 5. list of nodes in way
+    # 6. hash of way tags
+    # 7. array of nodes to change (each one is [lon,lat,id,version,tags]),
+    # 8. hash of nodes to delete (id->version).
+    #
+    # Returns:
+    # 0. '0' (code for success),
+    # 1. message,
+    # 2. original way id (unchanged),
+    # 3. new way id,
+    # 4. hash of renumbered nodes (old id=>new id),
+    # 5. way version,
+    # 6. hash of changed node versions (node=>version)
+    # 7. hash of deleted node versions (node=>version)
+
+    def putway(renumberednodes, usertoken, changeset_id, wayversion, originalway, pointlist, attributes, nodes, deletednodes)
+      amf_handle_error("'putway' #{originalway}", "way", originalway) do
+        # -- Initialise
+
+        user = getuser(usertoken)
+        return -1, "You are not logged in, so the way could not be saved." unless user
+        return -1, t("application.setup_user_auth.blocked") if user.blocks.active.exists?
+        return -1, "You must accept the contributor terms before you can edit." if user.terms_agreed.nil?
+
+        return -2, "Server error - way is only #{pointlist.length} points long." if pointlist.length < 2
+
+        return -1, "One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1." unless tags_ok(attributes)
+
+        attributes = strip_non_xml_chars attributes
+
+        originalway = originalway.to_i
+        pointlist.collect!(&:to_i)
+
+        way = nil # this is returned, so scope it outside the transaction
+        nodeversions = {}
+        Way.transaction do
+          # -- Update each changed node
+
+          nodes.each do |a|
+            lon = a[0].to_f
+            lat = a[1].to_f
+            id = a[2].to_i
+            version = a[3].to_i
+
+            return -2, "Server error - node with id 0 found in way #{originalway}." if id.zero?
+            return -2, "Server error - node with latitude -90 found in way #{originalway}." if lat == 90
+
+            id = renumberednodes[id] if renumberednodes[id]
+
+            node = Node.new
+            node.changeset_id = changeset_id
+            node.lat = lat
+            node.lon = lon
+            node.tags = a[4]
+
+            # fixup node tags in a way as well
+            return -1, "One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1." unless tags_ok(node.tags)
+
+            node.tags = strip_non_xml_chars node.tags
+
+            node.tags.delete("created_by")
+            node.version = version
+            if id <= 0
+              # We're creating the node
+              node.create_with_history(user)
+              renumberednodes[id] = node.id
+              nodeversions[node.id] = node.version
+            else
+              # We're updating an existing node
+              previous = Node.find(id)
+              node.id = id
+              previous.update_from(node, user)
+              nodeversions[previous.id] = previous.version
+            end
+          end
+
+          # -- Save revised way
+
+          pointlist.collect! do |a|
+            renumberednodes[a] || a
+          end
+          new_way = Way.new
+          new_way.tags = attributes
+          new_way.nds = pointlist
+          new_way.changeset_id = changeset_id
+          new_way.version = wayversion
+          if originalway <= 0
+            new_way.create_with_history(user)
+            way = new_way # so we can get way.id and way.version
+          else
+            way = Way.find(originalway)
+            if way.tags != attributes || way.nds != pointlist || !way.visible?
+              new_way.id = originalway
+              way.update_from(new_way, user)
+            end
+          end
+
+          # -- Delete unwanted nodes
+
+          deletednodes.each do |id, v|
+            node = Node.find(id.to_i)
+            new_node = Node.new
+            new_node.changeset_id = changeset_id
+            new_node.version = v.to_i
+            new_node.id = id.to_i
+            begin
+              node.delete_with_history!(new_node, user)
+            rescue OSM::APIPreconditionFailedError
+              # We don't do anything here as the node is being used elsewhere
+              # and we don't want to delete it
+            end
+          end
+        end
+
+        [0, "", originalway, way.id, renumberednodes, way.version, nodeversions, deletednodes]
+      end
+    end
+
+    # Save POI to the database.
+    # Refuses save if the node has since become part of a way.
+    # Returns array with:
+    # 0. 0 (success),
+    # 1. success message,
+    # 2. original node id (unchanged),
+    # 3. new node id,
+    # 4. version.
+
+    def putpoi(usertoken, changeset_id, version, id, lon, lat, tags, visible)
+      amf_handle_error("'putpoi' #{id}", "node", id) do
+        user = getuser(usertoken)
+        return -1, "You are not logged in, so the point could not be saved." unless user
+        return -1, t("application.setup_user_auth.blocked") if user.blocks.active.exists?
+        return -1, "You must accept the contributor terms before you can edit." if user.terms_agreed.nil?
+
+        return -1, "One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1." unless tags_ok(tags)
+
+        tags = strip_non_xml_chars tags
+
+        id = id.to_i
+        visible = (visible.to_i == 1)
+        node = nil
+        new_node = nil
+        Node.transaction do
+          if id.positive?
+            begin
+              node = Node.find(id)
+            rescue ActiveRecord::RecordNotFound
+              return [-4, "node", id]
+            end
+
+            return -1, "Point #{id} has since become part of a way, so you cannot save it as a POI.", id, id, version unless visible || node.ways.empty?
+          end
+          # We always need a new node, based on the data that has been sent to us
+          new_node = Node.new
+
+          new_node.changeset_id = changeset_id
+          new_node.version = version
+          new_node.lat = lat
+          new_node.lon = lon
+          new_node.tags = tags
+          if id <= 0
+            # We're creating the node
+            new_node.create_with_history(user)
+          elsif visible
+            # We're updating the node
+            new_node.id = id
+            node.update_from(new_node, user)
+          else
+            # We're deleting the node
+            new_node.id = id
+            node.delete_with_history!(new_node, user)
+          end
+        end
+
+        if id <= 0
+          return [0, "", id, new_node.id, new_node.version]
+        else
+          return [0, "", id, node.id, node.version]
+        end
+      end
+    end
+
+    # Read POI from database
+    # (only called on revert: POIs are usually read by whichways).
+    #
+    # Returns array of id, long, lat, hash of tags, (current) version.
+
+    def getpoi(id, timestamp)
+      amf_handle_error("'getpoi' #{id}", "node", id) do
+        id = id.to_i
+        n = Node.where(:id => id).first
+        if n
+          v = n.version
+          n = OldNode.where("node_id = ? AND timestamp <= ?", id, timestamp).unredacted.order("timestamp DESC").first unless timestamp == ""
+        end
+
+        if n
+          return [0, "", id, n.lon, n.lat, n.tags, v]
+        else
+          return [-4, "node", id]
+        end
+      end
+    end
+
+    # Delete way and all constituent nodes.
+    # Params:
+    # * The user token
+    # * the changeset id
+    # * the id of the way to change
+    # * the version of the way that was downloaded
+    # * a hash of the id and versions of all the nodes that are in the way, if any
+    # of the nodes have been changed by someone else then, there is a problem!
+    # Returns 0 (success), unchanged way id, new way version, new node versions.
+
+    def deleteway(usertoken, changeset_id, way_id, way_version, deletednodes)
+      amf_handle_error("'deleteway' #{way_id}", "way", way_id) do
+        user = getuser(usertoken)
+        return -1, "You are not logged in, so the way could not be deleted." unless user
+        return -1, t("application.setup_user_auth.blocked") if user.blocks.active.exists?
+        return -1, "You must accept the contributor terms before you can edit." if user.terms_agreed.nil?
+
+        way_id = way_id.to_i
+        nodeversions = {}
+        old_way = nil # returned, so scope it outside the transaction
+        # Need a transaction so that if one item fails to delete, the whole delete fails.
+        Way.transaction do
+          # -- Delete the way
+
+          old_way = Way.find(way_id)
+          delete_way = Way.new
+          delete_way.version = way_version
+          delete_way.changeset_id = changeset_id
+          delete_way.id = way_id
+          old_way.delete_with_history!(delete_way, user)
+
+          # -- Delete unwanted nodes
+
+          deletednodes.each do |id, v|
+            node = Node.find(id.to_i)
+            new_node = Node.new
+            new_node.changeset_id = changeset_id
+            new_node.version = v.to_i
+            new_node.id = id.to_i
+            begin
+              node.delete_with_history!(new_node, user)
+              nodeversions[node.id] = node.version
+            rescue OSM::APIPreconditionFailedError
+              # We don't do anything with the exception as the node is in use
+              # elsewhere and we don't want to delete it
+            end
+          end
+        end
+        [0, "", way_id, old_way.version, nodeversions]
+      end
+    end
+
+    # ====================================================================
+    # Support functions
+
+    # Authenticate token
+    # (can also be of form user:pass)
+    # When we are writing to the api, we need the actual user model,
+    # not just the id, hence this abstraction
+
+    def getuser(token)
+      if token =~ /^(.+)\:(.+)$/
+        User.authenticate(:username => Regexp.last_match(1), :password => Regexp.last_match(2))
+      else
+        User.authenticate(:token => token)
+      end
+    end
+
+    def getlocales
+      @getlocales ||= Locale.list(Dir.glob(Rails.root.join("config", "potlatch", "locales", "*")).collect { |f| File.basename(f, ".yml") })
+    end
+
+    ##
+    # check that all key-value pairs are valid UTF-8.
+    def tags_ok(tags)
+      tags.each do |k, v|
+        return false unless UTF8.valid? k
+        return false unless UTF8.valid? v
+      end
+      true
+    end
+
+    ##
+    # strip characters which are invalid in XML documents from the strings
+    # in the +tags+ hash.
+    def strip_non_xml_chars(tags)
+      new_tags = {}
+      tags&.each do |k, v|
+        new_k = k.delete "\000-\037\ufffe\uffff", "^\011\012\015"
+        new_v = v.delete "\000-\037\ufffe\uffff", "^\011\012\015"
+        new_tags[new_k] = new_v
+      end
+      new_tags
+    end
+
+    # ====================================================================
+    # Alternative SQL queries for getway/whichways
+
+    def sql_find_ways_in_area(bbox)
+      sql = <<-SQL
+      SELECT DISTINCT current_ways.id AS wayid,current_ways.version AS version
+        FROM current_way_nodes
+      INNER JOIN current_nodes ON current_nodes.id=current_way_nodes.node_id
+      INNER JOIN current_ways  ON current_ways.id =current_way_nodes.id
+         WHERE current_nodes.visible=TRUE
+         AND current_ways.visible=TRUE
+         AND #{OSM.sql_for_area(bbox, 'current_nodes.')}
+      SQL
+      ActiveRecord::Base.connection.select_all(sql).collect { |a| [a["wayid"].to_i, a["version"].to_i] }
+    end
+
+    def sql_find_pois_in_area(bbox)
+      pois = []
+      sql = <<-SQL
+        SELECT current_nodes.id,current_nodes.latitude*0.0000001 AS lat,current_nodes.longitude*0.0000001 AS lon,current_nodes.version
+        FROM current_nodes
+         LEFT OUTER JOIN current_way_nodes cwn ON cwn.node_id=current_nodes.id
+         WHERE current_nodes.visible=TRUE
+         AND cwn.id IS NULL
+         AND #{OSM.sql_for_area(bbox, 'current_nodes.')}
+      SQL
+      ActiveRecord::Base.connection.select_all(sql).each do |row|
+        poitags = {}
+        ActiveRecord::Base.connection.select_all("SELECT k,v FROM current_node_tags WHERE id=#{row['id']}").each do |n|
+          poitags[n["k"]] = n["v"]
+        end
+        pois << [row["id"].to_i, row["lon"].to_f, row["lat"].to_f, poitags, row["version"].to_i]
+      end
+      pois
+    end
+
+    def sql_find_relations_in_area_and_ways(bbox, way_ids)
+      # ** It would be more Potlatchy to get relations for nodes within ways
+      #    during 'getway', not here
+      sql = <<-SQL
+        SELECT DISTINCT cr.id AS relid,cr.version AS version
+        FROM current_relations cr
+        INNER JOIN current_relation_members crm ON crm.id=cr.id
+        INNER JOIN current_nodes cn ON crm.member_id=cn.id AND crm.member_type='Node'
+         WHERE #{OSM.sql_for_area(bbox, 'cn.')}
+      SQL
+      unless way_ids.empty?
+        sql += <<-SQL
+         UNION
+          SELECT DISTINCT cr.id AS relid,cr.version AS version
+          FROM current_relations cr
+          INNER JOIN current_relation_members crm ON crm.id=cr.id
+           WHERE crm.member_type='Way'
+           AND crm.member_id IN (#{way_ids.join(',')})
+        SQL
+      end
+      ActiveRecord::Base.connection.select_all(sql).collect { |a| [a["relid"].to_i, a["version"].to_i] }
+    end
+
+    def sql_get_nodes_in_way(wayid)
+      points = []
+      sql = <<-SQL
+        SELECT latitude*0.0000001 AS lat,longitude*0.0000001 AS lon,current_nodes.id,current_nodes.version
+        FROM current_way_nodes,current_nodes
+         WHERE current_way_nodes.id=#{wayid.to_i}
+         AND current_way_nodes.node_id=current_nodes.id
+         AND current_nodes.visible=TRUE
+        ORDER BY sequence_id
+      SQL
+      ActiveRecord::Base.connection.select_all(sql).each do |row|
+        nodetags = {}
+        ActiveRecord::Base.connection.select_all("SELECT k,v FROM current_node_tags WHERE id=#{row['id']}").each do |n|
+          nodetags[n["k"]] = n["v"]
+        end
+        nodetags.delete("created_by")
+        points << [row["lon"].to_f, row["lat"].to_f, row["id"].to_i, nodetags, row["version"].to_i]
+      end
+      points
+    end
+
+    def sql_get_tags_in_way(wayid)
+      tags = {}
+      ActiveRecord::Base.connection.select_all("SELECT k,v FROM current_way_tags WHERE id=#{wayid.to_i}").each do |row|
+        tags[row["k"]] = row["v"]
+      end
+      tags
+    end
+
+    def sql_get_way_version(wayid)
+      ActiveRecord::Base.connection.select_one("SELECT version FROM current_ways WHERE id=#{wayid.to_i}")["version"]
+    end
+
+    def sql_get_way_user(wayid)
+      ActiveRecord::Base.connection.select_one("SELECT user FROM current_ways,changesets WHERE current_ways.id=#{wayid.to_i} AND current_ways.changeset=changesets.id")["user"]
+    end
+  end
+end
diff --git a/app/controllers/api/changeset_comments_controller.rb b/app/controllers/api/changeset_comments_controller.rb
new file mode 100644 (file)
index 0000000..6093f52
--- /dev/null
@@ -0,0 +1,85 @@
+module Api
+  class ChangesetCommentsController < ApplicationController
+    skip_before_action :verify_authenticity_token
+    before_action :authorize
+    before_action :api_deny_access_handler
+
+    authorize_resource
+
+    before_action :require_public_data, :only => [:create]
+    before_action :check_api_writable
+    before_action :check_api_readable, :except => [:create]
+    around_action :api_call_handle_error
+    around_action :api_call_timeout
+
+    ##
+    # Add a comment to a changeset
+    def create
+      # Check the arguments are sane
+      raise OSM::APIBadUserInput, "No id was given" unless params[:id]
+      raise OSM::APIBadUserInput, "No text was given" if params[:text].blank?
+
+      # Extract the arguments
+      id = params[:id].to_i
+      body = params[:text]
+
+      # Find the changeset and check it is valid
+      changeset = Changeset.find(id)
+      raise OSM::APIChangesetNotYetClosedError, changeset if changeset.is_open?
+
+      # Add a comment to the changeset
+      comment = changeset.comments.create(:changeset => changeset,
+                                          :body => body,
+                                          :author => current_user)
+
+      # Notify current subscribers of the new comment
+      changeset.subscribers.visible.each do |user|
+        Notifier.changeset_comment_notification(comment, user).deliver_later if current_user != user
+      end
+
+      # Add the commenter to the subscribers if necessary
+      changeset.subscribers << current_user unless changeset.subscribers.exists?(current_user.id)
+
+      # Return a copy of the updated changeset
+      render :xml => changeset.to_xml.to_s
+    end
+
+    ##
+    # Sets visible flag on comment to false
+    def destroy
+      # Check the arguments are sane
+      raise OSM::APIBadUserInput, "No id was given" unless params[:id]
+
+      # Extract the arguments
+      id = params[:id].to_i
+
+      # Find the changeset
+      comment = ChangesetComment.find(id)
+
+      # Hide the comment
+      comment.update(:visible => false)
+
+      # Return a copy of the updated changeset
+      render :xml => comment.changeset.to_xml.to_s
+    end
+
+    ##
+    # Sets visible flag on comment to true
+    def restore
+      # Check the arguments are sane
+      raise OSM::APIBadUserInput, "No id was given" unless params[:id]
+
+      # Extract the arguments
+      id = params[:id].to_i
+
+      # Find the changeset
+      comment = ChangesetComment.find(id)
+
+      # Unhide the comment
+      comment.update(:visible => true)
+
+      # Return a copy of the updated changeset
+      render :xml => comment.changeset.to_xml.to_s
+    end
+  end
+end
diff --git a/app/controllers/api/changesets_controller.rb b/app/controllers/api/changesets_controller.rb
new file mode 100644 (file)
index 0000000..853ee38
--- /dev/null
@@ -0,0 +1,422 @@
+# The ChangesetController is the RESTful interface to Changeset objects
+
+module Api
+  class ChangesetsController < ApplicationController
+    layout "site"
+    require "xml/libxml"
+
+    skip_before_action :verify_authenticity_token
+    before_action :authorize, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe]
+    before_action :api_deny_access_handler, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe, :expand_bbox]
+
+    authorize_resource
+
+    before_action :require_public_data, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe]
+    before_action :check_api_writable, :only => [:create, :update, :upload, :subscribe, :unsubscribe]
+    before_action :check_api_readable, :except => [:create, :update, :upload, :download, :query, :subscribe, :unsubscribe]
+    before_action(:only => [:index, :feed]) { |c| c.check_database_readable(true) }
+    around_action :api_call_handle_error
+    around_action :api_call_timeout, :except => [:upload]
+
+    # Helper methods for checking consistency
+    include ConsistencyValidations
+
+    # Create a changeset from XML.
+    def create
+      assert_method :put
+
+      cs = Changeset.from_xml(request.raw_post, true)
+
+      # Assume that Changeset.from_xml has thrown an exception if there is an error parsing the xml
+      cs.user = current_user
+      cs.save_with_tags!
+
+      # Subscribe user to changeset comments
+      cs.subscribers << current_user
+
+      render :plain => cs.id.to_s
+    end
+
+    ##
+    # Return XML giving the basic info about the changeset. Does not
+    # return anything about the nodes, ways and relations in the changeset.
+    def show
+      changeset = Changeset.find(params[:id])
+
+      render :xml => changeset.to_xml(params[:include_discussion].presence).to_s
+    end
+
+    ##
+    # marks a changeset as closed. this may be called multiple times
+    # on the same changeset, so is idempotent.
+    def close
+      assert_method :put
+
+      changeset = Changeset.find(params[:id])
+      check_changeset_consistency(changeset, current_user)
+
+      # to close the changeset, we'll just set its closed_at time to
+      # now. this might not be enough if there are concurrency issues,
+      # but we'll have to wait and see.
+      changeset.set_closed_time_now
+
+      changeset.save!
+      head :ok
+    end
+
+    ##
+    # insert a (set of) points into a changeset bounding box. this can only
+    # increase the size of the bounding box. this is a hint that clients can
+    # set either before uploading a large number of changes, or changes that
+    # the client (but not the server) knows will affect areas further away.
+    def expand_bbox
+      # only allow POST requests, because although this method is
+      # idempotent, there is no "document" to PUT really...
+      assert_method :post
+
+      cs = Changeset.find(params[:id])
+      check_changeset_consistency(cs, current_user)
+
+      # keep an array of lons and lats
+      lon = []
+      lat = []
+
+      # the request is in pseudo-osm format... this is kind-of an
+      # abuse, maybe should change to some other format?
+      doc = XML::Parser.string(request.raw_post, :options => XML::Parser::Options::NOERROR).parse
+      doc.find("//osm/node").each do |n|
+        lon << n["lon"].to_f * GeoRecord::SCALE
+        lat << n["lat"].to_f * GeoRecord::SCALE
+      end
+
+      # add the existing bounding box to the lon-lat array
+      lon << cs.min_lon unless cs.min_lon.nil?
+      lat << cs.min_lat unless cs.min_lat.nil?
+      lon << cs.max_lon unless cs.max_lon.nil?
+      lat << cs.max_lat unless cs.max_lat.nil?
+
+      # collapse the arrays to minimum and maximum
+      cs.min_lon = lon.min
+      cs.min_lat = lat.min
+      cs.max_lon = lon.max
+      cs.max_lat = lat.max
+
+      # save the larger bounding box and return the changeset, which
+      # will include the bigger bounding box.
+      cs.save!
+      render :xml => cs.to_xml.to_s
+    end
+
+    ##
+    # Upload a diff in a single transaction.
+    #
+    # This means that each change within the diff must succeed, i.e: that
+    # each version number mentioned is still current. Otherwise the entire
+    # transaction *must* be rolled back.
+    #
+    # Furthermore, each element in the diff can only reference the current
+    # changeset.
+    #
+    # Returns: a diffResult document, as described in
+    # http://wiki.openstreetmap.org/wiki/OSM_Protocol_Version_0.6
+    def upload
+      # only allow POST requests, as the upload method is most definitely
+      # not idempotent, as several uploads with placeholder IDs will have
+      # different side-effects.
+      # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2
+      assert_method :post
+
+      changeset = Changeset.find(params[:id])
+      check_changeset_consistency(changeset, current_user)
+
+      diff_reader = DiffReader.new(request.raw_post, changeset)
+      Changeset.transaction do
+        result = diff_reader.commit
+        render :xml => result.to_s
+      end
+    end
+
+    ##
+    # download the changeset as an osmChange document.
+    #
+    # to make it easier to revert diffs it would be better if the osmChange
+    # format were reversible, i.e: contained both old and new versions of
+    # modified elements. but it doesn't at the moment...
+    #
+    # this method cannot order the database changes fully (i.e: timestamp and
+    # version number may be too coarse) so the resulting diff may not apply
+    # to a different database. however since changesets are not atomic this
+    # behaviour cannot be guaranteed anyway and is the result of a design
+    # choice.
+    def download
+      changeset = Changeset.find(params[:id])
+
+      # get all the elements in the changeset which haven't been redacted
+      # and stick them in a big array.
+      elements = [changeset.old_nodes.unredacted,
+                  changeset.old_ways.unredacted,
+                  changeset.old_relations.unredacted].flatten
+
+      # sort the elements by timestamp and version number, as this is the
+      # almost sensible ordering available. this would be much nicer if
+      # global (SVN-style) versioning were used - then that would be
+      # unambiguous.
+      elements.sort! do |a, b|
+        if a.timestamp == b.timestamp
+          a.version <=> b.version
+        else
+          a.timestamp <=> b.timestamp
+        end
+      end
+
+      # create changeset and user caches
+      changeset_cache = {}
+      user_display_name_cache = {}
+
+      # create an osmChange document for the output
+      result = OSM::API.new.get_xml_doc
+      result.root.name = "osmChange"
+
+      # generate an output element for each operation. note: we avoid looking
+      # at the history because it is simpler - but it would be more correct to
+      # check these assertions.
+      elements.each do |elt|
+        result.root <<
+          if elt.version == 1
+            # first version, so it must be newly-created.
+            created = XML::Node.new "create"
+            created << elt.to_xml_node(changeset_cache, user_display_name_cache)
+          elsif elt.visible
+            # must be a modify
+            modified = XML::Node.new "modify"
+            modified << elt.to_xml_node(changeset_cache, user_display_name_cache)
+          else
+            # if the element isn't visible then it must have been deleted
+            deleted = XML::Node.new "delete"
+            deleted << elt.to_xml_node(changeset_cache, user_display_name_cache)
+          end
+      end
+
+      render :xml => result.to_s
+    end
+
+    ##
+    # query changesets by bounding box, time, user or open/closed status.
+    def query
+      # find any bounding box
+      bbox = BoundingBox.from_bbox_params(params) if params["bbox"]
+
+      # create the conditions that the user asked for. some or all of
+      # these may be nil.
+      changesets = Changeset.all
+      changesets = conditions_bbox(changesets, bbox)
+      changesets = conditions_user(changesets, params["user"], params["display_name"])
+      changesets = conditions_time(changesets, params["time"])
+      changesets = conditions_open(changesets, params["open"])
+      changesets = conditions_closed(changesets, params["closed"])
+      changesets = conditions_ids(changesets, params["changesets"])
+
+      # sort and limit the changesets
+      changesets = changesets.order("created_at DESC").limit(100)
+
+      # preload users, tags and comments
+      changesets = changesets.preload(:user, :changeset_tags, :comments)
+
+      # create the results document
+      results = OSM::API.new.get_xml_doc
+
+      # add all matching changesets to the XML results document
+      changesets.order("created_at DESC").limit(100).each do |cs|
+        results.root << cs.to_xml_node
+      end
+
+      render :xml => results.to_s
+    end
+
+    ##
+    # updates a changeset's tags. none of the changeset's attributes are
+    # user-modifiable, so they will be ignored.
+    #
+    # changesets are not (yet?) versioned, so we don't have to deal with
+    # history tables here. changesets are locked to a single user, however.
+    #
+    # after succesful update, returns the XML of the changeset.
+    def update
+      # request *must* be a PUT.
+      assert_method :put
+
+      changeset = Changeset.find(params[:id])
+      new_changeset = Changeset.from_xml(request.raw_post)
+
+      check_changeset_consistency(changeset, current_user)
+      changeset.update_from(new_changeset, current_user)
+      render :xml => changeset.to_xml.to_s
+    end
+
+    ##
+    # Adds a subscriber to the changeset
+    def subscribe
+      # Check the arguments are sane
+      raise OSM::APIBadUserInput, "No id was given" unless params[:id]
+
+      # Extract the arguments
+      id = params[:id].to_i
+
+      # Find the changeset and check it is valid
+      changeset = Changeset.find(id)
+      raise OSM::APIChangesetAlreadySubscribedError, changeset if changeset.subscribers.exists?(current_user.id)
+
+      # Add the subscriber
+      changeset.subscribers << current_user
+
+      # Return a copy of the updated changeset
+      render :xml => changeset.to_xml.to_s
+    end
+
+    ##
+    # Removes a subscriber from the changeset
+    def unsubscribe
+      # Check the arguments are sane
+      raise OSM::APIBadUserInput, "No id was given" unless params[:id]
+
+      # Extract the arguments
+      id = params[:id].to_i
+
+      # Find the changeset and check it is valid
+      changeset = Changeset.find(id)
+      raise OSM::APIChangesetNotSubscribedError, changeset unless changeset.subscribers.exists?(current_user.id)
+
+      # Remove the subscriber
+      changeset.subscribers.delete(current_user)
+
+      # Return a copy of the updated changeset
+      render :xml => changeset.to_xml.to_s
+    end
+
+    private
+
+    #------------------------------------------------------------
+    # utility functions below.
+    #------------------------------------------------------------
+
+    ##
+    # if a bounding box was specified do some sanity checks.
+    # restrict changesets to those enclosed by a bounding box
+    # we need to return both the changesets and the bounding box
+    def conditions_bbox(changesets, bbox)
+      if bbox
+        bbox.check_boundaries
+        bbox = bbox.to_scaled
+
+        changesets.where("min_lon < ? and max_lon > ? and min_lat < ? and max_lat > ?",
+                         bbox.max_lon.to_i, bbox.min_lon.to_i,
+                         bbox.max_lat.to_i, bbox.min_lat.to_i)
+      else
+        changesets
+      end
+    end
+
+    ##
+    # restrict changesets to those by a particular user
+    def conditions_user(changesets, user, name)
+      if user.nil? && name.nil?
+        changesets
+      else
+        # shouldn't provide both name and UID
+        raise OSM::APIBadUserInput, "provide either the user ID or display name, but not both" if user && name
+
+        # use either the name or the UID to find the user which we're selecting on.
+        u = if name.nil?
+              # user input checking, we don't have any UIDs < 1
+              raise OSM::APIBadUserInput, "invalid user ID" if user.to_i < 1
+
+              u = User.find(user.to_i)
+            else
+              u = User.find_by(:display_name => name)
+            end
+
+        # make sure we found a user
+        raise OSM::APINotFoundError if u.nil?
+
+        # should be able to get changesets of public users only, or
+        # our own changesets regardless of public-ness.
+        unless u.data_public?
+          # get optional user auth stuff so that users can see their own
+          # changesets if they're non-public
+          setup_user_auth
+
+          raise OSM::APINotFoundError if current_user.nil? || current_user != u
+        end
+
+        changesets.where(:user_id => u.id)
+      end
+    end
+
+    ##
+    # restrict changes to those closed during a particular time period
+    def conditions_time(changesets, time)
+      if time.nil?
+        changesets
+      elsif time.count(",") == 1
+        # if there is a range, i.e: comma separated, then the first is
+        # low, second is high - same as with bounding boxes.
+
+        # check that we actually have 2 elements in the array
+        times = time.split(/,/)
+        raise OSM::APIBadUserInput, "bad time range" if times.size != 2
+
+        from, to = times.collect { |t| Time.parse(t) }
+        changesets.where("closed_at >= ? and created_at <= ?", from, to)
+      else
+        # if there is no comma, assume its a lower limit on time
+        changesets.where("closed_at >= ?", Time.parse(time))
+      end
+      # stupid Time seems to throw both of these for bad parsing, so
+      # we have to catch both and ensure the correct code path is taken.
+    rescue ArgumentError => ex
+      raise OSM::APIBadUserInput, ex.message.to_s
+    rescue RuntimeError => ex
+      raise OSM::APIBadUserInput, ex.message.to_s
+    end
+
+    ##
+    # return changesets which are open (haven't been closed yet)
+    # we do this by seeing if the 'closed at' time is in the future. Also if we've
+    # hit the maximum number of changes then it counts as no longer open.
+    # if parameter 'open' is nill then open and closed changesets are returned
+    def conditions_open(changesets, open)
+      if open.nil?
+        changesets
+      else
+        changesets.where("closed_at >= ? and num_changes <= ?",
+                         Time.now.getutc, Changeset::MAX_ELEMENTS)
+      end
+    end
+
+    ##
+    # query changesets which are closed
+    # ('closed at' time has passed or changes limit is hit)
+    def conditions_closed(changesets, closed)
+      if closed.nil?
+        changesets
+      else
+        changesets.where("closed_at < ? or num_changes > ?",
+                         Time.now.getutc, Changeset::MAX_ELEMENTS)
+      end
+    end
+
+    ##
+    # query changesets by a list of ids
+    # (either specified as array or comma-separated string)
+    def conditions_ids(changesets, ids)
+      if ids.nil?
+        changesets
+      elsif ids.empty?
+        raise OSM::APIBadUserInput, "No changesets were given to search for"
+      else
+        ids = ids.split(",").collect(&:to_i)
+        changesets.where(:id => ids)
+      end
+    end
+  end
+end
diff --git a/app/controllers/api/nodes_controller.rb b/app/controllers/api/nodes_controller.rb
new file mode 100644 (file)
index 0000000..4e46b38
--- /dev/null
@@ -0,0 +1,83 @@
+# The NodeController is the RESTful interface to Node objects
+
+module Api
+  class NodesController < ApplicationController
+    require "xml/libxml"
+
+    skip_before_action :verify_authenticity_token
+    before_action :authorize, :only => [:create, :update, :delete]
+    before_action :api_deny_access_handler
+
+    authorize_resource
+
+    before_action :require_public_data, :only => [:create, :update, :delete]
+    before_action :check_api_writable, :only => [:create, :update, :delete]
+    before_action :check_api_readable, :except => [:create, :update, :delete]
+    around_action :api_call_handle_error, :api_call_timeout
+
+    # Create a node from XML.
+    def create
+      assert_method :put
+
+      node = Node.from_xml(request.raw_post, true)
+
+      # Assume that Node.from_xml has thrown an exception if there is an error parsing the xml
+      node.create_with_history current_user
+      render :plain => node.id.to_s
+    end
+
+    # Dump the details on a node given in params[:id]
+    def show
+      node = Node.find(params[:id])
+
+      response.last_modified = node.timestamp
+
+      if node.visible
+        render :xml => node.to_xml.to_s
+      else
+        head :gone
+      end
+    end
+
+    # Update a node from given XML
+    def update
+      node = Node.find(params[:id])
+      new_node = Node.from_xml(request.raw_post)
+
+      raise OSM::APIBadUserInput, "The id in the url (#{node.id}) is not the same as provided in the xml (#{new_node.id})" unless new_node && new_node.id == node.id
+
+      node.update_from(new_node, current_user)
+      render :plain => node.version.to_s
+    end
+
+    # Delete a node. Doesn't actually delete it, but retains its history
+    # in a wiki-like way. We therefore treat it like an update, so the delete
+    # method returns the new version number.
+    def delete
+      node = Node.find(params[:id])
+      new_node = Node.from_xml(request.raw_post)
+
+      raise OSM::APIBadUserInput, "The id in the url (#{node.id}) is not the same as provided in the xml (#{new_node.id})" unless new_node && new_node.id == node.id
+
+      node.delete_with_history!(new_node, current_user)
+      render :plain => node.version.to_s
+    end
+
+    # Dump the details on many nodes whose ids are given in the "nodes" parameter.
+    def index
+      raise OSM::APIBadUserInput, "The parameter nodes is required, and must be of the form nodes=id[,id[,id...]]" unless params["nodes"]
+
+      ids = params["nodes"].split(",").collect(&:to_i)
+
+      raise OSM::APIBadUserInput, "No nodes were given to search for" if ids.empty?
+
+      doc = OSM::API.new.get_xml_doc
+
+      Node.find(ids).each do |node|
+        doc.root << node.to_xml_node
+      end
+
+      render :xml => doc.to_s
+    end
+  end
+end
diff --git a/app/controllers/api/notes_controller.rb b/app/controllers/api/notes_controller.rb
new file mode 100644 (file)
index 0000000..d4ebef5
--- /dev/null
@@ -0,0 +1,373 @@
+module Api
+  class NotesController < ApplicationController
+    layout "site", :only => [:mine]
+
+    skip_before_action :verify_authenticity_token
+    before_action :check_api_readable
+    before_action :setup_user_auth, :only => [:create, :comment, :show]
+    before_action :authorize, :only => [:close, :reopen, :destroy]
+    before_action :api_deny_access_handler
+
+    authorize_resource
+
+    before_action :check_api_writable, :only => [:create, :comment, :close, :reopen, :destroy]
+    before_action :set_locale
+    around_action :api_call_handle_error, :api_call_timeout
+
+    ##
+    # Return a list of notes in a given area
+    def index
+      # Figure out the bbox - we prefer a bbox argument but also
+      # support the old, deprecated, method with four arguments
+      if params[:bbox]
+        bbox = BoundingBox.from_bbox_params(params)
+      else
+        raise OSM::APIBadUserInput, "No l was given" unless params[:l]
+        raise OSM::APIBadUserInput, "No r was given" unless params[:r]
+        raise OSM::APIBadUserInput, "No b was given" unless params[:b]
+        raise OSM::APIBadUserInput, "No t was given" unless params[:t]
+
+        bbox = BoundingBox.from_lrbt_params(params)
+      end
+
+      # Get any conditions that need to be applied
+      notes = closed_condition(Note.all)
+
+      # Check that the boundaries are valid
+      bbox.check_boundaries
+
+      # Check the the bounding box is not too big
+      bbox.check_size(MAX_NOTE_REQUEST_AREA)
+
+      # Find the notes we want to return
+      @notes = notes.bbox(bbox).order("updated_at DESC").limit(result_limit).preload(:comments)
+
+      # Render the result
+      respond_to do |format|
+        format.rss
+        format.xml
+        format.json
+        format.gpx
+      end
+    end
+
+    ##
+    # Create a new note
+    def create
+      # Check the ACLs
+      raise OSM::APIAccessDenied if current_user.nil? && Acl.no_note_comment(request.remote_ip)
+
+      # Check the arguments are sane
+      raise OSM::APIBadUserInput, "No lat was given" unless params[:lat]
+      raise OSM::APIBadUserInput, "No lon was given" unless params[:lon]
+      raise OSM::APIBadUserInput, "No text was given" if params[:text].blank?
+
+      # Extract the arguments
+      lon = OSM.parse_float(params[:lon], OSM::APIBadUserInput, "lon was not a number")
+      lat = OSM.parse_float(params[:lat], OSM::APIBadUserInput, "lat was not a number")
+      comment = params[:text]
+
+      # Include in a transaction to ensure that there is always a note_comment for every note
+      Note.transaction do
+        # Create the note
+        @note = Note.create(:lat => lat, :lon => lon)
+        raise OSM::APIBadUserInput, "The note is outside this world" unless @note.in_world?
+
+        # Save the note
+        @note.save!
+
+        # Add a comment to the note
+        add_comment(@note, comment, "opened")
+      end
+
+      # Return a copy of the new note
+      respond_to do |format|
+        format.xml { render :action => :show }
+        format.json { render :action => :show }
+      end
+    end
+
+    ##
+    # Add a comment to an existing note
+    def comment
+      # Check the ACLs
+      raise OSM::APIAccessDenied if current_user.nil? && Acl.no_note_comment(request.remote_ip)
+
+      # Check the arguments are sane
+      raise OSM::APIBadUserInput, "No id was given" unless params[:id]
+      raise OSM::APIBadUserInput, "No text was given" if params[:text].blank?
+
+      # Extract the arguments
+      id = params[:id].to_i
+      comment = params[:text]
+
+      # Find the note and check it is valid
+      @note = Note.find(id)
+      raise OSM::APINotFoundError unless @note
+      raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible?
+      raise OSM::APINoteAlreadyClosedError, @note if @note.closed?
+
+      # Add a comment to the note
+      Note.transaction do
+        add_comment(@note, comment, "commented")
+      end
+
+      # Return a copy of the updated note
+      respond_to do |format|
+        format.xml { render :action => :show }
+        format.json { render :action => :show }
+      end
+    end
+
+    ##
+    # Close a note
+    def close
+      # Check the arguments are sane
+      raise OSM::APIBadUserInput, "No id was given" unless params[:id]
+
+      # Extract the arguments
+      id = params[:id].to_i
+      comment = params[:text]
+
+      # Find the note and check it is valid
+      @note = Note.find_by(:id => id)
+      raise OSM::APINotFoundError unless @note
+      raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible?
+      raise OSM::APINoteAlreadyClosedError, @note if @note.closed?
+
+      # Close the note and add a comment
+      Note.transaction do
+        @note.close
+
+        add_comment(@note, comment, "closed")
+      end
+
+      # Return a copy of the updated note
+      respond_to do |format|
+        format.xml { render :action => :show }
+        format.json { render :action => :show }
+      end
+    end
+
+    ##
+    # Reopen a note
+    def reopen
+      # Check the arguments are sane
+      raise OSM::APIBadUserInput, "No id was given" unless params[:id]
+
+      # Extract the arguments
+      id = params[:id].to_i
+      comment = params[:text]
+
+      # Find the note and check it is valid
+      @note = Note.find_by(:id => id)
+      raise OSM::APINotFoundError unless @note
+      raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible? || current_user.moderator?
+      raise OSM::APINoteAlreadyOpenError, @note unless @note.closed? || !@note.visible?
+
+      # Reopen the note and add a comment
+      Note.transaction do
+        @note.reopen
+
+        add_comment(@note, comment, "reopened")
+      end
+
+      # Return a copy of the updated note
+      respond_to do |format|
+        format.xml { render :action => :show }
+        format.json { render :action => :show }
+      end
+    end
+
+    ##
+    # Get a feed of recent notes and comments
+    def feed
+      # Get any conditions that need to be applied
+      notes = closed_condition(Note.all)
+
+      # Process any bbox
+      if params[:bbox]
+        bbox = BoundingBox.from_bbox_params(params)
+
+        bbox.check_boundaries
+        bbox.check_size(MAX_NOTE_REQUEST_AREA)
+
+        notes = notes.bbox(bbox)
+      end
+
+      # Find the comments we want to return
+      @comments = NoteComment.where(:note_id => notes).order("created_at DESC").limit(result_limit).preload(:note)
+
+      # Render the result
+      respond_to do |format|
+        format.rss
+      end
+    end
+
+    ##
+    # Read a note
+    def show
+      # Check the arguments are sane
+      raise OSM::APIBadUserInput, "No id was given" unless params[:id]
+
+      # Find the note and check it is valid
+      @note = Note.find(params[:id])
+      raise OSM::APINotFoundError unless @note
+      raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible? || current_user&.moderator?
+
+      # Render the result
+      respond_to do |format|
+        format.xml
+        format.rss
+        format.json
+        format.gpx
+      end
+    end
+
+    ##
+    # Delete (hide) a note
+    def destroy
+      # Check the arguments are sane
+      raise OSM::APIBadUserInput, "No id was given" unless params[:id]
+
+      # Extract the arguments
+      id = params[:id].to_i
+      comment = params[:text]
+
+      # Find the note and check it is valid
+      @note = Note.find(id)
+      raise OSM::APINotFoundError unless @note
+      raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible?
+
+      # Mark the note as hidden
+      Note.transaction do
+        @note.status = "hidden"
+        @note.save
+
+        add_comment(@note, comment, "hidden", false)
+      end
+
+      # Return a copy of the updated note
+      respond_to do |format|
+        format.xml { render :action => :show }
+        format.json { render :action => :show }
+      end
+    end
+
+    ##
+    # Return a list of notes matching a given string
+    def search
+      # Get the initial set of notes
+      @notes = closed_condition(Note.all)
+
+      # Add any user filter
+      if params[:display_name] || params[:user]
+        if params[:display_name]
+          @user = User.find_by(:display_name => params[:display_name])
+
+          raise OSM::APIBadUserInput, "User #{params[:display_name]} not known" unless @user
+        else
+          @user = User.find_by(:id => params[:user])
+
+          raise OSM::APIBadUserInput, "User #{params[:user]} not known" unless @user
+        end
+
+        @notes = @notes.joins(:comments).where(:note_comments => { :author_id => @user })
+      end
+
+      # Add any text filter
+      @notes = @notes.joins(:comments).where("to_tsvector('english', note_comments.body) @@ plainto_tsquery('english', ?)", params[:q]) if params[:q]
+
+      # Add any date filter
+      if params[:from]
+        begin
+          from = Time.parse(params[:from])
+        rescue ArgumentError
+          raise OSM::APIBadUserInput, "Date #{params[:from]} is in a wrong format"
+        end
+
+        begin
+          to = if params[:to]
+                 Time.parse(params[:to])
+               else
+                 Time.now
+               end
+        rescue ArgumentError
+          raise OSM::APIBadUserInput, "Date #{params[:to]} is in a wrong format"
+        end
+
+        @notes = @notes.where(:created_at => from..to)
+      end
+
+      # Find the notes we want to return
+      @notes = @notes.order("updated_at DESC").limit(result_limit).preload(:comments)
+
+      # Render the result
+      respond_to do |format|
+        format.rss { render :action => :index }
+        format.xml { render :action => :index }
+        format.json { render :action => :index }
+        format.gpx { render :action => :index }
+      end
+    end
+
+    private
+
+    #------------------------------------------------------------
+    # utility functions below.
+    #------------------------------------------------------------
+
+    ##
+    # Get the maximum number of results to return
+    def result_limit
+      if params[:limit]
+        if params[:limit].to_i.positive? && params[:limit].to_i <= 10000
+          params[:limit].to_i
+        else
+          raise OSM::APIBadUserInput, "Note limit must be between 1 and 10000"
+        end
+      else
+        100
+      end
+    end
+
+    ##
+    # Generate a condition to choose which notes we want based
+    # on their status and the user's request parameters
+    def closed_condition(notes)
+      closed_since = if params[:closed]
+                       params[:closed].to_i
+                     else
+                       7
+                     end
+
+      if closed_since.negative?
+        notes.where.not(:status => "hidden")
+      elsif closed_since.positive?
+        notes.where(:status => "open")
+             .or(notes.where(:status => "closed")
+                      .where(notes.arel_table[:closed_at].gt(Time.now - closed_since.days)))
+      else
+        notes.where(:status => "open")
+      end
+    end
+
+    ##
+    # Add a comment to a note
+    def add_comment(note, text, event, notify = true)
+      attributes = { :visible => true, :event => event, :body => text }
+
+      if current_user
+        attributes[:author_id] = current_user.id
+      else
+        attributes[:author_ip] = request.remote_ip
+      end
+
+      comment = note.comments.create!(attributes)
+
+      note.comments.map(&:author).uniq.each do |user|
+        Notifier.note_comment_notification(comment, user).deliver_later if notify && user && user != current_user && user.visible?
+      end
+    end
+  end
+end
diff --git a/app/controllers/api/old_controller.rb b/app/controllers/api/old_controller.rb
new file mode 100644 (file)
index 0000000..9a86bde
--- /dev/null
@@ -0,0 +1,79 @@
+# this class pulls together the logic for all the old_* controllers
+# into one place. as it turns out, the API methods for historical
+# nodes, ways and relations are basically identical.
+module Api
+  class OldController < ApplicationController
+    require "xml/libxml"
+
+    skip_before_action :verify_authenticity_token
+    before_action :setup_user_auth, :only => [:history, :version]
+    before_action :api_deny_access_handler
+    before_action :authorize, :only => [:redact]
+
+    authorize_resource
+
+    before_action :check_api_readable
+    before_action :check_api_writable, :only => [:redact]
+    around_action :api_call_handle_error, :api_call_timeout
+    before_action :lookup_old_element, :except => [:history]
+    before_action :lookup_old_element_versions, :only => [:history]
+
+    def history
+      # the .where() method used in the lookup_old_element_versions
+      # call won't throw an error if no records are found, so we have
+      # to do that ourselves.
+      raise OSM::APINotFoundError if @elements.empty?
+
+      doc = OSM::API.new.get_xml_doc
+
+      visible_elements = if show_redactions?
+                           @elements
+                         else
+                           @elements.unredacted
+                         end
+
+      visible_elements.each do |element|
+        doc.root << element.to_xml_node
+      end
+
+      render :xml => doc.to_s
+    end
+
+    def version
+      if @old_element.redacted? && !show_redactions?
+        head :forbidden
+
+      else
+        response.last_modified = @old_element.timestamp
+
+        doc = OSM::API.new.get_xml_doc
+        doc.root << @old_element.to_xml_node
+
+        render :xml => doc.to_s
+      end
+    end
+
+    def redact
+      redaction_id = params["redaction"]
+      if redaction_id.nil?
+        # if no redaction ID was provided, then this is an unredact
+        # operation.
+        @old_element.redact!(nil)
+      else
+        # if a redaction ID was specified, then set this element to
+        # be redacted in that redaction.
+        redaction = Redaction.find(redaction_id.to_i)
+        @old_element.redact!(redaction)
+      end
+
+      # just return an empty 200 OK for success
+      head :ok
+    end
+
+    private
+
+    def show_redactions?
+      current_user&.moderator? && params[:show_redactions] == "true"
+    end
+  end
+end
diff --git a/app/controllers/api/old_nodes_controller.rb b/app/controllers/api/old_nodes_controller.rb
new file mode 100644 (file)
index 0000000..7d0d340
--- /dev/null
@@ -0,0 +1,13 @@
+module Api
+  class OldNodesController < OldController
+    private
+
+    def lookup_old_element
+      @old_element = OldNode.find([params[:id], params[:version]])
+    end
+
+    def lookup_old_element_versions
+      @elements = OldNode.where(:node_id => params[:id]).order(:version)
+    end
+  end
+end
diff --git a/app/controllers/api/old_relations_controller.rb b/app/controllers/api/old_relations_controller.rb
new file mode 100644 (file)
index 0000000..ddc1684
--- /dev/null
@@ -0,0 +1,13 @@
+module Api
+  class OldRelationsController < OldController
+    private
+
+    def lookup_old_element
+      @old_element = OldRelation.find([params[:id], params[:version]])
+    end
+
+    def lookup_old_element_versions
+      @elements = OldRelation.where(:relation_id => params[:id]).order(:version)
+    end
+  end
+end
diff --git a/app/controllers/api/old_ways_controller.rb b/app/controllers/api/old_ways_controller.rb
new file mode 100644 (file)
index 0000000..66f3ce3
--- /dev/null
@@ -0,0 +1,13 @@
+module Api
+  class OldWaysController < OldController
+    private
+
+    def lookup_old_element
+      @old_element = OldWay.find([params[:id], params[:version]])
+    end
+
+    def lookup_old_element_versions
+      @elements = OldWay.where(:way_id => params[:id]).order(:version)
+    end
+  end
+end
diff --git a/app/controllers/api/relations_controller.rb b/app/controllers/api/relations_controller.rb
new file mode 100644 (file)
index 0000000..a0740b3
--- /dev/null
@@ -0,0 +1,169 @@
+module Api
+  class RelationsController < ApplicationController
+    require "xml/libxml"
+
+    skip_before_action :verify_authenticity_token
+    before_action :authorize, :only => [:create, :update, :delete]
+    before_action :api_deny_access_handler
+
+    authorize_resource
+
+    before_action :require_public_data, :only => [:create, :update, :delete]
+    before_action :check_api_writable, :only => [:create, :update, :delete]
+    before_action :check_api_readable, :except => [:create, :update, :delete]
+    around_action :api_call_handle_error, :api_call_timeout
+
+    def create
+      assert_method :put
+
+      relation = Relation.from_xml(request.raw_post, true)
+
+      # Assume that Relation.from_xml has thrown an exception if there is an error parsing the xml
+      relation.create_with_history current_user
+      render :plain => relation.id.to_s
+    end
+
+    def show
+      relation = Relation.find(params[:id])
+      response.last_modified = relation.timestamp
+      if relation.visible
+        render :xml => relation.to_xml.to_s
+      else
+        head :gone
+      end
+    end
+
+    def update
+      logger.debug request.raw_post
+
+      relation = Relation.find(params[:id])
+      new_relation = Relation.from_xml(request.raw_post)
+
+      raise OSM::APIBadUserInput, "The id in the url (#{relation.id}) is not the same as provided in the xml (#{new_relation.id})" unless new_relation && new_relation.id == relation.id
+
+      relation.update_from new_relation, current_user
+      render :plain => relation.version.to_s
+    end
+
+    def delete
+      relation = Relation.find(params[:id])
+      new_relation = Relation.from_xml(request.raw_post)
+      if new_relation && new_relation.id == relation.id
+        relation.delete_with_history!(new_relation, current_user)
+        render :plain => relation.version.to_s
+      else
+        head :bad_request
+      end
+    end
+
+    # -----------------------------------------------------------------
+    # full
+    #
+    # input parameters: id
+    #
+    # returns XML representation of one relation object plus all its
+    # members, plus all nodes part of member ways
+    # -----------------------------------------------------------------
+    def full
+      relation = Relation.find(params[:id])
+
+      if relation.visible
+
+        # first find the ids of nodes, ways and relations referenced by this
+        # relation - note that we exclude this relation just in case.
+
+        node_ids = relation.members.select { |m| m[0] == "Node" }.map { |m| m[1] }
+        way_ids = relation.members.select { |m| m[0] == "Way" }.map { |m| m[1] }
+        relation_ids = relation.members.select { |m| m[0] == "Relation" && m[1] != relation.id }.map { |m| m[1] }
+
+        # next load the relations and the ways.
+
+        relations = Relation.where(:id => relation_ids).includes(:relation_tags)
+        ways = Way.where(:id => way_ids).includes(:way_nodes, :way_tags)
+
+        # now additionally collect nodes referenced by ways. Note how we
+        # recursively evaluate ways but NOT relations.
+
+        way_node_ids = ways.collect do |way|
+          way.way_nodes.collect(&:node_id)
+        end
+        node_ids += way_node_ids.flatten
+        nodes = Node.where(:id => node_ids.uniq).includes(:node_tags)
+
+        # create XML.
+        doc = OSM::API.new.get_xml_doc
+        visible_nodes = {}
+        changeset_cache = {}
+        user_display_name_cache = {}
+
+        nodes.each do |node|
+          next unless node.visible? # should be unnecessary if data is consistent.
+
+          doc.root << node.to_xml_node(changeset_cache, user_display_name_cache)
+          visible_nodes[node.id] = node
+        end
+
+        ways.each do |way|
+          next unless way.visible? # should be unnecessary if data is consistent.
+
+          doc.root << way.to_xml_node(visible_nodes, changeset_cache, user_display_name_cache)
+        end
+
+        relations.each do |rel|
+          next unless rel.visible? # should be unnecessary if data is consistent.
+
+          doc.root << rel.to_xml_node(changeset_cache, user_display_name_cache)
+        end
+
+        # finally add self and output
+        doc.root << relation.to_xml_node(changeset_cache, user_display_name_cache)
+        render :xml => doc.to_s
+
+      else
+        head :gone
+      end
+    end
+
+    def index
+      raise OSM::APIBadUserInput, "The parameter relations is required, and must be of the form relations=id[,id[,id...]]" unless params["relations"]
+
+      ids = params["relations"].split(",").collect(&:to_i)
+
+      raise OSM::APIBadUserInput, "No relations were given to search for" if ids.empty?
+
+      doc = OSM::API.new.get_xml_doc
+
+      Relation.find(ids).each do |relation|
+        doc.root << relation.to_xml_node
+      end
+
+      render :xml => doc.to_s
+    end
+
+    def relations_for_way
+      relations_for_object("Way")
+    end
+
+    def relations_for_node
+      relations_for_object("Node")
+    end
+
+    def relations_for_relation
+      relations_for_object("Relation")
+    end
+
+    private
+
+    def relations_for_object(objtype)
+      relationids = RelationMember.where(:member_type => objtype, :member_id => params[:id]).collect(&:relation_id).uniq
+
+      doc = OSM::API.new.get_xml_doc
+
+      Relation.find(relationids).each do |relation|
+        doc.root << relation.to_xml_node if relation.visible
+      end
+
+      render :xml => doc.to_s
+    end
+  end
+end
diff --git a/app/controllers/api/search_controller.rb b/app/controllers/api/search_controller.rb
new file mode 100644 (file)
index 0000000..0afbbf8
--- /dev/null
@@ -0,0 +1,102 @@
+module Api
+  class SearchController < ApplicationController
+    # Support searching for nodes, ways, or all
+    # Can search by tag k, v, or both (type->k,value->v)
+    # Can search by name (k=name,v=....)
+    skip_before_action :verify_authenticity_token
+    authorize_resource :class => false
+
+    def search_all
+      do_search(true, true, true)
+    end
+
+    def search_ways
+      do_search(true, false, false)
+    end
+
+    def search_nodes
+      do_search(false, true, false)
+    end
+
+    def search_relations
+      do_search(false, false, true)
+    end
+
+    def do_search(do_ways, do_nodes, do_relations)
+      type = params["type"]
+      value = params["value"]
+      unless type || value
+        name = params["name"]
+        if name
+          type = "name"
+          value = name
+        end
+      end
+
+      if do_nodes
+        response.headers["Error"] = "Searching of nodes is currently unavailable"
+        head :service_unavailable
+        return false
+      end
+
+      unless value
+        response.headers["Error"] = "Searching for a key without value is currently unavailable"
+        head :service_unavailable
+        return false
+      end
+
+      # Matching for node tags table
+      if do_nodes
+        nodes = Node.joins(:node_tags)
+        nodes = nodes.where(:current_node_tags => { :k => type }) if type
+        nodes = nodes.where(:current_node_tags => { :v => value }) if value
+        nodes = nodes.limit(100)
+      else
+        nodes = []
+      end
+
+      # Matching for way tags table
+      if do_ways
+        ways = Way.joins(:way_tags)
+        ways = ways.where(:current_way_tags => { :k => type }) if type
+        ways = ways.where(:current_way_tags => { :v => value }) if value
+        ways = ways.limit(100)
+      else
+        ways = []
+      end
+
+      # Matching for relation tags table
+      if do_relations
+        relations = Relation.joins(:relation_tags)
+        relations = relations.where(:current_relation_tags => { :k => type }) if type
+        relations = relations.where(:current_relation_tags => { :v => value }) if value
+        relations = relations.limit(2000)
+      else
+        relations = []
+      end
+
+      # Fetch any node needed for our ways (only have matching nodes so far)
+      nodes += Node.find(ways.collect(&:nds).uniq)
+
+      # Print
+      visible_nodes = {}
+      changeset_cache = {}
+      user_display_name_cache = {}
+      doc = OSM::API.new.get_xml_doc
+      nodes.each do |node|
+        doc.root << node.to_xml_node(changeset_cache, user_display_name_cache)
+        visible_nodes[node.id] = node
+      end
+
+      ways.each do |way|
+        doc.root << way.to_xml_node(visible_nodes, changeset_cache, user_display_name_cache)
+      end
+
+      relations.each do |rel|
+        doc.root << rel.to_xml_node(changeset_cache, user_display_name_cache)
+      end
+
+      render :xml => doc.to_s
+    end
+  end
+end
diff --git a/app/controllers/api/swf_controller.rb b/app/controllers/api/swf_controller.rb
new file mode 100644 (file)
index 0000000..d48731b
--- /dev/null
@@ -0,0 +1,219 @@
+module Api
+  class SwfController < ApplicationController
+    skip_before_action :verify_authenticity_token
+    before_action :check_api_readable
+    authorize_resource :class => false
+
+    # to log:
+    # RAILS_DEFAULT_LOGGER.error("Args: #{args[0]}, #{args[1]}, #{args[2]}, #{args[3]}")
+    # $log.puts Time.new.to_s+','+Time.new.usec.to_s+": started GPS script"
+    # http://localhost:3000/api/0.4/swf/trackpoints?xmin=-2.32402605810577&xmax=-2.18386309423859&ymin=52.1546608755772&ymax=52.2272777906895&baselong=-2.25325793066437&basey=61.3948537948532&masterscale=5825.4222222222
+
+    # ====================================================================
+    # Public methods
+
+    # ---- trackpoints  compile SWF of trackpoints
+
+    def trackpoints
+      # -  Initialise
+
+      baselong = params["baselong"].to_f
+      basey = params["basey"].to_f
+      masterscale = params["masterscale"].to_f
+
+      bbox = BoundingBox.new(params["xmin"], params["ymin"],
+                             params["xmax"], params["ymax"])
+      start = params["start"].to_i
+
+      # -  Begin movie
+
+      bounds_left = 0
+      bounds_right = 320 * 20
+      bounds_bottom = 0
+      bounds_top = 240 * 20
+
+      m = ""
+      m += swf_record(9, 255.chr + 155.chr + 155.chr) # Background
+      absx = 0
+      absy = 0
+      xl = yb = 9999999
+      xr = yt = -9999999
+
+      # -  Send SQL for GPS tracks
+
+      b = ""
+      lasttime = 0
+      lasttrack = lastfile = "-1"
+
+      if params["token"]
+        user = User.authenticate(:token => params[:token])
+        sql = "SELECT gps_points.latitude*0.0000001 AS lat,gps_points.longitude*0.0000001 AS lon,gpx_files.id AS fileid," + "      EXTRACT(EPOCH FROM gps_points.timestamp) AS ts, gps_points.trackid AS trackid " + " FROM gpx_files,gps_points " + "WHERE gpx_files.id=gpx_id " + "  AND gpx_files.user_id=#{user.id} " + "  AND " + OSM.sql_for_area(bbox, "gps_points.") + "  AND (gps_points.timestamp IS NOT NULL) " + "ORDER BY fileid DESC,ts " + "LIMIT 10000 OFFSET #{start}"
+      else
+        sql = "SELECT latitude*0.0000001 AS lat,longitude*0.0000001 AS lon,gpx_id AS fileid," + "      EXTRACT(EPOCH FROM timestamp) AS ts, gps_points.trackid AS trackid " + " FROM gps_points " + "WHERE " + OSM.sql_for_area(bbox, "gps_points.") + "  AND (gps_points.timestamp IS NOT NULL) " + "ORDER BY fileid DESC,ts " + "LIMIT 10000 OFFSET #{start}"
+      end
+      gpslist = ActiveRecord::Base.connection.select_all sql
+
+      # - Draw GPS trace lines
+
+      r = start_shape
+      gpslist.each do |row|
+        xs = (long2coord(row["lon"].to_f, baselong, masterscale) * 20).floor
+        ys = (lat2coord(row["lat"].to_f, basey, masterscale) * 20).floor
+        xl = [xs, xl].min
+        xr = [xs, xr].max
+        yb = [ys, yb].min
+        yt = [ys, yt].max
+        if row["ts"].to_i - lasttime > 180 || row["fileid"] != lastfile || row["trackid"] != lasttrack # or row['ts'].to_i==lasttime
+          b += start_and_move(xs, ys, "01")
+          absx = xs.floor
+          absy = ys.floor
+        end
+        b += draw_to(absx, absy, xs, ys)
+        absx = xs.floor
+        absy = ys.floor
+        lasttime = row["ts"].to_i
+        lastfile = row["fileid"]
+        lasttrack = row["trackid"]
+        r += [b.slice!(0...80)].pack("B*") while b.length > 80
+      end
+
+      #   (Unwayed segments removed)
+
+      # - Write shape
+
+      b += end_shape
+      r += [b].pack("B*")
+      m += swf_record(2, pack_u16(1) + pack_rect(xl, xr, yb, yt) + r)
+      m += swf_record(4, pack_u16(1) + pack_u16(1))
+
+      # -  Create Flash header and write to browser
+
+      m += swf_record(1, "")                                                                   # Show frame
+      m += swf_record(0, "")                                                                   # End
+
+      m = pack_rect(bounds_left, bounds_right, bounds_bottom, bounds_top) + 0.chr + 12.chr + pack_u16(1) + m
+      m = "FWS" + 6.chr + pack_u32(m.length + 8) + m
+
+      render :body => m, :content_type => "application/x-shockwave-flash"
+    end
+
+    private
+
+    # =======================================================================
+    # SWF functions
+
+    # -----------------------------------------------------------------------
+    # Line-drawing
+
+    def start_shape
+      s = 0.chr                                    # No fill styles
+      s += 2.chr                                   # Two line styles
+      s += pack_u16(0) + 0.chr + 255.chr + 255.chr # Width 5, RGB #00FFFF
+      s += pack_u16(0) + 255.chr + 0.chr + 255.chr # Width 5, RGB #FF00FF
+      s += 34.chr # 2 fill, 2 line index bits
+      s
+    end
+
+    def end_shape
+      "000000"
+    end
+
+    def start_and_move(x, y, col)
+      d = "001001"     # Line style change, moveTo
+      l = [length_sb(x), length_sb(y)].max
+      d += format("%05b%0*b%0*b", l, l, x, l, y)
+      d += col # Select line style
+      d
+    end
+
+    def draw_to(absx, absy, x, y)
+      dx = x - absx
+      dy = y - absy
+
+      # Split the line up if there's anything>16383, because
+      # that would overflow the 4 bits allowed for length
+      mstep = [dx.abs / 16383, dy.abs / 16383, 1].max.ceil
+      xstep = dx / mstep
+      ystep = dy / mstep
+      d = ""
+      1.upto(mstep).each do
+        d += draw_section(x, y, x + xstep, y + ystep)
+        x += xstep
+        y += ystep
+      end
+      d
+    end
+
+    def draw_section(x1, y1, x2, y2)
+      d = "11"                                                                                 # TypeFlag, EdgeFlag
+      dx = x2 - x1
+      dy = y2 - y1
+      l = [length_sb(dx), length_sb(dy)].max
+      d += format("%04b", l - 2)
+      d += "1"                                                                                 # GeneralLine
+      d += format("%0*b%0*b", l, dx, l, dy)
+      d
+    end
+
+    # -----------------------------------------------------------------------
+    # Specific data types
+
+    # SWF data block type
+
+    def swf_record(id, r)
+      if r.length > 62
+        # Long header: tag id, 0x3F, length
+        pack_u16((id << 6) + 0x3F) + pack_u32(r.length) + r
+      else
+        # Short header: tag id, length
+        pack_u16((id << 6) + r.length) + r
+      end
+    end
+
+    # SWF RECT type
+
+    def pack_rect(a, b, c, d)
+      l = [length_sb(a),
+           length_sb(b),
+           length_sb(c),
+           length_sb(d)].max
+      # create binary string (00111001 etc.) - 5-byte length, then bbox
+      n = format("%05b%0*b%0*b%0*b%0*b", l, l, a, l, b, l, c, l, d)
+      # pack into byte string
+      [n].pack("B*")
+    end
+
+    # -----------------------------------------------------------------------
+    # Generic pack functions
+
+    def pack_u16(n)
+      [n.floor].pack("v")
+    end
+
+    def pack_u32(n)
+      [n.floor].pack("V")
+    end
+
+    # Find number of bits required to store arbitrary-length binary
+
+    def length_sb(n)
+      Math.frexp(n + (n.zero? ? 1 : 0))[1] + 1
+    end
+
+    # ====================================================================
+    # Co-ordinate conversion
+    # (this is duplicated from amf_controller, should probably share)
+
+    def lat2coord(a, basey, masterscale)
+      -(lat2y(a) - basey) * masterscale
+    end
+
+    def long2coord(a, baselong, masterscale)
+      (a - baselong) * masterscale
+    end
+
+    def lat2y(a)
+      180 / Math::PI * Math.log(Math.tan(Math::PI / 4 + a * (Math::PI / 180) / 2))
+    end
+  end
+end
diff --git a/app/controllers/api/traces_controller.rb b/app/controllers/api/traces_controller.rb
new file mode 100644 (file)
index 0000000..8401e78
--- /dev/null
@@ -0,0 +1,169 @@
+module Api
+  class TracesController < ApplicationController
+    layout "site", :except => :georss
+
+    skip_before_action :verify_authenticity_token
+    before_action :authorize_web
+    before_action :set_locale
+    before_action :authorize
+    before_action :api_deny_access_handler
+
+    authorize_resource
+
+    before_action :check_database_readable, :except => [:api_read, :api_data]
+    before_action :check_database_writable, :only => [:api_create, :api_update, :api_delete]
+    before_action :check_api_readable, :only => [:api_read, :api_data]
+    before_action :check_api_writable, :only => [:api_create, :api_update, :api_delete]
+    before_action :offline_redirect, :only => [:api_create, :api_delete, :api_data]
+    around_action :api_call_handle_error
+
+    def api_read
+      trace = Trace.visible.find(params[:id])
+
+      if trace.public? || trace.user == current_user
+        render :xml => trace.to_xml.to_s
+      else
+        head :forbidden
+      end
+    end
+
+    def api_update
+      trace = Trace.visible.find(params[:id])
+
+      if trace.user == current_user
+        trace.update_from_xml(request.raw_post)
+        trace.save!
+
+        head :ok
+      else
+        head :forbidden
+      end
+    end
+
+    def api_delete
+      trace = Trace.visible.find(params[:id])
+
+      if trace.user == current_user
+        trace.visible = false
+        trace.save!
+
+        head :ok
+      else
+        head :forbidden
+      end
+    end
+
+    def api_data
+      trace = Trace.visible.find(params[:id])
+
+      if trace.public? || trace.user == current_user
+        if request.format == Mime[:xml]
+          send_data(trace.xml_file.read, :filename => "#{trace.id}.xml", :type => request.format.to_s, :disposition => "attachment")
+        elsif request.format == Mime[:gpx]
+          send_data(trace.xml_file.read, :filename => "#{trace.id}.gpx", :type => request.format.to_s, :disposition => "attachment")
+        else
+          send_file(trace.trace_name, :filename => "#{trace.id}#{trace.extension_name}", :type => trace.mime_type, :disposition => "attachment")
+        end
+      else
+        head :forbidden
+      end
+    end
+
+    def api_create
+      tags = params[:tags] || ""
+      description = params[:description] || ""
+      visibility = params[:visibility]
+
+      if visibility.nil?
+        visibility = if params[:public]&.to_i&.nonzero?
+                       "public"
+                     else
+                       "private"
+                     end
+      end
+
+      if params[:file].respond_to?(:read)
+        trace = do_create(params[:file], tags, description, visibility)
+
+        if trace.id
+          render :plain => trace.id.to_s
+        elsif trace.valid?
+          head :internal_server_error
+        else
+          head :bad_request
+        end
+      else
+        head :bad_request
+      end
+    end
+
+    private
+
+    def do_create(file, tags, description, visibility)
+      # Sanitise the user's filename
+      name = file.original_filename.gsub(/[^a-zA-Z0-9.]/, "_")
+
+      # Get a temporary filename...
+      filename = "/tmp/#{rand}"
+
+      # ...and save the uploaded file to that location
+      File.open(filename, "wb") { |f| f.write(file.read) }
+
+      # Create the trace object, falsely marked as already
+      # inserted to stop the import daemon trying to load it
+      trace = Trace.new(
+        :name => name,
+        :tagstring => tags,
+        :description => description,
+        :visibility => visibility,
+        :inserted => true,
+        :user => current_user,
+        :timestamp => Time.now.getutc
+      )
+
+      if trace.valid?
+        Trace.transaction do
+          begin
+            # Save the trace object
+            trace.save!
+
+            # Rename the temporary file to the final name
+            FileUtils.mv(filename, trace.trace_name)
+          rescue StandardError
+            # Remove the file as we have failed to update the database
+            FileUtils.rm_f(filename)
+
+            # Pass the exception on
+            raise
+          end
+
+          begin
+            # Clear the inserted flag to make the import daemon load the trace
+            trace.inserted = false
+            trace.save!
+          rescue StandardError
+            # Remove the file as we have failed to update the database
+            FileUtils.rm_f(trace.trace_name)
+
+            # Pass the exception on
+            raise
+          end
+        end
+      end
+
+      # Finally save the user's preferred privacy level
+      if pref = current_user.preferences.where(:k => "gps.trace.visibility").first
+        pref.v = visibility
+        pref.save
+      else
+        current_user.preferences.create(:k => "gps.trace.visibility", :v => visibility)
+      end
+
+      trace
+    end
+
+    def offline_redirect
+      redirect_to :action => :offline if STATUS == :gpx_offline
+    end
+  end
+end
diff --git a/app/controllers/api/user_preferences_controller.rb b/app/controllers/api/user_preferences_controller.rb
new file mode 100644 (file)
index 0000000..82f6c6a
--- /dev/null
@@ -0,0 +1,90 @@
+# Update and read user preferences, which are arbitrayr key/val pairs
+module Api
+  class UserPreferencesController < ApplicationController
+    skip_before_action :verify_authenticity_token
+    before_action :authorize
+
+    authorize_resource
+
+    around_action :api_call_handle_error
+
+    ##
+    # return all the preferences as an XML document
+    def read
+      doc = OSM::API.new.get_xml_doc
+
+      prefs = current_user.preferences
+
+      el1 = XML::Node.new "preferences"
+
+      prefs.each do |pref|
+        el1 << pref.to_xml_node
+      end
+
+      doc.root << el1
+      render :xml => doc.to_s
+    end
+
+    ##
+    # return the value for a single preference
+    def read_one
+      pref = UserPreference.find([current_user.id, params[:preference_key]])
+
+      render :plain => pref.v.to_s
+    end
+
+    # update the entire set of preferences
+    def update
+      old_preferences = current_user.preferences.each_with_object({}) do |preference, preferences|
+        preferences[preference.k] = preference
+      end
+
+      new_preferences = {}
+
+      doc = XML::Parser.string(request.raw_post, :options => XML::Parser::Options::NOERROR).parse
+
+      doc.find("//preferences/preference").each do |pt|
+        if preference = old_preferences.delete(pt["k"])
+          preference.v = pt["v"]
+        elsif new_preferences.include?(pt["k"])
+          raise OSM::APIDuplicatePreferenceError, pt["k"]
+        else
+          preference = current_user.preferences.build(:k => pt["k"], :v => pt["v"])
+        end
+
+        new_preferences[preference.k] = preference
+      end
+
+      old_preferences.each_value(&:delete)
+
+      new_preferences.each_value(&:save!)
+
+      render :plain => ""
+    end
+
+    ##
+    # update the value of a single preference
+    def update_one
+      begin
+        pref = UserPreference.find([current_user.id, params[:preference_key]])
+      rescue ActiveRecord::RecordNotFound
+        pref = UserPreference.new
+        pref.user = current_user
+        pref.k = params[:preference_key]
+      end
+
+      pref.v = request.raw_post.chomp
+      pref.save!
+
+      render :plain => ""
+    end
+
+    ##
+    # delete a single preference
+    def delete_one
+      UserPreference.find([current_user.id, params[:preference_key]]).delete
+
+      render :plain => ""
+    end
+  end
+end
diff --git a/app/controllers/api/users_controller.rb b/app/controllers/api/users_controller.rb
new file mode 100644 (file)
index 0000000..70ad93f
--- /dev/null
@@ -0,0 +1,66 @@
+module Api
+  class UsersController < ApplicationController
+    layout "site", :except => [:api_details]
+
+    skip_before_action :verify_authenticity_token
+    before_action :disable_terms_redirect, :only => [:api_details]
+    before_action :authorize, :only => [:api_details, :api_gpx_files]
+    before_action :api_deny_access_handler
+
+    authorize_resource
+
+    before_action :check_api_readable
+    around_action :api_call_handle_error
+    before_action :lookup_user_by_id, :only => [:api_read]
+
+    def api_read
+      if @user.visible?
+        render :action => :api_read, :content_type => "text/xml"
+      else
+        head :gone
+      end
+    end
+
+    def api_details
+      @user = current_user
+      render :action => :api_read, :content_type => "text/xml"
+    end
+
+    def api_users
+      raise OSM::APIBadUserInput, "The parameter users is required, and must be of the form users=id[,id[,id...]]" unless params["users"]
+
+      ids = params["users"].split(",").collect(&:to_i)
+
+      raise OSM::APIBadUserInput, "No users were given to search for" if ids.empty?
+
+      @users = User.visible.find(ids)
+
+      render :action => :api_users, :content_type => "text/xml"
+    end
+
+    def api_gpx_files
+      doc = OSM::API.new.get_xml_doc
+      current_user.traces.reload.each do |trace|
+        doc.root << trace.to_xml_node
+      end
+      render :xml => doc.to_s
+    end
+
+    private
+
+    ##
+    # ensure that there is a "user" instance variable
+    def lookup_user_by_id
+      @user = User.find(params[:id])
+    end
+
+    ##
+    #
+    def disable_terms_redirect
+      # this is necessary otherwise going to the user terms page, when
+      # having not agreed already would cause an infinite redirect loop.
+      # it's .now so that this doesn't propagate to other pages.
+      flash.now[:skip_terms] = true
+    end
+  end
+end
diff --git a/app/controllers/api/ways_controller.rb b/app/controllers/api/ways_controller.rb
new file mode 100644 (file)
index 0000000..8684c5c
--- /dev/null
@@ -0,0 +1,120 @@
+module Api
+  class WaysController < ApplicationController
+    require "xml/libxml"
+
+    skip_before_action :verify_authenticity_token
+    before_action :authorize, :only => [:create, :update, :delete]
+    before_action :api_deny_access_handler
+
+    authorize_resource
+
+    before_action :require_public_data, :only => [:create, :update, :delete]
+    before_action :check_api_writable, :only => [:create, :update, :delete]
+    before_action :check_api_readable, :except => [:create, :update, :delete]
+    around_action :api_call_handle_error, :api_call_timeout
+
+    def create
+      assert_method :put
+
+      way = Way.from_xml(request.raw_post, true)
+
+      # Assume that Way.from_xml has thrown an exception if there is an error parsing the xml
+      way.create_with_history current_user
+      render :plain => way.id.to_s
+    end
+
+    def show
+      way = Way.find(params[:id])
+
+      response.last_modified = way.timestamp
+
+      if way.visible
+        render :xml => way.to_xml.to_s
+      else
+        head :gone
+      end
+    end
+
+    def update
+      way = Way.find(params[:id])
+      new_way = Way.from_xml(request.raw_post)
+
+      unless new_way && new_way.id == way.id
+        raise OSM::APIBadUserInput, "The id in the url (#{way.id}) is not the same as provided in the xml (#{new_way.id})"
+      end
+
+      way.update_from(new_way, current_user)
+      render :plain => way.version.to_s
+    end
+
+    # This is the API call to delete a way
+    def delete
+      way = Way.find(params[:id])
+      new_way = Way.from_xml(request.raw_post)
+
+      if new_way && new_way.id == way.id
+        way.delete_with_history!(new_way, current_user)
+        render :plain => way.version.to_s
+      else
+        head :bad_request
+      end
+    end
+
+    def full
+      way = Way.includes(:nodes => :node_tags).find(params[:id])
+
+      if way.visible
+        visible_nodes = {}
+        changeset_cache = {}
+        user_display_name_cache = {}
+
+        doc = OSM::API.new.get_xml_doc
+        way.nodes.uniq.each do |node|
+          if node.visible
+            doc.root << node.to_xml_node(changeset_cache, user_display_name_cache)
+            visible_nodes[node.id] = node
+          end
+        end
+        doc.root << way.to_xml_node(visible_nodes, changeset_cache, user_display_name_cache)
+
+        render :xml => doc.to_s
+      else
+        head :gone
+      end
+    end
+
+    def index
+      unless params["ways"]
+        raise OSM::APIBadUserInput, "The parameter ways is required, and must be of the form ways=id[,id[,id...]]"
+      end
+
+      ids = params["ways"].split(",").collect(&:to_i)
+
+      raise OSM::APIBadUserInput, "No ways were given to search for" if ids.empty?
+
+      doc = OSM::API.new.get_xml_doc
+
+      Way.find(ids).each do |way|
+        doc.root << way.to_xml_node
+      end
+
+      render :xml => doc.to_s
+    end
+
+    ##
+    # returns all the ways which are currently using the node given in the
+    # :id parameter. note that this used to return deleted ways as well, but
+    # this seemed not to be the expected behaviour, so it was removed.
+    def ways_for_node
+      wayids = WayNode.where(:node_id => params[:id]).collect { |ws| ws.id[0] }.uniq
+
+      doc = OSM::API.new.get_xml_doc
+
+      Way.find(wayids).each do |way|
+        doc.root << way.to_xml_node if way.visible
+      end
+
+      render :xml => doc.to_s
+    end
+  end
+end
index a3023af3eb3fd6e057781f4028e1d9c4bf28c6eb..05b28eacf01c9806759bcafa8138f33b5958ce44 100644 (file)
@@ -1,89 +1,11 @@
 class ChangesetCommentsController < ApplicationController
-  skip_before_action :verify_authenticity_token, :except => [:index]
-  before_action :authorize_web, :only => [:index]
-  before_action :set_locale, :only => [:index]
-  before_action :authorize, :only => [:create, :destroy, :restore]
-  before_action :api_deny_access_handler, :only => [:create, :destroy, :restore]
+  before_action :authorize_web
+  before_action :set_locale
 
   authorize_resource
 
-  before_action :require_public_data, :only => [:create]
-  before_action :check_api_writable, :only => [:create, :destroy, :restore]
-  before_action :check_api_readable, :except => [:create, :index]
   before_action(:only => [:index]) { |c| c.check_database_readable(true) }
-  around_action :api_call_handle_error, :except => [:index]
-  around_action :api_call_timeout, :except => [:index]
-  around_action :web_timeout, :only => [:index]
-
-  ##
-  # Add a comment to a changeset
-  def create
-    # Check the arguments are sane
-    raise OSM::APIBadUserInput, "No id was given" unless params[:id]
-    raise OSM::APIBadUserInput, "No text was given" if params[:text].blank?
-
-    # Extract the arguments
-    id = params[:id].to_i
-    body = params[:text]
-
-    # Find the changeset and check it is valid
-    changeset = Changeset.find(id)
-    raise OSM::APIChangesetNotYetClosedError, changeset if changeset.is_open?
-
-    # Add a comment to the changeset
-    comment = changeset.comments.create(:changeset => changeset,
-                                        :body => body,
-                                        :author => current_user)
-
-    # Notify current subscribers of the new comment
-    changeset.subscribers.visible.each do |user|
-      Notifier.changeset_comment_notification(comment, user).deliver_later if current_user != user
-    end
-
-    # Add the commenter to the subscribers if necessary
-    changeset.subscribers << current_user unless changeset.subscribers.exists?(current_user.id)
-
-    # Return a copy of the updated changeset
-    render :xml => changeset.to_xml.to_s
-  end
-
-  ##
-  # Sets visible flag on comment to false
-  def destroy
-    # Check the arguments are sane
-    raise OSM::APIBadUserInput, "No id was given" unless params[:id]
-
-    # Extract the arguments
-    id = params[:id].to_i
-
-    # Find the changeset
-    comment = ChangesetComment.find(id)
-
-    # Hide the comment
-    comment.update(:visible => false)
-
-    # Return a copy of the updated changeset
-    render :xml => comment.changeset.to_xml.to_s
-  end
-
-  ##
-  # Sets visible flag on comment to true
-  def restore
-    # Check the arguments are sane
-    raise OSM::APIBadUserInput, "No id was given" unless params[:id]
-
-    # Extract the arguments
-    id = params[:id].to_i
-
-    # Find the changeset
-    comment = ChangesetComment.find(id)
-
-    # Unhide the comment
-    comment.update(:visible => true)
-
-    # Return a copy of the updated changeset
-    render :xml => comment.changeset.to_xml.to_s
-  end
+  around_action :web_timeout
 
   ##
   # Get a feed of recent changeset comments
index 80b8aff48c4e590c83bf655cff6fc34b4e982337..a69d0d57b7daaa14b9e78459a87f71de8187bc45 100644 (file)
@@ -5,256 +5,17 @@ class ChangesetsController < ApplicationController
   require "xml/libxml"
 
   skip_before_action :verify_authenticity_token, :except => [:index]
-  before_action :authorize_web, :only => [:index, :feed]
-  before_action :set_locale, :only => [:index, :feed]
-  before_action :authorize, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe]
-  before_action :api_deny_access_handler, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe, :expand_bbox]
+  before_action :authorize_web
+  before_action :set_locale
 
   authorize_resource
 
-  before_action :require_public_data, :only => [:create, :update, :upload, :close, :subscribe, :unsubscribe]
-  before_action :check_api_writable, :only => [:create, :update, :upload, :subscribe, :unsubscribe]
-  before_action :check_api_readable, :except => [:create, :update, :upload, :download, :query, :index, :feed, :subscribe, :unsubscribe]
   before_action(:only => [:index, :feed]) { |c| c.check_database_readable(true) }
-  around_action :api_call_handle_error, :except => [:index, :feed]
-  around_action :api_call_timeout, :except => [:index, :feed, :upload]
-  around_action :web_timeout, :only => [:index, :feed]
+  around_action :web_timeout
 
   # Helper methods for checking consistency
   include ConsistencyValidations
 
-  # Create a changeset from XML.
-  def create
-    assert_method :put
-
-    cs = Changeset.from_xml(request.raw_post, true)
-
-    # Assume that Changeset.from_xml has thrown an exception if there is an error parsing the xml
-    cs.user = current_user
-    cs.save_with_tags!
-
-    # Subscribe user to changeset comments
-    cs.subscribers << current_user
-
-    render :plain => cs.id.to_s
-  end
-
-  ##
-  # Return XML giving the basic info about the changeset. Does not
-  # return anything about the nodes, ways and relations in the changeset.
-  def show
-    changeset = Changeset.find(params[:id])
-
-    render :xml => changeset.to_xml(params[:include_discussion].presence).to_s
-  end
-
-  ##
-  # marks a changeset as closed. this may be called multiple times
-  # on the same changeset, so is idempotent.
-  def close
-    assert_method :put
-
-    changeset = Changeset.find(params[:id])
-    check_changeset_consistency(changeset, current_user)
-
-    # to close the changeset, we'll just set its closed_at time to
-    # now. this might not be enough if there are concurrency issues,
-    # but we'll have to wait and see.
-    changeset.set_closed_time_now
-
-    changeset.save!
-    head :ok
-  end
-
-  ##
-  # insert a (set of) points into a changeset bounding box. this can only
-  # increase the size of the bounding box. this is a hint that clients can
-  # set either before uploading a large number of changes, or changes that
-  # the client (but not the server) knows will affect areas further away.
-  def expand_bbox
-    # only allow POST requests, because although this method is
-    # idempotent, there is no "document" to PUT really...
-    assert_method :post
-
-    cs = Changeset.find(params[:id])
-    check_changeset_consistency(cs, current_user)
-
-    # keep an array of lons and lats
-    lon = []
-    lat = []
-
-    # the request is in pseudo-osm format... this is kind-of an
-    # abuse, maybe should change to some other format?
-    doc = XML::Parser.string(request.raw_post, :options => XML::Parser::Options::NOERROR).parse
-    doc.find("//osm/node").each do |n|
-      lon << n["lon"].to_f * GeoRecord::SCALE
-      lat << n["lat"].to_f * GeoRecord::SCALE
-    end
-
-    # add the existing bounding box to the lon-lat array
-    lon << cs.min_lon unless cs.min_lon.nil?
-    lat << cs.min_lat unless cs.min_lat.nil?
-    lon << cs.max_lon unless cs.max_lon.nil?
-    lat << cs.max_lat unless cs.max_lat.nil?
-
-    # collapse the arrays to minimum and maximum
-    cs.min_lon = lon.min
-    cs.min_lat = lat.min
-    cs.max_lon = lon.max
-    cs.max_lat = lat.max
-
-    # save the larger bounding box and return the changeset, which
-    # will include the bigger bounding box.
-    cs.save!
-    render :xml => cs.to_xml.to_s
-  end
-
-  ##
-  # Upload a diff in a single transaction.
-  #
-  # This means that each change within the diff must succeed, i.e: that
-  # each version number mentioned is still current. Otherwise the entire
-  # transaction *must* be rolled back.
-  #
-  # Furthermore, each element in the diff can only reference the current
-  # changeset.
-  #
-  # Returns: a diffResult document, as described in
-  # http://wiki.openstreetmap.org/wiki/OSM_Protocol_Version_0.6
-  def upload
-    # only allow POST requests, as the upload method is most definitely
-    # not idempotent, as several uploads with placeholder IDs will have
-    # different side-effects.
-    # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2
-    assert_method :post
-
-    changeset = Changeset.find(params[:id])
-    check_changeset_consistency(changeset, current_user)
-
-    diff_reader = DiffReader.new(request.raw_post, changeset)
-    Changeset.transaction do
-      result = diff_reader.commit
-      render :xml => result.to_s
-    end
-  end
-
-  ##
-  # download the changeset as an osmChange document.
-  #
-  # to make it easier to revert diffs it would be better if the osmChange
-  # format were reversible, i.e: contained both old and new versions of
-  # modified elements. but it doesn't at the moment...
-  #
-  # this method cannot order the database changes fully (i.e: timestamp and
-  # version number may be too coarse) so the resulting diff may not apply
-  # to a different database. however since changesets are not atomic this
-  # behaviour cannot be guaranteed anyway and is the result of a design
-  # choice.
-  def download
-    changeset = Changeset.find(params[:id])
-
-    # get all the elements in the changeset which haven't been redacted
-    # and stick them in a big array.
-    elements = [changeset.old_nodes.unredacted,
-                changeset.old_ways.unredacted,
-                changeset.old_relations.unredacted].flatten
-
-    # sort the elements by timestamp and version number, as this is the
-    # almost sensible ordering available. this would be much nicer if
-    # global (SVN-style) versioning were used - then that would be
-    # unambiguous.
-    elements.sort! do |a, b|
-      if a.timestamp == b.timestamp
-        a.version <=> b.version
-      else
-        a.timestamp <=> b.timestamp
-      end
-    end
-
-    # create changeset and user caches
-    changeset_cache = {}
-    user_display_name_cache = {}
-
-    # create an osmChange document for the output
-    result = OSM::API.new.get_xml_doc
-    result.root.name = "osmChange"
-
-    # generate an output element for each operation. note: we avoid looking
-    # at the history because it is simpler - but it would be more correct to
-    # check these assertions.
-    elements.each do |elt|
-      result.root <<
-        if elt.version == 1
-          # first version, so it must be newly-created.
-          created = XML::Node.new "create"
-          created << elt.to_xml_node(changeset_cache, user_display_name_cache)
-        elsif elt.visible
-          # must be a modify
-          modified = XML::Node.new "modify"
-          modified << elt.to_xml_node(changeset_cache, user_display_name_cache)
-        else
-          # if the element isn't visible then it must have been deleted
-          deleted = XML::Node.new "delete"
-          deleted << elt.to_xml_node(changeset_cache, user_display_name_cache)
-        end
-    end
-
-    render :xml => result.to_s
-  end
-
-  ##
-  # query changesets by bounding box, time, user or open/closed status.
-  def query
-    # find any bounding box
-    bbox = BoundingBox.from_bbox_params(params) if params["bbox"]
-
-    # create the conditions that the user asked for. some or all of
-    # these may be nil.
-    changesets = Changeset.all
-    changesets = conditions_bbox(changesets, bbox)
-    changesets = conditions_user(changesets, params["user"], params["display_name"])
-    changesets = conditions_time(changesets, params["time"])
-    changesets = conditions_open(changesets, params["open"])
-    changesets = conditions_closed(changesets, params["closed"])
-    changesets = conditions_ids(changesets, params["changesets"])
-
-    # sort and limit the changesets
-    changesets = changesets.order("created_at DESC").limit(100)
-
-    # preload users, tags and comments
-    changesets = changesets.preload(:user, :changeset_tags, :comments)
-
-    # create the results document
-    results = OSM::API.new.get_xml_doc
-
-    # add all matching changesets to the XML results document
-    changesets.order("created_at DESC").limit(100).each do |cs|
-      results.root << cs.to_xml_node
-    end
-
-    render :xml => results.to_s
-  end
-
-  ##
-  # updates a changeset's tags. none of the changeset's attributes are
-  # user-modifiable, so they will be ignored.
-  #
-  # changesets are not (yet?) versioned, so we don't have to deal with
-  # history tables here. changesets are locked to a single user, however.
-  #
-  # after succesful update, returns the XML of the changeset.
-  def update
-    # request *must* be a PUT.
-    assert_method :put
-
-    changeset = Changeset.find(params[:id])
-    new_changeset = Changeset.from_xml(request.raw_post)
-
-    check_changeset_consistency(changeset, current_user)
-    changeset.update_from(new_changeset, current_user)
-    render :xml => changeset.to_xml.to_s
-  end
-
   ##
   # list non-empty changesets in reverse chronological order
   def index
@@ -312,46 +73,6 @@ class ChangesetsController < ApplicationController
     index
   end
 
-  ##
-  # Adds a subscriber to the changeset
-  def subscribe
-    # Check the arguments are sane
-    raise OSM::APIBadUserInput, "No id was given" unless params[:id]
-
-    # Extract the arguments
-    id = params[:id].to_i
-
-    # Find the changeset and check it is valid
-    changeset = Changeset.find(id)
-    raise OSM::APIChangesetAlreadySubscribedError, changeset if changeset.subscribers.exists?(current_user.id)
-
-    # Add the subscriber
-    changeset.subscribers << current_user
-
-    # Return a copy of the updated changeset
-    render :xml => changeset.to_xml.to_s
-  end
-
-  ##
-  # Removes a subscriber from the changeset
-  def unsubscribe
-    # Check the arguments are sane
-    raise OSM::APIBadUserInput, "No id was given" unless params[:id]
-
-    # Extract the arguments
-    id = params[:id].to_i
-
-    # Find the changeset and check it is valid
-    changeset = Changeset.find(id)
-    raise OSM::APIChangesetNotSubscribedError, changeset unless changeset.subscribers.exists?(current_user.id)
-
-    # Remove the subscriber
-    changeset.subscribers.delete(current_user)
-
-    # Return a copy of the updated changeset
-    render :xml => changeset.to_xml.to_s
-  end
-
   private
 
   #------------------------------------------------------------
@@ -375,109 +96,6 @@ class ChangesetsController < ApplicationController
     end
   end
 
-  ##
-  # restrict changesets to those by a particular user
-  def conditions_user(changesets, user, name)
-    if user.nil? && name.nil?
-      changesets
-    else
-      # shouldn't provide both name and UID
-      raise OSM::APIBadUserInput, "provide either the user ID or display name, but not both" if user && name
-
-      # use either the name or the UID to find the user which we're selecting on.
-      u = if name.nil?
-            # user input checking, we don't have any UIDs < 1
-            raise OSM::APIBadUserInput, "invalid user ID" if user.to_i < 1
-
-            u = User.find(user.to_i)
-          else
-            u = User.find_by(:display_name => name)
-          end
-
-      # make sure we found a user
-      raise OSM::APINotFoundError if u.nil?
-
-      # should be able to get changesets of public users only, or
-      # our own changesets regardless of public-ness.
-      unless u.data_public?
-        # get optional user auth stuff so that users can see their own
-        # changesets if they're non-public
-        setup_user_auth
-
-        raise OSM::APINotFoundError if current_user.nil? || current_user != u
-      end
-
-      changesets.where(:user_id => u.id)
-    end
-  end
-
-  ##
-  # restrict changes to those closed during a particular time period
-  def conditions_time(changesets, time)
-    if time.nil?
-      changesets
-    elsif time.count(",") == 1
-      # if there is a range, i.e: comma separated, then the first is
-      # low, second is high - same as with bounding boxes.
-
-      # check that we actually have 2 elements in the array
-      times = time.split(/,/)
-      raise OSM::APIBadUserInput, "bad time range" if times.size != 2
-
-      from, to = times.collect { |t| Time.parse(t) }
-      changesets.where("closed_at >= ? and created_at <= ?", from, to)
-    else
-      # if there is no comma, assume its a lower limit on time
-      changesets.where("closed_at >= ?", Time.parse(time))
-    end
-    # stupid Time seems to throw both of these for bad parsing, so
-    # we have to catch both and ensure the correct code path is taken.
-  rescue ArgumentError => ex
-    raise OSM::APIBadUserInput, ex.message.to_s
-  rescue RuntimeError => ex
-    raise OSM::APIBadUserInput, ex.message.to_s
-  end
-
-  ##
-  # return changesets which are open (haven't been closed yet)
-  # we do this by seeing if the 'closed at' time is in the future. Also if we've
-  # hit the maximum number of changes then it counts as no longer open.
-  # if parameter 'open' is nill then open and closed changesets are returned
-  def conditions_open(changesets, open)
-    if open.nil?
-      changesets
-    else
-      changesets.where("closed_at >= ? and num_changes <= ?",
-                       Time.now.getutc, Changeset::MAX_ELEMENTS)
-    end
-  end
-
-  ##
-  # query changesets which are closed
-  # ('closed at' time has passed or changes limit is hit)
-  def conditions_closed(changesets, closed)
-    if closed.nil?
-      changesets
-    else
-      changesets.where("closed_at < ? or num_changes > ?",
-                       Time.now.getutc, Changeset::MAX_ELEMENTS)
-    end
-  end
-
-  ##
-  # query changesets by a list of ids
-  # (either specified as array or comma-separated string)
-  def conditions_ids(changesets, ids)
-    if ids.nil?
-      changesets
-    elsif ids.empty?
-      raise OSM::APIBadUserInput, "No changesets were given to search for"
-    else
-      ids = ids.split(",").collect(&:to_i)
-      changesets.where(:id => ids)
-    end
-  end
-
   ##
   # eliminate empty changesets (where the bbox has not been set)
   # this should be applied to all changeset list displays
diff --git a/app/controllers/nodes_controller.rb b/app/controllers/nodes_controller.rb
deleted file mode 100644 (file)
index 6c1d66d..0000000
+++ /dev/null
@@ -1,81 +0,0 @@
-# The NodeController is the RESTful interface to Node objects
-
-class NodesController < ApplicationController
-  require "xml/libxml"
-
-  skip_before_action :verify_authenticity_token
-  before_action :authorize, :only => [:create, :update, :delete]
-  before_action :api_deny_access_handler
-
-  authorize_resource
-
-  before_action :require_public_data, :only => [:create, :update, :delete]
-  before_action :check_api_writable, :only => [:create, :update, :delete]
-  before_action :check_api_readable, :except => [:create, :update, :delete]
-  around_action :api_call_handle_error, :api_call_timeout
-
-  # Create a node from XML.
-  def create
-    assert_method :put
-
-    node = Node.from_xml(request.raw_post, true)
-
-    # Assume that Node.from_xml has thrown an exception if there is an error parsing the xml
-    node.create_with_history current_user
-    render :plain => node.id.to_s
-  end
-
-  # Dump the details on a node given in params[:id]
-  def show
-    node = Node.find(params[:id])
-
-    response.last_modified = node.timestamp
-
-    if node.visible
-      render :xml => node.to_xml.to_s
-    else
-      head :gone
-    end
-  end
-
-  # Update a node from given XML
-  def update
-    node = Node.find(params[:id])
-    new_node = Node.from_xml(request.raw_post)
-
-    raise OSM::APIBadUserInput, "The id in the url (#{node.id}) is not the same as provided in the xml (#{new_node.id})" unless new_node && new_node.id == node.id
-
-    node.update_from(new_node, current_user)
-    render :plain => node.version.to_s
-  end
-
-  # Delete a node. Doesn't actually delete it, but retains its history
-  # in a wiki-like way. We therefore treat it like an update, so the delete
-  # method returns the new version number.
-  def delete
-    node = Node.find(params[:id])
-    new_node = Node.from_xml(request.raw_post)
-
-    raise OSM::APIBadUserInput, "The id in the url (#{node.id}) is not the same as provided in the xml (#{new_node.id})" unless new_node && new_node.id == node.id
-
-    node.delete_with_history!(new_node, current_user)
-    render :plain => node.version.to_s
-  end
-
-  # Dump the details on many nodes whose ids are given in the "nodes" parameter.
-  def index
-    raise OSM::APIBadUserInput, "The parameter nodes is required, and must be of the form nodes=id[,id[,id...]]" unless params["nodes"]
-
-    ids = params["nodes"].split(",").collect(&:to_i)
-
-    raise OSM::APIBadUserInput, "No nodes were given to search for" if ids.empty?
-
-    doc = OSM::API.new.get_xml_doc
-
-    Node.find(ids).each do |node|
-      doc.root << node.to_xml_node
-    end
-
-    render :xml => doc.to_s
-  end
-end
index 036238db1abae3c5dcc9e42dd113208e0c4a7470..54fdb28100a37a69d1896887bad5c0844d57cc67 100644 (file)
 class NotesController < ApplicationController
   layout "site", :only => [:mine]
 
-  skip_before_action :verify_authenticity_token, :except => [:mine]
   before_action :check_api_readable
-  before_action :authorize_web, :only => [:mine]
-  before_action :setup_user_auth, :only => [:create, :comment, :show]
-  before_action :authorize, :only => [:close, :reopen, :destroy]
-  before_action :api_deny_access_handler, :except => [:mine]
+  before_action :authorize_web
 
   authorize_resource
 
-  before_action :check_api_writable, :only => [:create, :comment, :close, :reopen, :destroy]
   before_action :set_locale
   around_action :api_call_handle_error, :api_call_timeout
 
-  ##
-  # Return a list of notes in a given area
-  def index
-    # Figure out the bbox - we prefer a bbox argument but also
-    # support the old, deprecated, method with four arguments
-    if params[:bbox]
-      bbox = BoundingBox.from_bbox_params(params)
-    else
-      raise OSM::APIBadUserInput, "No l was given" unless params[:l]
-      raise OSM::APIBadUserInput, "No r was given" unless params[:r]
-      raise OSM::APIBadUserInput, "No b was given" unless params[:b]
-      raise OSM::APIBadUserInput, "No t was given" unless params[:t]
-
-      bbox = BoundingBox.from_lrbt_params(params)
-    end
-
-    # Get any conditions that need to be applied
-    notes = closed_condition(Note.all)
-
-    # Check that the boundaries are valid
-    bbox.check_boundaries
-
-    # Check the the bounding box is not too big
-    bbox.check_size(MAX_NOTE_REQUEST_AREA)
-
-    # Find the notes we want to return
-    @notes = notes.bbox(bbox).order("updated_at DESC").limit(result_limit).preload(:comments)
-
-    # Render the result
-    respond_to do |format|
-      format.rss
-      format.xml
-      format.json
-      format.gpx
-    end
-  end
-
-  ##
-  # Create a new note
-  def create
-    # Check the ACLs
-    raise OSM::APIAccessDenied if current_user.nil? && Acl.no_note_comment(request.remote_ip)
-
-    # Check the arguments are sane
-    raise OSM::APIBadUserInput, "No lat was given" unless params[:lat]
-    raise OSM::APIBadUserInput, "No lon was given" unless params[:lon]
-    raise OSM::APIBadUserInput, "No text was given" if params[:text].blank?
-
-    # Extract the arguments
-    lon = OSM.parse_float(params[:lon], OSM::APIBadUserInput, "lon was not a number")
-    lat = OSM.parse_float(params[:lat], OSM::APIBadUserInput, "lat was not a number")
-    comment = params[:text]
-
-    # Include in a transaction to ensure that there is always a note_comment for every note
-    Note.transaction do
-      # Create the note
-      @note = Note.create(:lat => lat, :lon => lon)
-      raise OSM::APIBadUserInput, "The note is outside this world" unless @note.in_world?
-
-      # Save the note
-      @note.save!
-
-      # Add a comment to the note
-      add_comment(@note, comment, "opened")
-    end
-
-    # Return a copy of the new note
-    respond_to do |format|
-      format.xml { render :action => :show }
-      format.json { render :action => :show }
-    end
-  end
-
-  ##
-  # Add a comment to an existing note
-  def comment
-    # Check the ACLs
-    raise OSM::APIAccessDenied if current_user.nil? && Acl.no_note_comment(request.remote_ip)
-
-    # Check the arguments are sane
-    raise OSM::APIBadUserInput, "No id was given" unless params[:id]
-    raise OSM::APIBadUserInput, "No text was given" if params[:text].blank?
-
-    # Extract the arguments
-    id = params[:id].to_i
-    comment = params[:text]
-
-    # Find the note and check it is valid
-    @note = Note.find(id)
-    raise OSM::APINotFoundError unless @note
-    raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible?
-    raise OSM::APINoteAlreadyClosedError, @note if @note.closed?
-
-    # Add a comment to the note
-    Note.transaction do
-      add_comment(@note, comment, "commented")
-    end
-
-    # Return a copy of the updated note
-    respond_to do |format|
-      format.xml { render :action => :show }
-      format.json { render :action => :show }
-    end
-  end
-
-  ##
-  # Close a note
-  def close
-    # Check the arguments are sane
-    raise OSM::APIBadUserInput, "No id was given" unless params[:id]
-
-    # Extract the arguments
-    id = params[:id].to_i
-    comment = params[:text]
-
-    # Find the note and check it is valid
-    @note = Note.find_by(:id => id)
-    raise OSM::APINotFoundError unless @note
-    raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible?
-    raise OSM::APINoteAlreadyClosedError, @note if @note.closed?
-
-    # Close the note and add a comment
-    Note.transaction do
-      @note.close
-
-      add_comment(@note, comment, "closed")
-    end
-
-    # Return a copy of the updated note
-    respond_to do |format|
-      format.xml { render :action => :show }
-      format.json { render :action => :show }
-    end
-  end
-
-  ##
-  # Reopen a note
-  def reopen
-    # Check the arguments are sane
-    raise OSM::APIBadUserInput, "No id was given" unless params[:id]
-
-    # Extract the arguments
-    id = params[:id].to_i
-    comment = params[:text]
-
-    # Find the note and check it is valid
-    @note = Note.find_by(:id => id)
-    raise OSM::APINotFoundError unless @note
-    raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible? || current_user.moderator?
-    raise OSM::APINoteAlreadyOpenError, @note unless @note.closed? || !@note.visible?
-
-    # Reopen the note and add a comment
-    Note.transaction do
-      @note.reopen
-
-      add_comment(@note, comment, "reopened")
-    end
-
-    # Return a copy of the updated note
-    respond_to do |format|
-      format.xml { render :action => :show }
-      format.json { render :action => :show }
-    end
-  end
-
-  ##
-  # Get a feed of recent notes and comments
-  def feed
-    # Get any conditions that need to be applied
-    notes = closed_condition(Note.all)
-
-    # Process any bbox
-    if params[:bbox]
-      bbox = BoundingBox.from_bbox_params(params)
-
-      bbox.check_boundaries
-      bbox.check_size(MAX_NOTE_REQUEST_AREA)
-
-      notes = notes.bbox(bbox)
-    end
-
-    # Find the comments we want to return
-    @comments = NoteComment.where(:note_id => notes).order("created_at DESC").limit(result_limit).preload(:note)
-
-    # Render the result
-    respond_to do |format|
-      format.rss
-    end
-  end
-
-  ##
-  # Read a note
-  def show
-    # Check the arguments are sane
-    raise OSM::APIBadUserInput, "No id was given" unless params[:id]
-
-    # Find the note and check it is valid
-    @note = Note.find(params[:id])
-    raise OSM::APINotFoundError unless @note
-    raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible? || current_user&.moderator?
-
-    # Render the result
-    respond_to do |format|
-      format.xml
-      format.rss
-      format.json
-      format.gpx
-    end
-  end
-
-  ##
-  # Delete (hide) a note
-  def destroy
-    # Check the arguments are sane
-    raise OSM::APIBadUserInput, "No id was given" unless params[:id]
-
-    # Extract the arguments
-    id = params[:id].to_i
-    comment = params[:text]
-
-    # Find the note and check it is valid
-    @note = Note.find(id)
-    raise OSM::APINotFoundError unless @note
-    raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible?
-
-    # Mark the note as hidden
-    Note.transaction do
-      @note.status = "hidden"
-      @note.save
-
-      add_comment(@note, comment, "hidden", false)
-    end
-
-    # Return a copy of the updated note
-    respond_to do |format|
-      format.xml { render :action => :show }
-      format.json { render :action => :show }
-    end
-  end
-
-  ##
-  # Return a list of notes matching a given string
-  def search
-    # Get the initial set of notes
-    @notes = closed_condition(Note.all)
-
-    # Add any user filter
-    if params[:display_name] || params[:user]
-      if params[:display_name]
-        @user = User.find_by(:display_name => params[:display_name])
-
-        raise OSM::APIBadUserInput, "User #{params[:display_name]} not known" unless @user
-      else
-        @user = User.find_by(:id => params[:user])
-
-        raise OSM::APIBadUserInput, "User #{params[:user]} not known" unless @user
-      end
-
-      @notes = @notes.joins(:comments).where(:note_comments => { :author_id => @user })
-    end
-
-    # Add any text filter
-    @notes = @notes.joins(:comments).where("to_tsvector('english', note_comments.body) @@ plainto_tsquery('english', ?)", params[:q]) if params[:q]
-
-    # Add any date filter
-    if params[:from]
-      begin
-        from = Time.parse(params[:from])
-      rescue ArgumentError
-        raise OSM::APIBadUserInput, "Date #{params[:from]} is in a wrong format"
-      end
-
-      begin
-        to = if params[:to]
-               Time.parse(params[:to])
-             else
-               Time.now
-             end
-      rescue ArgumentError
-        raise OSM::APIBadUserInput, "Date #{params[:to]} is in a wrong format"
-      end
-
-      @notes = @notes.where(:created_at => from..to)
-    end
-
-    # Find the notes we want to return
-    @notes = @notes.order("updated_at DESC").limit(result_limit).preload(:comments)
-
-    # Render the result
-    respond_to do |format|
-      format.rss { render :action => :index }
-      format.xml { render :action => :index }
-      format.json { render :action => :index }
-      format.gpx { render :action => :index }
-    end
-  end
-
   ##
   # Display a list of notes by a specified user
   def mine
@@ -333,63 +31,4 @@ class NotesController < ApplicationController
       end
     end
   end
-
-  private
-
-  #------------------------------------------------------------
-  # utility functions below.
-  #------------------------------------------------------------
-
-  ##
-  # Get the maximum number of results to return
-  def result_limit
-    if params[:limit]
-      if params[:limit].to_i.positive? && params[:limit].to_i <= 10000
-        params[:limit].to_i
-      else
-        raise OSM::APIBadUserInput, "Note limit must be between 1 and 10000"
-      end
-    else
-      100
-    end
-  end
-
-  ##
-  # Generate a condition to choose which notes we want based
-  # on their status and the user's request parameters
-  def closed_condition(notes)
-    closed_since = if params[:closed]
-                     params[:closed].to_i
-                   else
-                     7
-                   end
-
-    if closed_since.negative?
-      notes.where.not(:status => "hidden")
-    elsif closed_since.positive?
-      notes.where(:status => "open")
-           .or(notes.where(:status => "closed")
-                    .where(notes.arel_table[:closed_at].gt(Time.now - closed_since.days)))
-    else
-      notes.where(:status => "open")
-    end
-  end
-
-  ##
-  # Add a comment to a note
-  def add_comment(note, text, event, notify = true)
-    attributes = { :visible => true, :event => event, :body => text }
-
-    if current_user
-      attributes[:author_id] = current_user.id
-    else
-      attributes[:author_ip] = request.remote_ip
-    end
-
-    comment = note.comments.create!(attributes)
-
-    note.comments.map(&:author).uniq.each do |user|
-      Notifier.note_comment_notification(comment, user).deliver_later if notify && user && user != current_user && user.visible?
-    end
-  end
 end
diff --git a/app/controllers/old_controller.rb b/app/controllers/old_controller.rb
deleted file mode 100644 (file)
index 74fe088..0000000
+++ /dev/null
@@ -1,77 +0,0 @@
-# this class pulls together the logic for all the old_* controllers
-# into one place. as it turns out, the API methods for historical
-# nodes, ways and relations are basically identical.
-class OldController < ApplicationController
-  require "xml/libxml"
-
-  skip_before_action :verify_authenticity_token
-  before_action :setup_user_auth, :only => [:history, :version]
-  before_action :api_deny_access_handler
-  before_action :authorize, :only => [:redact]
-
-  authorize_resource
-
-  before_action :check_api_readable
-  before_action :check_api_writable, :only => [:redact]
-  around_action :api_call_handle_error, :api_call_timeout
-  before_action :lookup_old_element, :except => [:history]
-  before_action :lookup_old_element_versions, :only => [:history]
-
-  def history
-    # the .where() method used in the lookup_old_element_versions
-    # call won't throw an error if no records are found, so we have
-    # to do that ourselves.
-    raise OSM::APINotFoundError if @elements.empty?
-
-    doc = OSM::API.new.get_xml_doc
-
-    visible_elements = if show_redactions?
-                         @elements
-                       else
-                         @elements.unredacted
-                       end
-
-    visible_elements.each do |element|
-      doc.root << element.to_xml_node
-    end
-
-    render :xml => doc.to_s
-  end
-
-  def version
-    if @old_element.redacted? && !show_redactions?
-      head :forbidden
-
-    else
-      response.last_modified = @old_element.timestamp
-
-      doc = OSM::API.new.get_xml_doc
-      doc.root << @old_element.to_xml_node
-
-      render :xml => doc.to_s
-    end
-  end
-
-  def redact
-    redaction_id = params["redaction"]
-    if redaction_id.nil?
-      # if no redaction ID was provided, then this is an unredact
-      # operation.
-      @old_element.redact!(nil)
-    else
-      # if a redaction ID was specified, then set this element to
-      # be redacted in that redaction.
-      redaction = Redaction.find(redaction_id.to_i)
-      @old_element.redact!(redaction)
-    end
-
-    # just return an empty 200 OK for success
-    head :ok
-  end
-
-  private
-
-  def show_redactions?
-    current_user&.moderator? && params[:show_redactions] == "true"
-  end
-end
diff --git a/app/controllers/old_nodes_controller.rb b/app/controllers/old_nodes_controller.rb
deleted file mode 100644 (file)
index 43c8b6b..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-class OldNodesController < OldController
-  private
-
-  def lookup_old_element
-    @old_element = OldNode.find([params[:id], params[:version]])
-  end
-
-  def lookup_old_element_versions
-    @elements = OldNode.where(:node_id => params[:id]).order(:version)
-  end
-end
diff --git a/app/controllers/old_relations_controller.rb b/app/controllers/old_relations_controller.rb
deleted file mode 100644 (file)
index 40c4503..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-class OldRelationsController < OldController
-  private
-
-  def lookup_old_element
-    @old_element = OldRelation.find([params[:id], params[:version]])
-  end
-
-  def lookup_old_element_versions
-    @elements = OldRelation.where(:relation_id => params[:id]).order(:version)
-  end
-end
diff --git a/app/controllers/old_ways_controller.rb b/app/controllers/old_ways_controller.rb
deleted file mode 100644 (file)
index c8185c6..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-class OldWaysController < OldController
-  private
-
-  def lookup_old_element
-    @old_element = OldWay.find([params[:id], params[:version]])
-  end
-
-  def lookup_old_element_versions
-    @elements = OldWay.where(:way_id => params[:id]).order(:version)
-  end
-end
diff --git a/app/controllers/relations_controller.rb b/app/controllers/relations_controller.rb
deleted file mode 100644 (file)
index 8c8005a..0000000
+++ /dev/null
@@ -1,167 +0,0 @@
-class RelationsController < ApplicationController
-  require "xml/libxml"
-
-  skip_before_action :verify_authenticity_token
-  before_action :authorize, :only => [:create, :update, :delete]
-  before_action :api_deny_access_handler
-
-  authorize_resource
-
-  before_action :require_public_data, :only => [:create, :update, :delete]
-  before_action :check_api_writable, :only => [:create, :update, :delete]
-  before_action :check_api_readable, :except => [:create, :update, :delete]
-  around_action :api_call_handle_error, :api_call_timeout
-
-  def create
-    assert_method :put
-
-    relation = Relation.from_xml(request.raw_post, true)
-
-    # Assume that Relation.from_xml has thrown an exception if there is an error parsing the xml
-    relation.create_with_history current_user
-    render :plain => relation.id.to_s
-  end
-
-  def show
-    relation = Relation.find(params[:id])
-    response.last_modified = relation.timestamp
-    if relation.visible
-      render :xml => relation.to_xml.to_s
-    else
-      head :gone
-    end
-  end
-
-  def update
-    logger.debug request.raw_post
-
-    relation = Relation.find(params[:id])
-    new_relation = Relation.from_xml(request.raw_post)
-
-    raise OSM::APIBadUserInput, "The id in the url (#{relation.id}) is not the same as provided in the xml (#{new_relation.id})" unless new_relation && new_relation.id == relation.id
-
-    relation.update_from new_relation, current_user
-    render :plain => relation.version.to_s
-  end
-
-  def delete
-    relation = Relation.find(params[:id])
-    new_relation = Relation.from_xml(request.raw_post)
-    if new_relation && new_relation.id == relation.id
-      relation.delete_with_history!(new_relation, current_user)
-      render :plain => relation.version.to_s
-    else
-      head :bad_request
-    end
-  end
-
-  # -----------------------------------------------------------------
-  # full
-  #
-  # input parameters: id
-  #
-  # returns XML representation of one relation object plus all its
-  # members, plus all nodes part of member ways
-  # -----------------------------------------------------------------
-  def full
-    relation = Relation.find(params[:id])
-
-    if relation.visible
-
-      # first find the ids of nodes, ways and relations referenced by this
-      # relation - note that we exclude this relation just in case.
-
-      node_ids = relation.members.select { |m| m[0] == "Node" }.map { |m| m[1] }
-      way_ids = relation.members.select { |m| m[0] == "Way" }.map { |m| m[1] }
-      relation_ids = relation.members.select { |m| m[0] == "Relation" && m[1] != relation.id }.map { |m| m[1] }
-
-      # next load the relations and the ways.
-
-      relations = Relation.where(:id => relation_ids).includes(:relation_tags)
-      ways = Way.where(:id => way_ids).includes(:way_nodes, :way_tags)
-
-      # now additionally collect nodes referenced by ways. Note how we
-      # recursively evaluate ways but NOT relations.
-
-      way_node_ids = ways.collect do |way|
-        way.way_nodes.collect(&:node_id)
-      end
-      node_ids += way_node_ids.flatten
-      nodes = Node.where(:id => node_ids.uniq).includes(:node_tags)
-
-      # create XML.
-      doc = OSM::API.new.get_xml_doc
-      visible_nodes = {}
-      changeset_cache = {}
-      user_display_name_cache = {}
-
-      nodes.each do |node|
-        next unless node.visible? # should be unnecessary if data is consistent.
-
-        doc.root << node.to_xml_node(changeset_cache, user_display_name_cache)
-        visible_nodes[node.id] = node
-      end
-
-      ways.each do |way|
-        next unless way.visible? # should be unnecessary if data is consistent.
-
-        doc.root << way.to_xml_node(visible_nodes, changeset_cache, user_display_name_cache)
-      end
-
-      relations.each do |rel|
-        next unless rel.visible? # should be unnecessary if data is consistent.
-
-        doc.root << rel.to_xml_node(changeset_cache, user_display_name_cache)
-      end
-
-      # finally add self and output
-      doc.root << relation.to_xml_node(changeset_cache, user_display_name_cache)
-      render :xml => doc.to_s
-
-    else
-      head :gone
-    end
-  end
-
-  def index
-    raise OSM::APIBadUserInput, "The parameter relations is required, and must be of the form relations=id[,id[,id...]]" unless params["relations"]
-
-    ids = params["relations"].split(",").collect(&:to_i)
-
-    raise OSM::APIBadUserInput, "No relations were given to search for" if ids.empty?
-
-    doc = OSM::API.new.get_xml_doc
-
-    Relation.find(ids).each do |relation|
-      doc.root << relation.to_xml_node
-    end
-
-    render :xml => doc.to_s
-  end
-
-  def relations_for_way
-    relations_for_object("Way")
-  end
-
-  def relations_for_node
-    relations_for_object("Node")
-  end
-
-  def relations_for_relation
-    relations_for_object("Relation")
-  end
-
-  private
-
-  def relations_for_object(objtype)
-    relationids = RelationMember.where(:member_type => objtype, :member_id => params[:id]).collect(&:relation_id).uniq
-
-    doc = OSM::API.new.get_xml_doc
-
-    Relation.find(relationids).each do |relation|
-      doc.root << relation.to_xml_node if relation.visible
-    end
-
-    render :xml => doc.to_s
-  end
-end
diff --git a/app/controllers/search_controller.rb b/app/controllers/search_controller.rb
deleted file mode 100644 (file)
index 3a2e404..0000000
+++ /dev/null
@@ -1,100 +0,0 @@
-class SearchController < ApplicationController
-  # Support searching for nodes, ways, or all
-  # Can search by tag k, v, or both (type->k,value->v)
-  # Can search by name (k=name,v=....)
-  skip_before_action :verify_authenticity_token
-  authorize_resource :class => false
-
-  def search_all
-    do_search(true, true, true)
-  end
-
-  def search_ways
-    do_search(true, false, false)
-  end
-
-  def search_nodes
-    do_search(false, true, false)
-  end
-
-  def search_relations
-    do_search(false, false, true)
-  end
-
-  def do_search(do_ways, do_nodes, do_relations)
-    type = params["type"]
-    value = params["value"]
-    unless type || value
-      name = params["name"]
-      if name
-        type = "name"
-        value = name
-      end
-    end
-
-    if do_nodes
-      response.headers["Error"] = "Searching of nodes is currently unavailable"
-      head :service_unavailable
-      return false
-    end
-
-    unless value
-      response.headers["Error"] = "Searching for a key without value is currently unavailable"
-      head :service_unavailable
-      return false
-    end
-
-    # Matching for node tags table
-    if do_nodes
-      nodes = Node.joins(:node_tags)
-      nodes = nodes.where(:current_node_tags => { :k => type }) if type
-      nodes = nodes.where(:current_node_tags => { :v => value }) if value
-      nodes = nodes.limit(100)
-    else
-      nodes = []
-    end
-
-    # Matching for way tags table
-    if do_ways
-      ways = Way.joins(:way_tags)
-      ways = ways.where(:current_way_tags => { :k => type }) if type
-      ways = ways.where(:current_way_tags => { :v => value }) if value
-      ways = ways.limit(100)
-    else
-      ways = []
-    end
-
-    # Matching for relation tags table
-    if do_relations
-      relations = Relation.joins(:relation_tags)
-      relations = relations.where(:current_relation_tags => { :k => type }) if type
-      relations = relations.where(:current_relation_tags => { :v => value }) if value
-      relations = relations.limit(2000)
-    else
-      relations = []
-    end
-
-    # Fetch any node needed for our ways (only have matching nodes so far)
-    nodes += Node.find(ways.collect(&:nds).uniq)
-
-    # Print
-    visible_nodes = {}
-    changeset_cache = {}
-    user_display_name_cache = {}
-    doc = OSM::API.new.get_xml_doc
-    nodes.each do |node|
-      doc.root << node.to_xml_node(changeset_cache, user_display_name_cache)
-      visible_nodes[node.id] = node
-    end
-
-    ways.each do |way|
-      doc.root << way.to_xml_node(visible_nodes, changeset_cache, user_display_name_cache)
-    end
-
-    relations.each do |rel|
-      doc.root << rel.to_xml_node(changeset_cache, user_display_name_cache)
-    end
-
-    render :xml => doc.to_s
-  end
-end
diff --git a/app/controllers/swf_controller.rb b/app/controllers/swf_controller.rb
deleted file mode 100644 (file)
index 1a424c3..0000000
+++ /dev/null
@@ -1,217 +0,0 @@
-class SwfController < ApplicationController
-  skip_before_action :verify_authenticity_token
-  before_action :check_api_readable
-  authorize_resource :class => false
-
-  # to log:
-  # RAILS_DEFAULT_LOGGER.error("Args: #{args[0]}, #{args[1]}, #{args[2]}, #{args[3]}")
-  # $log.puts Time.new.to_s+','+Time.new.usec.to_s+": started GPS script"
-  # http://localhost:3000/api/0.4/swf/trackpoints?xmin=-2.32402605810577&xmax=-2.18386309423859&ymin=52.1546608755772&ymax=52.2272777906895&baselong=-2.25325793066437&basey=61.3948537948532&masterscale=5825.4222222222
-
-  # ====================================================================
-  # Public methods
-
-  # ---- trackpoints  compile SWF of trackpoints
-
-  def trackpoints
-    # -  Initialise
-
-    baselong = params["baselong"].to_f
-    basey = params["basey"].to_f
-    masterscale = params["masterscale"].to_f
-
-    bbox = BoundingBox.new(params["xmin"], params["ymin"],
-                           params["xmax"], params["ymax"])
-    start = params["start"].to_i
-
-    # -  Begin movie
-
-    bounds_left = 0
-    bounds_right = 320 * 20
-    bounds_bottom = 0
-    bounds_top = 240 * 20
-
-    m = ""
-    m += swf_record(9, 255.chr + 155.chr + 155.chr) # Background
-    absx = 0
-    absy = 0
-    xl = yb = 9999999
-    xr = yt = -9999999
-
-    # -  Send SQL for GPS tracks
-
-    b = ""
-    lasttime = 0
-    lasttrack = lastfile = "-1"
-
-    if params["token"]
-      user = User.authenticate(:token => params[:token])
-      sql = "SELECT gps_points.latitude*0.0000001 AS lat,gps_points.longitude*0.0000001 AS lon,gpx_files.id AS fileid," + "      EXTRACT(EPOCH FROM gps_points.timestamp) AS ts, gps_points.trackid AS trackid " + " FROM gpx_files,gps_points " + "WHERE gpx_files.id=gpx_id " + "  AND gpx_files.user_id=#{user.id} " + "  AND " + OSM.sql_for_area(bbox, "gps_points.") + "  AND (gps_points.timestamp IS NOT NULL) " + "ORDER BY fileid DESC,ts " + "LIMIT 10000 OFFSET #{start}"
-    else
-      sql = "SELECT latitude*0.0000001 AS lat,longitude*0.0000001 AS lon,gpx_id AS fileid," + "      EXTRACT(EPOCH FROM timestamp) AS ts, gps_points.trackid AS trackid " + " FROM gps_points " + "WHERE " + OSM.sql_for_area(bbox, "gps_points.") + "  AND (gps_points.timestamp IS NOT NULL) " + "ORDER BY fileid DESC,ts " + "LIMIT 10000 OFFSET #{start}"
-    end
-    gpslist = ActiveRecord::Base.connection.select_all sql
-
-    # - Draw GPS trace lines
-
-    r = start_shape
-    gpslist.each do |row|
-      xs = (long2coord(row["lon"].to_f, baselong, masterscale) * 20).floor
-      ys = (lat2coord(row["lat"].to_f, basey, masterscale) * 20).floor
-      xl = [xs, xl].min
-      xr = [xs, xr].max
-      yb = [ys, yb].min
-      yt = [ys, yt].max
-      if row["ts"].to_i - lasttime > 180 || row["fileid"] != lastfile || row["trackid"] != lasttrack # or row['ts'].to_i==lasttime
-        b += start_and_move(xs, ys, "01")
-        absx = xs.floor
-        absy = ys.floor
-      end
-      b += draw_to(absx, absy, xs, ys)
-      absx = xs.floor
-      absy = ys.floor
-      lasttime = row["ts"].to_i
-      lastfile = row["fileid"]
-      lasttrack = row["trackid"]
-      r += [b.slice!(0...80)].pack("B*") while b.length > 80
-    end
-
-    #   (Unwayed segments removed)
-
-    # - Write shape
-
-    b += end_shape
-    r += [b].pack("B*")
-    m += swf_record(2, pack_u16(1) + pack_rect(xl, xr, yb, yt) + r)
-    m += swf_record(4, pack_u16(1) + pack_u16(1))
-
-    # -  Create Flash header and write to browser
-
-    m += swf_record(1, "")                                                                     # Show frame
-    m += swf_record(0, "")                                                                     # End
-
-    m = pack_rect(bounds_left, bounds_right, bounds_bottom, bounds_top) + 0.chr + 12.chr + pack_u16(1) + m
-    m = "FWS" + 6.chr + pack_u32(m.length + 8) + m
-
-    render :body => m, :content_type => "application/x-shockwave-flash"
-  end
-
-  private
-
-  # =======================================================================
-  # SWF functions
-
-  # -----------------------------------------------------------------------
-  # Line-drawing
-
-  def start_shape
-    s = 0.chr                                    # No fill styles
-    s += 2.chr                                   # Two line styles
-    s += pack_u16(0) + 0.chr + 255.chr + 255.chr # Width 5, RGB #00FFFF
-    s += pack_u16(0) + 255.chr + 0.chr + 255.chr # Width 5, RGB #FF00FF
-    s += 34.chr # 2 fill, 2 line index bits
-    s
-  end
-
-  def end_shape
-    "000000"
-  end
-
-  def start_and_move(x, y, col)
-    d = "001001"       # Line style change, moveTo
-    l = [length_sb(x), length_sb(y)].max
-    d += format("%05b%0*b%0*b", l, l, x, l, y)
-    d += col # Select line style
-    d
-  end
-
-  def draw_to(absx, absy, x, y)
-    dx = x - absx
-    dy = y - absy
-
-    # Split the line up if there's anything>16383, because
-    # that would overflow the 4 bits allowed for length
-    mstep = [dx.abs / 16383, dy.abs / 16383, 1].max.ceil
-    xstep = dx / mstep
-    ystep = dy / mstep
-    d = ""
-    1.upto(mstep).each do
-      d += draw_section(x, y, x + xstep, y + ystep)
-      x += xstep
-      y += ystep
-    end
-    d
-  end
-
-  def draw_section(x1, y1, x2, y2)
-    d = "11"                                                                                   # TypeFlag, EdgeFlag
-    dx = x2 - x1
-    dy = y2 - y1
-    l = [length_sb(dx), length_sb(dy)].max
-    d += format("%04b", l - 2)
-    d += "1"                                                                                   # GeneralLine
-    d += format("%0*b%0*b", l, dx, l, dy)
-    d
-  end
-
-  # -----------------------------------------------------------------------
-  # Specific data types
-
-  # SWF data block type
-
-  def swf_record(id, r)
-    if r.length > 62
-      # Long header: tag id, 0x3F, length
-      pack_u16((id << 6) + 0x3F) + pack_u32(r.length) + r
-    else
-      # Short header: tag id, length
-      pack_u16((id << 6) + r.length) + r
-    end
-  end
-
-  # SWF RECT type
-
-  def pack_rect(a, b, c, d)
-    l = [length_sb(a),
-         length_sb(b),
-         length_sb(c),
-         length_sb(d)].max
-    # create binary string (00111001 etc.) - 5-byte length, then bbox
-    n = format("%05b%0*b%0*b%0*b%0*b", l, l, a, l, b, l, c, l, d)
-    # pack into byte string
-    [n].pack("B*")
-  end
-
-  # -----------------------------------------------------------------------
-  # Generic pack functions
-
-  def pack_u16(n)
-    [n.floor].pack("v")
-  end
-
-  def pack_u32(n)
-    [n.floor].pack("V")
-  end
-
-  # Find number of bits required to store arbitrary-length binary
-
-  def length_sb(n)
-    Math.frexp(n + (n.zero? ? 1 : 0))[1] + 1
-  end
-
-  # ====================================================================
-  # Co-ordinate conversion
-  # (this is duplicated from amf_controller, should probably share)
-
-  def lat2coord(a, basey, masterscale)
-    -(lat2y(a) - basey) * masterscale
-  end
-
-  def long2coord(a, baselong, masterscale)
-    (a - baselong) * masterscale
-  end
-
-  def lat2y(a)
-    180 / Math::PI * Math.log(Math.tan(Math::PI / 4 + a * (Math::PI / 180) / 2))
-  end
-end
index 2e499787788373c7f209fc75970b63d52a07e4e6..b488d717aefcefc736d01568889c3b48a8ae8257 100644 (file)
@@ -1,21 +1,15 @@
 class TracesController < ApplicationController
   layout "site", :except => :georss
 
-  skip_before_action :verify_authenticity_token, :only => [:api_create, :api_read, :api_update, :api_delete, :api_data]
   before_action :authorize_web
   before_action :set_locale
-  before_action :authorize, :only => [:api_create, :api_read, :api_update, :api_delete, :api_data]
-  before_action :api_deny_access_handler, :only => [:api_create, :api_read, :api_update, :api_delete, :api_data]
 
   authorize_resource
 
-  before_action :check_database_readable, :except => [:api_read, :api_data]
-  before_action :check_database_writable, :only => [:new, :create, :edit, :delete, :api_create, :api_update, :api_delete]
-  before_action :check_api_readable, :only => [:api_read, :api_data]
-  before_action :check_api_writable, :only => [:api_create, :api_update, :api_delete]
+  before_action :check_database_readable
+  before_action :check_database_writable, :only => [:new, :create, :edit, :delete]
   before_action :offline_warning, :only => [:mine, :show]
-  before_action :offline_redirect, :only => [:new, :create, :edit, :delete, :data, :api_create, :api_delete, :api_data]
-  around_action :api_call_handle_error, :only => [:api_create, :api_read, :api_update, :api_delete, :api_data]
+  before_action :offline_redirect, :only => [:new, :create, :edit, :delete, :data]
 
   # Counts and selects pages of GPX traces for various criteria (by user, tags, public etc.).
   #  target_user - if set, specifies the user to fetch traces for.  if not set will fetch all traces
@@ -263,86 +257,6 @@ class TracesController < ApplicationController
     head :not_found
   end
 
-  def api_read
-    trace = Trace.visible.find(params[:id])
-
-    if trace.public? || trace.user == current_user
-      render :xml => trace.to_xml.to_s
-    else
-      head :forbidden
-    end
-  end
-
-  def api_update
-    trace = Trace.visible.find(params[:id])
-
-    if trace.user == current_user
-      trace.update_from_xml(request.raw_post)
-      trace.save!
-
-      head :ok
-    else
-      head :forbidden
-    end
-  end
-
-  def api_delete
-    trace = Trace.visible.find(params[:id])
-
-    if trace.user == current_user
-      trace.visible = false
-      trace.save!
-
-      head :ok
-    else
-      head :forbidden
-    end
-  end
-
-  def api_data
-    trace = Trace.visible.find(params[:id])
-
-    if trace.public? || trace.user == current_user
-      if request.format == Mime[:xml]
-        send_data(trace.xml_file.read, :filename => "#{trace.id}.xml", :type => request.format.to_s, :disposition => "attachment")
-      elsif request.format == Mime[:gpx]
-        send_data(trace.xml_file.read, :filename => "#{trace.id}.gpx", :type => request.format.to_s, :disposition => "attachment")
-      else
-        send_file(trace.trace_name, :filename => "#{trace.id}#{trace.extension_name}", :type => trace.mime_type, :disposition => "attachment")
-      end
-    else
-      head :forbidden
-    end
-  end
-
-  def api_create
-    tags = params[:tags] || ""
-    description = params[:description] || ""
-    visibility = params[:visibility]
-
-    if visibility.nil?
-      visibility = if params[:public]&.to_i&.nonzero?
-                     "public"
-                   else
-                     "private"
-                   end
-    end
-
-    if params[:file].respond_to?(:read)
-      trace = do_create(params[:file], tags, description, visibility)
-
-      if trace.id
-        render :plain => trace.id.to_s
-      elsif trace.valid?
-        head :internal_server_error
-      else
-        head :bad_request
-      end
-    else
-      head :bad_request
-    end
-  end
-
   private
 
   def do_create(file, tags, description, visibility)
diff --git a/app/controllers/user_preferences_controller.rb b/app/controllers/user_preferences_controller.rb
deleted file mode 100644 (file)
index 915c847..0000000
+++ /dev/null
@@ -1,88 +0,0 @@
-# Update and read user preferences, which are arbitrayr key/val pairs
-class UserPreferencesController < ApplicationController
-  skip_before_action :verify_authenticity_token
-  before_action :authorize
-
-  authorize_resource
-
-  around_action :api_call_handle_error
-
-  ##
-  # return all the preferences as an XML document
-  def read
-    doc = OSM::API.new.get_xml_doc
-
-    prefs = current_user.preferences
-
-    el1 = XML::Node.new "preferences"
-
-    prefs.each do |pref|
-      el1 << pref.to_xml_node
-    end
-
-    doc.root << el1
-    render :xml => doc.to_s
-  end
-
-  ##
-  # return the value for a single preference
-  def read_one
-    pref = UserPreference.find([current_user.id, params[:preference_key]])
-
-    render :plain => pref.v.to_s
-  end
-
-  # update the entire set of preferences
-  def update
-    old_preferences = current_user.preferences.each_with_object({}) do |preference, preferences|
-      preferences[preference.k] = preference
-    end
-
-    new_preferences = {}
-
-    doc = XML::Parser.string(request.raw_post, :options => XML::Parser::Options::NOERROR).parse
-
-    doc.find("//preferences/preference").each do |pt|
-      if preference = old_preferences.delete(pt["k"])
-        preference.v = pt["v"]
-      elsif new_preferences.include?(pt["k"])
-        raise OSM::APIDuplicatePreferenceError, pt["k"]
-      else
-        preference = current_user.preferences.build(:k => pt["k"], :v => pt["v"])
-      end
-
-      new_preferences[preference.k] = preference
-    end
-
-    old_preferences.each_value(&:delete)
-
-    new_preferences.each_value(&:save!)
-
-    render :plain => ""
-  end
-
-  ##
-  # update the value of a single preference
-  def update_one
-    begin
-      pref = UserPreference.find([current_user.id, params[:preference_key]])
-    rescue ActiveRecord::RecordNotFound
-      pref = UserPreference.new
-      pref.user = current_user
-      pref.k = params[:preference_key]
-    end
-
-    pref.v = request.raw_post.chomp
-    pref.save!
-
-    render :plain => ""
-  end
-
-  ##
-  # delete a single preference
-  def delete_one
-    UserPreference.find([current_user.id, params[:preference_key]]).delete
-
-    render :plain => ""
-  end
-end
index e872712c1c4ed64eaa842db6e565bc486fc62cd2..fa5b22a98951479efea3f00a4e3bb28a36a767b5 100644 (file)
@@ -1,22 +1,17 @@
 class UsersController < ApplicationController
-  layout "site", :except => [:api_details]
+  layout "site"
 
-  skip_before_action :verify_authenticity_token, :only => [:api_read, :api_users, :api_details, :api_gpx_files, :auth_success]
-  before_action :disable_terms_redirect, :only => [:terms, :save, :logout, :api_details]
-  before_action :authorize, :only => [:api_details, :api_gpx_files]
-  before_action :authorize_web, :except => [:api_read, :api_users, :api_details, :api_gpx_files]
-  before_action :set_locale, :except => [:api_read, :api_users, :api_details, :api_gpx_files]
-  before_action :api_deny_access_handler, :only => [:api_read, :api_users, :api_details, :api_gpx_files]
+  skip_before_action :verify_authenticity_token, :only => [:auth_success]
+  before_action :disable_terms_redirect, :only => [:terms, :save, :logout]
+  before_action :authorize_web
+  before_action :set_locale
 
   authorize_resource
 
   before_action :require_self, :only => [:account]
-  before_action :check_database_readable, :except => [:login, :api_read, :api_users, :api_details, :api_gpx_files]
+  before_action :check_database_readable, :except => [:login]
   before_action :check_database_writable, :only => [:new, :account, :confirm, :confirm_email, :lost_password, :reset_password, :go_public, :make_friend, :remove_friend]
-  before_action :check_api_readable, :only => [:api_read, :api_users, :api_details, :api_gpx_files]
   before_action :require_cookies, :only => [:new, :login, :confirm]
-  around_action :api_call_handle_error, :only => [:api_read, :api_users, :api_details, :api_gpx_files]
-  before_action :lookup_user_by_id, :only => [:api_read]
   before_action :lookup_user_by_name, :only => [:set_status, :delete]
   before_action :allow_thirdparty_images, :only => [:show, :account]
 
@@ -373,39 +368,6 @@ class UsersController < ApplicationController
     end
   end
 
-  def api_read
-    if @user.visible?
-      render :action => :api_read, :content_type => "text/xml"
-    else
-      head :gone
-    end
-  end
-
-  def api_details
-    @user = current_user
-    render :action => :api_read, :content_type => "text/xml"
-  end
-
-  def api_users
-    raise OSM::APIBadUserInput, "The parameter users is required, and must be of the form users=id[,id[,id...]]" unless params["users"]
-
-    ids = params["users"].split(",").collect(&:to_i)
-
-    raise OSM::APIBadUserInput, "No users were given to search for" if ids.empty?
-
-    @users = User.visible.find(ids)
-
-    render :action => :api_users, :content_type => "text/xml"
-  end
-
-  def api_gpx_files
-    doc = OSM::API.new.get_xml_doc
-    current_user.traces.reload.each do |trace|
-      doc.root << trace.to_xml_node
-    end
-    render :xml => doc.to_s
-  end
-
   def show
     @user = User.find_by(:display_name => params[:display_name])
 
@@ -752,12 +714,6 @@ class UsersController < ApplicationController
     head :forbidden if params[:display_name] != current_user.display_name
   end
 
-  ##
-  # ensure that there is a "user" instance variable
-  def lookup_user_by_id
-    @user = User.find(params[:id])
-  end
-
   ##
   # ensure that there is a "user" instance variable
   def lookup_user_by_name
diff --git a/app/controllers/ways_controller.rb b/app/controllers/ways_controller.rb
deleted file mode 100644 (file)
index caf7871..0000000
+++ /dev/null
@@ -1,118 +0,0 @@
-class WaysController < ApplicationController
-  require "xml/libxml"
-
-  skip_before_action :verify_authenticity_token
-  before_action :authorize, :only => [:create, :update, :delete]
-  before_action :api_deny_access_handler
-
-  authorize_resource
-
-  before_action :require_public_data, :only => [:create, :update, :delete]
-  before_action :check_api_writable, :only => [:create, :update, :delete]
-  before_action :check_api_readable, :except => [:create, :update, :delete]
-  around_action :api_call_handle_error, :api_call_timeout
-
-  def create
-    assert_method :put
-
-    way = Way.from_xml(request.raw_post, true)
-
-    # Assume that Way.from_xml has thrown an exception if there is an error parsing the xml
-    way.create_with_history current_user
-    render :plain => way.id.to_s
-  end
-
-  def show
-    way = Way.find(params[:id])
-
-    response.last_modified = way.timestamp
-
-    if way.visible
-      render :xml => way.to_xml.to_s
-    else
-      head :gone
-    end
-  end
-
-  def update
-    way = Way.find(params[:id])
-    new_way = Way.from_xml(request.raw_post)
-
-    unless new_way && new_way.id == way.id
-      raise OSM::APIBadUserInput, "The id in the url (#{way.id}) is not the same as provided in the xml (#{new_way.id})"
-    end
-
-    way.update_from(new_way, current_user)
-    render :plain => way.version.to_s
-  end
-
-  # This is the API call to delete a way
-  def delete
-    way = Way.find(params[:id])
-    new_way = Way.from_xml(request.raw_post)
-
-    if new_way && new_way.id == way.id
-      way.delete_with_history!(new_way, current_user)
-      render :plain => way.version.to_s
-    else
-      head :bad_request
-    end
-  end
-
-  def full
-    way = Way.includes(:nodes => :node_tags).find(params[:id])
-
-    if way.visible
-      visible_nodes = {}
-      changeset_cache = {}
-      user_display_name_cache = {}
-
-      doc = OSM::API.new.get_xml_doc
-      way.nodes.uniq.each do |node|
-        if node.visible
-          doc.root << node.to_xml_node(changeset_cache, user_display_name_cache)
-          visible_nodes[node.id] = node
-        end
-      end
-      doc.root << way.to_xml_node(visible_nodes, changeset_cache, user_display_name_cache)
-
-      render :xml => doc.to_s
-    else
-      head :gone
-    end
-  end
-
-  def index
-    unless params["ways"]
-      raise OSM::APIBadUserInput, "The parameter ways is required, and must be of the form ways=id[,id[,id...]]"
-    end
-
-    ids = params["ways"].split(",").collect(&:to_i)
-
-    raise OSM::APIBadUserInput, "No ways were given to search for" if ids.empty?
-
-    doc = OSM::API.new.get_xml_doc
-
-    Way.find(ids).each do |way|
-      doc.root << way.to_xml_node
-    end
-
-    render :xml => doc.to_s
-  end
-
-  ##
-  # returns all the ways which are currently using the node given in the
-  # :id parameter. note that this used to return deleted ways as well, but
-  # this seemed not to be the expected behaviour, so it was removed.
-  def ways_for_node
-    wayids = WayNode.where(:node_id => params[:id]).collect { |ws| ws.id[0] }.uniq
-
-    doc = OSM::API.new.get_xml_doc
-
-    Way.find(wayids).each do |way|
-      doc.root << way.to_xml_node if way.visible
-    end
-
-    render :xml => doc.to_s
-  end
-end
index 89c8cc376a24b7eadaa2b042be51e845306a9b62..4b5be42d78b8786988be869e4dc5d2b5ca3c1901 100644 (file)
@@ -18,7 +18,7 @@ module NoteHelper
     elsif author.status == "deleted"
       t("users.no_such_user.deleted")
     else
-      link_to h(author.display_name), link_options.merge(:controller => "users", :action => "show", :display_name => author.display_name)
+      link_to h(author.display_name), link_options.merge(:controller => "/users", :action => "show", :display_name => author.display_name)
     end
   end
 end
similarity index 73%
rename from app/views/notes/_note.rss.builder
rename to app/views/api/notes/_note.rss.builder
index 9c72b8a5d42c15cd2e30ca248f659852be0c922b..4dc47d158d5d12b41deae7e66e4bd5df095c5bc5 100644 (file)
@@ -2,11 +2,11 @@ xml.item do
   location = describe_location(note.lat, note.lon, 14, locale)
 
   if note.closed?
-    xml.title t("notes.rss.closed", :place => location)
+    xml.title t("api.notes.rss.closed", :place => location)
   elsif note.comments.length > 1
-    xml.title t("notes.rss.commented", :place => location)
+    xml.title t("api.notes.rss.commented", :place => location)
   else
-    xml.title t("notes.rss.opened", :place => location)
+    xml.title t("api.notes.rss.opened", :place => location)
   end
 
   xml.link browse_note_url(note)
similarity index 56%
rename from app/views/notes/feed.rss.builder
rename to app/views/api/notes/feed.rss.builder
index 4a4fb3e1a75c05bb6b1ec9340163f6cdf5a6694a..1b9e5b584ed90105b2ab4a19f090151dbeb9cba1 100644 (file)
@@ -5,18 +5,18 @@ xml.rss("version" => "2.0",
         "xmlns:geo" => "http://www.w3.org/2003/01/geo/wgs84_pos#",
         "xmlns:georss" => "http://www.georss.org/georss") do
   xml.channel do
-    xml.title t("notes.rss.title")
-    xml.description t("notes.rss.description_area", :min_lat => @min_lat, :min_lon => @min_lon, :max_lat => @max_lat, :max_lon => @max_lon)
-    xml.link url_for(:controller => "site", :action => "index", :only_path => false)
+    xml.title t("api.notes.rss.title")
+    xml.description t("api.notes.rss.description_area", :min_lat => @min_lat, :min_lon => @min_lon, :max_lat => @max_lat, :max_lon => @max_lon)
+    xml.link url_for(:controller => "/site", :action => "index", :only_path => false)
 
     @comments.each do |comment|
       location = describe_location(comment.note.lat, comment.note.lon, 14, locale)
 
       xml.item do
-        xml.title t("notes.rss.#{comment.event}", :place => location)
+        xml.title t("api.notes.rss.#{comment.event}", :place => location)
 
-        xml.link url_for(:controller => "browse", :action => "note", :id => comment.note.id, :anchor => "c#{comment.id}", :only_path => false)
-        xml.guid url_for(:controller => "browse", :action => "note", :id => comment.note.id, :anchor => "c#{comment.id}", :only_path => false)
+        xml.link url_for(:controller => "/browse", :action => "note", :id => comment.note.id, :anchor => "c#{comment.id}", :only_path => false)
+        xml.guid url_for(:controller => "/browse", :action => "note", :id => comment.note.id, :anchor => "c#{comment.id}", :only_path => false)
 
         xml.description do
           xml.cdata! render(:partial => "entry", :object => comment, :formats => [:html])
similarity index 54%
rename from app/views/notes/index.rss.builder
rename to app/views/api/notes/index.rss.builder
index d28efa1942da01a918fb9f38cea6b508b3f2eae5..96ba4b73412cb5ddc3bd496ce01b442607150d0c 100644 (file)
@@ -5,9 +5,9 @@ xml.rss("version" => "2.0",
         "xmlns:geo" => "http://www.w3.org/2003/01/geo/wgs84_pos#",
         "xmlns:georss" => "http://www.georss.org/georss") do
   xml.channel do
-    xml.title t("notes.rss.title")
-    xml.description t("notes.rss.description_area", :min_lat => @min_lat, :min_lon => @min_lon, :max_lat => @max_lat, :max_lon => @max_lon)
-    xml.link url_for(:controller => "site", :action => "index", :only_path => false)
+    xml.title t("api.notes.rss.title")
+    xml.description t("api.notes.rss.description_area", :min_lat => @min_lat, :min_lon => @min_lon, :max_lat => @max_lat, :max_lon => @max_lon)
+    xml.link url_for(:controller => "/site", :action => "index", :only_path => false)
 
     xml << (render(:partial => "note", :collection => @notes) || "")
   end
similarity index 56%
rename from app/views/notes/show.rss.builder
rename to app/views/api/notes/show.rss.builder
index f406479008471afa2eaeaba5ad3a516afb84e1a0..61ee0857a456562052e1186f75d53ed10e81f8df 100644 (file)
@@ -4,9 +4,9 @@ xml.rss("version" => "2.0",
         "xmlns:geo" => "http://www.w3.org/2003/01/geo/wgs84_pos#",
         "xmlns:georss" => "http://www.georss.org/georss") do
   xml.channel do
-    xml.title t("notes.rss.title")
-    xml.description t("notes.rss.description_item", :id => @note.id)
-    xml.link url_for(:controller => "site", :action => "index", :only_path => false)
+    xml.title t("api.notes.rss.title")
+    xml.description t("api.notes.rss.description_item", :id => @note.id)
+    xml.link url_for(:controller => "/site", :action => "index", :only_path => false)
 
     xml << render(:partial => "note", :object => @note)
   end
index 0b73fa083d62bdaea53a90148abc799b4eab448d..1328461d77c0e3c574061f80b195f959775dacc5 100644 (file)
 <% end %>
 
 <div class='secondary-actions'>
-  <%= link_to(t('.changesetxml'), :controller => "changesets", :action => "show") %>
+  <%= link_to(t('.changesetxml'), :controller => "api/changesets", :action => "show") %>
   &middot;
-  <%= link_to(t('.osmchangexml'), :controller => "changesets", :action => "download") %>
+  <%= link_to(t('.osmchangexml'), :controller => "api/changesets", :action => "download") %>
 </div>
index 5674f21b08af018a16be415be697abb45fee47d6..d21d8d0c2b3d513d0b13af3d792fb87e62cef75a 100644 (file)
@@ -8,7 +8,7 @@
 <%= render :partial => @type, :object => @feature %>
 
 <div class='secondary-actions'>
-  <%= link_to(t('browse.download_xml'), :controller => @type.pluralize, :action => :show) %>
+  <%= link_to(t('browse.download_xml'), :controller => "api/#{@type.pluralize}", :action => :show) %>
   &middot;
   <%= link_to(t('browse.view_history'), :action => "#{@type}_history") %>
 </div>
index 6cf0a35698fc6e8eadcdf9337a54692a0dc9665b..b7de0093a2a2565503b05f388a22893155a479f8 100644 (file)
@@ -8,7 +8,7 @@
 <%= render :partial => @type, :collection => @feature.send("old_#{@type}s").reverse %>
 
 <div class='secondary-actions'>
-  <%= link_to(t('browse.download_xml'), :controller => "old_#{@type.pluralize}", :action => "history") %>
+  <%= link_to(t('browse.download_xml'), :controller => "api/old_#{@type.pluralize}", :action => "history") %>
   &middot;
   <%= link_to(t('browse.view_details'), :action => @type) %>
 </div>
index 577efd1743eaea53b8e412a6aeb17c6c3dcc9dc2..1d51c2d15745540f540801d58326d3d7ab034050 100644 (file)
@@ -98,6 +98,28 @@ en:
     remote:
       name: "Remote Control"
       description: "Remote Control (JOSM or Merkaartor)"
+  api:
+    notes:
+      comment:
+        opened_at_html: "Created %{when} ago"
+        opened_at_by_html: "Created %{when} ago by %{user}"
+        commented_at_html: "Updated %{when} ago"
+        commented_at_by_html: "Updated %{when} ago by %{user}"
+        closed_at_html: "Resolved %{when} ago"
+        closed_at_by_html: "Resolved %{when} ago by %{user}"
+        reopened_at_html: "Reactivated %{when} ago"
+        reopened_at_by_html: "Reactivated %{when} ago by %{user}"
+      rss:
+        title: "OpenStreetMap Notes"
+        description_area: "A list of notes, reported, commented on or closed in your area [(%{min_lat}|%{min_lon}) -- (%{max_lat}|%{max_lon})]"
+        description_item: "An rss feed for note %{id}"
+        opened: "new note (near %{place})"
+        commented: "new comment (near %{place})"
+        closed: "closed note (near %{place})"
+        reopened: "reactivated note (near %{place})"
+      entry:
+        comment: Comment
+        full: Full note
   browse:
     created: "Created"
     closed: "Closed"
@@ -2331,26 +2353,6 @@ en:
       next: "Next Â»"
       previous: "« Previous"
   notes:
-    comment:
-      opened_at_html: "Created %{when} ago"
-      opened_at_by_html: "Created %{when} ago by %{user}"
-      commented_at_html: "Updated %{when} ago"
-      commented_at_by_html: "Updated %{when} ago by %{user}"
-      closed_at_html: "Resolved %{when} ago"
-      closed_at_by_html: "Resolved %{when} ago by %{user}"
-      reopened_at_html: "Reactivated %{when} ago"
-      reopened_at_by_html: "Reactivated %{when} ago by %{user}"
-    rss:
-      title: "OpenStreetMap Notes"
-      description_area: "A list of notes, reported, commented on or closed in your area [(%{min_lat}|%{min_lon}) -- (%{max_lat}|%{max_lon})]"
-      description_item: "An rss feed for note %{id}"
-      opened: "new note (near %{place})"
-      commented: "new comment (near %{place})"
-      closed: "closed note (near %{place})"
-      reopened: "reactivated note (near %{place})"
-    entry:
-      comment: Comment
-      full: Full note
     mine:
       title: "Notes submitted or commented on by %{user}"
       heading: "%{user}'s notes"
index 3c0cf61f1587c6050109bf54bf8452f9d5b760e3..32cd397aadd8e3e68f16cdd295b5608c2a0207a2 100644 (file)
@@ -8,52 +8,52 @@ OpenStreetMap::Application.routes.draw do
     get "capabilities" => "api/capabilities#show"
     get "permissions" => "api/permissions#show"
 
-    put "changeset/create" => "changesets#create"
-    post "changeset/:id/upload" => "changesets#upload", :id => /\d+/
-    get "changeset/:id/download" => "changesets#download", :as => :changeset_download, :id => /\d+/
-    post "changeset/:id/expand_bbox" => "changesets#expand_bbox", :id => /\d+/
-    get "changeset/:id" => "changesets#show", :as => :changeset_show, :id => /\d+/
-    post "changeset/:id/subscribe" => "changesets#subscribe", :as => :changeset_subscribe, :id => /\d+/
-    post "changeset/:id/unsubscribe" => "changesets#unsubscribe", :as => :changeset_unsubscribe, :id => /\d+/
-    put "changeset/:id" => "changesets#update", :id => /\d+/
-    put "changeset/:id/close" => "changesets#close", :id => /\d+/
-    get "changesets" => "changesets#query"
-    post "changeset/:id/comment" => "changeset_comments#create", :as => :changeset_comment, :id => /\d+/
-    post "changeset/comment/:id/hide" => "changeset_comments#destroy", :as => :changeset_comment_hide, :id => /\d+/
-    post "changeset/comment/:id/unhide" => "changeset_comments#restore", :as => :changeset_comment_unhide, :id => /\d+/
-
-    put "node/create" => "nodes#create"
-    get "node/:id/ways" => "ways#ways_for_node", :id => /\d+/
-    get "node/:id/relations" => "relations#relations_for_node", :id => /\d+/
-    get "node/:id/history" => "old_nodes#history", :id => /\d+/
-    post "node/:id/:version/redact" => "old_nodes#redact", :version => /\d+/, :id => /\d+/
-    get "node/:id/:version" => "old_nodes#version", :id => /\d+/, :version => /\d+/
-    get "node/:id" => "nodes#show", :id => /\d+/
-    put "node/:id" => "nodes#update", :id => /\d+/
-    delete "node/:id" => "nodes#delete", :id => /\d+/
-    get "nodes" => "nodes#index"
-
-    put "way/create" => "ways#create"
-    get "way/:id/history" => "old_ways#history", :id => /\d+/
-    get "way/:id/full" => "ways#full", :id => /\d+/
-    get "way/:id/relations" => "relations#relations_for_way", :id => /\d+/
-    post "way/:id/:version/redact" => "old_ways#redact", :version => /\d+/, :id => /\d+/
-    get "way/:id/:version" => "old_ways#version", :id => /\d+/, :version => /\d+/
-    get "way/:id" => "ways#show", :id => /\d+/
-    put "way/:id" => "ways#update", :id => /\d+/
-    delete "way/:id" => "ways#delete", :id => /\d+/
-    get "ways" => "ways#index"
-
-    put "relation/create" => "relations#create"
-    get "relation/:id/relations" => "relations#relations_for_relation", :id => /\d+/
-    get "relation/:id/history" => "old_relations#history", :id => /\d+/
-    get "relation/:id/full" => "relations#full", :id => /\d+/
-    post "relation/:id/:version/redact" => "old_relations#redact", :version => /\d+/, :id => /\d+/
-    get "relation/:id/:version" => "old_relations#version", :id => /\d+/, :version => /\d+/
-    get "relation/:id" => "relations#show", :id => /\d+/
-    put "relation/:id" => "relations#update", :id => /\d+/
-    delete "relation/:id" => "relations#delete", :id => /\d+/
-    get "relations" => "relations#index"
+    put "changeset/create" => "api/changesets#create"
+    post "changeset/:id/upload" => "api/changesets#upload", :id => /\d+/
+    get "changeset/:id/download" => "api/changesets#download", :as => :changeset_download, :id => /\d+/
+    post "changeset/:id/expand_bbox" => "api/changesets#expand_bbox", :id => /\d+/
+    get "changeset/:id" => "api/changesets#show", :as => :changeset_show, :id => /\d+/
+    post "changeset/:id/subscribe" => "api/changesets#subscribe", :as => :changeset_subscribe, :id => /\d+/
+    post "changeset/:id/unsubscribe" => "api/changesets#unsubscribe", :as => :changeset_unsubscribe, :id => /\d+/
+    put "changeset/:id" => "api/changesets#update", :id => /\d+/
+    put "changeset/:id/close" => "api/changesets#close", :id => /\d+/
+    get "changesets" => "api/changesets#query"
+    post "changeset/:id/comment" => "api/changeset_comments#create", :as => :changeset_comment, :id => /\d+/
+    post "changeset/comment/:id/hide" => "api/changeset_comments#destroy", :as => :changeset_comment_hide, :id => /\d+/
+    post "changeset/comment/:id/unhide" => "api/changeset_comments#restore", :as => :changeset_comment_unhide, :id => /\d+/
+
+    put "node/create" => "api/nodes#create"
+    get "node/:id/ways" => "api/ways#ways_for_node", :id => /\d+/
+    get "node/:id/relations" => "api/relations#relations_for_node", :id => /\d+/
+    get "node/:id/history" => "api/old_nodes#history", :id => /\d+/
+    post "node/:id/:version/redact" => "api/old_nodes#redact", :version => /\d+/, :id => /\d+/
+    get "node/:id/:version" => "api/old_nodes#version", :id => /\d+/, :version => /\d+/
+    get "node/:id" => "api/nodes#show", :id => /\d+/
+    put "node/:id" => "api/nodes#update", :id => /\d+/
+    delete "node/:id" => "api/nodes#delete", :id => /\d+/
+    get "nodes" => "api/nodes#index"
+
+    put "way/create" => "api/ways#create"
+    get "way/:id/history" => "api/old_ways#history", :id => /\d+/
+    get "way/:id/full" => "api/ways#full", :id => /\d+/
+    get "way/:id/relations" => "api/relations#relations_for_way", :id => /\d+/
+    post "way/:id/:version/redact" => "api/old_ways#redact", :version => /\d+/, :id => /\d+/
+    get "way/:id/:version" => "api/old_ways#version", :id => /\d+/, :version => /\d+/
+    get "way/:id" => "api/ways#show", :id => /\d+/
+    put "way/:id" => "api/ways#update", :id => /\d+/
+    delete "way/:id" => "api/ways#delete", :id => /\d+/
+    get "ways" => "api/ways#index"
+
+    put "relation/create" => "api/relations#create"
+    get "relation/:id/relations" => "api/relations#relations_for_relation", :id => /\d+/
+    get "relation/:id/history" => "api/old_relations#history", :id => /\d+/
+    get "relation/:id/full" => "api/relations#full", :id => /\d+/
+    post "relation/:id/:version/redact" => "api/old_relations#redact", :version => /\d+/, :id => /\d+/
+    get "relation/:id/:version" => "api/old_relations#version", :id => /\d+/, :version => /\d+/
+    get "relation/:id" => "api/relations#show", :id => /\d+/
+    put "relation/:id" => "api/relations#update", :id => /\d+/
+    delete "relation/:id" => "api/relations#delete", :id => /\d+/
+    get "relations" => "api/relations#index"
 
     get "map" => "api/map#index"
 
@@ -61,36 +61,36 @@ OpenStreetMap::Application.routes.draw do
 
     get "changes" => "api/changes#index"
 
-    get "search" => "search#search_all", :as => "api_search"
-    get "ways/search" => "search#search_ways"
-    get "relations/search" => "search#search_relations"
-    get "nodes/search" => "search#search_nodes"
-
-    get "user/:id" => "users#api_read", :id => /\d+/
-    get "user/details" => "users#api_details"
-    get "user/gpx_files" => "users#api_gpx_files"
-    get "users" => "users#api_users", :as => :api_users
-
-    get "user/preferences" => "user_preferences#read"
-    get "user/preferences/:preference_key" => "user_preferences#read_one"
-    put "user/preferences" => "user_preferences#update"
-    put "user/preferences/:preference_key" => "user_preferences#update_one"
-    delete "user/preferences/:preference_key" => "user_preferences#delete_one"
-
-    post "gpx/create" => "traces#api_create"
-    get "gpx/:id" => "traces#api_read", :id => /\d+/
-    put "gpx/:id" => "traces#api_update", :id => /\d+/
-    delete "gpx/:id" => "traces#api_delete", :id => /\d+/
-    get "gpx/:id/details" => "traces#api_read", :id => /\d+/
-    get "gpx/:id/data" => "traces#api_data"
+    get "search" => "api/search#search_all", :as => "api_search"
+    get "ways/search" => "api/search#search_ways"
+    get "relations/search" => "api/search#search_relations"
+    get "nodes/search" => "api/search#search_nodes"
+
+    get "user/:id" => "api/users#api_read", :id => /\d+/
+    get "user/details" => "api/users#api_details"
+    get "user/gpx_files" => "api/users#api_gpx_files"
+    get "users" => "api/users#api_users", :as => :api_users
+
+    get "user/preferences" => "api/user_preferences#read"
+    get "user/preferences/:preference_key" => "api/user_preferences#read_one"
+    put "user/preferences" => "api/user_preferences#update"
+    put "user/preferences/:preference_key" => "api/user_preferences#update_one"
+    delete "user/preferences/:preference_key" => "api/user_preferences#delete_one"
+
+    post "gpx/create" => "api/traces#api_create"
+    get "gpx/:id" => "api/traces#api_read", :id => /\d+/
+    put "gpx/:id" => "api/traces#api_update", :id => /\d+/
+    delete "gpx/:id" => "api/traces#api_delete", :id => /\d+/
+    get "gpx/:id/details" => "api/traces#api_read", :id => /\d+/
+    get "gpx/:id/data" => "api/traces#api_data"
 
     # AMF (ActionScript) API
-    post "amf/read" => "amf#amf_read"
-    post "amf/write" => "amf#amf_write"
-    get "swf/trackpoints" => "swf#trackpoints"
+    post "amf/read" => "api/amf#amf_read"
+    post "amf/write" => "api/amf#amf_write"
+    get "swf/trackpoints" => "api/swf#trackpoints"
 
     # Map notes API
-    resources :notes, :except => [:new, :edit, :update], :constraints => { :id => /\d+/ }, :defaults => { :format => "xml" } do
+    resources :notes, :except => [:new, :edit, :update], :constraints => { :id => /\d+/ }, :defaults => { :format => "xml" }, :controller => "api/notes" do
       collection do
         get "search"
         get "feed", :defaults => { :format => "rss" }
@@ -103,11 +103,11 @@ OpenStreetMap::Application.routes.draw do
       end
     end
 
-    post "notes/addPOIexec" => "notes#create"
-    post "notes/closePOIexec" => "notes#close"
-    post "notes/editPOIexec" => "notes#comment"
-    get "notes/getGPX" => "notes#index", :format => "gpx"
-    get "notes/getRSSfeed" => "notes#feed", :format => "rss"
+    post "notes/addPOIexec" => "api/notes#create"
+    post "notes/closePOIexec" => "api/notes#close"
+    post "notes/editPOIexec" => "api/notes#comment"
+    get "notes/getGPX" => "api/notes#index", :format => "gpx"
+    get "notes/getRSSfeed" => "api/notes#feed", :format => "rss"
   end
 
   # Data browsing
diff --git a/test/controllers/amf_controller_test.rb b/test/controllers/amf_controller_test.rb
deleted file mode 100644 (file)
index 0fb20fa..0000000
+++ /dev/null
@@ -1,1463 +0,0 @@
-require "test_helper"
-
-class AmfControllerTest < ActionController::TestCase
-  include Potlatch
-
-  ##
-  # test all routes which lead to this controller
-  def test_routes
-    assert_routing(
-      { :path => "/api/0.6/amf/read", :method => :post },
-      { :controller => "amf", :action => "amf_read" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/amf/write", :method => :post },
-      { :controller => "amf", :action => "amf_write" }
-    )
-  end
-
-  def test_getpresets
-    user_en_de = create(:user, :languages => %w[en de])
-    user_de = create(:user, :languages => %w[de])
-    [user_en_de, user_de].each do |user|
-      post :amf_read, :body => amf_content("getpresets", "/1", ["#{user.email}:test", ""])
-      assert_response :success
-      amf_parse_response
-      presets = amf_result("/1")
-
-      assert_equal 15, presets.length
-      assert_equal POTLATCH_PRESETS[0], presets[0]
-      assert_equal POTLATCH_PRESETS[1], presets[1]
-      assert_equal POTLATCH_PRESETS[2], presets[2]
-      assert_equal POTLATCH_PRESETS[3], presets[3]
-      assert_equal POTLATCH_PRESETS[4], presets[4]
-      assert_equal POTLATCH_PRESETS[5], presets[5]
-      assert_equal POTLATCH_PRESETS[6], presets[6]
-      assert_equal POTLATCH_PRESETS[7], presets[7]
-      assert_equal POTLATCH_PRESETS[8], presets[8]
-      assert_equal POTLATCH_PRESETS[9], presets[9]
-      assert_equal POTLATCH_PRESETS[10], presets[10]
-      assert_equal POTLATCH_PRESETS[12], presets[12]
-      assert_equal user.languages.first, presets[13]["__potlatch_locale"]
-    end
-  end
-
-  def test_getway
-    # check a visible way
-    way = create(:way_with_nodes, :nodes_count => 1)
-    node = way.nodes.first
-    user = way.changeset.user
-
-    post :amf_read, :body => amf_content("getway", "/1", [way.id])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-    assert_equal way.id, result[2]
-    assert_equal 1, result[3].length
-    assert_equal node.id, result[3][0][2]
-    assert_equal way.version, result[5]
-    assert_equal user.id, result[6]
-  end
-
-  def test_getway_invisible
-    # check an invisible way
-    id = create(:way, :deleted).id
-
-    post :amf_read, :body => amf_content("getway", "/1", [id])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-    assert_equal(-4, result[0])
-    assert_equal "way", result[1]
-    assert_equal id, result[2]
-    assert(result[3].nil? && result[4].nil? && result[5].nil? && result[6].nil?)
-  end
-
-  def test_getway_with_versions
-    # check a way with multiple versions
-    way = create(:way, :with_history, :version => 4)
-    create(:way_node, :way => way)
-    node = way.nodes.first
-    user = way.changeset.user
-
-    post :amf_read, :body => amf_content("getway", "/1", [way.id])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-    assert_equal way.id, result[2]
-    assert_equal 1, result[3].length
-    assert_equal node.id, result[3][0][2]
-    assert_equal way.version, result[5]
-    assert_equal user.id, result[6]
-  end
-
-  def test_getway_with_duplicate_nodes
-    # check a way with duplicate nodes
-    way = create(:way)
-    node = create(:node)
-    create(:way_node, :way => way, :node => node, :sequence_id => 1)
-    create(:way_node, :way => way, :node => node, :sequence_id => 2)
-    user = way.changeset.user
-
-    post :amf_read, :body => amf_content("getway", "/1", [way.id])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-    assert_equal way.id, result[2]
-    assert_equal 2, result[3].length
-    assert_equal node.id, result[3][0][2]
-    assert_equal node.id, result[3][1][2]
-    assert_equal way.version, result[5]
-    assert_equal user.id, result[6]
-  end
-
-  def test_getway_with_multiple_nodes
-    # check a way with multiple nodes
-    way = create(:way_with_nodes, :nodes_count => 3)
-    a = way.nodes[0].id
-    b = way.nodes[1].id
-    c = way.nodes[2].id
-    user = way.changeset.user
-
-    post :amf_read, :body => amf_content("getway", "/1", [way.id])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-    assert_equal way.id, result[2]
-    assert_equal 3, result[3].length
-    assert_equal a, result[3][0][2]
-    assert_equal b, result[3][1][2]
-    assert_equal c, result[3][2][2]
-    assert_equal way.version, result[5]
-    assert_equal user.id, result[6]
-  end
-
-  def test_getway_nonexistent
-    # check chat a non-existent way is not returned
-    post :amf_read, :body => amf_content("getway", "/1", [0])
-    assert_response :success
-    amf_parse_response
-    way = amf_result("/1")
-    assert_equal(-4, way[0])
-    assert_equal "way", way[1]
-    assert_equal 0, way[2]
-    assert(way[3].nil?) && way[4].nil? && way[5].nil? && way[6].nil?
-  end
-
-  def test_whichways
-    node = create(:node, :lat => 3.0, :lon => 3.0)
-    way = create(:way)
-    deleted_way = create(:way, :deleted)
-    create(:way_node, :way => way, :node => node)
-    create(:way_node, :way => deleted_way, :node => node)
-    create(:way_tag, :way => way)
-
-    minlon = node.lon - 0.1
-    minlat = node.lat - 0.1
-    maxlon = node.lon + 0.1
-    maxlat = node.lat + 0.1
-    post :amf_read, :body => amf_content("whichways", "/1", [minlon, minlat, maxlon, maxlat])
-    assert_response :success
-    amf_parse_response
-
-    # check contents of message
-    map = amf_result "/1"
-    assert_equal 0, map[0], "map error code should be 0"
-    assert_equal "", map[1], "map error text should be empty"
-
-    # check the formatting of the message
-    assert_equal 5, map.length, "map should have length 5"
-    assert_equal Array, map[2].class, 'map "ways" element should be an array'
-    assert_equal Array, map[3].class, 'map "nodes" element should be an array'
-    assert_equal Array, map[4].class, 'map "relations" element should be an array'
-    map[2].each do |w|
-      assert_equal 2, w.length, "way should be (id, version) pair"
-      assert w[0] == w[0].floor, "way ID should be an integer"
-      assert w[1] == w[1].floor, "way version should be an integer"
-    end
-
-    map[3].each do |n|
-      assert_equal 5, w.length, "node should be (id, lat, lon, [tags], version) tuple"
-      assert n[0] == n[0].floor, "node ID should be an integer"
-      assert n[1] >= minlat - 0.01, "node lat should be greater than min"
-      assert n[1] <= maxlat - 0.01, "node lat should be less than max"
-      assert n[2] >= minlon - 0.01, "node lon should be greater than min"
-      assert n[2] <= maxlon - 0.01, "node lon should be less than max"
-      assert_equal Array, a[3].class, "node tags should be array"
-      assert n[4] == n[4].floor, "node version should be an integer"
-    end
-
-    map[4].each do |r|
-      assert_equal 2, r.length, "relation should be (id, version) pair"
-      assert r[0] == r[0].floor, "relation ID should be an integer"
-      assert r[1] == r[1].floor, "relation version should be an integer"
-    end
-
-    # TODO: looks like amf_controller changed since this test was written
-    # so someone who knows what they're doing should check this!
-    ways = map[2].collect { |x| x[0] }
-    assert ways.include?(way.id),
-           "map should include used way"
-    assert_not ways.include?(deleted_way.id),
-               "map should not include deleted way"
-  end
-
-  ##
-  # checks that too-large a bounding box will not be served.
-  def test_whichways_toobig
-    bbox = [-0.1, -0.1, 1.1, 1.1]
-    check_bboxes_are_bad [bbox] do |map, _bbox|
-      assert_boundary_error map, " The server said: The maximum bbox size is 0.25, and your request was too large. Either request a smaller area, or use planet.osm"
-    end
-  end
-
-  ##
-  # checks that an invalid bounding box will not be served. in this case
-  # one with max < min latitudes.
-  #
-  # NOTE: the controller expands the bbox by 0.01 in each direction!
-  def test_whichways_badlat
-    bboxes = [[0, 0.1, 0.1, 0], [-0.1, 80, 0.1, 70], [0.24, 54.35, 0.25, 54.33]]
-    check_bboxes_are_bad bboxes do |map, bbox|
-      assert_boundary_error map, " The server said: The minimum latitude must be less than the maximum latitude, but it wasn't", bbox.inspect
-    end
-  end
-
-  ##
-  # same as test_whichways_badlat, but for longitudes
-  #
-  # NOTE: the controller expands the bbox by 0.01 in each direction!
-  def test_whichways_badlon
-    bboxes = [[80, -0.1, 70, 0.1], [54.35, 0.24, 54.33, 0.25]]
-    check_bboxes_are_bad bboxes do |map, bbox|
-      assert_boundary_error map, " The server said: The minimum longitude must be less than the maximum longitude, but it wasn't", bbox.inspect
-    end
-  end
-
-  def test_whichways_deleted
-    node = create(:node, :with_history, :lat => 24.0, :lon => 24.0)
-    way = create(:way, :with_history)
-    way_v1 = way.old_ways.find_by(:version => 1)
-    deleted_way = create(:way, :with_history, :deleted)
-    deleted_way_v1 = deleted_way.old_ways.find_by(:version => 1)
-    create(:way_node, :way => way, :node => node)
-    create(:way_node, :way => deleted_way, :node => node)
-    create(:old_way_node, :old_way => way_v1, :node => node)
-    create(:old_way_node, :old_way => deleted_way_v1, :node => node)
-
-    minlon = node.lon - 0.1
-    minlat = node.lat - 0.1
-    maxlon = node.lon + 0.1
-    maxlat = node.lat + 0.1
-    post :amf_read, :body => amf_content("whichways_deleted", "/1", [minlon, minlat, maxlon, maxlat])
-    assert_response :success
-    amf_parse_response
-
-    # check contents of message
-    map = amf_result "/1"
-    assert_equal 0, map[0], "first map element should be 0"
-    assert_equal "", map[1], "second map element should be an empty string"
-    assert_equal Array, map[2].class, "third map element should be an array"
-    # TODO: looks like amf_controller changed since this test was written
-    # so someone who knows what they're doing should check this!
-    assert_not map[2].include?(way.id),
-               "map should not include visible way"
-    assert map[2].include?(deleted_way.id),
-           "map should include deleted way"
-  end
-
-  def test_whichways_deleted_toobig
-    bbox = [-0.1, -0.1, 1.1, 1.1]
-    post :amf_read, :body => amf_content("whichways_deleted", "/1", bbox)
-    assert_response :success
-    amf_parse_response
-
-    map = amf_result "/1"
-    assert_deleted_boundary_error map, " The server said: The maximum bbox size is 0.25, and your request was too large. Either request a smaller area, or use planet.osm"
-  end
-
-  def test_getrelation
-    id = create(:relation).id
-    post :amf_read, :body => amf_content("getrelation", "/1", [id])
-    assert_response :success
-    amf_parse_response
-    rel = amf_result("/1")
-    assert_equal rel[0], 0
-    assert_equal rel[2], id
-  end
-
-  def test_getrelation_invisible
-    id = create(:relation, :deleted).id
-    post :amf_read, :body => amf_content("getrelation", "/1", [id])
-    assert_response :success
-    amf_parse_response
-    rel = amf_result("/1")
-    assert_equal rel[0], -4
-    assert_equal rel[1], "relation"
-    assert_equal rel[2], id
-    assert(rel[3].nil?) && rel[4].nil?
-  end
-
-  def test_getrelation_nonexistent
-    id = 0
-    post :amf_read, :body => amf_content("getrelation", "/1", [id])
-    assert_response :success
-    amf_parse_response
-    rel = amf_result("/1")
-    assert_equal rel[0], -4
-    assert_equal rel[1], "relation"
-    assert_equal rel[2], id
-    assert(rel[3].nil?) && rel[4].nil?
-  end
-
-  def test_getway_old
-    latest = create(:way, :version => 2)
-    v1 = create(:old_way, :current_way => latest, :version => 1, :timestamp => Time.now.utc - 2.minutes)
-    _v2 = create(:old_way, :current_way => latest, :version => 2, :timestamp => Time.now.utc - 1.minute)
-
-    # try to get the last visible version (specified by <0) (should be current version)
-    # NOTE: looks from the API changes that this now expects a timestamp
-    # instead of a version number...
-    # try to get version 1
-    { latest.id => "",
-      v1.way_id => (v1.timestamp + 1).strftime("%d %b %Y, %H:%M:%S") }.each do |id, t|
-      post :amf_read, :body => amf_content("getway_old", "/1", [id, t])
-      assert_response :success
-      amf_parse_response
-      returned_way = amf_result("/1")
-      assert_equal 0, returned_way[0]
-      assert_equal id, returned_way[2]
-      # API returns the *latest* version, even for old ways...
-      assert_equal latest.version, returned_way[5]
-    end
-  end
-
-  ##
-  # test that the server doesn't fall over when rubbish is passed
-  # into the method args.
-  def test_getway_old_invalid
-    way_id = create(:way, :with_history, :version => 2).id
-    { "foo" => "bar",
-      way_id => "not a date",
-      way_id => "2009-03-25 00:00:00",                   # <- wrong format
-      way_id => "0 Jan 2009 00:00:00",                   # <- invalid date
-      -1 => "1 Jan 2009 00:00:00" }.each do |id, t| # <- invalid
-      post :amf_read, :body => amf_content("getway_old", "/1", [id, t])
-      assert_response :success
-      amf_parse_response
-      returned_way = amf_result("/1")
-      assert_equal(-1, returned_way[0])
-      assert returned_way[3].nil?
-      assert returned_way[4].nil?
-      assert returned_way[5].nil?
-    end
-  end
-
-  def test_getway_old_nonexistent
-    # try to get the last version-10 (shoudn't exist)
-    way = create(:way, :with_history, :version => 2)
-    v1 = way.old_ways.find_by(:version => 1)
-    # try to get last visible version of non-existent way
-    # try to get specific version of non-existent way
-    [[0, ""],
-     [0, "1 Jan 1970, 00:00:00"],
-     [v1.way_id, (v1.timestamp - 10).strftime("%d %b %Y, %H:%M:%S")]].each do |id, t|
-      post :amf_read, :body => amf_content("getway_old", "/1", [id, t])
-      assert_response :success
-      amf_parse_response
-      returned_way = amf_result("/1")
-      assert_equal(-1, returned_way[0])
-      assert returned_way[3].nil?
-      assert returned_way[4].nil?
-      assert returned_way[5].nil?
-    end
-  end
-
-  def test_getway_old_invisible
-    way = create(:way, :deleted, :with_history, :version => 1)
-    v1 = way.old_ways.find_by(:version => 1)
-    # try to get deleted version
-    [[v1.way_id, (v1.timestamp + 10).strftime("%d %b %Y, %H:%M:%S")]].each do |id, t|
-      post :amf_read, :body => amf_content("getway_old", "/1", [id, t])
-      assert_response :success
-      amf_parse_response
-      returned_way = amf_result("/1")
-      assert_equal(-1, returned_way[0])
-      assert returned_way[3].nil?
-      assert returned_way[4].nil?
-      assert returned_way[5].nil?
-    end
-  end
-
-  def test_getway_history
-    latest = create(:way, :version => 2)
-    oldest = create(:old_way, :current_way => latest, :version => 1, :timestamp => latest.timestamp - 2.minutes)
-    create(:old_way, :current_way => latest, :version => 2, :timestamp => latest.timestamp)
-
-    post :amf_read, :body => amf_content("getway_history", "/1", [latest.id])
-    assert_response :success
-    amf_parse_response
-    history = amf_result("/1")
-
-    # ['way',wayid,history]
-    assert_equal "way", history[0]
-    assert_equal latest.id, history[1]
-    # We use dates rather than version numbers here, because you might
-    # have moved a node within a way (i.e. way version not incremented).
-    # The timestamp is +1 because we say "give me the revision of 15:33:02",
-    # but that might actually include changes at 15:33:02.457.
-    assert_equal (latest.timestamp + 1).strftime("%d %b %Y, %H:%M:%S"), history[2].first[0]
-    assert_equal (oldest.timestamp + 1).strftime("%d %b %Y, %H:%M:%S"), history[2].last[0]
-  end
-
-  def test_getway_history_nonexistent
-    post :amf_read, :body => amf_content("getway_history", "/1", [0])
-    assert_response :success
-    amf_parse_response
-    history = amf_result("/1")
-
-    # ['way',wayid,history]
-    assert_equal history[0], "way"
-    assert_equal history[1], 0
-    assert history[2].empty?
-  end
-
-  def test_getnode_history
-    node = create(:node, :version => 2)
-    node_v1 = create(:old_node, :current_node => node, :version => 1, :timestamp => 3.days.ago)
-    _node_v2 = create(:old_node, :current_node => node, :version => 2, :timestamp => 2.days.ago)
-    node_v3 = create(:old_node, :current_node => node, :version => 3, :timestamp => 1.day.ago)
-
-    post :amf_read, :body => amf_content("getnode_history", "/1", [node.id])
-    assert_response :success
-    amf_parse_response
-    history = amf_result("/1")
-
-    # ['node',nodeid,history]
-    # note that (as per getway_history) we actually round up
-    # to the next second
-    assert_equal history[0], "node",
-                 'first element should be "node"'
-    assert_equal history[1], node.id,
-                 "second element should be the input node ID"
-    assert_equal history[2].first[0],
-                 (node_v3.timestamp + 1).strftime("%d %b %Y, %H:%M:%S"),
-                 "first element in third element (array) should be the latest version"
-    assert_equal history[2].last[0],
-                 (node_v1.timestamp + 1).strftime("%d %b %Y, %H:%M:%S"),
-                 "last element in third element (array) should be the initial version"
-  end
-
-  def test_getnode_history_nonexistent
-    post :amf_read, :body => amf_content("getnode_history", "/1", [0])
-    assert_response :success
-    amf_parse_response
-    history = amf_result("/1")
-
-    # ['node',nodeid,history]
-    assert_equal history[0], "node"
-    assert_equal history[1], 0
-    assert history[2].empty?
-  end
-
-  def test_findgpx_bad_user
-    post :amf_read, :body => amf_content("findgpx", "/1", [1, "test@example.com:wrong"])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 2, result.length
-    assert_equal(-1, result[0])
-    assert_match(/must be logged in/, result[1])
-
-    blocked_user = create(:user)
-    create(:user_block, :user => blocked_user)
-    post :amf_read, :body => amf_content("findgpx", "/1", [1, "#{blocked_user.email}:test"])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 2, result.length
-    assert_equal(-1, result[0])
-    assert_match(/access to the API has been blocked/, result[1])
-  end
-
-  def test_findgpx_by_id
-    user = create(:user)
-    trace = create(:trace, :visibility => "private", :user => user)
-
-    post :amf_read, :body => amf_content("findgpx", "/1", [trace.id, "#{user.email}:test"])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 3, result.length
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-    traces = result[2]
-    assert_equal 1, traces.length
-    assert_equal 3, traces[0].length
-    assert_equal trace.id, traces[0][0]
-    assert_equal trace.name, traces[0][1]
-    assert_equal trace.description, traces[0][2]
-  end
-
-  def test_findgpx_by_name
-    user = create(:user)
-
-    post :amf_read, :body => amf_content("findgpx", "/1", ["Trace", "#{user.email}:test"])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    # find by name fails as it uses mysql text search syntax...
-    assert_equal 2, result.length
-    assert_equal(-2, result[0])
-  end
-
-  def test_findrelations_by_id
-    relation = create(:relation, :version => 4)
-
-    post :amf_read, :body => amf_content("findrelations", "/1", [relation.id])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 1, result.length
-    assert_equal 4, result[0].length
-    assert_equal relation.id, result[0][0]
-    assert_equal relation.tags, result[0][1]
-    assert_equal relation.members, result[0][2]
-    assert_equal relation.version, result[0][3]
-
-    post :amf_read, :body => amf_content("findrelations", "/1", [999999])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 0, result.length
-  end
-
-  def test_findrelations_by_tags
-    visible_relation = create(:relation)
-    create(:relation_tag, :relation => visible_relation, :k => "test", :v => "yes")
-    used_relation = create(:relation)
-    super_relation = create(:relation)
-    create(:relation_member, :relation => super_relation, :member => used_relation)
-    create(:relation_tag, :relation => used_relation, :k => "test", :v => "yes")
-    create(:relation_tag, :relation => used_relation, :k => "name", :v => "Test Relation")
-
-    post :amf_read, :body => amf_content("findrelations", "/1", ["yes"])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1").sort
-
-    assert_equal 2, result.length
-    assert_equal 4, result[0].length
-    assert_equal visible_relation.id, result[0][0]
-    assert_equal visible_relation.tags, result[0][1]
-    assert_equal visible_relation.members, result[0][2]
-    assert_equal visible_relation.version, result[0][3]
-    assert_equal 4, result[1].length
-    assert_equal used_relation.id, result[1][0]
-    assert_equal used_relation.tags, result[1][1]
-    assert_equal used_relation.members, result[1][2]
-    assert_equal used_relation.version, result[1][3]
-
-    post :amf_read, :body => amf_content("findrelations", "/1", ["no"])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1").sort
-
-    assert_equal 0, result.length
-  end
-
-  def test_getpoi_without_timestamp
-    node = create(:node, :with_history, :version => 4)
-    create(:node_tag, :node => node)
-
-    post :amf_read, :body => amf_content("getpoi", "/1", [node.id, ""])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 7, result.length
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-    assert_equal node.id, result[2]
-    assert_equal node.lon, result[3]
-    assert_equal node.lat, result[4]
-    assert_equal node.tags, result[5]
-    assert_equal node.version, result[6]
-
-    post :amf_read, :body => amf_content("getpoi", "/1", [999999, ""])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 3, result.length
-    assert_equal(-4, result[0])
-    assert_equal "node", result[1]
-    assert_equal 999999, result[2]
-  end
-
-  def test_getpoi_with_timestamp
-    current_node = create(:node, :with_history, :version => 4)
-    node = current_node.old_nodes.find_by(:version => 2)
-
-    # Timestamps are stored with microseconds, but xmlschema truncates them to
-    # previous whole second, causing <= comparison to fail
-    timestamp = (node.timestamp + 1.second).xmlschema
-
-    post :amf_read, :body => amf_content("getpoi", "/1", [node.node_id, timestamp])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 7, result.length
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-    assert_equal node.node_id, result[2]
-    assert_equal node.lon, result[3]
-    assert_equal node.lat, result[4]
-    assert_equal node.tags, result[5]
-    assert_equal current_node.version, result[6]
-
-    post :amf_read, :body => amf_content("getpoi", "/1", [node.node_id, "2000-01-01T00:00:00Z"])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 3, result.length
-    assert_equal(-4, result[0])
-    assert_equal "node", result[1]
-    assert_equal node.node_id, result[2]
-
-    post :amf_read, :body => amf_content("getpoi", "/1", [999999, Time.now.xmlschema])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 3, result.length
-    assert_equal(-4, result[0])
-    assert_equal "node", result[1]
-    assert_equal 999999, result[2]
-  end
-
-  # ************************************************************
-  # AMF Write tests
-
-  # check that we can update a poi
-  def test_putpoi_update_valid
-    nd = create(:node)
-    cs_id = nd.changeset.id
-    user = nd.changeset.user
-    post :amf_write, :body => amf_content("putpoi", "/1", ["#{user.email}:test", cs_id, nd.version, nd.id, nd.lon, nd.lat, nd.tags, nd.visible])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 5, result.size
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-    assert_equal nd.id, result[2]
-    assert_equal nd.id, result[3]
-    assert_equal nd.version + 1, result[4]
-
-    # Now try to update again, with a different lat/lon, using the updated version number
-    lat = nd.lat + 0.1
-    lon = nd.lon - 0.1
-    post :amf_write, :body => amf_content("putpoi", "/2", ["#{user.email}:test", cs_id, nd.version + 1, nd.id, lon, lat, nd.tags, nd.visible])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/2")
-
-    assert_equal 5, result.size
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-    assert_equal nd.id, result[2]
-    assert_equal nd.id, result[3]
-    assert_equal nd.version + 2, result[4]
-  end
-
-  # Check that we can create a no valid poi
-  # Using similar method for the node controller test
-  def test_putpoi_create_valid
-    # This node has no tags
-
-    # create a node with random lat/lon
-    lat = rand(-50..49) + rand
-    lon = rand(-50..49) + rand
-
-    changeset = create(:changeset)
-    user = changeset.user
-
-    post :amf_write, :body => amf_content("putpoi", "/1", ["#{user.email}:test", changeset.id, nil, nil, lon, lat, {}, nil])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    # check the array returned by the amf
-    assert_equal 5, result.size
-    assert_equal 0, result[0], "expected to get the status ok from the amf"
-    assert_equal 0, result[2], "The old id should be 0"
-    assert result[3].positive?, "The new id should be greater than 0"
-    assert_equal 1, result[4], "The new version should be 1"
-
-    # Finally check that the node that was saved has saved the data correctly
-    # in both the current and history tables
-    # First check the current table
-    current_node = Node.find(result[3].to_i)
-    assert_in_delta lat, current_node.lat, 0.00001, "The latitude was not retreieved correctly"
-    assert_in_delta lon, current_node.lon, 0.00001, "The longitude was not retreived correctly"
-    assert_equal 0, current_node.tags.size, "There seems to be a tag that has been added to the node"
-    assert_equal result[4], current_node.version, "The version returned, is different to the one returned by the amf"
-    # Now check the history table
-    historic_nodes = OldNode.where(:node_id => result[3])
-    assert_equal 1, historic_nodes.size, "There should only be one historic node created"
-    first_historic_node = historic_nodes.first
-    assert_in_delta lat, first_historic_node.lat, 0.00001, "The latitude was not retreived correctly"
-    assert_in_delta lon, first_historic_node.lon, 0.00001, "The longitude was not retreuved correctly"
-    assert_equal 0, first_historic_node.tags.size, "There seems to be a tag that have been attached to this node"
-    assert_equal result[4], first_historic_node.version, "The version returned, is different to the one returned by the amf"
-
-    ####
-    # This node has some tags
-
-    # create a node with random lat/lon
-    lat = rand(-50..49) + rand
-    lon = rand(-50..49) + rand
-
-    post :amf_write, :body => amf_content("putpoi", "/2", ["#{user.email}:test", changeset.id, nil, nil, lon, lat, { "key" => "value", "ping" => "pong" }, nil])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/2")
-
-    # check the array returned by the amf
-    assert_equal 5, result.size
-    assert_equal 0, result[0], "Expected to get the status ok in the amf"
-    assert_equal 0, result[2], "The old id should be 0"
-    assert result[3].positive?, "The new id should be greater than 0"
-    assert_equal 1, result[4], "The new version should be 1"
-
-    # Finally check that the node that was saved has saved the data correctly
-    # in both the current and history tables
-    # First check the current table
-    current_node = Node.find(result[3].to_i)
-    assert_in_delta lat, current_node.lat, 0.00001, "The latitude was not retreieved correctly"
-    assert_in_delta lon, current_node.lon, 0.00001, "The longitude was not retreived correctly"
-    assert_equal 2, current_node.tags.size, "There seems to be a tag that has been added to the node"
-    assert_equal({ "key" => "value", "ping" => "pong" }, current_node.tags, "tags are different")
-    assert_equal result[4], current_node.version, "The version returned, is different to the one returned by the amf"
-    # Now check the history table
-    historic_nodes = OldNode.where(:node_id => result[3])
-    assert_equal 1, historic_nodes.size, "There should only be one historic node created"
-    first_historic_node = historic_nodes.first
-    assert_in_delta lat, first_historic_node.lat, 0.00001, "The latitude was not retreived correctly"
-    assert_in_delta lon, first_historic_node.lon, 0.00001, "The longitude was not retreuved correctly"
-    assert_equal 2, first_historic_node.tags.size, "There seems to be a tag that have been attached to this node"
-    assert_equal({ "key" => "value", "ping" => "pong" }, first_historic_node.tags, "tags are different")
-    assert_equal result[4], first_historic_node.version, "The version returned, is different to the one returned by the amf"
-  end
-
-  # try creating a POI with rubbish in the tags
-  def test_putpoi_create_with_control_chars
-    # This node has no tags
-
-    # create a node with random lat/lon
-    lat = rand(-50..49) + rand
-    lon = rand(-50..49) + rand
-
-    changeset = create(:changeset)
-    user = changeset.user
-
-    mostly_invalid = (0..31).to_a.map(&:chr).join
-    tags = { "something" => "foo#{mostly_invalid}bar" }
-
-    post :amf_write, :body => amf_content("putpoi", "/1", ["#{user.email}:test", changeset.id, nil, nil, lon, lat, tags, nil])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    # check the array returned by the amf
-    assert_equal 5, result.size
-    assert_equal 0, result[0], "Expected to get the status ok in the amf"
-    assert_equal 0, result[2], "The old id should be 0"
-    assert result[3].positive?, "The new id should be greater than 0"
-    assert_equal 1, result[4], "The new version should be 1"
-
-    # Finally check that the node that was saved has saved the data correctly
-    # in both the current and history tables
-    # First check the current table
-    current_node = Node.find(result[3].to_i)
-    assert_equal 1, current_node.tags.size, "There seems to be a tag that has been added to the node"
-    assert_equal({ "something" => "foo\t\n\rbar" }, current_node.tags, "tags were not fixed correctly")
-    assert_equal result[4], current_node.version, "The version returned, is different to the one returned by the amf"
-  end
-
-  # try creating a POI with rubbish in the tags
-  def test_putpoi_create_with_invalid_utf8
-    # This node has no tags
-
-    # create a node with random lat/lon
-    lat = rand(-50..49) + rand
-    lon = rand(-50..49) + rand
-
-    changeset = create(:changeset)
-    user = changeset.user
-
-    invalid = "\xc0\xc0"
-    tags = { "something" => "foo#{invalid}bar" }
-
-    post :amf_write, :body => amf_content("putpoi", "/1", ["#{user.email}:test", changeset.id, nil, nil, lon, lat, tags, nil])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 2, result.size
-    assert_equal(-1, result[0], "Expected to get the status FAIL in the amf")
-    assert_equal "One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1.", result[1]
-  end
-
-  # try deleting a node
-  def test_putpoi_delete_valid
-    nd = create(:node)
-    cs_id = nd.changeset.id
-    user = nd.changeset.user
-
-    post :amf_write, :body => amf_content("putpoi", "/1", ["#{user.email}:test", cs_id, nd.version, nd.id, nd.lon, nd.lat, nd.tags, false])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 5, result.size
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-    assert_equal nd.id, result[2]
-    assert_equal nd.id, result[3]
-    assert_equal nd.version + 1, result[4]
-
-    current_node = Node.find(result[3].to_i)
-    assert_equal false, current_node.visible
-  end
-
-  # try deleting a node that is already deleted
-  def test_putpoi_delete_already_deleted
-    nd = create(:node, :deleted)
-    cs_id = nd.changeset.id
-    user = nd.changeset.user
-
-    post :amf_write, :body => amf_content("putpoi", "/1", ["#{user.email}:test", cs_id, nd.version, nd.id, nd.lon, nd.lat, nd.tags, false])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 3, result.size
-    assert_equal(-4, result[0])
-    assert_equal "node", result[1]
-    assert_equal nd.id, result[2]
-  end
-
-  # try deleting a node that has never existed
-  def test_putpoi_delete_not_found
-    changeset = create(:changeset)
-    cs_id = changeset.id
-    user = changeset.user
-
-    post :amf_write, :body => amf_content("putpoi", "/1", ["#{user.email}:test", cs_id, 1, 999999, 0, 0, {}, false])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 3, result.size
-    assert_equal(-4, result[0])
-    assert_equal "node", result[1]
-    assert_equal 999999, result[2]
-  end
-
-  # try setting an invalid location on a node
-  def test_putpoi_invalid_latlon
-    nd = create(:node)
-    cs_id = nd.changeset.id
-    user = nd.changeset.user
-
-    post :amf_write, :body => amf_content("putpoi", "/1", ["#{user.email}:test", cs_id, nd.version, nd.id, 200, 100, nd.tags, true])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 2, result.size
-    assert_equal(-2, result[0])
-    assert_match(/Node is not in the world/, result[1])
-  end
-
-  # check that we can create a way
-  def test_putway_create_valid
-    changeset = create(:changeset)
-    cs_id = changeset.id
-    user = changeset.user
-
-    a = create(:node).id
-    b = create(:node).id
-    c = create(:node).id
-    d = create(:node).id
-    e = create(:node).id
-
-    post :amf_write, :body => amf_content("putway", "/1", ["#{user.email}:test", cs_id, 0, -1, [a, b, c], { "test" => "new" }, [], {}])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-    new_way_id = result[3].to_i
-
-    assert_equal 8, result.size
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-    assert_equal(-1, result[2])
-    assert_not_equal(-1, result[3])
-    assert_equal({}, result[4])
-    assert_equal 1, result[5]
-    assert_equal({}, result[6])
-    assert_equal({}, result[7])
-
-    new_way = Way.find(new_way_id)
-    assert_equal 1, new_way.version
-    assert_equal [a, b, c], new_way.nds
-    assert_equal({ "test" => "new" }, new_way.tags)
-
-    post :amf_write, :body => amf_content("putway", "/1", ["#{user.email}:test", cs_id, 0, -1, [b, d, e, a], { "test" => "newer" }, [], {}])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-    new_way_id = result[3].to_i
-
-    assert_equal 8, result.size
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-    assert_equal(-1, result[2])
-    assert_not_equal(-1, result[3])
-    assert_equal({}, result[4])
-    assert_equal 1, result[5]
-    assert_equal({}, result[6])
-    assert_equal({}, result[7])
-
-    new_way = Way.find(new_way_id)
-    assert_equal 1, new_way.version
-    assert_equal [b, d, e, a], new_way.nds
-    assert_equal({ "test" => "newer" }, new_way.tags)
-
-    post :amf_write, :body => amf_content("putway", "/1", ["#{user.email}:test", cs_id, 0, -1, [b, -1, d, e], { "test" => "newest" }, [[4.56, 12.34, -1, 0, { "test" => "new" }], [12.34, 4.56, d, 1, { "test" => "ok" }]], { a => 1 }])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-    new_way_id = result[3].to_i
-    new_node_id = result[4]["-1"].to_i
-
-    assert_equal 8, result.size
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-    assert_equal(-1, result[2])
-    assert_not_equal(-1, result[3])
-    assert_equal({ "-1" => new_node_id }, result[4])
-    assert_equal 1, result[5]
-    assert_equal({ new_node_id.to_s => 1, d.to_s => 2 }, result[6])
-    assert_equal({ a.to_s => 1 }, result[7])
-
-    new_way = Way.find(new_way_id)
-    assert_equal 1, new_way.version
-    assert_equal [b, new_node_id, d, e], new_way.nds
-    assert_equal({ "test" => "newest" }, new_way.tags)
-
-    new_node = Node.find(new_node_id)
-    assert_equal 1, new_node.version
-    assert_equal true, new_node.visible
-    assert_equal 4.56, new_node.lon
-    assert_equal 12.34, new_node.lat
-    assert_equal({ "test" => "new" }, new_node.tags)
-
-    changed_node = Node.find(d)
-    assert_equal 2, changed_node.version
-    assert_equal true, changed_node.visible
-    assert_equal 12.34, changed_node.lon
-    assert_equal 4.56, changed_node.lat
-    assert_equal({ "test" => "ok" }, changed_node.tags)
-
-    # node is not deleted because our other ways are using it
-    deleted_node = Node.find(a)
-    assert_equal 1, deleted_node.version
-    assert_equal true, deleted_node.visible
-  end
-
-  # check that we can update a way
-  def test_putway_update_valid
-    way = create(:way_with_nodes, :nodes_count => 3)
-    cs_id = way.changeset.id
-    user = way.changeset.user
-
-    assert_not_equal({ "test" => "ok" }, way.tags)
-    post :amf_write, :body => amf_content("putway", "/1", ["#{user.email}:test", cs_id, way.version, way.id, way.nds, { "test" => "ok" }, [], {}])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 8, result.size
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-    assert_equal way.id, result[2]
-    assert_equal way.id, result[3]
-    assert_equal({}, result[4])
-    assert_equal way.version + 1, result[5]
-    assert_equal({}, result[6])
-    assert_equal({}, result[7])
-
-    new_way = Way.find(way.id)
-    assert_equal way.version + 1, new_way.version
-    assert_equal way.nds, new_way.nds
-    assert_equal({ "test" => "ok" }, new_way.tags)
-
-    # Test changing the nodes in the way
-    a = create(:node).id
-    b = create(:node).id
-    c = create(:node).id
-    d = create(:node).id
-
-    assert_not_equal [a, b, c, d], way.nds
-    post :amf_write, :body => amf_content("putway", "/1", ["#{user.email}:test", cs_id, way.version + 1, way.id, [a, b, c, d], way.tags, [], {}])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 8, result.size
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-    assert_equal way.id, result[2]
-    assert_equal way.id, result[3]
-    assert_equal({}, result[4])
-    assert_equal way.version + 2, result[5]
-    assert_equal({}, result[6])
-    assert_equal({}, result[7])
-
-    new_way = Way.find(way.id)
-    assert_equal way.version + 2, new_way.version
-    assert_equal [a, b, c, d], new_way.nds
-    assert_equal way.tags, new_way.tags
-
-    post :amf_write, :body => amf_content("putway", "/1", ["#{user.email}:test", cs_id, way.version + 2, way.id, [a, -1, b, c], way.tags, [[4.56, 12.34, -1, 0, { "test" => "new" }], [12.34, 4.56, b, 1, { "test" => "ok" }]], { d => 1 }])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-    new_node_id = result[4]["-1"].to_i
-
-    assert_equal 8, result.size
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-    assert_equal way.id, result[2]
-    assert_equal way.id, result[3]
-    assert_equal({ "-1" => new_node_id }, result[4])
-    assert_equal way.version + 3, result[5]
-    assert_equal({ new_node_id.to_s => 1, b.to_s => 2 }, result[6])
-    assert_equal({ d.to_s => 1 }, result[7])
-
-    new_way = Way.find(way.id)
-    assert_equal way.version + 3, new_way.version
-    assert_equal [a, new_node_id, b, c], new_way.nds
-    assert_equal way.tags, new_way.tags
-
-    new_node = Node.find(new_node_id)
-    assert_equal 1, new_node.version
-    assert_equal true, new_node.visible
-    assert_equal 4.56, new_node.lon
-    assert_equal 12.34, new_node.lat
-    assert_equal({ "test" => "new" }, new_node.tags)
-
-    changed_node = Node.find(b)
-    assert_equal 2, changed_node.version
-    assert_equal true, changed_node.visible
-    assert_equal 12.34, changed_node.lon
-    assert_equal 4.56, changed_node.lat
-    assert_equal({ "test" => "ok" }, changed_node.tags)
-
-    deleted_node = Node.find(d)
-    assert_equal 2, deleted_node.version
-    assert_equal false, deleted_node.visible
-  end
-
-  # check that we can delete a way
-  def test_deleteway_valid
-    way = create(:way_with_nodes, :nodes_count => 3)
-    nodes = way.nodes.each_with_object({}) { |n, ns| ns[n.id] = n.version }
-    cs_id = way.changeset.id
-    user = way.changeset.user
-
-    # Of the three nodes, two should be kept since they are used in
-    # a different way, and the third deleted since it's unused
-
-    a = way.nodes[0]
-    create(:way_node, :node => a)
-    b = way.nodes[1]
-    create(:way_node, :node => b)
-    c = way.nodes[2]
-
-    post :amf_write, :body => amf_content("deleteway", "/1", ["#{user.email}:test", cs_id, way.id, way.version, nodes])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 5, result.size
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-    assert_equal way.id, result[2]
-    assert_equal way.version + 1, result[3]
-    assert_equal({ c.id.to_s => 2 }, result[4])
-
-    new_way = Way.find(way.id)
-    assert_equal way.version + 1, new_way.version
-    assert_equal false, new_way.visible
-
-    way.nds.each do |node_id|
-      assert_equal result[4][node_id.to_s].nil?, Node.find(node_id).visible
-    end
-  end
-
-  # check that we can't delete a way that is in use
-  def test_deleteway_inuse
-    way = create(:way_with_nodes, :nodes_count => 4)
-    create(:relation_member, :member => way)
-    nodes = way.nodes.each_with_object({}) { |n, ns| ns[n.id] = n.version }
-    cs_id = way.changeset.id
-    user = way.changeset.user
-
-    post :amf_write, :body => amf_content("deleteway", "/1", ["#{user.email}:test", cs_id, way.id, way.version, nodes])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 2, result.size
-    assert_equal(-1, result[0])
-    assert_match(/Way #{way.id} is still used/, result[1])
-
-    new_way = Way.find(way.id)
-    assert_equal way.version, new_way.version
-    assert_equal true, new_way.visible
-
-    way.nds.each do |node_id|
-      assert_equal true, Node.find(node_id).visible
-    end
-  end
-
-  # check that we can create a relation
-  def test_putrelation_create_valid
-    changeset = create(:changeset)
-    user = changeset.user
-    cs_id = changeset.id
-
-    node = create(:node)
-    way = create(:way_with_nodes, :nodes_count => 2)
-    relation = create(:relation)
-
-    post :amf_write, :body => amf_content("putrelation", "/1", ["#{user.email}:test", cs_id, 0, -1, { "test" => "new" }, [["Node", node.id, "node"], ["Way", way.id, "way"], ["Relation", relation.id, "relation"]], true])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-    new_relation_id = result[3].to_i
-
-    assert_equal 5, result.size
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-    assert_equal(-1, result[2])
-    assert_not_equal(-1, result[3])
-    assert_equal 1, result[4]
-
-    new_relation = Relation.find(new_relation_id)
-    assert_equal 1, new_relation.version
-    assert_equal [["Node", node.id, "node"], ["Way", way.id, "way"], ["Relation", relation.id, "relation"]], new_relation.members
-    assert_equal({ "test" => "new" }, new_relation.tags)
-    assert_equal true, new_relation.visible
-  end
-
-  # check that we can update a relation
-  def test_putrelation_update_valid
-    relation = create(:relation)
-    create(:relation_member, :relation => relation)
-    user = relation.changeset.user
-    cs_id = relation.changeset.id
-
-    assert_not_equal({ "test" => "ok" }, relation.tags)
-    post :amf_write, :body => amf_content("putrelation", "/1", ["#{user.email}:test", cs_id, relation.version, relation.id, { "test" => "ok" }, relation.members, true])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 5, result.size
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-    assert_equal relation.id, result[2]
-    assert_equal relation.id, result[3]
-    assert_equal relation.version + 1, result[4]
-
-    new_relation = Relation.find(relation.id)
-    assert_equal relation.version + 1, new_relation.version
-    assert_equal relation.members, new_relation.members
-    assert_equal({ "test" => "ok" }, new_relation.tags)
-    assert_equal true, new_relation.visible
-  end
-
-  # check that we can delete a relation
-  def test_putrelation_delete_valid
-    relation = create(:relation)
-    create(:relation_member, :relation => relation)
-    create(:relation_tag, :relation => relation)
-    cs_id = relation.changeset.id
-    user = relation.changeset.user
-
-    post :amf_write, :body => amf_content("putrelation", "/1", ["#{user.email}:test", cs_id, relation.version, relation.id, relation.tags, relation.members, false])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 5, result.size
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-    assert_equal relation.id, result[2]
-    assert_equal relation.id, result[3]
-    assert_equal relation.version + 1, result[4]
-
-    new_relation = Relation.find(relation.id)
-    assert_equal relation.version + 1, new_relation.version
-    assert_equal [], new_relation.members
-    assert_equal({}, new_relation.tags)
-    assert_equal false, new_relation.visible
-  end
-
-  # check that we can't delete a relation that is in use
-  def test_putrelation_delete_inuse
-    relation = create(:relation)
-    super_relation = create(:relation)
-    create(:relation_member, :relation => super_relation, :member => relation)
-    cs_id = relation.changeset.id
-    user = relation.changeset.user
-
-    post :amf_write, :body => amf_content("putrelation", "/1", ["#{user.email}:test", cs_id, relation.version, relation.id, relation.tags, relation.members, false])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 2, result.size
-    assert_equal(-1, result[0])
-    assert_match(/relation #{relation.id} is used in/, result[1])
-
-    new_relation = Relation.find(relation.id)
-    assert_equal relation.version, new_relation.version
-    assert_equal relation.members, new_relation.members
-    assert_equal relation.tags, new_relation.tags
-    assert_equal true, new_relation.visible
-  end
-
-  # check that we can open a changeset
-  def test_startchangeset_valid
-    user = create(:user)
-
-    post :amf_write, :body => amf_content("startchangeset", "/1", ["#{user.email}:test", { "source" => "new" }, nil, "new", 1])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-    new_cs_id = result[2].to_i
-
-    assert_equal 3, result.size
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-
-    cs = Changeset.find(new_cs_id)
-    assert_equal true, cs.is_open?
-    assert_equal({ "comment" => "new", "source" => "new" }, cs.tags)
-
-    old_cs_id = new_cs_id
-
-    post :amf_write, :body => amf_content("startchangeset", "/1", ["#{user.email}:test", { "source" => "newer" }, old_cs_id, "newer", 1])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-    new_cs_id = result[2].to_i
-
-    assert_not_equal old_cs_id, new_cs_id
-
-    assert_equal 3, result.size
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-
-    cs = Changeset.find(old_cs_id)
-    assert_equal false, cs.is_open?
-    assert_equal({ "comment" => "newer", "source" => "new" }, cs.tags)
-
-    cs = Changeset.find(new_cs_id)
-    assert_equal true, cs.is_open?
-    assert_equal({ "comment" => "newer", "source" => "newer" }, cs.tags)
-
-    old_cs_id = new_cs_id
-
-    post :amf_write, :body => amf_content("startchangeset", "/1", ["#{user.email}:test", {}, old_cs_id, "", 0])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 3, result.size
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-    assert_nil result[2]
-
-    cs = Changeset.find(old_cs_id)
-    assert_equal false, cs.is_open?
-    assert_equal({ "comment" => "newer", "source" => "newer" }, cs.tags)
-  end
-
-  # check that we can't close somebody elses changeset
-  def test_startchangeset_invalid_wrong_user
-    user = create(:user)
-    user2 = create(:user)
-
-    post :amf_write, :body => amf_content("startchangeset", "/1", ["#{user.email}:test", { "source" => "new" }, nil, "new", 1])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-    cs_id = result[2].to_i
-
-    assert_equal 3, result.size
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-
-    cs = Changeset.find(cs_id)
-    assert_equal true, cs.is_open?
-    assert_equal({ "comment" => "new", "source" => "new" }, cs.tags)
-
-    post :amf_write, :body => amf_content("startchangeset", "/1", ["#{user2.email}:test", {}, cs_id, "delete", 0])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-
-    assert_equal 2, result.size
-    assert_equal(-2, result[0])
-    assert_equal "The user doesn't own that changeset", result[1]
-
-    cs = Changeset.find(cs_id)
-    assert_equal true, cs.is_open?
-    assert_equal({ "comment" => "new", "source" => "new" }, cs.tags)
-  end
-
-  # check that invalid characters are stripped from changeset tags
-  def test_startchangeset_invalid_xmlchar_comment
-    user = create(:user)
-
-    invalid = "\035\022"
-    comment = "foo#{invalid}bar"
-
-    post :amf_write, :body => amf_content("startchangeset", "/1", ["#{user.email}:test", {}, nil, comment, 1])
-    assert_response :success
-    amf_parse_response
-    result = amf_result("/1")
-    new_cs_id = result[2].to_i
-
-    assert_equal 3, result.size
-    assert_equal 0, result[0]
-    assert_equal "", result[1]
-
-    cs = Changeset.find(new_cs_id)
-    assert_equal true, cs.is_open?
-    assert_equal({ "comment" => "foobar" }, cs.tags)
-  end
-
-  private
-
-  # ************************************************************
-  # AMF Helper functions
-
-  # Get the result record for the specified ID
-  # It's an assertion FAIL if the record does not exist
-  def amf_result(ref)
-    assert @amf_result.key?("#{ref}/onResult")
-    @amf_result["#{ref}/onResult"]
-  end
-
-  # Encode the AMF message to invoke "target" with parameters as
-  # the passed data. The ref is used to retrieve the results.
-  def amf_content(target, ref, data)
-    a, b = 1.divmod(256)
-    c = StringIO.new
-    c.write 0.chr + 0.chr   # version 0
-    c.write 0.chr + 0.chr   # n headers
-    c.write a.chr + b.chr   # n bodies
-    c.write AMF.encodestring(target)
-    c.write AMF.encodestring(ref)
-    c.write [-1].pack("N")
-    c.write AMF.encodevalue(data)
-
-    c.string
-  end
-
-  # Parses the @response object as an AMF messsage.
-  # The result is a hash of message_ref => data.
-  # The attribute @amf_result is initialised to this hash.
-  def amf_parse_response
-    req = StringIO.new(@response.body)
-
-    req.read(2) # version
-
-    # parse through any headers
-    headers = AMF.getint(req)        # Read number of headers
-    headers.times do                 # Read each header
-      AMF.getstring(req)             #  |
-      req.getc                       #  | skip boolean
-      AMF.getvalue(req)              #  |
-    end
-
-    # parse through responses
-    results = {}
-    bodies = AMF.getint(req)         # Read number of bodies
-    bodies.times do                  # Read each body
-      message = AMF.getstring(req)   #  | get message name
-      AMF.getstring(req)             #  | get index in response sequence
-      AMF.getlong(req)               #  | get total size in bytes
-      args = AMF.getvalue(req)       #  | get response (probably an array)
-      results[message] = args
-    end
-    @amf_result = results
-    results
-  end
-
-  ##
-  # given an array of bounding boxes (each an array of 4 floats), call the
-  # AMF "whichways" controller for each and pass the result back to the
-  # caller's block for assertion testing.
-  def check_bboxes_are_bad(bboxes)
-    bboxes.each do |bbox|
-      post :amf_read, :body => amf_content("whichways", "/1", bbox)
-      assert_response :success
-      amf_parse_response
-
-      # pass the response back to the caller's block to be tested
-      # against what the caller expected.
-      map = amf_result "/1"
-      yield map, bbox
-    end
-  end
-
-  # this should be what AMF controller returns when the bbox of a
-  # whichways request is invalid or too large.
-  def assert_boundary_error(map, msg = nil, error_hint = nil)
-    expected_map = [-2, "Sorry - I can't get the map for that area.#{msg}"]
-    assert_equal expected_map, map, "AMF controller should have returned an error. (#{error_hint})"
-  end
-
-  # this should be what AMF controller returns when the bbox of a
-  # whichways_deleted request is invalid or too large.
-  def assert_deleted_boundary_error(map, msg = nil, error_hint = nil)
-    expected_map = [-2, "Sorry - I can't get the map for that area.#{msg}"]
-    assert_equal expected_map, map, "AMF controller should have returned an error. (#{error_hint})"
-  end
-end
diff --git a/test/controllers/api/amf_controller_test.rb b/test/controllers/api/amf_controller_test.rb
new file mode 100644 (file)
index 0000000..2240504
--- /dev/null
@@ -0,0 +1,1465 @@
+require "test_helper"
+
+module Api
+  class AmfControllerTest < ActionController::TestCase
+    include Potlatch
+
+    ##
+    # test all routes which lead to this controller
+    def test_routes
+      assert_routing(
+        { :path => "/api/0.6/amf/read", :method => :post },
+        { :controller => "api/amf", :action => "amf_read" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/amf/write", :method => :post },
+        { :controller => "api/amf", :action => "amf_write" }
+      )
+    end
+
+    def test_getpresets
+      user_en_de = create(:user, :languages => %w[en de])
+      user_de = create(:user, :languages => %w[de])
+      [user_en_de, user_de].each do |user|
+        post :amf_read, :body => amf_content("getpresets", "/1", ["#{user.email}:test", ""])
+        assert_response :success
+        amf_parse_response
+        presets = amf_result("/1")
+
+        assert_equal 15, presets.length
+        assert_equal POTLATCH_PRESETS[0], presets[0]
+        assert_equal POTLATCH_PRESETS[1], presets[1]
+        assert_equal POTLATCH_PRESETS[2], presets[2]
+        assert_equal POTLATCH_PRESETS[3], presets[3]
+        assert_equal POTLATCH_PRESETS[4], presets[4]
+        assert_equal POTLATCH_PRESETS[5], presets[5]
+        assert_equal POTLATCH_PRESETS[6], presets[6]
+        assert_equal POTLATCH_PRESETS[7], presets[7]
+        assert_equal POTLATCH_PRESETS[8], presets[8]
+        assert_equal POTLATCH_PRESETS[9], presets[9]
+        assert_equal POTLATCH_PRESETS[10], presets[10]
+        assert_equal POTLATCH_PRESETS[12], presets[12]
+        assert_equal user.languages.first, presets[13]["__potlatch_locale"]
+      end
+    end
+
+    def test_getway
+      # check a visible way
+      way = create(:way_with_nodes, :nodes_count => 1)
+      node = way.nodes.first
+      user = way.changeset.user
+
+      post :amf_read, :body => amf_content("getway", "/1", [way.id])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+      assert_equal way.id, result[2]
+      assert_equal 1, result[3].length
+      assert_equal node.id, result[3][0][2]
+      assert_equal way.version, result[5]
+      assert_equal user.id, result[6]
+    end
+
+    def test_getway_invisible
+      # check an invisible way
+      id = create(:way, :deleted).id
+
+      post :amf_read, :body => amf_content("getway", "/1", [id])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+      assert_equal(-4, result[0])
+      assert_equal "way", result[1]
+      assert_equal id, result[2]
+      assert(result[3].nil? && result[4].nil? && result[5].nil? && result[6].nil?)
+    end
+
+    def test_getway_with_versions
+      # check a way with multiple versions
+      way = create(:way, :with_history, :version => 4)
+      create(:way_node, :way => way)
+      node = way.nodes.first
+      user = way.changeset.user
+
+      post :amf_read, :body => amf_content("getway", "/1", [way.id])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+      assert_equal way.id, result[2]
+      assert_equal 1, result[3].length
+      assert_equal node.id, result[3][0][2]
+      assert_equal way.version, result[5]
+      assert_equal user.id, result[6]
+    end
+
+    def test_getway_with_duplicate_nodes
+      # check a way with duplicate nodes
+      way = create(:way)
+      node = create(:node)
+      create(:way_node, :way => way, :node => node, :sequence_id => 1)
+      create(:way_node, :way => way, :node => node, :sequence_id => 2)
+      user = way.changeset.user
+
+      post :amf_read, :body => amf_content("getway", "/1", [way.id])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+      assert_equal way.id, result[2]
+      assert_equal 2, result[3].length
+      assert_equal node.id, result[3][0][2]
+      assert_equal node.id, result[3][1][2]
+      assert_equal way.version, result[5]
+      assert_equal user.id, result[6]
+    end
+
+    def test_getway_with_multiple_nodes
+      # check a way with multiple nodes
+      way = create(:way_with_nodes, :nodes_count => 3)
+      a = way.nodes[0].id
+      b = way.nodes[1].id
+      c = way.nodes[2].id
+      user = way.changeset.user
+
+      post :amf_read, :body => amf_content("getway", "/1", [way.id])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+      assert_equal way.id, result[2]
+      assert_equal 3, result[3].length
+      assert_equal a, result[3][0][2]
+      assert_equal b, result[3][1][2]
+      assert_equal c, result[3][2][2]
+      assert_equal way.version, result[5]
+      assert_equal user.id, result[6]
+    end
+
+    def test_getway_nonexistent
+      # check chat a non-existent way is not returned
+      post :amf_read, :body => amf_content("getway", "/1", [0])
+      assert_response :success
+      amf_parse_response
+      way = amf_result("/1")
+      assert_equal(-4, way[0])
+      assert_equal "way", way[1]
+      assert_equal 0, way[2]
+      assert(way[3].nil?) && way[4].nil? && way[5].nil? && way[6].nil?
+    end
+
+    def test_whichways
+      node = create(:node, :lat => 3.0, :lon => 3.0)
+      way = create(:way)
+      deleted_way = create(:way, :deleted)
+      create(:way_node, :way => way, :node => node)
+      create(:way_node, :way => deleted_way, :node => node)
+      create(:way_tag, :way => way)
+
+      minlon = node.lon - 0.1
+      minlat = node.lat - 0.1
+      maxlon = node.lon + 0.1
+      maxlat = node.lat + 0.1
+      post :amf_read, :body => amf_content("whichways", "/1", [minlon, minlat, maxlon, maxlat])
+      assert_response :success
+      amf_parse_response
+
+      # check contents of message
+      map = amf_result "/1"
+      assert_equal 0, map[0], "map error code should be 0"
+      assert_equal "", map[1], "map error text should be empty"
+
+      # check the formatting of the message
+      assert_equal 5, map.length, "map should have length 5"
+      assert_equal Array, map[2].class, 'map "ways" element should be an array'
+      assert_equal Array, map[3].class, 'map "nodes" element should be an array'
+      assert_equal Array, map[4].class, 'map "relations" element should be an array'
+      map[2].each do |w|
+        assert_equal 2, w.length, "way should be (id, version) pair"
+        assert w[0] == w[0].floor, "way ID should be an integer"
+        assert w[1] == w[1].floor, "way version should be an integer"
+      end
+
+      map[3].each do |n|
+        assert_equal 5, w.length, "node should be (id, lat, lon, [tags], version) tuple"
+        assert n[0] == n[0].floor, "node ID should be an integer"
+        assert n[1] >= minlat - 0.01, "node lat should be greater than min"
+        assert n[1] <= maxlat - 0.01, "node lat should be less than max"
+        assert n[2] >= minlon - 0.01, "node lon should be greater than min"
+        assert n[2] <= maxlon - 0.01, "node lon should be less than max"
+        assert_equal Array, a[3].class, "node tags should be array"
+        assert n[4] == n[4].floor, "node version should be an integer"
+      end
+
+      map[4].each do |r|
+        assert_equal 2, r.length, "relation should be (id, version) pair"
+        assert r[0] == r[0].floor, "relation ID should be an integer"
+        assert r[1] == r[1].floor, "relation version should be an integer"
+      end
+
+      # TODO: looks like amf_controller changed since this test was written
+      # so someone who knows what they're doing should check this!
+      ways = map[2].collect { |x| x[0] }
+      assert ways.include?(way.id),
+             "map should include used way"
+      assert_not ways.include?(deleted_way.id),
+                 "map should not include deleted way"
+    end
+
+    ##
+    # checks that too-large a bounding box will not be served.
+    def test_whichways_toobig
+      bbox = [-0.1, -0.1, 1.1, 1.1]
+      check_bboxes_are_bad [bbox] do |map, _bbox|
+        assert_boundary_error map, " The server said: The maximum bbox size is 0.25, and your request was too large. Either request a smaller area, or use planet.osm"
+      end
+    end
+
+    ##
+    # checks that an invalid bounding box will not be served. in this case
+    # one with max < min latitudes.
+    #
+    # NOTE: the controller expands the bbox by 0.01 in each direction!
+    def test_whichways_badlat
+      bboxes = [[0, 0.1, 0.1, 0], [-0.1, 80, 0.1, 70], [0.24, 54.35, 0.25, 54.33]]
+      check_bboxes_are_bad bboxes do |map, bbox|
+        assert_boundary_error map, " The server said: The minimum latitude must be less than the maximum latitude, but it wasn't", bbox.inspect
+      end
+    end
+
+    ##
+    # same as test_whichways_badlat, but for longitudes
+    #
+    # NOTE: the controller expands the bbox by 0.01 in each direction!
+    def test_whichways_badlon
+      bboxes = [[80, -0.1, 70, 0.1], [54.35, 0.24, 54.33, 0.25]]
+      check_bboxes_are_bad bboxes do |map, bbox|
+        assert_boundary_error map, " The server said: The minimum longitude must be less than the maximum longitude, but it wasn't", bbox.inspect
+      end
+    end
+
+    def test_whichways_deleted
+      node = create(:node, :with_history, :lat => 24.0, :lon => 24.0)
+      way = create(:way, :with_history)
+      way_v1 = way.old_ways.find_by(:version => 1)
+      deleted_way = create(:way, :with_history, :deleted)
+      deleted_way_v1 = deleted_way.old_ways.find_by(:version => 1)
+      create(:way_node, :way => way, :node => node)
+      create(:way_node, :way => deleted_way, :node => node)
+      create(:old_way_node, :old_way => way_v1, :node => node)
+      create(:old_way_node, :old_way => deleted_way_v1, :node => node)
+
+      minlon = node.lon - 0.1
+      minlat = node.lat - 0.1
+      maxlon = node.lon + 0.1
+      maxlat = node.lat + 0.1
+      post :amf_read, :body => amf_content("whichways_deleted", "/1", [minlon, minlat, maxlon, maxlat])
+      assert_response :success
+      amf_parse_response
+
+      # check contents of message
+      map = amf_result "/1"
+      assert_equal 0, map[0], "first map element should be 0"
+      assert_equal "", map[1], "second map element should be an empty string"
+      assert_equal Array, map[2].class, "third map element should be an array"
+      # TODO: looks like amf_controller changed since this test was written
+      # so someone who knows what they're doing should check this!
+      assert_not map[2].include?(way.id),
+                 "map should not include visible way"
+      assert map[2].include?(deleted_way.id),
+             "map should include deleted way"
+    end
+
+    def test_whichways_deleted_toobig
+      bbox = [-0.1, -0.1, 1.1, 1.1]
+      post :amf_read, :body => amf_content("whichways_deleted", "/1", bbox)
+      assert_response :success
+      amf_parse_response
+
+      map = amf_result "/1"
+      assert_deleted_boundary_error map, " The server said: The maximum bbox size is 0.25, and your request was too large. Either request a smaller area, or use planet.osm"
+    end
+
+    def test_getrelation
+      id = create(:relation).id
+      post :amf_read, :body => amf_content("getrelation", "/1", [id])
+      assert_response :success
+      amf_parse_response
+      rel = amf_result("/1")
+      assert_equal rel[0], 0
+      assert_equal rel[2], id
+    end
+
+    def test_getrelation_invisible
+      id = create(:relation, :deleted).id
+      post :amf_read, :body => amf_content("getrelation", "/1", [id])
+      assert_response :success
+      amf_parse_response
+      rel = amf_result("/1")
+      assert_equal rel[0], -4
+      assert_equal rel[1], "relation"
+      assert_equal rel[2], id
+      assert(rel[3].nil?) && rel[4].nil?
+    end
+
+    def test_getrelation_nonexistent
+      id = 0
+      post :amf_read, :body => amf_content("getrelation", "/1", [id])
+      assert_response :success
+      amf_parse_response
+      rel = amf_result("/1")
+      assert_equal rel[0], -4
+      assert_equal rel[1], "relation"
+      assert_equal rel[2], id
+      assert(rel[3].nil?) && rel[4].nil?
+    end
+
+    def test_getway_old
+      latest = create(:way, :version => 2)
+      v1 = create(:old_way, :current_way => latest, :version => 1, :timestamp => Time.now.utc - 2.minutes)
+      _v2 = create(:old_way, :current_way => latest, :version => 2, :timestamp => Time.now.utc - 1.minute)
+
+      # try to get the last visible version (specified by <0) (should be current version)
+      # NOTE: looks from the API changes that this now expects a timestamp
+      # instead of a version number...
+      # try to get version 1
+      { latest.id => "",
+        v1.way_id => (v1.timestamp + 1).strftime("%d %b %Y, %H:%M:%S") }.each do |id, t|
+        post :amf_read, :body => amf_content("getway_old", "/1", [id, t])
+        assert_response :success
+        amf_parse_response
+        returned_way = amf_result("/1")
+        assert_equal 0, returned_way[0]
+        assert_equal id, returned_way[2]
+        # API returns the *latest* version, even for old ways...
+        assert_equal latest.version, returned_way[5]
+      end
+    end
+
+    ##
+    # test that the server doesn't fall over when rubbish is passed
+    # into the method args.
+    def test_getway_old_invalid
+      way_id = create(:way, :with_history, :version => 2).id
+      { "foo" => "bar",
+        way_id => "not a date",
+        way_id => "2009-03-25 00:00:00",                   # <- wrong format
+        way_id => "0 Jan 2009 00:00:00",                   # <- invalid date
+        -1 => "1 Jan 2009 00:00:00" }.each do |id, t| # <- invalid
+        post :amf_read, :body => amf_content("getway_old", "/1", [id, t])
+        assert_response :success
+        amf_parse_response
+        returned_way = amf_result("/1")
+        assert_equal(-1, returned_way[0])
+        assert returned_way[3].nil?
+        assert returned_way[4].nil?
+        assert returned_way[5].nil?
+      end
+    end
+
+    def test_getway_old_nonexistent
+      # try to get the last version-10 (shoudn't exist)
+      way = create(:way, :with_history, :version => 2)
+      v1 = way.old_ways.find_by(:version => 1)
+      # try to get last visible version of non-existent way
+      # try to get specific version of non-existent way
+      [[0, ""],
+       [0, "1 Jan 1970, 00:00:00"],
+       [v1.way_id, (v1.timestamp - 10).strftime("%d %b %Y, %H:%M:%S")]].each do |id, t|
+        post :amf_read, :body => amf_content("getway_old", "/1", [id, t])
+        assert_response :success
+        amf_parse_response
+        returned_way = amf_result("/1")
+        assert_equal(-1, returned_way[0])
+        assert returned_way[3].nil?
+        assert returned_way[4].nil?
+        assert returned_way[5].nil?
+      end
+    end
+
+    def test_getway_old_invisible
+      way = create(:way, :deleted, :with_history, :version => 1)
+      v1 = way.old_ways.find_by(:version => 1)
+      # try to get deleted version
+      [[v1.way_id, (v1.timestamp + 10).strftime("%d %b %Y, %H:%M:%S")]].each do |id, t|
+        post :amf_read, :body => amf_content("getway_old", "/1", [id, t])
+        assert_response :success
+        amf_parse_response
+        returned_way = amf_result("/1")
+        assert_equal(-1, returned_way[0])
+        assert returned_way[3].nil?
+        assert returned_way[4].nil?
+        assert returned_way[5].nil?
+      end
+    end
+
+    def test_getway_history
+      latest = create(:way, :version => 2)
+      oldest = create(:old_way, :current_way => latest, :version => 1, :timestamp => latest.timestamp - 2.minutes)
+      create(:old_way, :current_way => latest, :version => 2, :timestamp => latest.timestamp)
+
+      post :amf_read, :body => amf_content("getway_history", "/1", [latest.id])
+      assert_response :success
+      amf_parse_response
+      history = amf_result("/1")
+
+      # ['way',wayid,history]
+      assert_equal "way", history[0]
+      assert_equal latest.id, history[1]
+      # We use dates rather than version numbers here, because you might
+      # have moved a node within a way (i.e. way version not incremented).
+      # The timestamp is +1 because we say "give me the revision of 15:33:02",
+      # but that might actually include changes at 15:33:02.457.
+      assert_equal (latest.timestamp + 1).strftime("%d %b %Y, %H:%M:%S"), history[2].first[0]
+      assert_equal (oldest.timestamp + 1).strftime("%d %b %Y, %H:%M:%S"), history[2].last[0]
+    end
+
+    def test_getway_history_nonexistent
+      post :amf_read, :body => amf_content("getway_history", "/1", [0])
+      assert_response :success
+      amf_parse_response
+      history = amf_result("/1")
+
+      # ['way',wayid,history]
+      assert_equal history[0], "way"
+      assert_equal history[1], 0
+      assert history[2].empty?
+    end
+
+    def test_getnode_history
+      node = create(:node, :version => 2)
+      node_v1 = create(:old_node, :current_node => node, :version => 1, :timestamp => 3.days.ago)
+      _node_v2 = create(:old_node, :current_node => node, :version => 2, :timestamp => 2.days.ago)
+      node_v3 = create(:old_node, :current_node => node, :version => 3, :timestamp => 1.day.ago)
+
+      post :amf_read, :body => amf_content("getnode_history", "/1", [node.id])
+      assert_response :success
+      amf_parse_response
+      history = amf_result("/1")
+
+      # ['node',nodeid,history]
+      # note that (as per getway_history) we actually round up
+      # to the next second
+      assert_equal history[0], "node",
+                   'first element should be "node"'
+      assert_equal history[1], node.id,
+                   "second element should be the input node ID"
+      assert_equal history[2].first[0],
+                   (node_v3.timestamp + 1).strftime("%d %b %Y, %H:%M:%S"),
+                   "first element in third element (array) should be the latest version"
+      assert_equal history[2].last[0],
+                   (node_v1.timestamp + 1).strftime("%d %b %Y, %H:%M:%S"),
+                   "last element in third element (array) should be the initial version"
+    end
+
+    def test_getnode_history_nonexistent
+      post :amf_read, :body => amf_content("getnode_history", "/1", [0])
+      assert_response :success
+      amf_parse_response
+      history = amf_result("/1")
+
+      # ['node',nodeid,history]
+      assert_equal history[0], "node"
+      assert_equal history[1], 0
+      assert history[2].empty?
+    end
+
+    def test_findgpx_bad_user
+      post :amf_read, :body => amf_content("findgpx", "/1", [1, "test@example.com:wrong"])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 2, result.length
+      assert_equal(-1, result[0])
+      assert_match(/must be logged in/, result[1])
+
+      blocked_user = create(:user)
+      create(:user_block, :user => blocked_user)
+      post :amf_read, :body => amf_content("findgpx", "/1", [1, "#{blocked_user.email}:test"])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 2, result.length
+      assert_equal(-1, result[0])
+      assert_match(/access to the API has been blocked/, result[1])
+    end
+
+    def test_findgpx_by_id
+      user = create(:user)
+      trace = create(:trace, :visibility => "private", :user => user)
+
+      post :amf_read, :body => amf_content("findgpx", "/1", [trace.id, "#{user.email}:test"])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 3, result.length
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+      traces = result[2]
+      assert_equal 1, traces.length
+      assert_equal 3, traces[0].length
+      assert_equal trace.id, traces[0][0]
+      assert_equal trace.name, traces[0][1]
+      assert_equal trace.description, traces[0][2]
+    end
+
+    def test_findgpx_by_name
+      user = create(:user)
+
+      post :amf_read, :body => amf_content("findgpx", "/1", ["Trace", "#{user.email}:test"])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      # find by name fails as it uses mysql text search syntax...
+      assert_equal 2, result.length
+      assert_equal(-2, result[0])
+    end
+
+    def test_findrelations_by_id
+      relation = create(:relation, :version => 4)
+
+      post :amf_read, :body => amf_content("findrelations", "/1", [relation.id])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 1, result.length
+      assert_equal 4, result[0].length
+      assert_equal relation.id, result[0][0]
+      assert_equal relation.tags, result[0][1]
+      assert_equal relation.members, result[0][2]
+      assert_equal relation.version, result[0][3]
+
+      post :amf_read, :body => amf_content("findrelations", "/1", [999999])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 0, result.length
+    end
+
+    def test_findrelations_by_tags
+      visible_relation = create(:relation)
+      create(:relation_tag, :relation => visible_relation, :k => "test", :v => "yes")
+      used_relation = create(:relation)
+      super_relation = create(:relation)
+      create(:relation_member, :relation => super_relation, :member => used_relation)
+      create(:relation_tag, :relation => used_relation, :k => "test", :v => "yes")
+      create(:relation_tag, :relation => used_relation, :k => "name", :v => "Test Relation")
+
+      post :amf_read, :body => amf_content("findrelations", "/1", ["yes"])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1").sort
+
+      assert_equal 2, result.length
+      assert_equal 4, result[0].length
+      assert_equal visible_relation.id, result[0][0]
+      assert_equal visible_relation.tags, result[0][1]
+      assert_equal visible_relation.members, result[0][2]
+      assert_equal visible_relation.version, result[0][3]
+      assert_equal 4, result[1].length
+      assert_equal used_relation.id, result[1][0]
+      assert_equal used_relation.tags, result[1][1]
+      assert_equal used_relation.members, result[1][2]
+      assert_equal used_relation.version, result[1][3]
+
+      post :amf_read, :body => amf_content("findrelations", "/1", ["no"])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1").sort
+
+      assert_equal 0, result.length
+    end
+
+    def test_getpoi_without_timestamp
+      node = create(:node, :with_history, :version => 4)
+      create(:node_tag, :node => node)
+
+      post :amf_read, :body => amf_content("getpoi", "/1", [node.id, ""])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 7, result.length
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+      assert_equal node.id, result[2]
+      assert_equal node.lon, result[3]
+      assert_equal node.lat, result[4]
+      assert_equal node.tags, result[5]
+      assert_equal node.version, result[6]
+
+      post :amf_read, :body => amf_content("getpoi", "/1", [999999, ""])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 3, result.length
+      assert_equal(-4, result[0])
+      assert_equal "node", result[1]
+      assert_equal 999999, result[2]
+    end
+
+    def test_getpoi_with_timestamp
+      current_node = create(:node, :with_history, :version => 4)
+      node = current_node.old_nodes.find_by(:version => 2)
+
+      # Timestamps are stored with microseconds, but xmlschema truncates them to
+      # previous whole second, causing <= comparison to fail
+      timestamp = (node.timestamp + 1.second).xmlschema
+
+      post :amf_read, :body => amf_content("getpoi", "/1", [node.node_id, timestamp])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 7, result.length
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+      assert_equal node.node_id, result[2]
+      assert_equal node.lon, result[3]
+      assert_equal node.lat, result[4]
+      assert_equal node.tags, result[5]
+      assert_equal current_node.version, result[6]
+
+      post :amf_read, :body => amf_content("getpoi", "/1", [node.node_id, "2000-01-01T00:00:00Z"])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 3, result.length
+      assert_equal(-4, result[0])
+      assert_equal "node", result[1]
+      assert_equal node.node_id, result[2]
+
+      post :amf_read, :body => amf_content("getpoi", "/1", [999999, Time.now.xmlschema])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 3, result.length
+      assert_equal(-4, result[0])
+      assert_equal "node", result[1]
+      assert_equal 999999, result[2]
+    end
+
+    # ************************************************************
+    # AMF Write tests
+
+    # check that we can update a poi
+    def test_putpoi_update_valid
+      nd = create(:node)
+      cs_id = nd.changeset.id
+      user = nd.changeset.user
+      post :amf_write, :body => amf_content("putpoi", "/1", ["#{user.email}:test", cs_id, nd.version, nd.id, nd.lon, nd.lat, nd.tags, nd.visible])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 5, result.size
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+      assert_equal nd.id, result[2]
+      assert_equal nd.id, result[3]
+      assert_equal nd.version + 1, result[4]
+
+      # Now try to update again, with a different lat/lon, using the updated version number
+      lat = nd.lat + 0.1
+      lon = nd.lon - 0.1
+      post :amf_write, :body => amf_content("putpoi", "/2", ["#{user.email}:test", cs_id, nd.version + 1, nd.id, lon, lat, nd.tags, nd.visible])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/2")
+
+      assert_equal 5, result.size
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+      assert_equal nd.id, result[2]
+      assert_equal nd.id, result[3]
+      assert_equal nd.version + 2, result[4]
+    end
+
+    # Check that we can create a no valid poi
+    # Using similar method for the node controller test
+    def test_putpoi_create_valid
+      # This node has no tags
+
+      # create a node with random lat/lon
+      lat = rand(-50..49) + rand
+      lon = rand(-50..49) + rand
+
+      changeset = create(:changeset)
+      user = changeset.user
+
+      post :amf_write, :body => amf_content("putpoi", "/1", ["#{user.email}:test", changeset.id, nil, nil, lon, lat, {}, nil])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      # check the array returned by the amf
+      assert_equal 5, result.size
+      assert_equal 0, result[0], "expected to get the status ok from the amf"
+      assert_equal 0, result[2], "The old id should be 0"
+      assert result[3].positive?, "The new id should be greater than 0"
+      assert_equal 1, result[4], "The new version should be 1"
+
+      # Finally check that the node that was saved has saved the data correctly
+      # in both the current and history tables
+      # First check the current table
+      current_node = Node.find(result[3].to_i)
+      assert_in_delta lat, current_node.lat, 0.00001, "The latitude was not retreieved correctly"
+      assert_in_delta lon, current_node.lon, 0.00001, "The longitude was not retreived correctly"
+      assert_equal 0, current_node.tags.size, "There seems to be a tag that has been added to the node"
+      assert_equal result[4], current_node.version, "The version returned, is different to the one returned by the amf"
+      # Now check the history table
+      historic_nodes = OldNode.where(:node_id => result[3])
+      assert_equal 1, historic_nodes.size, "There should only be one historic node created"
+      first_historic_node = historic_nodes.first
+      assert_in_delta lat, first_historic_node.lat, 0.00001, "The latitude was not retreived correctly"
+      assert_in_delta lon, first_historic_node.lon, 0.00001, "The longitude was not retreuved correctly"
+      assert_equal 0, first_historic_node.tags.size, "There seems to be a tag that have been attached to this node"
+      assert_equal result[4], first_historic_node.version, "The version returned, is different to the one returned by the amf"
+
+      ####
+      # This node has some tags
+
+      # create a node with random lat/lon
+      lat = rand(-50..49) + rand
+      lon = rand(-50..49) + rand
+
+      post :amf_write, :body => amf_content("putpoi", "/2", ["#{user.email}:test", changeset.id, nil, nil, lon, lat, { "key" => "value", "ping" => "pong" }, nil])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/2")
+
+      # check the array returned by the amf
+      assert_equal 5, result.size
+      assert_equal 0, result[0], "Expected to get the status ok in the amf"
+      assert_equal 0, result[2], "The old id should be 0"
+      assert result[3].positive?, "The new id should be greater than 0"
+      assert_equal 1, result[4], "The new version should be 1"
+
+      # Finally check that the node that was saved has saved the data correctly
+      # in both the current and history tables
+      # First check the current table
+      current_node = Node.find(result[3].to_i)
+      assert_in_delta lat, current_node.lat, 0.00001, "The latitude was not retreieved correctly"
+      assert_in_delta lon, current_node.lon, 0.00001, "The longitude was not retreived correctly"
+      assert_equal 2, current_node.tags.size, "There seems to be a tag that has been added to the node"
+      assert_equal({ "key" => "value", "ping" => "pong" }, current_node.tags, "tags are different")
+      assert_equal result[4], current_node.version, "The version returned, is different to the one returned by the amf"
+      # Now check the history table
+      historic_nodes = OldNode.where(:node_id => result[3])
+      assert_equal 1, historic_nodes.size, "There should only be one historic node created"
+      first_historic_node = historic_nodes.first
+      assert_in_delta lat, first_historic_node.lat, 0.00001, "The latitude was not retreived correctly"
+      assert_in_delta lon, first_historic_node.lon, 0.00001, "The longitude was not retreuved correctly"
+      assert_equal 2, first_historic_node.tags.size, "There seems to be a tag that have been attached to this node"
+      assert_equal({ "key" => "value", "ping" => "pong" }, first_historic_node.tags, "tags are different")
+      assert_equal result[4], first_historic_node.version, "The version returned, is different to the one returned by the amf"
+    end
+
+    # try creating a POI with rubbish in the tags
+    def test_putpoi_create_with_control_chars
+      # This node has no tags
+
+      # create a node with random lat/lon
+      lat = rand(-50..49) + rand
+      lon = rand(-50..49) + rand
+
+      changeset = create(:changeset)
+      user = changeset.user
+
+      mostly_invalid = (0..31).to_a.map(&:chr).join
+      tags = { "something" => "foo#{mostly_invalid}bar" }
+
+      post :amf_write, :body => amf_content("putpoi", "/1", ["#{user.email}:test", changeset.id, nil, nil, lon, lat, tags, nil])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      # check the array returned by the amf
+      assert_equal 5, result.size
+      assert_equal 0, result[0], "Expected to get the status ok in the amf"
+      assert_equal 0, result[2], "The old id should be 0"
+      assert result[3].positive?, "The new id should be greater than 0"
+      assert_equal 1, result[4], "The new version should be 1"
+
+      # Finally check that the node that was saved has saved the data correctly
+      # in both the current and history tables
+      # First check the current table
+      current_node = Node.find(result[3].to_i)
+      assert_equal 1, current_node.tags.size, "There seems to be a tag that has been added to the node"
+      assert_equal({ "something" => "foo\t\n\rbar" }, current_node.tags, "tags were not fixed correctly")
+      assert_equal result[4], current_node.version, "The version returned, is different to the one returned by the amf"
+    end
+
+    # try creating a POI with rubbish in the tags
+    def test_putpoi_create_with_invalid_utf8
+      # This node has no tags
+
+      # create a node with random lat/lon
+      lat = rand(-50..49) + rand
+      lon = rand(-50..49) + rand
+
+      changeset = create(:changeset)
+      user = changeset.user
+
+      invalid = "\xc0\xc0"
+      tags = { "something" => "foo#{invalid}bar" }
+
+      post :amf_write, :body => amf_content("putpoi", "/1", ["#{user.email}:test", changeset.id, nil, nil, lon, lat, tags, nil])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 2, result.size
+      assert_equal(-1, result[0], "Expected to get the status FAIL in the amf")
+      assert_equal "One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1.", result[1]
+    end
+
+    # try deleting a node
+    def test_putpoi_delete_valid
+      nd = create(:node)
+      cs_id = nd.changeset.id
+      user = nd.changeset.user
+
+      post :amf_write, :body => amf_content("putpoi", "/1", ["#{user.email}:test", cs_id, nd.version, nd.id, nd.lon, nd.lat, nd.tags, false])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 5, result.size
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+      assert_equal nd.id, result[2]
+      assert_equal nd.id, result[3]
+      assert_equal nd.version + 1, result[4]
+
+      current_node = Node.find(result[3].to_i)
+      assert_equal false, current_node.visible
+    end
+
+    # try deleting a node that is already deleted
+    def test_putpoi_delete_already_deleted
+      nd = create(:node, :deleted)
+      cs_id = nd.changeset.id
+      user = nd.changeset.user
+
+      post :amf_write, :body => amf_content("putpoi", "/1", ["#{user.email}:test", cs_id, nd.version, nd.id, nd.lon, nd.lat, nd.tags, false])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 3, result.size
+      assert_equal(-4, result[0])
+      assert_equal "node", result[1]
+      assert_equal nd.id, result[2]
+    end
+
+    # try deleting a node that has never existed
+    def test_putpoi_delete_not_found
+      changeset = create(:changeset)
+      cs_id = changeset.id
+      user = changeset.user
+
+      post :amf_write, :body => amf_content("putpoi", "/1", ["#{user.email}:test", cs_id, 1, 999999, 0, 0, {}, false])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 3, result.size
+      assert_equal(-4, result[0])
+      assert_equal "node", result[1]
+      assert_equal 999999, result[2]
+    end
+
+    # try setting an invalid location on a node
+    def test_putpoi_invalid_latlon
+      nd = create(:node)
+      cs_id = nd.changeset.id
+      user = nd.changeset.user
+
+      post :amf_write, :body => amf_content("putpoi", "/1", ["#{user.email}:test", cs_id, nd.version, nd.id, 200, 100, nd.tags, true])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 2, result.size
+      assert_equal(-2, result[0])
+      assert_match(/Node is not in the world/, result[1])
+    end
+
+    # check that we can create a way
+    def test_putway_create_valid
+      changeset = create(:changeset)
+      cs_id = changeset.id
+      user = changeset.user
+
+      a = create(:node).id
+      b = create(:node).id
+      c = create(:node).id
+      d = create(:node).id
+      e = create(:node).id
+
+      post :amf_write, :body => amf_content("putway", "/1", ["#{user.email}:test", cs_id, 0, -1, [a, b, c], { "test" => "new" }, [], {}])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+      new_way_id = result[3].to_i
+
+      assert_equal 8, result.size
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+      assert_equal(-1, result[2])
+      assert_not_equal(-1, result[3])
+      assert_equal({}, result[4])
+      assert_equal 1, result[5]
+      assert_equal({}, result[6])
+      assert_equal({}, result[7])
+
+      new_way = Way.find(new_way_id)
+      assert_equal 1, new_way.version
+      assert_equal [a, b, c], new_way.nds
+      assert_equal({ "test" => "new" }, new_way.tags)
+
+      post :amf_write, :body => amf_content("putway", "/1", ["#{user.email}:test", cs_id, 0, -1, [b, d, e, a], { "test" => "newer" }, [], {}])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+      new_way_id = result[3].to_i
+
+      assert_equal 8, result.size
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+      assert_equal(-1, result[2])
+      assert_not_equal(-1, result[3])
+      assert_equal({}, result[4])
+      assert_equal 1, result[5]
+      assert_equal({}, result[6])
+      assert_equal({}, result[7])
+
+      new_way = Way.find(new_way_id)
+      assert_equal 1, new_way.version
+      assert_equal [b, d, e, a], new_way.nds
+      assert_equal({ "test" => "newer" }, new_way.tags)
+
+      post :amf_write, :body => amf_content("putway", "/1", ["#{user.email}:test", cs_id, 0, -1, [b, -1, d, e], { "test" => "newest" }, [[4.56, 12.34, -1, 0, { "test" => "new" }], [12.34, 4.56, d, 1, { "test" => "ok" }]], { a => 1 }])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+      new_way_id = result[3].to_i
+      new_node_id = result[4]["-1"].to_i
+
+      assert_equal 8, result.size
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+      assert_equal(-1, result[2])
+      assert_not_equal(-1, result[3])
+      assert_equal({ "-1" => new_node_id }, result[4])
+      assert_equal 1, result[5]
+      assert_equal({ new_node_id.to_s => 1, d.to_s => 2 }, result[6])
+      assert_equal({ a.to_s => 1 }, result[7])
+
+      new_way = Way.find(new_way_id)
+      assert_equal 1, new_way.version
+      assert_equal [b, new_node_id, d, e], new_way.nds
+      assert_equal({ "test" => "newest" }, new_way.tags)
+
+      new_node = Node.find(new_node_id)
+      assert_equal 1, new_node.version
+      assert_equal true, new_node.visible
+      assert_equal 4.56, new_node.lon
+      assert_equal 12.34, new_node.lat
+      assert_equal({ "test" => "new" }, new_node.tags)
+
+      changed_node = Node.find(d)
+      assert_equal 2, changed_node.version
+      assert_equal true, changed_node.visible
+      assert_equal 12.34, changed_node.lon
+      assert_equal 4.56, changed_node.lat
+      assert_equal({ "test" => "ok" }, changed_node.tags)
+
+      # node is not deleted because our other ways are using it
+      deleted_node = Node.find(a)
+      assert_equal 1, deleted_node.version
+      assert_equal true, deleted_node.visible
+    end
+
+    # check that we can update a way
+    def test_putway_update_valid
+      way = create(:way_with_nodes, :nodes_count => 3)
+      cs_id = way.changeset.id
+      user = way.changeset.user
+
+      assert_not_equal({ "test" => "ok" }, way.tags)
+      post :amf_write, :body => amf_content("putway", "/1", ["#{user.email}:test", cs_id, way.version, way.id, way.nds, { "test" => "ok" }, [], {}])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 8, result.size
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+      assert_equal way.id, result[2]
+      assert_equal way.id, result[3]
+      assert_equal({}, result[4])
+      assert_equal way.version + 1, result[5]
+      assert_equal({}, result[6])
+      assert_equal({}, result[7])
+
+      new_way = Way.find(way.id)
+      assert_equal way.version + 1, new_way.version
+      assert_equal way.nds, new_way.nds
+      assert_equal({ "test" => "ok" }, new_way.tags)
+
+      # Test changing the nodes in the way
+      a = create(:node).id
+      b = create(:node).id
+      c = create(:node).id
+      d = create(:node).id
+
+      assert_not_equal [a, b, c, d], way.nds
+      post :amf_write, :body => amf_content("putway", "/1", ["#{user.email}:test", cs_id, way.version + 1, way.id, [a, b, c, d], way.tags, [], {}])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 8, result.size
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+      assert_equal way.id, result[2]
+      assert_equal way.id, result[3]
+      assert_equal({}, result[4])
+      assert_equal way.version + 2, result[5]
+      assert_equal({}, result[6])
+      assert_equal({}, result[7])
+
+      new_way = Way.find(way.id)
+      assert_equal way.version + 2, new_way.version
+      assert_equal [a, b, c, d], new_way.nds
+      assert_equal way.tags, new_way.tags
+
+      post :amf_write, :body => amf_content("putway", "/1", ["#{user.email}:test", cs_id, way.version + 2, way.id, [a, -1, b, c], way.tags, [[4.56, 12.34, -1, 0, { "test" => "new" }], [12.34, 4.56, b, 1, { "test" => "ok" }]], { d => 1 }])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+      new_node_id = result[4]["-1"].to_i
+
+      assert_equal 8, result.size
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+      assert_equal way.id, result[2]
+      assert_equal way.id, result[3]
+      assert_equal({ "-1" => new_node_id }, result[4])
+      assert_equal way.version + 3, result[5]
+      assert_equal({ new_node_id.to_s => 1, b.to_s => 2 }, result[6])
+      assert_equal({ d.to_s => 1 }, result[7])
+
+      new_way = Way.find(way.id)
+      assert_equal way.version + 3, new_way.version
+      assert_equal [a, new_node_id, b, c], new_way.nds
+      assert_equal way.tags, new_way.tags
+
+      new_node = Node.find(new_node_id)
+      assert_equal 1, new_node.version
+      assert_equal true, new_node.visible
+      assert_equal 4.56, new_node.lon
+      assert_equal 12.34, new_node.lat
+      assert_equal({ "test" => "new" }, new_node.tags)
+
+      changed_node = Node.find(b)
+      assert_equal 2, changed_node.version
+      assert_equal true, changed_node.visible
+      assert_equal 12.34, changed_node.lon
+      assert_equal 4.56, changed_node.lat
+      assert_equal({ "test" => "ok" }, changed_node.tags)
+
+      deleted_node = Node.find(d)
+      assert_equal 2, deleted_node.version
+      assert_equal false, deleted_node.visible
+    end
+
+    # check that we can delete a way
+    def test_deleteway_valid
+      way = create(:way_with_nodes, :nodes_count => 3)
+      nodes = way.nodes.each_with_object({}) { |n, ns| ns[n.id] = n.version }
+      cs_id = way.changeset.id
+      user = way.changeset.user
+
+      # Of the three nodes, two should be kept since they are used in
+      # a different way, and the third deleted since it's unused
+
+      a = way.nodes[0]
+      create(:way_node, :node => a)
+      b = way.nodes[1]
+      create(:way_node, :node => b)
+      c = way.nodes[2]
+
+      post :amf_write, :body => amf_content("deleteway", "/1", ["#{user.email}:test", cs_id, way.id, way.version, nodes])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 5, result.size
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+      assert_equal way.id, result[2]
+      assert_equal way.version + 1, result[3]
+      assert_equal({ c.id.to_s => 2 }, result[4])
+
+      new_way = Way.find(way.id)
+      assert_equal way.version + 1, new_way.version
+      assert_equal false, new_way.visible
+
+      way.nds.each do |node_id|
+        assert_equal result[4][node_id.to_s].nil?, Node.find(node_id).visible
+      end
+    end
+
+    # check that we can't delete a way that is in use
+    def test_deleteway_inuse
+      way = create(:way_with_nodes, :nodes_count => 4)
+      create(:relation_member, :member => way)
+      nodes = way.nodes.each_with_object({}) { |n, ns| ns[n.id] = n.version }
+      cs_id = way.changeset.id
+      user = way.changeset.user
+
+      post :amf_write, :body => amf_content("deleteway", "/1", ["#{user.email}:test", cs_id, way.id, way.version, nodes])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 2, result.size
+      assert_equal(-1, result[0])
+      assert_match(/Way #{way.id} is still used/, result[1])
+
+      new_way = Way.find(way.id)
+      assert_equal way.version, new_way.version
+      assert_equal true, new_way.visible
+
+      way.nds.each do |node_id|
+        assert_equal true, Node.find(node_id).visible
+      end
+    end
+
+    # check that we can create a relation
+    def test_putrelation_create_valid
+      changeset = create(:changeset)
+      user = changeset.user
+      cs_id = changeset.id
+
+      node = create(:node)
+      way = create(:way_with_nodes, :nodes_count => 2)
+      relation = create(:relation)
+
+      post :amf_write, :body => amf_content("putrelation", "/1", ["#{user.email}:test", cs_id, 0, -1, { "test" => "new" }, [["Node", node.id, "node"], ["Way", way.id, "way"], ["Relation", relation.id, "relation"]], true])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+      new_relation_id = result[3].to_i
+
+      assert_equal 5, result.size
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+      assert_equal(-1, result[2])
+      assert_not_equal(-1, result[3])
+      assert_equal 1, result[4]
+
+      new_relation = Relation.find(new_relation_id)
+      assert_equal 1, new_relation.version
+      assert_equal [["Node", node.id, "node"], ["Way", way.id, "way"], ["Relation", relation.id, "relation"]], new_relation.members
+      assert_equal({ "test" => "new" }, new_relation.tags)
+      assert_equal true, new_relation.visible
+    end
+
+    # check that we can update a relation
+    def test_putrelation_update_valid
+      relation = create(:relation)
+      create(:relation_member, :relation => relation)
+      user = relation.changeset.user
+      cs_id = relation.changeset.id
+
+      assert_not_equal({ "test" => "ok" }, relation.tags)
+      post :amf_write, :body => amf_content("putrelation", "/1", ["#{user.email}:test", cs_id, relation.version, relation.id, { "test" => "ok" }, relation.members, true])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 5, result.size
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+      assert_equal relation.id, result[2]
+      assert_equal relation.id, result[3]
+      assert_equal relation.version + 1, result[4]
+
+      new_relation = Relation.find(relation.id)
+      assert_equal relation.version + 1, new_relation.version
+      assert_equal relation.members, new_relation.members
+      assert_equal({ "test" => "ok" }, new_relation.tags)
+      assert_equal true, new_relation.visible
+    end
+
+    # check that we can delete a relation
+    def test_putrelation_delete_valid
+      relation = create(:relation)
+      create(:relation_member, :relation => relation)
+      create(:relation_tag, :relation => relation)
+      cs_id = relation.changeset.id
+      user = relation.changeset.user
+
+      post :amf_write, :body => amf_content("putrelation", "/1", ["#{user.email}:test", cs_id, relation.version, relation.id, relation.tags, relation.members, false])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 5, result.size
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+      assert_equal relation.id, result[2]
+      assert_equal relation.id, result[3]
+      assert_equal relation.version + 1, result[4]
+
+      new_relation = Relation.find(relation.id)
+      assert_equal relation.version + 1, new_relation.version
+      assert_equal [], new_relation.members
+      assert_equal({}, new_relation.tags)
+      assert_equal false, new_relation.visible
+    end
+
+    # check that we can't delete a relation that is in use
+    def test_putrelation_delete_inuse
+      relation = create(:relation)
+      super_relation = create(:relation)
+      create(:relation_member, :relation => super_relation, :member => relation)
+      cs_id = relation.changeset.id
+      user = relation.changeset.user
+
+      post :amf_write, :body => amf_content("putrelation", "/1", ["#{user.email}:test", cs_id, relation.version, relation.id, relation.tags, relation.members, false])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 2, result.size
+      assert_equal(-1, result[0])
+      assert_match(/relation #{relation.id} is used in/, result[1])
+
+      new_relation = Relation.find(relation.id)
+      assert_equal relation.version, new_relation.version
+      assert_equal relation.members, new_relation.members
+      assert_equal relation.tags, new_relation.tags
+      assert_equal true, new_relation.visible
+    end
+
+    # check that we can open a changeset
+    def test_startchangeset_valid
+      user = create(:user)
+
+      post :amf_write, :body => amf_content("startchangeset", "/1", ["#{user.email}:test", { "source" => "new" }, nil, "new", 1])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+      new_cs_id = result[2].to_i
+
+      assert_equal 3, result.size
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+
+      cs = Changeset.find(new_cs_id)
+      assert_equal true, cs.is_open?
+      assert_equal({ "comment" => "new", "source" => "new" }, cs.tags)
+
+      old_cs_id = new_cs_id
+
+      post :amf_write, :body => amf_content("startchangeset", "/1", ["#{user.email}:test", { "source" => "newer" }, old_cs_id, "newer", 1])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+      new_cs_id = result[2].to_i
+
+      assert_not_equal old_cs_id, new_cs_id
+
+      assert_equal 3, result.size
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+
+      cs = Changeset.find(old_cs_id)
+      assert_equal false, cs.is_open?
+      assert_equal({ "comment" => "newer", "source" => "new" }, cs.tags)
+
+      cs = Changeset.find(new_cs_id)
+      assert_equal true, cs.is_open?
+      assert_equal({ "comment" => "newer", "source" => "newer" }, cs.tags)
+
+      old_cs_id = new_cs_id
+
+      post :amf_write, :body => amf_content("startchangeset", "/1", ["#{user.email}:test", {}, old_cs_id, "", 0])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 3, result.size
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+      assert_nil result[2]
+
+      cs = Changeset.find(old_cs_id)
+      assert_equal false, cs.is_open?
+      assert_equal({ "comment" => "newer", "source" => "newer" }, cs.tags)
+    end
+
+    # check that we can't close somebody elses changeset
+    def test_startchangeset_invalid_wrong_user
+      user = create(:user)
+      user2 = create(:user)
+
+      post :amf_write, :body => amf_content("startchangeset", "/1", ["#{user.email}:test", { "source" => "new" }, nil, "new", 1])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+      cs_id = result[2].to_i
+
+      assert_equal 3, result.size
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+
+      cs = Changeset.find(cs_id)
+      assert_equal true, cs.is_open?
+      assert_equal({ "comment" => "new", "source" => "new" }, cs.tags)
+
+      post :amf_write, :body => amf_content("startchangeset", "/1", ["#{user2.email}:test", {}, cs_id, "delete", 0])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+
+      assert_equal 2, result.size
+      assert_equal(-2, result[0])
+      assert_equal "The user doesn't own that changeset", result[1]
+
+      cs = Changeset.find(cs_id)
+      assert_equal true, cs.is_open?
+      assert_equal({ "comment" => "new", "source" => "new" }, cs.tags)
+    end
+
+    # check that invalid characters are stripped from changeset tags
+    def test_startchangeset_invalid_xmlchar_comment
+      user = create(:user)
+
+      invalid = "\035\022"
+      comment = "foo#{invalid}bar"
+
+      post :amf_write, :body => amf_content("startchangeset", "/1", ["#{user.email}:test", {}, nil, comment, 1])
+      assert_response :success
+      amf_parse_response
+      result = amf_result("/1")
+      new_cs_id = result[2].to_i
+
+      assert_equal 3, result.size
+      assert_equal 0, result[0]
+      assert_equal "", result[1]
+
+      cs = Changeset.find(new_cs_id)
+      assert_equal true, cs.is_open?
+      assert_equal({ "comment" => "foobar" }, cs.tags)
+    end
+
+    private
+
+    # ************************************************************
+    # AMF Helper functions
+
+    # Get the result record for the specified ID
+    # It's an assertion FAIL if the record does not exist
+    def amf_result(ref)
+      assert @amf_result.key?("#{ref}/onResult")
+      @amf_result["#{ref}/onResult"]
+    end
+
+    # Encode the AMF message to invoke "target" with parameters as
+    # the passed data. The ref is used to retrieve the results.
+    def amf_content(target, ref, data)
+      a, b = 1.divmod(256)
+      c = StringIO.new
+      c.write 0.chr + 0.chr   # version 0
+      c.write 0.chr + 0.chr   # n headers
+      c.write a.chr + b.chr   # n bodies
+      c.write AMF.encodestring(target)
+      c.write AMF.encodestring(ref)
+      c.write [-1].pack("N")
+      c.write AMF.encodevalue(data)
+
+      c.string
+    end
+
+    # Parses the @response object as an AMF messsage.
+    # The result is a hash of message_ref => data.
+    # The attribute @amf_result is initialised to this hash.
+    def amf_parse_response
+      req = StringIO.new(@response.body)
+
+      req.read(2) # version
+
+      # parse through any headers
+      headers = AMF.getint(req)        # Read number of headers
+      headers.times do                 # Read each header
+        AMF.getstring(req)             #  |
+        req.getc                       #  | skip boolean
+        AMF.getvalue(req)              #  |
+      end
+
+      # parse through responses
+      results = {}
+      bodies = AMF.getint(req)         # Read number of bodies
+      bodies.times do                  # Read each body
+        message = AMF.getstring(req)   #  | get message name
+        AMF.getstring(req)             #  | get index in response sequence
+        AMF.getlong(req)               #  | get total size in bytes
+        args = AMF.getvalue(req)       #  | get response (probably an array)
+        results[message] = args
+      end
+      @amf_result = results
+      results
+    end
+
+    ##
+    # given an array of bounding boxes (each an array of 4 floats), call the
+    # AMF "whichways" controller for each and pass the result back to the
+    # caller's block for assertion testing.
+    def check_bboxes_are_bad(bboxes)
+      bboxes.each do |bbox|
+        post :amf_read, :body => amf_content("whichways", "/1", bbox)
+        assert_response :success
+        amf_parse_response
+
+        # pass the response back to the caller's block to be tested
+        # against what the caller expected.
+        map = amf_result "/1"
+        yield map, bbox
+      end
+    end
+
+    # this should be what AMF controller returns when the bbox of a
+    # whichways request is invalid or too large.
+    def assert_boundary_error(map, msg = nil, error_hint = nil)
+      expected_map = [-2, "Sorry - I can't get the map for that area.#{msg}"]
+      assert_equal expected_map, map, "AMF controller should have returned an error. (#{error_hint})"
+    end
+
+    # this should be what AMF controller returns when the bbox of a
+    # whichways_deleted request is invalid or too large.
+    def assert_deleted_boundary_error(map, msg = nil, error_hint = nil)
+      expected_map = [-2, "Sorry - I can't get the map for that area.#{msg}"]
+      assert_equal expected_map, map, "AMF controller should have returned an error. (#{error_hint})"
+    end
+  end
+end
diff --git a/test/controllers/api/changeset_comments_controller_test.rb b/test/controllers/api/changeset_comments_controller_test.rb
new file mode 100644 (file)
index 0000000..24228c2
--- /dev/null
@@ -0,0 +1,254 @@
+require "test_helper"
+
+module Api
+  class ChangesetCommentsControllerTest < ActionController::TestCase
+    ##
+    # test all routes which lead to this controller
+    def test_routes
+      assert_routing(
+        { :path => "/api/0.6/changeset/1/comment", :method => :post },
+        { :controller => "api/changeset_comments", :action => "create", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/changeset/comment/1/hide", :method => :post },
+        { :controller => "api/changeset_comments", :action => "destroy", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/changeset/comment/1/unhide", :method => :post },
+        { :controller => "api/changeset_comments", :action => "restore", :id => "1" }
+      )
+    end
+
+    ##
+    # create comment success
+    def test_create_comment_success
+      user = create(:user)
+      user2 = create(:user)
+      private_user = create(:user, :data_public => false)
+      suspended_user = create(:user, :suspended)
+      deleted_user = create(:user, :deleted)
+      private_user_closed_changeset = create(:changeset, :closed, :user => private_user)
+
+      basic_authorization user.email, "test"
+
+      assert_difference "ChangesetComment.count", 1 do
+        assert_no_difference "ActionMailer::Base.deliveries.size" do
+          perform_enqueued_jobs do
+            post :create, :params => { :id => private_user_closed_changeset.id, :text => "This is a comment" }
+          end
+        end
+      end
+      assert_response :success
+
+      changeset = create(:changeset, :closed, :user => private_user)
+      changeset.subscribers.push(private_user)
+      changeset.subscribers.push(user)
+      changeset.subscribers.push(suspended_user)
+      changeset.subscribers.push(deleted_user)
+
+      assert_difference "ChangesetComment.count", 1 do
+        assert_difference "ActionMailer::Base.deliveries.size", 1 do
+          perform_enqueued_jobs do
+            post :create, :params => { :id => changeset.id, :text => "This is a comment" }
+          end
+        end
+      end
+      assert_response :success
+
+      email = ActionMailer::Base.deliveries.first
+      assert_equal 1, email.to.length
+      assert_equal "[OpenStreetMap] #{user.display_name} has commented on one of your changesets", email.subject
+      assert_equal private_user.email, email.to.first
+
+      ActionMailer::Base.deliveries.clear
+
+      basic_authorization user2.email, "test"
+
+      assert_difference "ChangesetComment.count", 1 do
+        assert_difference "ActionMailer::Base.deliveries.size", 2 do
+          perform_enqueued_jobs do
+            post :create, :params => { :id => changeset.id, :text => "This is a comment" }
+          end
+        end
+      end
+      assert_response :success
+
+      email = ActionMailer::Base.deliveries.find { |e| e.to.first == private_user.email }
+      assert_not_nil email
+      assert_equal 1, email.to.length
+      assert_equal "[OpenStreetMap] #{user2.display_name} has commented on one of your changesets", email.subject
+
+      email = ActionMailer::Base.deliveries.find { |e| e.to.first == user.email }
+      assert_not_nil email
+      assert_equal 1, email.to.length
+      assert_equal "[OpenStreetMap] #{user2.display_name} has commented on a changeset you are interested in", email.subject
+
+      ActionMailer::Base.deliveries.clear
+    end
+
+    ##
+    # create comment fail
+    def test_create_comment_fail
+      # unauthorized
+      post :create, :params => { :id => create(:changeset, :closed).id, :text => "This is a comment" }
+      assert_response :unauthorized
+
+      basic_authorization create(:user).email, "test"
+
+      # bad changeset id
+      assert_no_difference "ChangesetComment.count" do
+        post :create, :params => { :id => 999111, :text => "This is a comment" }
+      end
+      assert_response :not_found
+
+      # not closed changeset
+      assert_no_difference "ChangesetComment.count" do
+        post :create, :params => { :id => create(:changeset).id, :text => "This is a comment" }
+      end
+      assert_response :conflict
+
+      # no text
+      assert_no_difference "ChangesetComment.count" do
+        post :create, :params => { :id => create(:changeset, :closed).id }
+      end
+      assert_response :bad_request
+
+      # empty text
+      assert_no_difference "ChangesetComment.count" do
+        post :create, :params => { :id => create(:changeset, :closed).id, :text => "" }
+      end
+      assert_response :bad_request
+    end
+
+    ##
+    # test hide comment fail
+    def test_destroy_comment_fail
+      # unauthorized
+      comment = create(:changeset_comment)
+      assert_equal true, comment.visible
+
+      post :destroy, :params => { :id => comment.id }
+      assert_response :unauthorized
+      assert_equal true, comment.reload.visible
+
+      basic_authorization create(:user).email, "test"
+
+      # not a moderator
+      post :destroy, :params => { :id => comment.id }
+      assert_response :forbidden
+      assert_equal true, comment.reload.visible
+
+      basic_authorization create(:moderator_user).email, "test"
+
+      # bad comment id
+      post :destroy, :params => { :id => 999111 }
+      assert_response :not_found
+      assert_equal true, comment.reload.visible
+    end
+
+    ##
+    # test hide comment succes
+    def test_hide_comment_success
+      comment = create(:changeset_comment)
+      assert_equal true, comment.visible
+
+      basic_authorization create(:moderator_user).email, "test"
+
+      post :destroy, :params => { :id => comment.id }
+      assert_response :success
+      assert_equal false, comment.reload.visible
+    end
+
+    ##
+    # test unhide comment fail
+    def test_restore_comment_fail
+      # unauthorized
+      comment = create(:changeset_comment, :visible => false)
+      assert_equal false, comment.visible
+
+      post :restore, :params => { :id => comment.id }
+      assert_response :unauthorized
+      assert_equal false, comment.reload.visible
+
+      basic_authorization create(:user).email, "test"
+
+      # not a moderator
+      post :restore, :params => { :id => comment.id }
+      assert_response :forbidden
+      assert_equal false, comment.reload.visible
+
+      basic_authorization create(:moderator_user).email, "test"
+
+      # bad comment id
+      post :restore, :params => { :id => 999111 }
+      assert_response :not_found
+      assert_equal false, comment.reload.visible
+    end
+
+    ##
+    # test unhide comment succes
+    def test_unhide_comment_success
+      comment = create(:changeset_comment, :visible => false)
+      assert_equal false, comment.visible
+
+      basic_authorization create(:moderator_user).email, "test"
+
+      post :restore, :params => { :id => comment.id }
+      assert_response :success
+      assert_equal true, comment.reload.visible
+    end
+
+    # This test ensures that token capabilities behave correctly for a method that
+    # requires the terms to have been agreed.
+    # (This would be better as an integration or system testcase, since the changeset_comment
+    # create method is simply a stand-in for any method that requires terms agreement.
+    # But writing oauth tests is hard, and so it's easier to put in a controller test.)
+    def test_api_write_and_terms_agreed_via_token
+      user = create(:user, :terms_agreed => nil)
+      token = create(:access_token, :user => user, :allow_write_api => true)
+      changeset = create(:changeset, :closed)
+
+      # Hack together an oauth request - an alternative would be to sign the request properly
+      @request.env["oauth.version"] = 1
+      @request.env["oauth.strategies"] = [:token]
+      @request.env["oauth.token"] = token
+
+      assert_difference "ChangesetComment.count", 0 do
+        post :create, :params => { :id => changeset.id, :text => "This is a comment" }
+      end
+      assert_response :forbidden
+
+      # Try again, after agreement with the terms
+      user.terms_agreed = Time.now
+      user.save!
+
+      assert_difference "ChangesetComment.count", 1 do
+        post :create, :params => { :id => changeset.id, :text => "This is a comment" }
+      end
+      assert_response :success
+    end
+
+    # This test does the same as above, but with basic auth, to similarly test that the
+    # abilities take into account terms agreement too.
+    def test_api_write_and_terms_agreed_via_basic_auth
+      user = create(:user, :terms_agreed => nil)
+      changeset = create(:changeset, :closed)
+
+      basic_authorization user.email, "test"
+
+      assert_difference "ChangesetComment.count", 0 do
+        post :create, :params => { :id => changeset.id, :text => "This is a comment" }
+      end
+      assert_response :forbidden
+
+      # Try again, after agreement with the terms
+      user.terms_agreed = Time.now
+      user.save!
+
+      assert_difference "ChangesetComment.count", 1 do
+        post :create, :params => { :id => changeset.id, :text => "This is a comment" }
+      end
+      assert_response :success
+    end
+  end
+end
diff --git a/test/controllers/api/changesets_controller_test.rb b/test/controllers/api/changesets_controller_test.rb
new file mode 100644 (file)
index 0000000..75896b2
--- /dev/null
@@ -0,0 +1,1963 @@
+require "test_helper"
+
+module Api
+  class ChangesetsControllerTest < ActionController::TestCase
+    ##
+    # test all routes which lead to this controller
+    def test_routes
+      assert_routing(
+        { :path => "/api/0.6/changeset/create", :method => :put },
+        { :controller => "api/changesets", :action => "create" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/changeset/1/upload", :method => :post },
+        { :controller => "api/changesets", :action => "upload", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/changeset/1/download", :method => :get },
+        { :controller => "api/changesets", :action => "download", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/changeset/1/expand_bbox", :method => :post },
+        { :controller => "api/changesets", :action => "expand_bbox", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/changeset/1", :method => :get },
+        { :controller => "api/changesets", :action => "show", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/changeset/1/subscribe", :method => :post },
+        { :controller => "api/changesets", :action => "subscribe", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/changeset/1/unsubscribe", :method => :post },
+        { :controller => "api/changesets", :action => "unsubscribe", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/changeset/1", :method => :put },
+        { :controller => "api/changesets", :action => "update", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/changeset/1/close", :method => :put },
+        { :controller => "api/changesets", :action => "close", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/changesets", :method => :get },
+        { :controller => "api/changesets", :action => "query" }
+      )
+    end
+
+    # -----------------------
+    # Test simple changeset creation
+    # -----------------------
+
+    def test_create
+      basic_authorization create(:user, :data_public => false).email, "test"
+      # Create the first user's changeset
+      xml = "<osm><changeset>" \
+            "<tag k='created_by' v='osm test suite checking changesets'/>" \
+            "</changeset></osm>"
+      put :create, :body => xml
+      assert_require_public_data
+
+      basic_authorization create(:user).email, "test"
+      # Create the first user's changeset
+      xml = "<osm><changeset>" \
+            "<tag k='created_by' v='osm test suite checking changesets'/>" \
+            "</changeset></osm>"
+      put :create, :body => xml
+
+      assert_response :success, "Creation of changeset did not return sucess status"
+      newid = @response.body.to_i
+
+      # check end time, should be an hour ahead of creation time
+      cs = Changeset.find(newid)
+      duration = cs.closed_at - cs.created_at
+      # the difference can either be a rational, or a floating point number
+      # of seconds, depending on the code path taken :-(
+      if duration.class == Rational
+        assert_equal Rational(1, 24), duration, "initial idle timeout should be an hour (#{cs.created_at} -> #{cs.closed_at})"
+      else
+        # must be number of seconds...
+        assert_equal 3600, duration.round, "initial idle timeout should be an hour (#{cs.created_at} -> #{cs.closed_at})"
+      end
+
+      # checks if uploader was subscribed
+      assert_equal 1, cs.subscribers.length
+    end
+
+    def test_create_invalid
+      basic_authorization create(:user, :data_public => false).email, "test"
+      xml = "<osm><changeset></osm>"
+      put :create, :body => xml
+      assert_require_public_data
+
+      ## Try the public user
+      basic_authorization create(:user).email, "test"
+      xml = "<osm><changeset></osm>"
+      put :create, :body => xml
+      assert_response :bad_request, "creating a invalid changeset should fail"
+    end
+
+    def test_create_invalid_no_content
+      ## First check with no auth
+      put :create
+      assert_response :unauthorized, "shouldn't be able to create a changeset with no auth"
+
+      ## Now try to with a non-public user
+      basic_authorization create(:user, :data_public => false).email, "test"
+      put :create
+      assert_require_public_data
+
+      ## Try an inactive user
+      basic_authorization create(:user, :pending).email, "test"
+      put :create
+      assert_inactive_user
+
+      ## Now try to use a normal user
+      basic_authorization create(:user).email, "test"
+      put :create
+      assert_response :bad_request, "creating a changeset with no content should fail"
+    end
+
+    def test_create_wrong_method
+      basic_authorization create(:user).email, "test"
+      get :create
+      assert_response :method_not_allowed
+      post :create
+      assert_response :method_not_allowed
+    end
+
+    ##
+    # check that the changeset can be shown and returns the correct
+    # document structure.
+    def test_show
+      changeset_id = create(:changeset).id
+
+      get :show, :params => { :id => changeset_id }
+      assert_response :success, "cannot get first changeset"
+
+      assert_select "osm[version='#{API_VERSION}'][generator='OpenStreetMap server']", 1
+      assert_select "osm>changeset[id='#{changeset_id}']", 1
+      assert_select "osm>changeset>discussion", 0
+
+      get :show, :params => { :id => changeset_id, :include_discussion => true }
+      assert_response :success, "cannot get first changeset with comments"
+
+      assert_select "osm[version='#{API_VERSION}'][generator='OpenStreetMap server']", 1
+      assert_select "osm>changeset[id='#{changeset_id}']", 1
+      assert_select "osm>changeset>discussion", 1
+      assert_select "osm>changeset>discussion>comment", 0
+
+      changeset_id = create(:changeset, :closed).id
+      create_list(:changeset_comment, 3, :changeset_id => changeset_id)
+
+      get :show, :params => { :id => changeset_id, :include_discussion => true }
+      assert_response :success, "cannot get closed changeset with comments"
+
+      assert_select "osm[version='#{API_VERSION}'][generator='OpenStreetMap server']", 1
+      assert_select "osm>changeset[id='#{changeset_id}']", 1
+      assert_select "osm>changeset>discussion", 1
+      assert_select "osm>changeset>discussion>comment", 3
+    end
+
+    ##
+    # check that a changeset that doesn't exist returns an appropriate message
+    def test_show_not_found
+      [0, -32, 233455644, "afg", "213"].each do |id|
+        begin
+          get :show, :params => { :id => id }
+          assert_response :not_found, "should get a not found"
+        rescue ActionController::UrlGenerationError => ex
+          assert_match(/No route matches/, ex.to_s)
+        end
+      end
+    end
+
+    ##
+    # test that the user who opened a change can close it
+    def test_close
+      private_user = create(:user, :data_public => false)
+      private_changeset = create(:changeset, :user => private_user)
+      user = create(:user)
+      changeset = create(:changeset, :user => user)
+
+      ## Try without authentication
+      put :close, :params => { :id => changeset.id }
+      assert_response :unauthorized
+
+      ## Try using the non-public user
+      basic_authorization private_user.email, "test"
+      put :close, :params => { :id => private_changeset.id }
+      assert_require_public_data
+
+      ## The try with the public user
+      basic_authorization user.email, "test"
+
+      cs_id = changeset.id
+      put :close, :params => { :id => cs_id }
+      assert_response :success
+
+      # test that it really is closed now
+      cs = Changeset.find(cs_id)
+      assert_not(cs.is_open?,
+                 "changeset should be closed now (#{cs.closed_at} > #{Time.now.getutc}.")
+    end
+
+    ##
+    # test that a different user can't close another user's changeset
+    def test_close_invalid
+      user = create(:user)
+      changeset = create(:changeset)
+
+      basic_authorization user.email, "test"
+
+      put :close, :params => { :id => changeset.id }
+      assert_response :conflict
+      assert_equal "The user doesn't own that changeset", @response.body
+    end
+
+    ##
+    # test that you can't close using another method
+    def test_close_method_invalid
+      user = create(:user)
+      changeset = create(:changeset, :user => user)
+
+      basic_authorization user.email, "test"
+
+      get :close, :params => { :id => changeset.id }
+      assert_response :method_not_allowed
+
+      post :close, :params => { :id => changeset.id }
+      assert_response :method_not_allowed
+    end
+
+    ##
+    # check that you can't close a changeset that isn't found
+    def test_close_not_found
+      cs_ids = [0, -132, "123"]
+
+      # First try to do it with no auth
+      cs_ids.each do |id|
+        begin
+          put :close, :params => { :id => id }
+          assert_response :unauthorized, "Shouldn't be able close the non-existant changeset #{id}, when not authorized"
+        rescue ActionController::UrlGenerationError => ex
+          assert_match(/No route matches/, ex.to_s)
+        end
+      end
+
+      # Now try with auth
+      basic_authorization create(:user).email, "test"
+      cs_ids.each do |id|
+        begin
+          put :close, :params => { :id => id }
+          assert_response :not_found, "The changeset #{id} doesn't exist, so can't be closed"
+        rescue ActionController::UrlGenerationError => ex
+          assert_match(/No route matches/, ex.to_s)
+        end
+      end
+    end
+
+    ##
+    # upload something simple, but valid and check that it can
+    # be read back ok
+    # Also try without auth and another user.
+    def test_upload_simple_valid
+      private_user = create(:user, :data_public => false)
+      private_changeset = create(:changeset, :user => private_user)
+      user = create(:user)
+      changeset = create(:changeset, :user => user)
+
+      node = create(:node)
+      way = create(:way)
+      relation = create(:relation)
+      other_relation = create(:relation)
+      # create some tags, since we test that they are removed later
+      create(:node_tag, :node => node)
+      create(:way_tag, :way => way)
+      create(:relation_tag, :relation => relation)
+
+      ## Try with no auth
+      changeset_id = changeset.id
+
+      # simple diff to change a node, way and relation by removing
+      # their tags
+      diff = <<CHANGESET.strip_heredoc
+        <osmChange>
+         <modify>
+          <node id='#{node.id}' lon='0' lat='0' changeset='#{changeset_id}' version='1'/>
+          <way id='#{way.id}' changeset='#{changeset_id}' version='1'>
+           <nd ref='#{node.id}'/>
+          </way>
+         </modify>
+         <modify>
+          <relation id='#{relation.id}' changeset='#{changeset_id}' version='1'>
+           <member type='way' role='some' ref='#{way.id}'/>
+           <member type='node' role='some' ref='#{node.id}'/>
+           <member type='relation' role='some' ref='#{other_relation.id}'/>
+          </relation>
+         </modify>
+        </osmChange>
+CHANGESET
+
+      # upload it
+      post :upload, :params => { :id => changeset_id }, :body => diff
+      assert_response :unauthorized,
+                      "shouldn't be able to upload a simple valid diff to changeset: #{@response.body}"
+
+      ## Now try with a private user
+      basic_authorization private_user.email, "test"
+      changeset_id = private_changeset.id
+
+      # simple diff to change a node, way and relation by removing
+      # their tags
+      diff = <<CHANGESET.strip_heredoc
+        <osmChange>
+         <modify>
+          <node id='#{node.id}' lon='0' lat='0' changeset='#{changeset_id}' version='1'/>
+          <way id='#{way.id}' changeset='#{changeset_id}' version='1'>
+           <nd ref='#{node.id}'/>
+          </way>
+         </modify>
+         <modify>
+          <relation id='#{relation.id}' changeset='#{changeset_id}' version='1'>
+           <member type='way' role='some' ref='#{way.id}'/>
+           <member type='node' role='some' ref='#{node.id}'/>
+           <member type='relation' role='some' ref='#{other_relation.id}'/>
+          </relation>
+         </modify>
+        </osmChange>
+CHANGESET
+
+      # upload it
+      post :upload, :params => { :id => changeset_id }, :body => diff
+      assert_response :forbidden,
+                      "can't upload a simple valid diff to changeset: #{@response.body}"
+
+      ## Now try with the public user
+      basic_authorization user.email, "test"
+      changeset_id = changeset.id
+
+      # simple diff to change a node, way and relation by removing
+      # their tags
+      diff = <<CHANGESET.strip_heredoc
+        <osmChange>
+         <modify>
+          <node id='#{node.id}' lon='0' lat='0' changeset='#{changeset_id}' version='1'/>
+          <way id='#{way.id}' changeset='#{changeset_id}' version='1'>
+           <nd ref='#{node.id}'/>
+          </way>
+         </modify>
+         <modify>
+          <relation id='#{relation.id}' changeset='#{changeset_id}' version='1'>
+           <member type='way' role='some' ref='#{way.id}'/>
+           <member type='node' role='some' ref='#{node.id}'/>
+           <member type='relation' role='some' ref='#{other_relation.id}'/>
+          </relation>
+         </modify>
+        </osmChange>
+CHANGESET
+
+      # upload it
+      post :upload, :params => { :id => changeset_id }, :body => diff
+      assert_response :success,
+                      "can't upload a simple valid diff to changeset: #{@response.body}"
+
+      # check that the changes made it into the database
+      assert_equal 0, Node.find(node.id).tags.size, "node #{node.id} should now have no tags"
+      assert_equal 0, Way.find(way.id).tags.size, "way #{way.id} should now have no tags"
+      assert_equal 0, Relation.find(relation.id).tags.size, "relation #{relation.id} should now have no tags"
+    end
+
+    ##
+    # upload something which creates new objects using placeholders
+    def test_upload_create_valid
+      user = create(:user)
+      changeset = create(:changeset, :user => user)
+      node = create(:node)
+      way = create(:way_with_nodes, :nodes_count => 2)
+      relation = create(:relation)
+
+      basic_authorization user.email, "test"
+
+      # simple diff to create a node way and relation using placeholders
+      diff = <<CHANGESET.strip_heredoc
+        <osmChange>
+         <create>
+          <node id='-1' lon='0' lat='0' changeset='#{changeset.id}'>
+           <tag k='foo' v='bar'/>
+           <tag k='baz' v='bat'/>
+          </node>
+          <way id='-1' changeset='#{changeset.id}'>
+           <nd ref='#{node.id}'/>
+          </way>
+         </create>
+         <create>
+          <relation id='-1' changeset='#{changeset.id}'>
+           <member type='way' role='some' ref='#{way.id}'/>
+           <member type='node' role='some' ref='#{node.id}'/>
+           <member type='relation' role='some' ref='#{relation.id}'/>
+          </relation>
+         </create>
+        </osmChange>
+CHANGESET
+
+      # upload it
+      post :upload, :params => { :id => changeset.id }, :body => diff
+      assert_response :success,
+                      "can't upload a simple valid creation to changeset: #{@response.body}"
+
+      # check the returned payload
+      assert_select "diffResult[version='#{API_VERSION}'][generator='OpenStreetMap server']", 1
+      assert_select "diffResult>node", 1
+      assert_select "diffResult>way", 1
+      assert_select "diffResult>relation", 1
+
+      # inspect the response to find out what the new element IDs are
+      doc = XML::Parser.string(@response.body).parse
+      new_node_id = doc.find("//diffResult/node").first["new_id"].to_i
+      new_way_id = doc.find("//diffResult/way").first["new_id"].to_i
+      new_rel_id = doc.find("//diffResult/relation").first["new_id"].to_i
+
+      # check the old IDs are all present and negative one
+      assert_equal(-1, doc.find("//diffResult/node").first["old_id"].to_i)
+      assert_equal(-1, doc.find("//diffResult/way").first["old_id"].to_i)
+      assert_equal(-1, doc.find("//diffResult/relation").first["old_id"].to_i)
+
+      # check the versions are present and equal one
+      assert_equal 1, doc.find("//diffResult/node").first["new_version"].to_i
+      assert_equal 1, doc.find("//diffResult/way").first["new_version"].to_i
+      assert_equal 1, doc.find("//diffResult/relation").first["new_version"].to_i
+
+      # check that the changes made it into the database
+      assert_equal 2, Node.find(new_node_id).tags.size, "new node should have two tags"
+      assert_equal 0, Way.find(new_way_id).tags.size, "new way should have no tags"
+      assert_equal 0, Relation.find(new_rel_id).tags.size, "new relation should have no tags"
+    end
+
+    ##
+    # test a complex delete where we delete elements which rely on eachother
+    # in the same transaction.
+    def test_upload_delete
+      changeset = create(:changeset)
+      super_relation = create(:relation)
+      used_relation = create(:relation)
+      used_way = create(:way)
+      used_node = create(:node)
+      create(:relation_member, :relation => super_relation, :member => used_relation)
+      create(:relation_member, :relation => super_relation, :member => used_way)
+      create(:relation_member, :relation => super_relation, :member => used_node)
+
+      basic_authorization changeset.user.display_name, "test"
+
+      diff = XML::Document.new
+      diff.root = XML::Node.new "osmChange"
+      delete = XML::Node.new "delete"
+      diff.root << delete
+      delete << super_relation.to_xml_node
+      delete << used_relation.to_xml_node
+      delete << used_way.to_xml_node
+      delete << used_node.to_xml_node
+
+      # update the changeset to one that this user owns
+      %w[node way relation].each do |type|
+        delete.find("//osmChange/delete/#{type}").each do |n|
+          n["changeset"] = changeset.id.to_s
+        end
+      end
+
+      # upload it
+      post :upload, :params => { :id => changeset.id }, :body => diff.to_s
+      assert_response :success,
+                      "can't upload a deletion diff to changeset: #{@response.body}"
+
+      # check the response is well-formed
+      assert_select "diffResult>node", 1
+      assert_select "diffResult>way", 1
+      assert_select "diffResult>relation", 2
+
+      # check that everything was deleted
+      assert_equal false, Node.find(used_node.id).visible
+      assert_equal false, Way.find(used_way.id).visible
+      assert_equal false, Relation.find(super_relation.id).visible
+      assert_equal false, Relation.find(used_relation.id).visible
+    end
+
+    ##
+    # test uploading a delete with no lat/lon, as they are optional in
+    # the osmChange spec.
+    def test_upload_nolatlon_delete
+      node = create(:node)
+      changeset = create(:changeset)
+
+      basic_authorization changeset.user.display_name, "test"
+      diff = "<osmChange><delete><node id='#{node.id}' version='#{node.version}' changeset='#{changeset.id}'/></delete></osmChange>"
+
+      # upload it
+      post :upload, :params => { :id => changeset.id }, :body => diff
+      assert_response :success,
+                      "can't upload a deletion diff to changeset: #{@response.body}"
+
+      # check the response is well-formed
+      assert_select "diffResult>node", 1
+
+      # check that everything was deleted
+      assert_equal false, Node.find(node.id).visible
+    end
+
+    def test_repeated_changeset_create
+      3.times do
+        basic_authorization create(:user).email, "test"
+
+        # create a temporary changeset
+        xml = "<osm><changeset>" \
+              "<tag k='created_by' v='osm test suite checking changesets'/>" \
+              "</changeset></osm>"
+        assert_difference "Changeset.count", 1 do
+          put :create, :body => xml
+        end
+        assert_response :success
+      end
+    end
+
+    def test_upload_large_changeset
+      basic_authorization create(:user).email, "test"
+
+      # create a changeset
+      put :create, :body => "<osm><changeset/></osm>"
+      assert_response :success, "Should be able to create a changeset: #{@response.body}"
+      changeset_id = @response.body.to_i
+
+      # upload some widely-spaced nodes, spiralling positive and negative
+      diff = <<CHANGESET.strip_heredoc
+        <osmChange>
+         <create>
+          <node id='-1' lon='-20' lat='-10' changeset='#{changeset_id}'/>
+          <node id='-10' lon='20'  lat='10' changeset='#{changeset_id}'/>
+          <node id='-2' lon='-40' lat='-20' changeset='#{changeset_id}'/>
+          <node id='-11' lon='40'  lat='20' changeset='#{changeset_id}'/>
+          <node id='-3' lon='-60' lat='-30' changeset='#{changeset_id}'/>
+          <node id='-12' lon='60'  lat='30' changeset='#{changeset_id}'/>
+          <node id='-4' lon='-80' lat='-40' changeset='#{changeset_id}'/>
+          <node id='-13' lon='80'  lat='40' changeset='#{changeset_id}'/>
+          <node id='-5' lon='-100' lat='-50' changeset='#{changeset_id}'/>
+          <node id='-14' lon='100'  lat='50' changeset='#{changeset_id}'/>
+          <node id='-6' lon='-120' lat='-60' changeset='#{changeset_id}'/>
+          <node id='-15' lon='120'  lat='60' changeset='#{changeset_id}'/>
+          <node id='-7' lon='-140' lat='-70' changeset='#{changeset_id}'/>
+          <node id='-16' lon='140'  lat='70' changeset='#{changeset_id}'/>
+          <node id='-8' lon='-160' lat='-80' changeset='#{changeset_id}'/>
+          <node id='-17' lon='160'  lat='80' changeset='#{changeset_id}'/>
+          <node id='-9' lon='-179.9' lat='-89.9' changeset='#{changeset_id}'/>
+          <node id='-18' lon='179.9'  lat='89.9' changeset='#{changeset_id}'/>
+         </create>
+        </osmChange>
+CHANGESET
+
+      # upload it, which used to cause an error like "PGError: ERROR:
+      # integer out of range" (bug #2152). but shouldn't any more.
+      post :upload, :params => { :id => changeset_id }, :body => diff
+      assert_response :success,
+                      "can't upload a spatially-large diff to changeset: #{@response.body}"
+
+      # check that the changeset bbox is within bounds
+      cs = Changeset.find(changeset_id)
+      assert cs.min_lon >= -180 * GeoRecord::SCALE, "Minimum longitude (#{cs.min_lon / GeoRecord::SCALE}) should be >= -180 to be valid."
+      assert cs.max_lon <= 180 * GeoRecord::SCALE, "Maximum longitude (#{cs.max_lon / GeoRecord::SCALE}) should be <= 180 to be valid."
+      assert cs.min_lat >= -90 * GeoRecord::SCALE, "Minimum latitude (#{cs.min_lat / GeoRecord::SCALE}) should be >= -90 to be valid."
+      assert cs.max_lat <= 90 * GeoRecord::SCALE, "Maximum latitude (#{cs.max_lat / GeoRecord::SCALE}) should be <= 90 to be valid."
+    end
+
+    ##
+    # test that deleting stuff in a transaction doesn't bypass the checks
+    # to ensure that used elements are not deleted.
+    def test_upload_delete_invalid
+      changeset = create(:changeset)
+      relation = create(:relation)
+      other_relation = create(:relation)
+      used_way = create(:way)
+      used_node = create(:node)
+      create(:relation_member, :relation => relation, :member => used_way)
+      create(:relation_member, :relation => relation, :member => used_node)
+
+      basic_authorization changeset.user.email, "test"
+
+      diff = XML::Document.new
+      diff.root = XML::Node.new "osmChange"
+      delete = XML::Node.new "delete"
+      diff.root << delete
+      delete << other_relation.to_xml_node
+      delete << used_way.to_xml_node
+      delete << used_node.to_xml_node
+
+      # update the changeset to one that this user owns
+      %w[node way relation].each do |type|
+        delete.find("//osmChange/delete/#{type}").each do |n|
+          n["changeset"] = changeset.id.to_s
+        end
+      end
+
+      # upload it
+      post :upload, :params => { :id => changeset.id }, :body => diff.to_s
+      assert_response :precondition_failed,
+                      "shouldn't be able to upload a invalid deletion diff: #{@response.body}"
+      assert_equal "Precondition failed: Way #{used_way.id} is still used by relations #{relation.id}.", @response.body
+
+      # check that nothing was, in fact, deleted
+      assert_equal true, Node.find(used_node.id).visible
+      assert_equal true, Way.find(used_way.id).visible
+      assert_equal true, Relation.find(relation.id).visible
+      assert_equal true, Relation.find(other_relation.id).visible
+    end
+
+    ##
+    # test that a conditional delete of an in use object works.
+    def test_upload_delete_if_unused
+      changeset = create(:changeset)
+      super_relation = create(:relation)
+      used_relation = create(:relation)
+      used_way = create(:way)
+      used_node = create(:node)
+      create(:relation_member, :relation => super_relation, :member => used_relation)
+      create(:relation_member, :relation => super_relation, :member => used_way)
+      create(:relation_member, :relation => super_relation, :member => used_node)
+
+      basic_authorization changeset.user.email, "test"
+
+      diff = XML::Document.new
+      diff.root = XML::Node.new "osmChange"
+      delete = XML::Node.new "delete"
+      diff.root << delete
+      delete["if-unused"] = ""
+      delete << used_relation.to_xml_node
+      delete << used_way.to_xml_node
+      delete << used_node.to_xml_node
+
+      # update the changeset to one that this user owns
+      %w[node way relation].each do |type|
+        delete.find("//osmChange/delete/#{type}").each do |n|
+          n["changeset"] = changeset.id.to_s
+        end
+      end
+
+      # upload it
+      post :upload, :params => { :id => changeset.id }, :body => diff.to_s
+      assert_response :success,
+                      "can't do a conditional delete of in use objects: #{@response.body}"
+
+      # check the returned payload
+      assert_select "diffResult[version='#{API_VERSION}'][generator='OpenStreetMap server']", 1
+      assert_select "diffResult>node", 1
+      assert_select "diffResult>way", 1
+      assert_select "diffResult>relation", 1
+
+      # parse the response
+      doc = XML::Parser.string(@response.body).parse
+
+      # check the old IDs are all present and what we expect
+      assert_equal used_node.id, doc.find("//diffResult/node").first["old_id"].to_i
+      assert_equal used_way.id, doc.find("//diffResult/way").first["old_id"].to_i
+      assert_equal used_relation.id, doc.find("//diffResult/relation").first["old_id"].to_i
+
+      # check the new IDs are all present and unchanged
+      assert_equal used_node.id, doc.find("//diffResult/node").first["new_id"].to_i
+      assert_equal used_way.id, doc.find("//diffResult/way").first["new_id"].to_i
+      assert_equal used_relation.id, doc.find("//diffResult/relation").first["new_id"].to_i
+
+      # check the new versions are all present and unchanged
+      assert_equal used_node.version, doc.find("//diffResult/node").first["new_version"].to_i
+      assert_equal used_way.version, doc.find("//diffResult/way").first["new_version"].to_i
+      assert_equal used_relation.version, doc.find("//diffResult/relation").first["new_version"].to_i
+
+      # check that nothing was, in fact, deleted
+      assert_equal true, Node.find(used_node.id).visible
+      assert_equal true, Way.find(used_way.id).visible
+      assert_equal true, Relation.find(used_relation.id).visible
+    end
+
+    ##
+    # upload an element with a really long tag value
+    def test_upload_invalid_too_long_tag
+      changeset = create(:changeset)
+
+      basic_authorization changeset.user.email, "test"
+
+      # simple diff to create a node way and relation using placeholders
+      diff = <<CHANGESET.strip_heredoc
+        <osmChange>
+         <create>
+          <node id='-1' lon='0' lat='0' changeset='#{changeset.id}'>
+           <tag k='foo' v='#{'x' * 256}'/>
+          </node>
+         </create>
+        </osmChange>
+CHANGESET
+
+      # upload it
+      post :upload, :params => { :id => changeset.id }, :body => diff
+      assert_response :bad_request,
+                      "shoudln't be able to upload too long a tag to changeset: #{@response.body}"
+    end
+
+    ##
+    # upload something which creates new objects and inserts them into
+    # existing containers using placeholders.
+    def test_upload_complex
+      way = create(:way)
+      node = create(:node)
+      relation = create(:relation)
+      create(:way_node, :way => way, :node => node)
+
+      changeset = create(:changeset)
+
+      basic_authorization changeset.user.email, "test"
+
+      # simple diff to create a node way and relation using placeholders
+      diff = <<CHANGESET.strip_heredoc
+        <osmChange>
+         <create>
+          <node id='-1' lon='0' lat='0' changeset='#{changeset.id}'>
+           <tag k='foo' v='bar'/>
+           <tag k='baz' v='bat'/>
+          </node>
+         </create>
+         <modify>
+          <way id='#{way.id}' changeset='#{changeset.id}' version='1'>
+           <nd ref='-1'/>
+           <nd ref='#{node.id}'/>
+          </way>
+          <relation id='#{relation.id}' changeset='#{changeset.id}' version='1'>
+           <member type='way' role='some' ref='#{way.id}'/>
+           <member type='node' role='some' ref='-1'/>
+           <member type='relation' role='some' ref='#{relation.id}'/>
+          </relation>
+         </modify>
+        </osmChange>
+CHANGESET
+
+      # upload it
+      post :upload, :params => { :id => changeset.id }, :body => diff
+      assert_response :success,
+                      "can't upload a complex diff to changeset: #{@response.body}"
+
+      # check the returned payload
+      assert_select "diffResult[version='#{API_VERSION}'][generator='#{GENERATOR}']", 1
+      assert_select "diffResult>node", 1
+      assert_select "diffResult>way", 1
+      assert_select "diffResult>relation", 1
+
+      # inspect the response to find out what the new element IDs are
+      doc = XML::Parser.string(@response.body).parse
+      new_node_id = doc.find("//diffResult/node").first["new_id"].to_i
+
+      # check that the changes made it into the database
+      assert_equal 2, Node.find(new_node_id).tags.size, "new node should have two tags"
+      assert_equal [new_node_id, node.id], Way.find(way.id).nds, "way nodes should match"
+      Relation.find(relation.id).members.each do |type, id, _role|
+        assert_equal new_node_id, id, "relation should contain new node" if type == "node"
+      end
+    end
+
+    ##
+    # create a diff which references several changesets, which should cause
+    # a rollback and none of the diff gets committed
+    def test_upload_invalid_changesets
+      changeset = create(:changeset)
+      other_changeset = create(:changeset, :user => changeset.user)
+      node = create(:node)
+      way = create(:way)
+      relation = create(:relation)
+      other_relation = create(:relation)
+
+      basic_authorization changeset.user.email, "test"
+
+      # simple diff to create a node way and relation using placeholders
+      diff = <<CHANGESET.strip_heredoc
+        <osmChange>
+         <modify>
+          <node id='#{node.id}' lon='0' lat='0' changeset='#{changeset.id}' version='1'/>
+          <way id='#{way.id}' changeset='#{changeset.id}' version='1'>
+           <nd ref='#{node.id}'/>
+          </way>
+         </modify>
+         <modify>
+          <relation id='#{relation.id}' changeset='#{changeset.id}' version='1'>
+           <member type='way' role='some' ref='#{way.id}'/>
+           <member type='node' role='some' ref='#{node.id}'/>
+           <member type='relation' role='some' ref='#{other_relation.id}'/>
+          </relation>
+         </modify>
+         <create>
+          <node id='-1' lon='0' lat='0' changeset='#{other_changeset.id}'>
+           <tag k='foo' v='bar'/>
+           <tag k='baz' v='bat'/>
+          </node>
+         </create>
+        </osmChange>
+CHANGESET
+
+      # upload it
+      post :upload, :params => { :id => changeset.id }, :body => diff
+      assert_response :conflict,
+                      "uploading a diff with multiple changesets should have failed"
+
+      # check that objects are unmodified
+      assert_nodes_are_equal(node, Node.find(node.id))
+      assert_ways_are_equal(way, Way.find(way.id))
+      assert_relations_are_equal(relation, Relation.find(relation.id))
+    end
+
+    ##
+    # upload multiple versions of the same element in the same diff.
+    def test_upload_multiple_valid
+      node = create(:node)
+      changeset = create(:changeset)
+      basic_authorization changeset.user.email, "test"
+
+      # change the location of a node multiple times, each time referencing
+      # the last version. doesn't this depend on version numbers being
+      # sequential?
+      diff = <<CHANGESET.strip_heredoc
+        <osmChange>
+         <modify>
+          <node id='#{node.id}' lon='0' lat='0' changeset='#{changeset.id}' version='1'/>
+          <node id='#{node.id}' lon='1' lat='0' changeset='#{changeset.id}' version='2'/>
+          <node id='#{node.id}' lon='1' lat='1' changeset='#{changeset.id}' version='3'/>
+          <node id='#{node.id}' lon='1' lat='2' changeset='#{changeset.id}' version='4'/>
+          <node id='#{node.id}' lon='2' lat='2' changeset='#{changeset.id}' version='5'/>
+          <node id='#{node.id}' lon='3' lat='2' changeset='#{changeset.id}' version='6'/>
+          <node id='#{node.id}' lon='3' lat='3' changeset='#{changeset.id}' version='7'/>
+          <node id='#{node.id}' lon='9' lat='9' changeset='#{changeset.id}' version='8'/>
+         </modify>
+        </osmChange>
+CHANGESET
+
+      # upload it
+      post :upload, :params => { :id => changeset.id }, :body => diff
+      assert_response :success,
+                      "can't upload multiple versions of an element in a diff: #{@response.body}"
+
+      # check the response is well-formed. its counter-intuitive, but the
+      # API will return multiple elements with the same ID and different
+      # version numbers for each change we made.
+      assert_select "diffResult>node", 8
+    end
+
+    ##
+    # upload multiple versions of the same element in the same diff, but
+    # keep the version numbers the same.
+    def test_upload_multiple_duplicate
+      node = create(:node)
+      changeset = create(:changeset)
+
+      basic_authorization changeset.user.email, "test"
+
+      diff = <<CHANGESET.strip_heredoc
+        <osmChange>
+         <modify>
+          <node id='#{node.id}' lon='0' lat='0' changeset='#{changeset.id}' version='1'/>
+          <node id='#{node.id}' lon='1' lat='1' changeset='#{changeset.id}' version='1'/>
+         </modify>
+        </osmChange>
+CHANGESET
+
+      # upload it
+      post :upload, :params => { :id => changeset.id }, :body => diff
+      assert_response :conflict,
+                      "shouldn't be able to upload the same element twice in a diff: #{@response.body}"
+    end
+
+    ##
+    # try to upload some elements without specifying the version
+    def test_upload_missing_version
+      changeset = create(:changeset)
+
+      basic_authorization changeset.user.email, "test"
+
+      diff = <<CHANGESET.strip_heredoc
+        <osmChange>
+         <modify>
+         <node id='1' lon='1' lat='1' changeset='#{changeset.id}'/>
+         </modify>
+        </osmChange>
+CHANGESET
+
+      # upload it
+      post :upload, :params => { :id => changeset.id }, :body => diff
+      assert_response :bad_request,
+                      "shouldn't be able to upload an element without version: #{@response.body}"
+    end
+
+    ##
+    # try to upload with commands other than create, modify, or delete
+    def test_action_upload_invalid
+      changeset = create(:changeset)
+
+      basic_authorization changeset.user.email, "test"
+
+      diff = <<CHANGESET.strip_heredoc
+        <osmChange>
+          <ping>
+           <node id='1' lon='1' lat='1' changeset='#{changeset.id}' />
+          </ping>
+        </osmChange>
+CHANGESET
+      post :upload, :params => { :id => changeset.id }, :body => diff
+      assert_response :bad_request, "Shouldn't be able to upload a diff with the action ping"
+      assert_equal @response.body, "Unknown action ping, choices are create, modify, delete"
+    end
+
+    ##
+    # upload a valid changeset which has a mixture of whitespace
+    # to check a bug reported by ivansanchez (#1565).
+    def test_upload_whitespace_valid
+      changeset = create(:changeset)
+      node = create(:node)
+      way = create(:way_with_nodes, :nodes_count => 2)
+      relation = create(:relation)
+      other_relation = create(:relation)
+      create(:relation_tag, :relation => relation)
+
+      basic_authorization changeset.user.email, "test"
+
+      diff = <<CHANGESET.strip_heredoc
+        <osmChange>
+         <modify><node id='#{node.id}' lon='0' lat='0' changeset='#{changeset.id}'
+          version='1'></node>
+          <node id='#{node.id}' lon='1' lat='1' changeset='#{changeset.id}' version='2'><tag k='k' v='v'/></node></modify>
+         <modify>
+         <relation id='#{relation.id}' changeset='#{changeset.id}' version='1'><member
+           type='way' role='some' ref='#{way.id}'/><member
+            type='node' role='some' ref='#{node.id}'/>
+           <member type='relation' role='some' ref='#{other_relation.id}'/>
+          </relation>
+         </modify></osmChange>
+CHANGESET
+
+      # upload it
+      post :upload, :params => { :id => changeset.id }, :body => diff
+      assert_response :success,
+                      "can't upload a valid diff with whitespace variations to changeset: #{@response.body}"
+
+      # check the response is well-formed
+      assert_select "diffResult>node", 2
+      assert_select "diffResult>relation", 1
+
+      # check that the changes made it into the database
+      assert_equal 1, Node.find(node.id).tags.size, "node #{node.id} should now have one tag"
+      assert_equal 0, Relation.find(relation.id).tags.size, "relation #{relation.id} should now have no tags"
+    end
+
+    ##
+    # test that a placeholder can be reused within the same upload.
+    def test_upload_reuse_placeholder_valid
+      changeset = create(:changeset)
+
+      basic_authorization changeset.user.email, "test"
+
+      diff = <<CHANGESET.strip_heredoc
+        <osmChange>
+         <create>
+          <node id='-1' lon='0' lat='0' changeset='#{changeset.id}'>
+           <tag k="foo" v="bar"/>
+          </node>
+         </create>
+         <modify>
+          <node id='-1' lon='1' lat='1' changeset='#{changeset.id}' version='1'/>
+         </modify>
+         <delete>
+          <node id='-1' lon='2' lat='2' changeset='#{changeset.id}' version='2'/>
+         </delete>
+        </osmChange>
+CHANGESET
+
+      # upload it
+      post :upload, :params => { :id => changeset.id }, :body => diff
+      assert_response :success,
+                      "can't upload a valid diff with re-used placeholders to changeset: #{@response.body}"
+
+      # check the response is well-formed
+      assert_select "diffResult>node", 3
+      assert_select "diffResult>node[old_id='-1']", 3
+    end
+
+    ##
+    # test what happens if a diff upload re-uses placeholder IDs in an
+    # illegal way.
+    def test_upload_placeholder_invalid
+      changeset = create(:changeset)
+
+      basic_authorization changeset.user.email, "test"
+
+      diff = <<CHANGESET.strip_heredoc
+        <osmChange>
+         <create>
+          <node id='-1' lon='0' lat='0' changeset='#{changeset.id}' version='1'/>
+          <node id='-1' lon='1' lat='1' changeset='#{changeset.id}' version='1'/>
+          <node id='-1' lon='2' lat='2' changeset='#{changeset.id}' version='2'/>
+         </create>
+        </osmChange>
+CHANGESET
+
+      # upload it
+      post :upload, :params => { :id => changeset.id }, :body => diff
+      assert_response :bad_request,
+                      "shouldn't be able to re-use placeholder IDs"
+    end
+
+    ##
+    # test that uploading a way referencing invalid placeholders gives a
+    # proper error, not a 500.
+    def test_upload_placeholder_invalid_way
+      changeset = create(:changeset)
+      way = create(:way)
+
+      basic_authorization changeset.user.email, "test"
+
+      diff = <<CHANGESET.strip_heredoc
+        <osmChange>
+         <create>
+          <node id="-1" lon="0" lat="0" changeset="#{changeset.id}" version="1"/>
+          <node id="-2" lon="1" lat="1" changeset="#{changeset.id}" version="1"/>
+          <node id="-3" lon="2" lat="2" changeset="#{changeset.id}" version="1"/>
+          <way id="-1" changeset="#{changeset.id}" version="1">
+           <nd ref="-1"/>
+           <nd ref="-2"/>
+           <nd ref="-3"/>
+           <nd ref="-4"/>
+          </way>
+         </create>
+        </osmChange>
+CHANGESET
+
+      # upload it
+      post :upload, :params => { :id => changeset.id }, :body => diff
+      assert_response :bad_request,
+                      "shouldn't be able to use invalid placeholder IDs"
+      assert_equal "Placeholder node not found for reference -4 in way -1", @response.body
+
+      # the same again, but this time use an existing way
+      diff = <<CHANGESET.strip_heredoc
+        <osmChange>
+         <create>
+          <node id="-1" lon="0" lat="0" changeset="#{changeset.id}" version="1"/>
+          <node id="-2" lon="1" lat="1" changeset="#{changeset.id}" version="1"/>
+          <node id="-3" lon="2" lat="2" changeset="#{changeset.id}" version="1"/>
+          <way id="#{way.id}" changeset="#{changeset.id}" version="1">
+           <nd ref="-1"/>
+           <nd ref="-2"/>
+           <nd ref="-3"/>
+           <nd ref="-4"/>
+          </way>
+         </create>
+        </osmChange>
+CHANGESET
+
+      # upload it
+      post :upload, :params => { :id => changeset.id }, :body => diff
+      assert_response :bad_request,
+                      "shouldn't be able to use invalid placeholder IDs"
+      assert_equal "Placeholder node not found for reference -4 in way #{way.id}", @response.body
+    end
+
+    ##
+    # test that uploading a relation referencing invalid placeholders gives a
+    # proper error, not a 500.
+    def test_upload_placeholder_invalid_relation
+      changeset = create(:changeset)
+      relation = create(:relation)
+
+      basic_authorization changeset.user.email, "test"
+
+      diff = <<CHANGESET.strip_heredoc
+        <osmChange>
+         <create>
+          <node id="-1" lon="0" lat="0" changeset="#{changeset.id}" version="1"/>
+          <node id="-2" lon="1" lat="1" changeset="#{changeset.id}" version="1"/>
+          <node id="-3" lon="2" lat="2" changeset="#{changeset.id}" version="1"/>
+          <relation id="-1" changeset="#{changeset.id}" version="1">
+           <member type="node" role="foo" ref="-1"/>
+           <member type="node" role="foo" ref="-2"/>
+           <member type="node" role="foo" ref="-3"/>
+           <member type="node" role="foo" ref="-4"/>
+          </relation>
+         </create>
+        </osmChange>
+CHANGESET
+
+      # upload it
+      post :upload, :params => { :id => changeset.id }, :body => diff
+      assert_response :bad_request,
+                      "shouldn't be able to use invalid placeholder IDs"
+      assert_equal "Placeholder Node not found for reference -4 in relation -1.", @response.body
+
+      # the same again, but this time use an existing relation
+      diff = <<CHANGESET.strip_heredoc
+        <osmChange>
+         <create>
+          <node id="-1" lon="0" lat="0" changeset="#{changeset.id}" version="1"/>
+          <node id="-2" lon="1" lat="1" changeset="#{changeset.id}" version="1"/>
+          <node id="-3" lon="2" lat="2" changeset="#{changeset.id}" version="1"/>
+          <relation id="#{relation.id}" changeset="#{changeset.id}" version="1">
+           <member type="node" role="foo" ref="-1"/>
+           <member type="node" role="foo" ref="-2"/>
+           <member type="node" role="foo" ref="-3"/>
+           <member type="way" role="bar" ref="-1"/>
+          </relation>
+         </create>
+        </osmChange>
+CHANGESET
+
+      # upload it
+      post :upload, :params => { :id => changeset.id }, :body => diff
+      assert_response :bad_request,
+                      "shouldn't be able to use invalid placeholder IDs"
+      assert_equal "Placeholder Way not found for reference -1 in relation #{relation.id}.", @response.body
+    end
+
+    ##
+    # test what happens if a diff is uploaded containing only a node
+    # move.
+    def test_upload_node_move
+      basic_authorization create(:user).email, "test"
+
+      xml = "<osm><changeset>" \
+            "<tag k='created_by' v='osm test suite checking changesets'/>" \
+            "</changeset></osm>"
+      put :create, :body => xml
+      assert_response :success
+      changeset_id = @response.body.to_i
+
+      old_node = create(:node, :lat => 1, :lon => 1)
+
+      diff = XML::Document.new
+      diff.root = XML::Node.new "osmChange"
+      modify = XML::Node.new "modify"
+      xml_old_node = old_node.to_xml_node
+      xml_old_node["lat"] = 2.0.to_s
+      xml_old_node["lon"] = 2.0.to_s
+      xml_old_node["changeset"] = changeset_id.to_s
+      modify << xml_old_node
+      diff.root << modify
+
+      # upload it
+      post :upload, :params => { :id => changeset_id }, :body => diff.to_s
+      assert_response :success,
+                      "diff should have uploaded OK"
+
+      # check the bbox
+      changeset = Changeset.find(changeset_id)
+      assert_equal 1 * GeoRecord::SCALE, changeset.min_lon, "min_lon should be 1 degree"
+      assert_equal 2 * GeoRecord::SCALE, changeset.max_lon, "max_lon should be 2 degrees"
+      assert_equal 1 * GeoRecord::SCALE, changeset.min_lat, "min_lat should be 1 degree"
+      assert_equal 2 * GeoRecord::SCALE, changeset.max_lat, "max_lat should be 2 degrees"
+    end
+
+    ##
+    # test what happens if a diff is uploaded adding a node to a way.
+    def test_upload_way_extend
+      basic_authorization create(:user).email, "test"
+
+      xml = "<osm><changeset>" \
+            "<tag k='created_by' v='osm test suite checking changesets'/>" \
+            "</changeset></osm>"
+      put :create, :body => xml
+      assert_response :success
+      changeset_id = @response.body.to_i
+
+      old_way = create(:way)
+      create(:way_node, :way => old_way, :node => create(:node, :lat => 1, :lon => 1))
+
+      diff = XML::Document.new
+      diff.root = XML::Node.new "osmChange"
+      modify = XML::Node.new "modify"
+      xml_old_way = old_way.to_xml_node
+      nd_ref = XML::Node.new "nd"
+      nd_ref["ref"] = create(:node, :lat => 3, :lon => 3).id.to_s
+      xml_old_way << nd_ref
+      xml_old_way["changeset"] = changeset_id.to_s
+      modify << xml_old_way
+      diff.root << modify
+
+      # upload it
+      post :upload, :params => { :id => changeset_id }, :body => diff.to_s
+      assert_response :success,
+                      "diff should have uploaded OK"
+
+      # check the bbox
+      changeset = Changeset.find(changeset_id)
+      assert_equal 1 * GeoRecord::SCALE, changeset.min_lon, "min_lon should be 1 degree"
+      assert_equal 3 * GeoRecord::SCALE, changeset.max_lon, "max_lon should be 3 degrees"
+      assert_equal 1 * GeoRecord::SCALE, changeset.min_lat, "min_lat should be 1 degree"
+      assert_equal 3 * GeoRecord::SCALE, changeset.max_lat, "max_lat should be 3 degrees"
+    end
+
+    ##
+    # test for more issues in #1568
+    def test_upload_empty_invalid
+      changeset = create(:changeset)
+
+      basic_authorization changeset.user.email, "test"
+
+      ["<osmChange/>",
+       "<osmChange></osmChange>",
+       "<osmChange><modify/></osmChange>",
+       "<osmChange><modify></modify></osmChange>"].each do |diff|
+        # upload it
+        post :upload, :params => { :id => changeset.id }, :body => diff
+        assert_response(:success, "should be able to upload " \
+                        "empty changeset: " + diff)
+      end
+    end
+
+    ##
+    # test that the X-Error-Format header works to request XML errors
+    def test_upload_xml_errors
+      changeset = create(:changeset)
+      node = create(:node)
+      create(:relation_member, :member => node)
+
+      basic_authorization changeset.user.email, "test"
+
+      # try and delete a node that is in use
+      diff = XML::Document.new
+      diff.root = XML::Node.new "osmChange"
+      delete = XML::Node.new "delete"
+      diff.root << delete
+      delete << node.to_xml_node
+
+      # upload it
+      error_format "xml"
+      post :upload, :params => { :id => changeset.id }, :body => diff.to_s
+      assert_response :success,
+                      "failed to return error in XML format"
+
+      # check the returned payload
+      assert_select "osmError[version='#{API_VERSION}'][generator='OpenStreetMap server']", 1
+      assert_select "osmError>status", 1
+      assert_select "osmError>message", 1
+    end
+
+    ##
+    # when we make some simple changes we get the same changes back from the
+    # diff download.
+    def test_diff_download_simple
+      node = create(:node)
+
+      ## First try with a non-public user, which should get a forbidden
+      basic_authorization create(:user, :data_public => false).email, "test"
+
+      # create a temporary changeset
+      xml = "<osm><changeset>" \
+            "<tag k='created_by' v='osm test suite checking changesets'/>" \
+            "</changeset></osm>"
+      put :create, :body => xml
+      assert_response :forbidden
+
+      ## Now try with a normal user
+      basic_authorization create(:user).email, "test"
+
+      # create a temporary changeset
+      xml = "<osm><changeset>" \
+            "<tag k='created_by' v='osm test suite checking changesets'/>" \
+            "</changeset></osm>"
+      put :create, :body => xml
+      assert_response :success
+      changeset_id = @response.body.to_i
+
+      # add a diff to it
+      diff = <<CHANGESET.strip_heredoc
+        <osmChange>
+         <modify>
+          <node id='#{node.id}' lon='0' lat='0' changeset='#{changeset_id}' version='1'/>
+          <node id='#{node.id}' lon='1' lat='0' changeset='#{changeset_id}' version='2'/>
+          <node id='#{node.id}' lon='1' lat='1' changeset='#{changeset_id}' version='3'/>
+          <node id='#{node.id}' lon='1' lat='2' changeset='#{changeset_id}' version='4'/>
+          <node id='#{node.id}' lon='2' lat='2' changeset='#{changeset_id}' version='5'/>
+          <node id='#{node.id}' lon='3' lat='2' changeset='#{changeset_id}' version='6'/>
+          <node id='#{node.id}' lon='3' lat='3' changeset='#{changeset_id}' version='7'/>
+          <node id='#{node.id}' lon='9' lat='9' changeset='#{changeset_id}' version='8'/>
+         </modify>
+        </osmChange>
+CHANGESET
+
+      # upload it
+      post :upload, :params => { :id => changeset_id }, :body => diff
+      assert_response :success,
+                      "can't upload multiple versions of an element in a diff: #{@response.body}"
+
+      get :download, :params => { :id => changeset_id }
+      assert_response :success
+
+      assert_select "osmChange", 1
+      assert_select "osmChange>modify", 8
+      assert_select "osmChange>modify>node", 8
+    end
+
+    ##
+    # culled this from josm to ensure that nothing in the way that josm
+    # is formatting the request is causing it to fail.
+    #
+    # NOTE: the error turned out to be something else completely!
+    def test_josm_upload
+      basic_authorization create(:user).email, "test"
+
+      # create a temporary changeset
+      xml = "<osm><changeset>" \
+            "<tag k='created_by' v='osm test suite checking changesets'/>" \
+            "</changeset></osm>"
+      put :create, :body => xml
+      assert_response :success
+      changeset_id = @response.body.to_i
+
+      diff = <<OSMFILE.strip_heredoc
+        <osmChange version="0.6" generator="JOSM">
+        <create version="0.6" generator="JOSM">
+          <node id='-1' visible='true' changeset='#{changeset_id}' lat='51.49619982187321' lon='-0.18722061869438314' />
+          <node id='-2' visible='true' changeset='#{changeset_id}' lat='51.496359883909605' lon='-0.18653093576241928' />
+          <node id='-3' visible='true' changeset='#{changeset_id}' lat='51.49598132358285' lon='-0.18719613290981638' />
+          <node id='-4' visible='true' changeset='#{changeset_id}' lat='51.4961591711078' lon='-0.18629015888084607' />
+          <node id='-5' visible='true' changeset='#{changeset_id}' lat='51.49582126021711' lon='-0.18708186591517145' />
+          <node id='-6' visible='true' changeset='#{changeset_id}' lat='51.49591018437858' lon='-0.1861432441734455' />
+          <node id='-7' visible='true' changeset='#{changeset_id}' lat='51.49560784152179' lon='-0.18694719410005425' />
+          <node id='-8' visible='true' changeset='#{changeset_id}' lat='51.49567389979617' lon='-0.1860289771788006' />
+          <node id='-9' visible='true' changeset='#{changeset_id}' lat='51.49543761398892' lon='-0.186820684213126' />
+          <way id='-10' action='modiy' visible='true' changeset='#{changeset_id}'>
+            <nd ref='-1' />
+            <nd ref='-2' />
+            <nd ref='-3' />
+            <nd ref='-4' />
+            <nd ref='-5' />
+            <nd ref='-6' />
+            <nd ref='-7' />
+            <nd ref='-8' />
+            <nd ref='-9' />
+            <tag k='highway' v='residential' />
+            <tag k='name' v='Foobar Street' />
+          </way>
+        </create>
+        </osmChange>
+OSMFILE
+
+      # upload it
+      post :upload, :params => { :id => changeset_id }, :body => diff
+      assert_response :success,
+                      "can't upload a diff from JOSM: #{@response.body}"
+
+      get :download, :params => { :id => changeset_id }
+      assert_response :success
+
+      assert_select "osmChange", 1
+      assert_select "osmChange>create>node", 9
+      assert_select "osmChange>create>way", 1
+      assert_select "osmChange>create>way>nd", 9
+      assert_select "osmChange>create>way>tag", 2
+    end
+
+    ##
+    # when we make some complex changes we get the same changes back from the
+    # diff download.
+    def test_diff_download_complex
+      node = create(:node)
+      node2 = create(:node)
+      way = create(:way)
+      basic_authorization create(:user).email, "test"
+
+      # create a temporary changeset
+      xml = "<osm><changeset>" \
+            "<tag k='created_by' v='osm test suite checking changesets'/>" \
+            "</changeset></osm>"
+      put :create, :body => xml
+      assert_response :success
+      changeset_id = @response.body.to_i
+
+      # add a diff to it
+      diff = <<CHANGESET.strip_heredoc
+        <osmChange>
+         <delete>
+          <node id='#{node.id}' lon='0' lat='0' changeset='#{changeset_id}' version='1'/>
+         </delete>
+         <create>
+          <node id='-1' lon='9' lat='9' changeset='#{changeset_id}' version='0'/>
+          <node id='-2' lon='8' lat='9' changeset='#{changeset_id}' version='0'/>
+          <node id='-3' lon='7' lat='9' changeset='#{changeset_id}' version='0'/>
+         </create>
+         <modify>
+          <node id='#{node2.id}' lon='20' lat='15' changeset='#{changeset_id}' version='1'/>
+          <way id='#{way.id}' changeset='#{changeset_id}' version='1'>
+           <nd ref='#{node2.id}'/>
+           <nd ref='-1'/>
+           <nd ref='-2'/>
+           <nd ref='-3'/>
+          </way>
+         </modify>
+        </osmChange>
+CHANGESET
+
+      # upload it
+      post :upload, :params => { :id => changeset_id }, :body => diff
+      assert_response :success,
+                      "can't upload multiple versions of an element in a diff: #{@response.body}"
+
+      get :download, :params => { :id => changeset_id }
+      assert_response :success
+
+      assert_select "osmChange", 1
+      assert_select "osmChange>create", 3
+      assert_select "osmChange>delete", 1
+      assert_select "osmChange>modify", 2
+      assert_select "osmChange>create>node", 3
+      assert_select "osmChange>delete>node", 1
+      assert_select "osmChange>modify>node", 1
+      assert_select "osmChange>modify>way", 1
+    end
+
+    def test_changeset_download
+      changeset = create(:changeset)
+      node = create(:node, :with_history, :version => 1, :changeset => changeset)
+      tag = create(:old_node_tag, :old_node => node.old_nodes.find_by(:version => 1))
+      node2 = create(:node, :with_history, :version => 1, :changeset => changeset)
+      _node3 = create(:node, :with_history, :deleted, :version => 1, :changeset => changeset)
+      _relation = create(:relation, :with_history, :version => 1, :changeset => changeset)
+      _relation2 = create(:relation, :with_history, :deleted, :version => 1, :changeset => changeset)
+
+      get :download, :params => { :id => changeset.id }
+
+      assert_response :success
+      assert_template nil
+      # print @response.body
+      # FIXME: needs more assert_select tests
+      assert_select "osmChange[version='#{API_VERSION}'][generator='#{GENERATOR}']" do
+        assert_select "create", :count => 5
+        assert_select "create>node[id='#{node.id}'][visible='#{node.visible?}'][version='#{node.version}']" do
+          assert_select "tag[k='#{tag.k}'][v='#{tag.v}']"
+        end
+        assert_select "create>node[id='#{node2.id}']"
+      end
+    end
+
+    ##
+    # check that the bounding box of a changeset gets updated correctly
+    # FIXME: This should really be moded to a integration test due to the with_controller
+    def test_changeset_bbox
+      way = create(:way)
+      create(:way_node, :way => way, :node => create(:node, :lat => 3, :lon => 3))
+
+      basic_authorization create(:user).email, "test"
+
+      # create a new changeset
+      xml = "<osm><changeset/></osm>"
+      put :create, :body => xml
+      assert_response :success, "Creating of changeset failed."
+      changeset_id = @response.body.to_i
+
+      # add a single node to it
+      with_controller(NodesController.new) do
+        xml = "<osm><node lon='1' lat='2' changeset='#{changeset_id}'/></osm>"
+        put :create, :body => xml
+        assert_response :success, "Couldn't create node."
+      end
+
+      # get the bounding box back from the changeset
+      get :show, :params => { :id => changeset_id }
+      assert_response :success, "Couldn't read back changeset."
+      assert_select "osm>changeset[min_lon='1.0000000']", 1
+      assert_select "osm>changeset[max_lon='1.0000000']", 1
+      assert_select "osm>changeset[min_lat='2.0000000']", 1
+      assert_select "osm>changeset[max_lat='2.0000000']", 1
+
+      # add another node to it
+      with_controller(NodesController.new) do
+        xml = "<osm><node lon='2' lat='1' changeset='#{changeset_id}'/></osm>"
+        put :create, :body => xml
+        assert_response :success, "Couldn't create second node."
+      end
+
+      # get the bounding box back from the changeset
+      get :show, :params => { :id => changeset_id }
+      assert_response :success, "Couldn't read back changeset for the second time."
+      assert_select "osm>changeset[min_lon='1.0000000']", 1
+      assert_select "osm>changeset[max_lon='2.0000000']", 1
+      assert_select "osm>changeset[min_lat='1.0000000']", 1
+      assert_select "osm>changeset[max_lat='2.0000000']", 1
+
+      # add (delete) a way to it, which contains a point at (3,3)
+      with_controller(WaysController.new) do
+        xml = update_changeset(way.to_xml, changeset_id)
+        put :delete, :params => { :id => way.id }, :body => xml.to_s
+        assert_response :success, "Couldn't delete a way."
+      end
+
+      # get the bounding box back from the changeset
+      get :show, :params => { :id => changeset_id }
+      assert_response :success, "Couldn't read back changeset for the third time."
+      assert_select "osm>changeset[min_lon='1.0000000']", 1
+      assert_select "osm>changeset[max_lon='3.0000000']", 1
+      assert_select "osm>changeset[min_lat='1.0000000']", 1
+      assert_select "osm>changeset[max_lat='3.0000000']", 1
+    end
+
+    ##
+    # test that the changeset :include method works as it should
+    def test_changeset_include
+      basic_authorization create(:user).display_name, "test"
+
+      # create a new changeset
+      put :create, :body => "<osm><changeset/></osm>"
+      assert_response :success, "Creating of changeset failed."
+      changeset_id = @response.body.to_i
+
+      # NOTE: the include method doesn't over-expand, like inserting
+      # a real method does. this is because we expect the client to
+      # know what it is doing!
+      check_after_include(changeset_id, 1, 1, [1, 1, 1, 1])
+      check_after_include(changeset_id, 3, 3, [1, 1, 3, 3])
+      check_after_include(changeset_id, 4, 2, [1, 1, 4, 3])
+      check_after_include(changeset_id, 2, 2, [1, 1, 4, 3])
+      check_after_include(changeset_id, -1, -1, [-1, -1, 4, 3])
+      check_after_include(changeset_id, -2, 5, [-2, -1, 4, 5])
+    end
+
+    ##
+    # test that a not found, wrong method with the expand bbox works as expected
+    def test_changeset_expand_bbox_error
+      basic_authorization create(:user).display_name, "test"
+
+      # create a new changeset
+      xml = "<osm><changeset/></osm>"
+      put :create, :body => xml
+      assert_response :success, "Creating of changeset failed."
+      changeset_id = @response.body.to_i
+
+      lon = 58.2
+      lat = -0.45
+
+      # Try and put
+      xml = "<osm><node lon='#{lon}' lat='#{lat}'/></osm>"
+      put :expand_bbox, :params => { :id => changeset_id }, :body => xml
+      assert_response :method_not_allowed, "shouldn't be able to put a bbox expand"
+
+      # Try to get the update
+      xml = "<osm><node lon='#{lon}' lat='#{lat}'/></osm>"
+      get :expand_bbox, :params => { :id => changeset_id }, :body => xml
+      assert_response :method_not_allowed, "shouldn't be able to get a bbox expand"
+
+      # Try to use a hopefully missing changeset
+      xml = "<osm><node lon='#{lon}' lat='#{lat}'/></osm>"
+      post :expand_bbox, :params => { :id => changeset_id + 13245 }, :body => xml
+      assert_response :not_found, "shouldn't be able to do a bbox expand on a nonexistant changeset"
+    end
+
+    ##
+    # test the query functionality of changesets
+    def test_query
+      private_user = create(:user, :data_public => false)
+      private_user_changeset = create(:changeset, :user => private_user)
+      private_user_closed_changeset = create(:changeset, :closed, :user => private_user)
+      user = create(:user)
+      changeset = create(:changeset, :user => user)
+      closed_changeset = create(:changeset, :closed, :user => user, :created_at => Time.utc(2008, 1, 1, 0, 0, 0), :closed_at => Time.utc(2008, 1, 2, 0, 0, 0))
+      changeset2 = create(:changeset, :min_lat => 5 * GeoRecord::SCALE, :min_lon => 5 * GeoRecord::SCALE, :max_lat => 15 * GeoRecord::SCALE, :max_lon => 15 * GeoRecord::SCALE)
+      changeset3 = create(:changeset, :min_lat => 4.5 * GeoRecord::SCALE, :min_lon => 4.5 * GeoRecord::SCALE, :max_lat => 5 * GeoRecord::SCALE, :max_lon => 5 * GeoRecord::SCALE)
+
+      get :query, :params => { :bbox => "-10,-10, 10, 10" }
+      assert_response :success, "can't get changesets in bbox"
+      assert_changesets [changeset2, changeset3]
+
+      get :query, :params => { :bbox => "4.5,4.5,4.6,4.6" }
+      assert_response :success, "can't get changesets in bbox"
+      assert_changesets [changeset3]
+
+      # not found when looking for changesets of non-existing users
+      get :query, :params => { :user => User.maximum(:id) + 1 }
+      assert_response :not_found
+      get :query, :params => { :display_name => " " }
+      assert_response :not_found
+
+      # can't get changesets of user 1 without authenticating
+      get :query, :params => { :user => private_user.id }
+      assert_response :not_found, "shouldn't be able to get changesets by non-public user (ID)"
+      get :query, :params => { :display_name => private_user.display_name }
+      assert_response :not_found, "shouldn't be able to get changesets by non-public user (name)"
+
+      # but this should work
+      basic_authorization private_user.email, "test"
+      get :query, :params => { :user => private_user.id }
+      assert_response :success, "can't get changesets by user ID"
+      assert_changesets [private_user_changeset, private_user_closed_changeset]
+
+      get :query, :params => { :display_name => private_user.display_name }
+      assert_response :success, "can't get changesets by user name"
+      assert_changesets [private_user_changeset, private_user_closed_changeset]
+
+      # check that the correct error is given when we provide both UID and name
+      get :query, :params => { :user => private_user.id,
+                               :display_name => private_user.display_name }
+      assert_response :bad_request, "should be a bad request to have both ID and name specified"
+
+      get :query, :params => { :user => private_user.id, :open => true }
+      assert_response :success, "can't get changesets by user and open"
+      assert_changesets [private_user_changeset]
+
+      get :query, :params => { :time => "2007-12-31" }
+      assert_response :success, "can't get changesets by time-since"
+      assert_changesets [private_user_changeset, private_user_closed_changeset, changeset, closed_changeset, changeset2, changeset3]
+
+      get :query, :params => { :time => "2008-01-01T12:34Z" }
+      assert_response :success, "can't get changesets by time-since with hour"
+      assert_changesets [private_user_changeset, private_user_closed_changeset, changeset, closed_changeset, changeset2, changeset3]
+
+      get :query, :params => { :time => "2007-12-31T23:59Z,2008-01-02T00:01Z" }
+      assert_response :success, "can't get changesets by time-range"
+      assert_changesets [closed_changeset]
+
+      get :query, :params => { :open => "true" }
+      assert_response :success, "can't get changesets by open-ness"
+      assert_changesets [private_user_changeset, changeset, changeset2, changeset3]
+
+      get :query, :params => { :closed => "true" }
+      assert_response :success, "can't get changesets by closed-ness"
+      assert_changesets [private_user_closed_changeset, closed_changeset]
+
+      get :query, :params => { :closed => "true", :user => private_user.id }
+      assert_response :success, "can't get changesets by closed-ness and user"
+      assert_changesets [private_user_closed_changeset]
+
+      get :query, :params => { :closed => "true", :user => user.id }
+      assert_response :success, "can't get changesets by closed-ness and user"
+      assert_changesets [closed_changeset]
+
+      get :query, :params => { :changesets => "#{private_user_changeset.id},#{changeset.id},#{closed_changeset.id}" }
+      assert_response :success, "can't get changesets by id (as comma-separated string)"
+      assert_changesets [private_user_changeset, changeset, closed_changeset]
+
+      get :query, :params => { :changesets => "" }
+      assert_response :bad_request, "should be a bad request since changesets is empty"
+    end
+
+    ##
+    # check that errors are returned if garbage is inserted
+    # into query strings
+    def test_query_invalid
+      ["abracadabra!",
+       "1,2,3,F",
+       ";drop table users;"].each do |bbox|
+        get :query, :params => { :bbox => bbox }
+        assert_response :bad_request, "'#{bbox}' isn't a bbox"
+      end
+
+      ["now()",
+       "00-00-00",
+       ";drop table users;",
+       ",",
+       "-,-"].each do |time|
+        get :query, :params => { :time => time }
+        assert_response :bad_request, "'#{time}' isn't a valid time range"
+      end
+
+      ["me",
+       "foobar",
+       "-1",
+       "0"].each do |uid|
+        get :query, :params => { :user => uid }
+        assert_response :bad_request, "'#{uid}' isn't a valid user ID"
+      end
+    end
+
+    ##
+    # check updating tags on a changeset
+    def test_changeset_update
+      private_user = create(:user, :data_public => false)
+      private_changeset = create(:changeset, :user => private_user)
+      user = create(:user)
+      changeset = create(:changeset, :user => user)
+
+      ## First try with a non-public user
+      new_changeset = private_changeset.to_xml
+      new_tag = XML::Node.new "tag"
+      new_tag["k"] = "tagtesting"
+      new_tag["v"] = "valuetesting"
+      new_changeset.find("//osm/changeset").first << new_tag
+
+      # try without any authorization
+      put :update, :params => { :id => private_changeset.id }, :body => new_changeset.to_s
+      assert_response :unauthorized
+
+      # try with the wrong authorization
+      basic_authorization create(:user).email, "test"
+      put :update, :params => { :id => private_changeset.id }, :body => new_changeset.to_s
+      assert_response :conflict
+
+      # now this should get an unauthorized
+      basic_authorization private_user.email, "test"
+      put :update, :params => { :id => private_changeset.id }, :body => new_changeset.to_s
+      assert_require_public_data "user with their data non-public, shouldn't be able to edit their changeset"
+
+      ## Now try with the public user
+      create(:changeset_tag, :changeset => changeset)
+      new_changeset = changeset.to_xml
+      new_tag = XML::Node.new "tag"
+      new_tag["k"] = "tagtesting"
+      new_tag["v"] = "valuetesting"
+      new_changeset.find("//osm/changeset").first << new_tag
+
+      # try without any authorization
+      @request.env["HTTP_AUTHORIZATION"] = nil
+      put :update, :params => { :id => changeset.id }, :body => new_changeset.to_s
+      assert_response :unauthorized
+
+      # try with the wrong authorization
+      basic_authorization create(:user).email, "test"
+      put :update, :params => { :id => changeset.id }, :body => new_changeset.to_s
+      assert_response :conflict
+
+      # now this should work...
+      basic_authorization user.email, "test"
+      put :update, :params => { :id => changeset.id }, :body => new_changeset.to_s
+      assert_response :success
+
+      assert_select "osm>changeset[id='#{changeset.id}']", 1
+      assert_select "osm>changeset>tag", 2
+      assert_select "osm>changeset>tag[k='tagtesting'][v='valuetesting']", 1
+    end
+
+    ##
+    # check that a user different from the one who opened the changeset
+    # can't modify it.
+    def test_changeset_update_invalid
+      basic_authorization create(:user).email, "test"
+
+      changeset = create(:changeset)
+      new_changeset = changeset.to_xml
+      new_tag = XML::Node.new "tag"
+      new_tag["k"] = "testing"
+      new_tag["v"] = "testing"
+      new_changeset.find("//osm/changeset").first << new_tag
+
+      put :update, :params => { :id => changeset.id }, :body => new_changeset.to_s
+      assert_response :conflict
+    end
+
+    ##
+    # check that a changeset can contain a certain max number of changes.
+    ## FIXME should be changed to an integration test due to the with_controller
+    def test_changeset_limits
+      basic_authorization create(:user).email, "test"
+
+      # open a new changeset
+      xml = "<osm><changeset/></osm>"
+      put :create, :body => xml
+      assert_response :success, "can't create a new changeset"
+      cs_id = @response.body.to_i
+
+      # start the counter just short of where the changeset should finish.
+      offset = 10
+      # alter the database to set the counter on the changeset directly,
+      # otherwise it takes about 6 minutes to fill all of them.
+      changeset = Changeset.find(cs_id)
+      changeset.num_changes = Changeset::MAX_ELEMENTS - offset
+      changeset.save!
+
+      with_controller(NodesController.new) do
+        # create a new node
+        xml = "<osm><node changeset='#{cs_id}' lat='0.0' lon='0.0'/></osm>"
+        put :create, :body => xml
+        assert_response :success, "can't create a new node"
+        node_id = @response.body.to_i
+
+        get :show, :params => { :id => node_id }
+        assert_response :success, "can't read back new node"
+        node_doc = XML::Parser.string(@response.body).parse
+        node_xml = node_doc.find("//osm/node").first
+
+        # loop until we fill the changeset with nodes
+        offset.times do |i|
+          node_xml["lat"] = rand.to_s
+          node_xml["lon"] = rand.to_s
+          node_xml["version"] = (i + 1).to_s
+
+          put :update, :params => { :id => node_id }, :body => node_doc.to_s
+          assert_response :success, "attempt #{i} should have succeeded"
+        end
+
+        # trying again should fail
+        node_xml["lat"] = rand.to_s
+        node_xml["lon"] = rand.to_s
+        node_xml["version"] = offset.to_s
+
+        put :update, :params => { :id => node_id }, :body => node_doc.to_s
+        assert_response :conflict, "final attempt should have failed"
+      end
+
+      changeset = Changeset.find(cs_id)
+      assert_equal Changeset::MAX_ELEMENTS + 1, changeset.num_changes
+
+      # check that the changeset is now closed as well
+      assert_not(changeset.is_open?,
+                 "changeset should have been auto-closed by exceeding " \
+                 "element limit.")
+    end
+
+    ##
+    # check that the changeset download for a changeset with a redacted
+    # element in it doesn't contain that element.
+    def test_diff_download_redacted
+      changeset = create(:changeset)
+      node = create(:node, :with_history, :version => 2, :changeset => changeset)
+      node_v1 = node.old_nodes.find_by(:version => 1)
+      node_v1.redact!(create(:redaction))
+
+      get :download, :params => { :id => changeset.id }
+      assert_response :success
+
+      assert_select "osmChange", 1
+      # this changeset contains the node in versions 1 & 2, but 1 should
+      # be hidden.
+      assert_select "osmChange node[id='#{node.id}']", 1
+      assert_select "osmChange node[id='#{node.id}'][version='1']", 0
+    end
+
+    ##
+    # test subscribe success
+    def test_subscribe_success
+      basic_authorization create(:user).email, "test"
+      changeset = create(:changeset, :closed)
+
+      assert_difference "changeset.subscribers.count", 1 do
+        post :subscribe, :params => { :id => changeset.id }
+      end
+      assert_response :success
+
+      # not closed changeset
+      changeset = create(:changeset)
+      assert_difference "changeset.subscribers.count", 1 do
+        post :subscribe, :params => { :id => changeset.id }
+      end
+      assert_response :success
+    end
+
+    ##
+    # test subscribe fail
+    def test_subscribe_fail
+      user = create(:user)
+
+      # unauthorized
+      changeset = create(:changeset, :closed)
+      assert_no_difference "changeset.subscribers.count" do
+        post :subscribe, :params => { :id => changeset.id }
+      end
+      assert_response :unauthorized
+
+      basic_authorization user.email, "test"
+
+      # bad changeset id
+      assert_no_difference "changeset.subscribers.count" do
+        post :subscribe, :params => { :id => 999111 }
+      end
+      assert_response :not_found
+
+      # trying to subscribe when already subscribed
+      changeset = create(:changeset, :closed)
+      changeset.subscribers.push(user)
+      assert_no_difference "changeset.subscribers.count" do
+        post :subscribe, :params => { :id => changeset.id }
+      end
+      assert_response :conflict
+    end
+
+    ##
+    # test unsubscribe success
+    def test_unsubscribe_success
+      user = create(:user)
+      basic_authorization user.email, "test"
+      changeset = create(:changeset, :closed)
+      changeset.subscribers.push(user)
+
+      assert_difference "changeset.subscribers.count", -1 do
+        post :unsubscribe, :params => { :id => changeset.id }
+      end
+      assert_response :success
+
+      # not closed changeset
+      changeset = create(:changeset)
+      changeset.subscribers.push(user)
+
+      assert_difference "changeset.subscribers.count", -1 do
+        post :unsubscribe, :params => { :id => changeset.id }
+      end
+      assert_response :success
+    end
+
+    ##
+    # test unsubscribe fail
+    def test_unsubscribe_fail
+      # unauthorized
+      changeset = create(:changeset, :closed)
+      assert_no_difference "changeset.subscribers.count" do
+        post :unsubscribe, :params => { :id => changeset.id }
+      end
+      assert_response :unauthorized
+
+      basic_authorization create(:user).email, "test"
+
+      # bad changeset id
+      assert_no_difference "changeset.subscribers.count" do
+        post :unsubscribe, :params => { :id => 999111 }
+      end
+      assert_response :not_found
+
+      # trying to unsubscribe when not subscribed
+      changeset = create(:changeset, :closed)
+      assert_no_difference "changeset.subscribers.count" do
+        post :unsubscribe, :params => { :id => changeset.id }
+      end
+      assert_response :not_found
+    end
+
+    private
+
+    ##
+    # boilerplate for checking that certain changesets exist in the
+    # output.
+    def assert_changesets(changesets)
+      assert_select "osm>changeset", changesets.size
+      changesets.each do |changeset|
+        assert_select "osm>changeset[id='#{changeset.id}']", 1
+      end
+    end
+
+    ##
+    # call the include method and assert properties of the bbox
+    def check_after_include(changeset_id, lon, lat, bbox)
+      xml = "<osm><node lon='#{lon}' lat='#{lat}'/></osm>"
+      post :expand_bbox, :params => { :id => changeset_id }, :body => xml
+      assert_response :success, "Setting include of changeset failed: #{@response.body}"
+
+      # check exactly one changeset
+      assert_select "osm>changeset", 1
+      assert_select "osm>changeset[id='#{changeset_id}']", 1
+
+      # check the bbox
+      doc = XML::Parser.string(@response.body).parse
+      changeset = doc.find("//osm/changeset").first
+      assert_equal bbox[0], changeset["min_lon"].to_f, "min lon"
+      assert_equal bbox[1], changeset["min_lat"].to_f, "min lat"
+      assert_equal bbox[2], changeset["max_lon"].to_f, "max lon"
+      assert_equal bbox[3], changeset["max_lat"].to_f, "max lat"
+    end
+
+    ##
+    # update the changeset_id of a way element
+    def update_changeset(xml, changeset_id)
+      xml_attr_rewrite(xml, "changeset", changeset_id)
+    end
+
+    ##
+    # update an attribute in a way element
+    def xml_attr_rewrite(xml, name, value)
+      xml.find("//osm/way").first[name] = value.to_s
+      xml
+    end
+  end
+end
diff --git a/test/controllers/api/nodes_controller_test.rb b/test/controllers/api/nodes_controller_test.rb
new file mode 100644 (file)
index 0000000..6d990a8
--- /dev/null
@@ -0,0 +1,552 @@
+require "test_helper"
+
+module Api
+  class NodesControllerTest < ActionController::TestCase
+    ##
+    # test all routes which lead to this controller
+    def test_routes
+      assert_routing(
+        { :path => "/api/0.6/node/create", :method => :put },
+        { :controller => "api/nodes", :action => "create" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/node/1", :method => :get },
+        { :controller => "api/nodes", :action => "show", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/node/1", :method => :put },
+        { :controller => "api/nodes", :action => "update", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/node/1", :method => :delete },
+        { :controller => "api/nodes", :action => "delete", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/nodes", :method => :get },
+        { :controller => "api/nodes", :action => "index" }
+      )
+    end
+
+    def test_create
+      private_user = create(:user, :data_public => false)
+      private_changeset = create(:changeset, :user => private_user)
+      user = create(:user)
+      changeset = create(:changeset, :user => user)
+
+      # create a node with random lat/lon
+      lat = rand(-50..50) + rand
+      lon = rand(-50..50) + rand
+
+      ## First try with no auth
+      # create a minimal xml file
+      xml = "<osm><node lat='#{lat}' lon='#{lon}' changeset='#{changeset.id}'/></osm>"
+      assert_difference("OldNode.count", 0) do
+        put :create, :body => xml
+      end
+      # hope for unauthorized
+      assert_response :unauthorized, "node upload did not return unauthorized status"
+
+      ## Now try with the user which doesn't have their data public
+      basic_authorization private_user.email, "test"
+
+      # create a minimal xml file
+      xml = "<osm><node lat='#{lat}' lon='#{lon}' changeset='#{private_changeset.id}'/></osm>"
+      assert_difference("Node.count", 0) do
+        put :create, :body => xml
+      end
+      # hope for success
+      assert_require_public_data "node create did not return forbidden status"
+
+      ## Now try with the user that has the public data
+      basic_authorization user.email, "test"
+
+      # create a minimal xml file
+      xml = "<osm><node lat='#{lat}' lon='#{lon}' changeset='#{changeset.id}'/></osm>"
+      put :create, :body => xml
+      # hope for success
+      assert_response :success, "node upload did not return success status"
+
+      # read id of created node and search for it
+      nodeid = @response.body
+      checknode = Node.find(nodeid)
+      assert_not_nil checknode, "uploaded node not found in data base after upload"
+      # compare values
+      assert_in_delta lat * 10000000, checknode.latitude, 1, "saved node does not match requested latitude"
+      assert_in_delta lon * 10000000, checknode.longitude, 1, "saved node does not match requested longitude"
+      assert_equal changeset.id, checknode.changeset_id, "saved node does not belong to changeset that it was created in"
+      assert_equal true, checknode.visible, "saved node is not visible"
+    end
+
+    def test_create_invalid_xml
+      ## Only test public user here, as test_create should cover what's the forbiddens
+      ## that would occur here
+
+      user = create(:user)
+      changeset = create(:changeset, :user => user)
+
+      basic_authorization user.email, "test"
+      lat = 3.434
+      lon = 3.23
+
+      # test that the upload is rejected when xml is valid, but osm doc isn't
+      xml = "<create/>"
+      put :create, :body => xml
+      assert_response :bad_request, "node upload did not return bad_request status"
+      assert_equal "Cannot parse valid node from xml string <create/>. XML doesn't contain an osm/node element.", @response.body
+
+      # test that the upload is rejected when no lat is supplied
+      # create a minimal xml file
+      xml = "<osm><node lon='#{lon}' changeset='#{changeset.id}'/></osm>"
+      put :create, :body => xml
+      # hope for success
+      assert_response :bad_request, "node upload did not return bad_request status"
+      assert_equal "Cannot parse valid node from xml string <node lon=\"3.23\" changeset=\"#{changeset.id}\"/>. lat missing", @response.body
+
+      # test that the upload is rejected when no lon is supplied
+      # create a minimal xml file
+      xml = "<osm><node lat='#{lat}' changeset='#{changeset.id}'/></osm>"
+      put :create, :body => xml
+      # hope for success
+      assert_response :bad_request, "node upload did not return bad_request status"
+      assert_equal "Cannot parse valid node from xml string <node lat=\"3.434\" changeset=\"#{changeset.id}\"/>. lon missing", @response.body
+
+      # test that the upload is rejected when lat is non-numeric
+      # create a minimal xml file
+      xml = "<osm><node lat='abc' lon='#{lon}' changeset='#{changeset.id}'/></osm>"
+      put :create, :body => xml
+      # hope for success
+      assert_response :bad_request, "node upload did not return bad_request status"
+      assert_equal "Cannot parse valid node from xml string <node lat=\"abc\" lon=\"#{lon}\" changeset=\"#{changeset.id}\"/>. lat not a number", @response.body
+
+      # test that the upload is rejected when lon is non-numeric
+      # create a minimal xml file
+      xml = "<osm><node lat='#{lat}' lon='abc' changeset='#{changeset.id}'/></osm>"
+      put :create, :body => xml
+      # hope for success
+      assert_response :bad_request, "node upload did not return bad_request status"
+      assert_equal "Cannot parse valid node from xml string <node lat=\"#{lat}\" lon=\"abc\" changeset=\"#{changeset.id}\"/>. lon not a number", @response.body
+
+      # test that the upload is rejected when we have a tag which is too long
+      xml = "<osm><node lat='#{lat}' lon='#{lon}' changeset='#{changeset.id}'><tag k='foo' v='#{'x' * 256}'/></node></osm>"
+      put :create, :body => xml
+      assert_response :bad_request, "node upload did not return bad_request status"
+      assert_equal ["NodeTag ", " v: is too long (maximum is 255 characters) (\"#{'x' * 256}\")"], @response.body.split(/[0-9]+,foo:/)
+    end
+
+    def test_show
+      # check that a visible node is returned properly
+      get :show, :params => { :id => create(:node).id }
+      assert_response :success
+
+      # check that an deleted node is not returned
+      get :show, :params => { :id => create(:node, :deleted).id }
+      assert_response :gone
+
+      # check chat a non-existent node is not returned
+      get :show, :params => { :id => 0 }
+      assert_response :not_found
+    end
+
+    # this tests deletion restrictions - basic deletion is tested in the unit
+    # tests for node!
+    def test_delete
+      private_user = create(:user, :data_public => false)
+      private_user_changeset = create(:changeset, :user => private_user)
+      private_user_closed_changeset = create(:changeset, :closed, :user => private_user)
+      private_node = create(:node, :changeset => private_user_changeset)
+      private_deleted_node = create(:node, :deleted, :changeset => private_user_changeset)
+
+      ## first try to delete node without auth
+      delete :delete, :params => { :id => private_node.id }
+      assert_response :unauthorized
+
+      ## now set auth for the non-data public user
+      basic_authorization private_user.email, "test"
+
+      # try to delete with an invalid (closed) changeset
+      xml = update_changeset(private_node.to_xml, private_user_closed_changeset.id)
+      delete :delete, :params => { :id => private_node.id }, :body => xml.to_s
+      assert_require_public_data("non-public user shouldn't be able to delete node")
+
+      # try to delete with an invalid (non-existent) changeset
+      xml = update_changeset(private_node.to_xml, 0)
+      delete :delete, :params => { :id => private_node.id }, :body => xml.to_s
+      assert_require_public_data("shouldn't be able to delete node, when user's data is private")
+
+      # valid delete now takes a payload
+      xml = private_node.to_xml
+      delete :delete, :params => { :id => private_node.id }, :body => xml.to_s
+      assert_require_public_data("shouldn't be able to delete node when user's data isn't public'")
+
+      # this won't work since the node is already deleted
+      xml = private_deleted_node.to_xml
+      delete :delete, :params => { :id => private_deleted_node.id }, :body => xml.to_s
+      assert_require_public_data
+
+      # this won't work since the node never existed
+      delete :delete, :params => { :id => 0 }
+      assert_require_public_data
+
+      ## these test whether nodes which are in-use can be deleted:
+      # in a way...
+      private_used_node = create(:node, :changeset => private_user_changeset)
+      create(:way_node, :node => private_used_node)
+
+      xml = private_used_node.to_xml
+      delete :delete, :params => { :id => private_used_node.id }, :body => xml.to_s
+      assert_require_public_data "shouldn't be able to delete a node used in a way (#{@response.body})"
+
+      # in a relation...
+      private_used_node2 = create(:node, :changeset => private_user_changeset)
+      create(:relation_member, :member => private_used_node2)
+
+      xml = private_used_node2.to_xml
+      delete :delete, :params => { :id => private_used_node2.id }, :body => xml.to_s
+      assert_require_public_data "shouldn't be able to delete a node used in a relation (#{@response.body})"
+
+      ## now setup for the public data user
+      user = create(:user, :data_public => true)
+      changeset = create(:changeset, :user => user)
+      closed_changeset = create(:changeset, :closed, :user => user)
+      node = create(:node, :changeset => changeset)
+      basic_authorization user.email, "test"
+
+      # try to delete with an invalid (closed) changeset
+      xml = update_changeset(node.to_xml, closed_changeset.id)
+      delete :delete, :params => { :id => node.id }, :body => xml.to_s
+      assert_response :conflict
+
+      # try to delete with an invalid (non-existent) changeset
+      xml = update_changeset(node.to_xml, 0)
+      delete :delete, :params => { :id => node.id }, :body => xml.to_s
+      assert_response :conflict
+
+      # try to delete a node with a different ID
+      other_node = create(:node)
+      xml = other_node.to_xml
+      delete :delete, :params => { :id => node.id }, :body => xml.to_s
+      assert_response :bad_request,
+                      "should not be able to delete a node with a different ID from the XML"
+
+      # try to delete a node rubbish in the payloads
+      xml = "<delete/>"
+      delete :delete, :params => { :id => node.id }, :body => xml.to_s
+      assert_response :bad_request,
+                      "should not be able to delete a node without a valid XML payload"
+
+      # valid delete now takes a payload
+      xml = node.to_xml
+      delete :delete, :params => { :id => node.id }, :body => xml.to_s
+      assert_response :success
+
+      # valid delete should return the new version number, which should
+      # be greater than the old version number
+      assert @response.body.to_i > node.version,
+             "delete request should return a new version number for node"
+
+      # deleting the same node twice doesn't work
+      xml = node.to_xml
+      delete :delete, :params => { :id => node.id }, :body => xml.to_s
+      assert_response :gone
+
+      # this won't work since the node never existed
+      delete :delete, :params => { :id => 0 }
+      assert_response :not_found
+
+      ## these test whether nodes which are in-use can be deleted:
+      # in a way...
+      used_node = create(:node, :changeset => create(:changeset, :user => user))
+      way_node = create(:way_node, :node => used_node)
+      way_node2 = create(:way_node, :node => used_node)
+
+      xml = used_node.to_xml
+      delete :delete, :params => { :id => used_node.id }, :body => xml.to_s
+      assert_response :precondition_failed,
+                      "shouldn't be able to delete a node used in a way (#{@response.body})"
+      assert_equal "Precondition failed: Node #{used_node.id} is still used by ways #{way_node.way.id},#{way_node2.way.id}.", @response.body
+
+      # in a relation...
+      used_node2 = create(:node, :changeset => create(:changeset, :user => user))
+      relation_member = create(:relation_member, :member => used_node2)
+      relation_member2 = create(:relation_member, :member => used_node2)
+
+      xml = used_node2.to_xml
+      delete :delete, :params => { :id => used_node2.id }, :body => xml.to_s
+      assert_response :precondition_failed,
+                      "shouldn't be able to delete a node used in a relation (#{@response.body})"
+      assert_equal "Precondition failed: Node #{used_node2.id} is still used by relations #{relation_member.relation.id},#{relation_member2.relation.id}.", @response.body
+    end
+
+    ##
+    # tests whether the API works and prevents incorrect use while trying
+    # to update nodes.
+    def test_update
+      ## First test with no user credentials
+      # try and update a node without authorisation
+      # first try to delete node without auth
+      private_user = create(:user, :data_public => false)
+      private_node = create(:node, :changeset => create(:changeset, :user => private_user))
+      user = create(:user)
+      node = create(:node, :changeset => create(:changeset, :user => user))
+
+      xml = node.to_xml
+      put :update, :params => { :id => node.id }, :body => xml.to_s
+      assert_response :unauthorized
+
+      ## Second test with the private user
+
+      # setup auth
+      basic_authorization private_user.email, "test"
+
+      ## trying to break changesets
+
+      # try and update in someone else's changeset
+      xml = update_changeset(private_node.to_xml,
+                             create(:changeset).id)
+      put :update, :params => { :id => private_node.id }, :body => xml.to_s
+      assert_require_public_data "update with other user's changeset should be forbidden when data isn't public"
+
+      # try and update in a closed changeset
+      xml = update_changeset(private_node.to_xml,
+                             create(:changeset, :closed, :user => private_user).id)
+      put :update, :params => { :id => private_node.id }, :body => xml.to_s
+      assert_require_public_data "update with closed changeset should be forbidden, when data isn't public"
+
+      # try and update in a non-existant changeset
+      xml = update_changeset(private_node.to_xml, 0)
+      put :update, :params => { :id => private_node.id }, :body => xml.to_s
+      assert_require_public_data "update with changeset=0 should be forbidden, when data isn't public"
+
+      ## try and submit invalid updates
+      xml = xml_attr_rewrite(private_node.to_xml, "lat", 91.0)
+      put :update, :params => { :id => private_node.id }, :body => xml.to_s
+      assert_require_public_data "node at lat=91 should be forbidden, when data isn't public"
+
+      xml = xml_attr_rewrite(private_node.to_xml, "lat", -91.0)
+      put :update, :params => { :id => private_node.id }, :body => xml.to_s
+      assert_require_public_data "node at lat=-91 should be forbidden, when data isn't public"
+
+      xml = xml_attr_rewrite(private_node.to_xml, "lon", 181.0)
+      put :update, :params => { :id => private_node.id }, :body => xml.to_s
+      assert_require_public_data "node at lon=181 should be forbidden, when data isn't public"
+
+      xml = xml_attr_rewrite(private_node.to_xml, "lon", -181.0)
+      put :update, :params => { :id => private_node.id }, :body => xml.to_s
+      assert_require_public_data "node at lon=-181 should be forbidden, when data isn't public"
+
+      ## finally, produce a good request which still won't work
+      xml = private_node.to_xml
+      put :update, :params => { :id => private_node.id }, :body => xml.to_s
+      assert_require_public_data "should have failed with a forbidden when data isn't public"
+
+      ## Finally test with the public user
+
+      # try and update a node without authorisation
+      # first try to update node without auth
+      xml = node.to_xml
+      put :update, :params => { :id => node.id }, :body => xml.to_s
+      assert_response :forbidden
+
+      # setup auth
+      basic_authorization user.email, "test"
+
+      ## trying to break changesets
+
+      # try and update in someone else's changeset
+      xml = update_changeset(node.to_xml,
+                             create(:changeset).id)
+      put :update, :params => { :id => node.id }, :body => xml.to_s
+      assert_response :conflict, "update with other user's changeset should be rejected"
+
+      # try and update in a closed changeset
+      xml = update_changeset(node.to_xml,
+                             create(:changeset, :closed, :user => user).id)
+      put :update, :params => { :id => node.id }, :body => xml.to_s
+      assert_response :conflict, "update with closed changeset should be rejected"
+
+      # try and update in a non-existant changeset
+      xml = update_changeset(node.to_xml, 0)
+      put :update, :params => { :id => node.id }, :body => xml.to_s
+      assert_response :conflict, "update with changeset=0 should be rejected"
+
+      ## try and submit invalid updates
+      xml = xml_attr_rewrite(node.to_xml, "lat", 91.0)
+      put :update, :params => { :id => node.id }, :body => xml.to_s
+      assert_response :bad_request, "node at lat=91 should be rejected"
+
+      xml = xml_attr_rewrite(node.to_xml, "lat", -91.0)
+      put :update, :params => { :id => node.id }, :body => xml.to_s
+      assert_response :bad_request, "node at lat=-91 should be rejected"
+
+      xml = xml_attr_rewrite(node.to_xml, "lon", 181.0)
+      put :update, :params => { :id => node.id }, :body => xml.to_s
+      assert_response :bad_request, "node at lon=181 should be rejected"
+
+      xml = xml_attr_rewrite(node.to_xml, "lon", -181.0)
+      put :update, :params => { :id => node.id }, :body => xml.to_s
+      assert_response :bad_request, "node at lon=-181 should be rejected"
+
+      ## next, attack the versioning
+      current_node_version = node.version
+
+      # try and submit a version behind
+      xml = xml_attr_rewrite(node.to_xml,
+                             "version", current_node_version - 1)
+      put :update, :params => { :id => node.id }, :body => xml.to_s
+      assert_response :conflict, "should have failed on old version number"
+
+      # try and submit a version ahead
+      xml = xml_attr_rewrite(node.to_xml,
+                             "version", current_node_version + 1)
+      put :update, :params => { :id => node.id }, :body => xml.to_s
+      assert_response :conflict, "should have failed on skipped version number"
+
+      # try and submit total crap in the version field
+      xml = xml_attr_rewrite(node.to_xml,
+                             "version", "p1r4t3s!")
+      put :update, :params => { :id => node.id }, :body => xml.to_s
+      assert_response :conflict,
+                      "should not be able to put 'p1r4at3s!' in the version field"
+
+      ## try an update with the wrong ID
+      xml = create(:node).to_xml
+      put :update, :params => { :id => node.id }, :body => xml.to_s
+      assert_response :bad_request,
+                      "should not be able to update a node with a different ID from the XML"
+
+      ## try an update with a minimal valid XML doc which isn't a well-formed OSM doc.
+      xml = "<update/>"
+      put :update, :params => { :id => node.id }, :body => xml.to_s
+      assert_response :bad_request,
+                      "should not be able to update a node with non-OSM XML doc."
+
+      ## finally, produce a good request which should work
+      xml = node.to_xml
+      put :update, :params => { :id => node.id }, :body => xml.to_s
+      assert_response :success, "a valid update request failed"
+    end
+
+    ##
+    # test fetching multiple nodes
+    def test_index
+      node1 = create(:node)
+      node2 = create(:node, :deleted)
+      node3 = create(:node)
+      node4 = create(:node, :with_history, :version => 2)
+      node5 = create(:node, :deleted, :with_history, :version => 2)
+
+      # check error when no parameter provided
+      get :index
+      assert_response :bad_request
+
+      # check error when no parameter value provided
+      get :index, :params => { :nodes => "" }
+      assert_response :bad_request
+
+      # test a working call
+      get :index, :params => { :nodes => "#{node1.id},#{node2.id},#{node3.id},#{node4.id},#{node5.id}" }
+      assert_response :success
+      assert_select "osm" do
+        assert_select "node", :count => 5
+        assert_select "node[id='#{node1.id}'][visible='true']", :count => 1
+        assert_select "node[id='#{node2.id}'][visible='false']", :count => 1
+        assert_select "node[id='#{node3.id}'][visible='true']", :count => 1
+        assert_select "node[id='#{node4.id}'][visible='true']", :count => 1
+        assert_select "node[id='#{node5.id}'][visible='false']", :count => 1
+      end
+
+      # check error when a non-existent node is included
+      get :index, :params => { :nodes => "#{node1.id},#{node2.id},#{node3.id},#{node4.id},#{node5.id},0" }
+      assert_response :not_found
+    end
+
+    ##
+    # test adding tags to a node
+    def test_duplicate_tags
+      existing_tag = create(:node_tag)
+      assert_equal true, existing_tag.node.changeset.user.data_public
+      # setup auth
+      basic_authorization existing_tag.node.changeset.user.email, "test"
+
+      # add an identical tag to the node
+      tag_xml = XML::Node.new("tag")
+      tag_xml["k"] = existing_tag.k
+      tag_xml["v"] = existing_tag.v
+
+      # add the tag into the existing xml
+      node_xml = existing_tag.node.to_xml
+      node_xml.find("//osm/node").first << tag_xml
+
+      # try and upload it
+      put :update, :params => { :id => existing_tag.node.id }, :body => node_xml.to_s
+      assert_response :bad_request,
+                      "adding duplicate tags to a node should fail with 'bad request'"
+      assert_equal "Element node/#{existing_tag.node.id} has duplicate tags with key #{existing_tag.k}", @response.body
+    end
+
+    # test whether string injection is possible
+    def test_string_injection
+      private_user = create(:user, :data_public => false)
+      private_changeset = create(:changeset, :user => private_user)
+      user = create(:user)
+      changeset = create(:changeset, :user => user)
+
+      ## First try with the non-data public user
+      basic_authorization private_user.email, "test"
+
+      # try and put something into a string that the API might
+      # use unquoted and therefore allow code injection...
+      xml = "<osm><node lat='0' lon='0' changeset='#{private_changeset.id}'>" \
+            '<tag k="#{@user.inspect}" v="0"/>' \
+            "</node></osm>"
+      put :create, :body => xml
+      assert_require_public_data "Shouldn't be able to create with non-public user"
+
+      ## Then try with the public data user
+      basic_authorization user.email, "test"
+
+      # try and put something into a string that the API might
+      # use unquoted and therefore allow code injection...
+      xml = "<osm><node lat='0' lon='0' changeset='#{changeset.id}'>" \
+            '<tag k="#{@user.inspect}" v="0"/>' \
+            "</node></osm>"
+      put :create, :body => xml
+      assert_response :success
+      nodeid = @response.body
+
+      # find the node in the database
+      checknode = Node.find(nodeid)
+      assert_not_nil checknode, "node not found in data base after upload"
+
+      # and grab it using the api
+      get :show, :params => { :id => nodeid }
+      assert_response :success
+      apinode = Node.from_xml(@response.body)
+      assert_not_nil apinode, "downloaded node is nil, but shouldn't be"
+
+      # check the tags are not corrupted
+      assert_equal checknode.tags, apinode.tags
+      assert apinode.tags.include?("\#{@user.inspect}")
+    end
+
+    ##
+    # update the changeset_id of a node element
+    def update_changeset(xml, changeset_id)
+      xml_attr_rewrite(xml, "changeset", changeset_id)
+    end
+
+    ##
+    # update an attribute in the node element
+    def xml_attr_rewrite(xml, name, value)
+      xml.find("//osm/node").first[name] = value.to_s
+      xml
+    end
+
+    ##
+    # parse some xml
+    def xml_parse(xml)
+      parser = XML::Parser.string(xml)
+      parser.parse
+    end
+  end
+end
diff --git a/test/controllers/api/notes_controller_test.rb b/test/controllers/api/notes_controller_test.rb
new file mode 100644 (file)
index 0000000..1254c4f
--- /dev/null
@@ -0,0 +1,1090 @@
+require "test_helper"
+
+module Api
+  class NotesControllerTest < ActionController::TestCase
+    def setup
+      # Stub nominatim response for note locations
+      stub_request(:get, %r{^https://nominatim\.openstreetmap\.org/reverse\?})
+        .to_return(:status => 404)
+    end
+
+    ##
+    # test all routes which lead to this controller
+    def test_routes
+      assert_routing(
+        { :path => "/api/0.6/notes", :method => :post },
+        { :controller => "api/notes", :action => "create", :format => "xml" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/notes/1", :method => :get },
+        { :controller => "api/notes", :action => "show", :id => "1", :format => "xml" }
+      )
+      assert_recognizes(
+        { :controller => "api/notes", :action => "show", :id => "1", :format => "xml" },
+        { :path => "/api/0.6/notes/1.xml", :method => :get }
+      )
+      assert_routing(
+        { :path => "/api/0.6/notes/1.rss", :method => :get },
+        { :controller => "api/notes", :action => "show", :id => "1", :format => "rss" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/notes/1.json", :method => :get },
+        { :controller => "api/notes", :action => "show", :id => "1", :format => "json" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/notes/1.gpx", :method => :get },
+        { :controller => "api/notes", :action => "show", :id => "1", :format => "gpx" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/notes/1/comment", :method => :post },
+        { :controller => "api/notes", :action => "comment", :id => "1", :format => "xml" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/notes/1/close", :method => :post },
+        { :controller => "api/notes", :action => "close", :id => "1", :format => "xml" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/notes/1/reopen", :method => :post },
+        { :controller => "api/notes", :action => "reopen", :id => "1", :format => "xml" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/notes/1", :method => :delete },
+        { :controller => "api/notes", :action => "destroy", :id => "1", :format => "xml" }
+      )
+
+      assert_routing(
+        { :path => "/api/0.6/notes", :method => :get },
+        { :controller => "api/notes", :action => "index", :format => "xml" }
+      )
+      assert_recognizes(
+        { :controller => "api/notes", :action => "index", :format => "xml" },
+        { :path => "/api/0.6/notes.xml", :method => :get }
+      )
+      assert_routing(
+        { :path => "/api/0.6/notes.rss", :method => :get },
+        { :controller => "api/notes", :action => "index", :format => "rss" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/notes.json", :method => :get },
+        { :controller => "api/notes", :action => "index", :format => "json" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/notes.gpx", :method => :get },
+        { :controller => "api/notes", :action => "index", :format => "gpx" }
+      )
+
+      assert_routing(
+        { :path => "/api/0.6/notes/search", :method => :get },
+        { :controller => "api/notes", :action => "search", :format => "xml" }
+      )
+      assert_recognizes(
+        { :controller => "api/notes", :action => "search", :format => "xml" },
+        { :path => "/api/0.6/notes/search.xml", :method => :get }
+      )
+      assert_routing(
+        { :path => "/api/0.6/notes/search.rss", :method => :get },
+        { :controller => "api/notes", :action => "search", :format => "rss" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/notes/search.json", :method => :get },
+        { :controller => "api/notes", :action => "search", :format => "json" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/notes/search.gpx", :method => :get },
+        { :controller => "api/notes", :action => "search", :format => "gpx" }
+      )
+
+      assert_routing(
+        { :path => "/api/0.6/notes/feed", :method => :get },
+        { :controller => "api/notes", :action => "feed", :format => "rss" }
+      )
+
+      assert_recognizes(
+        { :controller => "api/notes", :action => "create" },
+        { :path => "/api/0.6/notes/addPOIexec", :method => :post }
+      )
+      assert_recognizes(
+        { :controller => "api/notes", :action => "close" },
+        { :path => "/api/0.6/notes/closePOIexec", :method => :post }
+      )
+      assert_recognizes(
+        { :controller => "api/notes", :action => "comment" },
+        { :path => "/api/0.6/notes/editPOIexec", :method => :post }
+      )
+      assert_recognizes(
+        { :controller => "api/notes", :action => "index", :format => "gpx" },
+        { :path => "/api/0.6/notes/getGPX", :method => :get }
+      )
+      assert_recognizes(
+        { :controller => "api/notes", :action => "feed", :format => "rss" },
+        { :path => "/api/0.6/notes/getRSSfeed", :method => :get }
+      )
+    end
+
+    def test_create_success
+      assert_difference "Note.count", 1 do
+        assert_difference "NoteComment.count", 1 do
+          post :create, :params => { :lat => -1.0, :lon => -1.0, :text => "This is a comment", :format => "json" }
+        end
+      end
+      assert_response :success
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "Feature", js["type"]
+      assert_equal "Point", js["geometry"]["type"]
+      assert_equal [-1.0, -1.0], js["geometry"]["coordinates"]
+      assert_equal "open", js["properties"]["status"]
+      assert_equal 1, js["properties"]["comments"].count
+      assert_equal "opened", js["properties"]["comments"].last["action"]
+      assert_equal "This is a comment", js["properties"]["comments"].last["text"]
+      assert_nil js["properties"]["comments"].last["user"]
+      id = js["properties"]["id"]
+
+      get :show, :params => { :id => id, :format => "json" }
+      assert_response :success
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "Feature", js["type"]
+      assert_equal "Point", js["geometry"]["type"]
+      assert_equal [-1.0, -1.0], js["geometry"]["coordinates"]
+      assert_equal id, js["properties"]["id"]
+      assert_equal "open", js["properties"]["status"]
+      assert_equal 1, js["properties"]["comments"].count
+      assert_equal "opened", js["properties"]["comments"].last["action"]
+      assert_equal "This is a comment", js["properties"]["comments"].last["text"]
+      assert_nil js["properties"]["comments"].last["user"]
+    end
+
+    def test_create_fail
+      assert_no_difference "Note.count" do
+        assert_no_difference "NoteComment.count" do
+          post :create, :params => { :lon => -1.0, :text => "This is a comment" }
+        end
+      end
+      assert_response :bad_request
+
+      assert_no_difference "Note.count" do
+        assert_no_difference "NoteComment.count" do
+          post :create, :params => { :lat => -1.0, :text => "This is a comment" }
+        end
+      end
+      assert_response :bad_request
+
+      assert_no_difference "Note.count" do
+        assert_no_difference "NoteComment.count" do
+          post :create, :params => { :lat => -1.0, :lon => -1.0 }
+        end
+      end
+      assert_response :bad_request
+
+      assert_no_difference "Note.count" do
+        assert_no_difference "NoteComment.count" do
+          post :create, :params => { :lat => -1.0, :lon => -1.0, :text => "" }
+        end
+      end
+      assert_response :bad_request
+
+      assert_no_difference "Note.count" do
+        assert_no_difference "NoteComment.count" do
+          post :create, :params => { :lat => -100.0, :lon => -1.0, :text => "This is a comment" }
+        end
+      end
+      assert_response :bad_request
+
+      assert_no_difference "Note.count" do
+        assert_no_difference "NoteComment.count" do
+          post :create, :params => { :lat => -1.0, :lon => -200.0, :text => "This is a comment" }
+        end
+      end
+      assert_response :bad_request
+
+      assert_no_difference "Note.count" do
+        assert_no_difference "NoteComment.count" do
+          post :create, :params => { :lat => "abc", :lon => -1.0, :text => "This is a comment" }
+        end
+      end
+      assert_response :bad_request
+
+      assert_no_difference "Note.count" do
+        assert_no_difference "NoteComment.count" do
+          post :create, :params => { :lat => -1.0, :lon => "abc", :text => "This is a comment" }
+        end
+      end
+      assert_response :bad_request
+
+      assert_no_difference "Note.count" do
+        assert_no_difference "NoteComment.count" do
+          post :create, :params => { :lat => -1.0, :lon => -1.0, :text => "x\u0000y" }
+        end
+      end
+      assert_response :bad_request
+    end
+
+    def test_comment_success
+      open_note_with_comment = create(:note_with_comments)
+      assert_difference "NoteComment.count", 1 do
+        assert_no_difference "ActionMailer::Base.deliveries.size" do
+          perform_enqueued_jobs do
+            post :comment, :params => { :id => open_note_with_comment.id, :text => "This is an additional comment", :format => "json" }
+          end
+        end
+      end
+      assert_response :success
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "Feature", js["type"]
+      assert_equal open_note_with_comment.id, js["properties"]["id"]
+      assert_equal "open", js["properties"]["status"]
+      assert_equal 2, js["properties"]["comments"].count
+      assert_equal "commented", js["properties"]["comments"].last["action"]
+      assert_equal "This is an additional comment", js["properties"]["comments"].last["text"]
+      assert_nil js["properties"]["comments"].last["user"]
+
+      get :show, :params => { :id => open_note_with_comment.id, :format => "json" }
+      assert_response :success
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "Feature", js["type"]
+      assert_equal open_note_with_comment.id, js["properties"]["id"]
+      assert_equal "open", js["properties"]["status"]
+      assert_equal 2, js["properties"]["comments"].count
+      assert_equal "commented", js["properties"]["comments"].last["action"]
+      assert_equal "This is an additional comment", js["properties"]["comments"].last["text"]
+      assert_nil js["properties"]["comments"].last["user"]
+
+      # Ensure that emails are sent to users
+      first_user = create(:user)
+      second_user = create(:user)
+      third_user = create(:user)
+
+      note_with_comments_by_users = create(:note) do |note|
+        create(:note_comment, :note => note, :author => first_user)
+        create(:note_comment, :note => note, :author => second_user)
+      end
+      assert_difference "NoteComment.count", 1 do
+        assert_difference "ActionMailer::Base.deliveries.size", 2 do
+          perform_enqueued_jobs do
+            post :comment, :params => { :id => note_with_comments_by_users.id, :text => "This is an additional comment", :format => "json" }
+          end
+        end
+      end
+      assert_response :success
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "Feature", js["type"]
+      assert_equal note_with_comments_by_users.id, js["properties"]["id"]
+      assert_equal "open", js["properties"]["status"]
+      assert_equal 3, js["properties"]["comments"].count
+      assert_equal "commented", js["properties"]["comments"].last["action"]
+      assert_equal "This is an additional comment", js["properties"]["comments"].last["text"]
+      assert_nil js["properties"]["comments"].last["user"]
+
+      email = ActionMailer::Base.deliveries.find { |e| e.to.first == first_user.email }
+      assert_not_nil email
+      assert_equal 1, email.to.length
+      assert_equal "[OpenStreetMap] An anonymous user has commented on one of your notes", email.subject
+
+      email = ActionMailer::Base.deliveries.find { |e| e.to.first == second_user.email }
+      assert_not_nil email
+      assert_equal 1, email.to.length
+      assert_equal "[OpenStreetMap] An anonymous user has commented on a note you are interested in", email.subject
+
+      get :show, :params => { :id => note_with_comments_by_users.id, :format => "json" }
+      assert_response :success
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "Feature", js["type"]
+      assert_equal note_with_comments_by_users.id, js["properties"]["id"]
+      assert_equal "open", js["properties"]["status"]
+      assert_equal 3, js["properties"]["comments"].count
+      assert_equal "commented", js["properties"]["comments"].last["action"]
+      assert_equal "This is an additional comment", js["properties"]["comments"].last["text"]
+      assert_nil js["properties"]["comments"].last["user"]
+
+      ActionMailer::Base.deliveries.clear
+
+      basic_authorization third_user.email, "test"
+
+      assert_difference "NoteComment.count", 1 do
+        assert_difference "ActionMailer::Base.deliveries.size", 2 do
+          perform_enqueued_jobs do
+            post :comment, :params => { :id => note_with_comments_by_users.id, :text => "This is an additional comment", :format => "json" }
+          end
+        end
+      end
+      assert_response :success
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "Feature", js["type"]
+      assert_equal note_with_comments_by_users.id, js["properties"]["id"]
+      assert_equal "open", js["properties"]["status"]
+      assert_equal 4, js["properties"]["comments"].count
+      assert_equal "commented", js["properties"]["comments"].last["action"]
+      assert_equal "This is an additional comment", js["properties"]["comments"].last["text"]
+      assert_equal third_user.display_name, js["properties"]["comments"].last["user"]
+
+      email = ActionMailer::Base.deliveries.find { |e| e.to.first == first_user.email }
+      assert_not_nil email
+      assert_equal 1, email.to.length
+      assert_equal "[OpenStreetMap] #{third_user.display_name} has commented on one of your notes", email.subject
+      assert_equal first_user.email, email.to.first
+
+      email = ActionMailer::Base.deliveries.find { |e| e.to.first == second_user.email }
+      assert_not_nil email
+      assert_equal 1, email.to.length
+      assert_equal "[OpenStreetMap] #{third_user.display_name} has commented on a note you are interested in", email.subject
+
+      get :show, :params => { :id => note_with_comments_by_users.id, :format => "json" }
+      assert_response :success
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "Feature", js["type"]
+      assert_equal note_with_comments_by_users.id, js["properties"]["id"]
+      assert_equal "open", js["properties"]["status"]
+      assert_equal 4, js["properties"]["comments"].count
+      assert_equal "commented", js["properties"]["comments"].last["action"]
+      assert_equal "This is an additional comment", js["properties"]["comments"].last["text"]
+      assert_equal third_user.display_name, js["properties"]["comments"].last["user"]
+
+      ActionMailer::Base.deliveries.clear
+    end
+
+    def test_comment_fail
+      open_note_with_comment = create(:note_with_comments)
+
+      assert_no_difference "NoteComment.count" do
+        post :comment, :params => { :text => "This is an additional comment" }
+      end
+      assert_response :bad_request
+
+      assert_no_difference "NoteComment.count" do
+        post :comment, :params => { :id => open_note_with_comment.id }
+      end
+      assert_response :bad_request
+
+      assert_no_difference "NoteComment.count" do
+        post :comment, :params => { :id => open_note_with_comment.id, :text => "" }
+      end
+      assert_response :bad_request
+
+      assert_no_difference "NoteComment.count" do
+        post :comment, :params => { :id => 12345, :text => "This is an additional comment" }
+      end
+      assert_response :not_found
+
+      hidden_note_with_comment = create(:note_with_comments, :status => "hidden")
+
+      assert_no_difference "NoteComment.count" do
+        post :comment, :params => { :id => hidden_note_with_comment.id, :text => "This is an additional comment" }
+      end
+      assert_response :gone
+
+      closed_note_with_comment = create(:note_with_comments, :status => "closed", :closed_at => Time.now)
+
+      assert_no_difference "NoteComment.count" do
+        post :comment, :params => { :id => closed_note_with_comment.id, :text => "This is an additional comment" }
+      end
+      assert_response :conflict
+
+      assert_no_difference "NoteComment.count" do
+        post :comment, :params => { :id => open_note_with_comment.id, :text => "x\u0000y" }
+      end
+      assert_response :bad_request
+    end
+
+    def test_close_success
+      open_note_with_comment = create(:note_with_comments)
+      user = create(:user)
+
+      post :close, :params => { :id => open_note_with_comment.id, :text => "This is a close comment", :format => "json" }
+      assert_response :unauthorized
+
+      basic_authorization user.email, "test"
+
+      post :close, :params => { :id => open_note_with_comment.id, :text => "This is a close comment", :format => "json" }
+      assert_response :success
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "Feature", js["type"]
+      assert_equal open_note_with_comment.id, js["properties"]["id"]
+      assert_equal "closed", js["properties"]["status"]
+      assert_equal 2, js["properties"]["comments"].count
+      assert_equal "closed", js["properties"]["comments"].last["action"]
+      assert_equal "This is a close comment", js["properties"]["comments"].last["text"]
+      assert_equal user.display_name, js["properties"]["comments"].last["user"]
+
+      get :show, :params => { :id => open_note_with_comment.id, :format => "json" }
+      assert_response :success
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "Feature", js["type"]
+      assert_equal open_note_with_comment.id, js["properties"]["id"]
+      assert_equal "closed", js["properties"]["status"]
+      assert_equal 2, js["properties"]["comments"].count
+      assert_equal "closed", js["properties"]["comments"].last["action"]
+      assert_equal "This is a close comment", js["properties"]["comments"].last["text"]
+      assert_equal user.display_name, js["properties"]["comments"].last["user"]
+    end
+
+    def test_close_fail
+      post :close
+      assert_response :unauthorized
+
+      basic_authorization create(:user).email, "test"
+
+      post :close
+      assert_response :bad_request
+
+      post :close, :params => { :id => 12345 }
+      assert_response :not_found
+
+      hidden_note_with_comment = create(:note_with_comments, :status => "hidden")
+
+      post :close, :params => { :id => hidden_note_with_comment.id }
+      assert_response :gone
+
+      closed_note_with_comment = create(:note_with_comments, :status => "closed", :closed_at => Time.now)
+
+      post :close, :params => { :id => closed_note_with_comment.id }
+      assert_response :conflict
+    end
+
+    def test_reopen_success
+      closed_note_with_comment = create(:note_with_comments, :status => "closed", :closed_at => Time.now)
+      user = create(:user)
+
+      post :reopen, :params => { :id => closed_note_with_comment.id, :text => "This is a reopen comment", :format => "json" }
+      assert_response :unauthorized
+
+      basic_authorization user.email, "test"
+
+      post :reopen, :params => { :id => closed_note_with_comment.id, :text => "This is a reopen comment", :format => "json" }
+      assert_response :success
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "Feature", js["type"]
+      assert_equal closed_note_with_comment.id, js["properties"]["id"]
+      assert_equal "open", js["properties"]["status"]
+      assert_equal 2, js["properties"]["comments"].count
+      assert_equal "reopened", js["properties"]["comments"].last["action"]
+      assert_equal "This is a reopen comment", js["properties"]["comments"].last["text"]
+      assert_equal user.display_name, js["properties"]["comments"].last["user"]
+
+      get :show, :params => { :id => closed_note_with_comment.id, :format => "json" }
+      assert_response :success
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "Feature", js["type"]
+      assert_equal closed_note_with_comment.id, js["properties"]["id"]
+      assert_equal "open", js["properties"]["status"]
+      assert_equal 2, js["properties"]["comments"].count
+      assert_equal "reopened", js["properties"]["comments"].last["action"]
+      assert_equal "This is a reopen comment", js["properties"]["comments"].last["text"]
+      assert_equal user.display_name, js["properties"]["comments"].last["user"]
+    end
+
+    def test_reopen_fail
+      hidden_note_with_comment = create(:note_with_comments, :status => "hidden")
+
+      post :reopen, :params => { :id => hidden_note_with_comment.id }
+      assert_response :unauthorized
+
+      basic_authorization create(:user).email, "test"
+
+      post :reopen, :params => { :id => 12345 }
+      assert_response :not_found
+
+      post :reopen, :params => { :id => hidden_note_with_comment.id }
+      assert_response :gone
+
+      open_note_with_comment = create(:note_with_comments)
+
+      post :reopen, :params => { :id => open_note_with_comment.id }
+      assert_response :conflict
+    end
+
+    def test_show_success
+      open_note = create(:note_with_comments)
+
+      get :show, :params => { :id => open_note.id, :format => "xml" }
+      assert_response :success
+      assert_equal "application/xml", @response.content_type
+      assert_select "osm", :count => 1 do
+        assert_select "note[lat='#{open_note.lat}'][lon='#{open_note.lon}']", :count => 1 do
+          assert_select "id", open_note.id.to_s
+          assert_select "url", note_url(open_note, :format => "xml")
+          assert_select "comment_url", comment_note_url(open_note, :format => "xml")
+          assert_select "close_url", close_note_url(open_note, :format => "xml")
+          assert_select "date_created", open_note.created_at.to_s
+          assert_select "status", open_note.status
+          assert_select "comments", :count => 1 do
+            assert_select "comment", :count => 1
+          end
+        end
+      end
+
+      get :show, :params => { :id => open_note.id, :format => "rss" }
+      assert_response :success
+      assert_equal "application/rss+xml", @response.content_type
+      assert_select "rss", :count => 1 do
+        assert_select "channel", :count => 1 do
+          assert_select "item", :count => 1 do
+            assert_select "link", browse_note_url(open_note)
+            assert_select "guid", note_url(open_note)
+            assert_select "pubDate", open_note.created_at.to_s(:rfc822)
+            #          assert_select "geo:lat", open_note.lat.to_s
+            #          assert_select "geo:long", open_note.lon
+            #          assert_select "georss:point", "#{open_note.lon} #{open_note.lon}"
+          end
+        end
+      end
+
+      get :show, :params => { :id => open_note.id, :format => "json" }
+      assert_response :success
+      assert_equal "application/json", @response.content_type
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "Feature", js["type"]
+      assert_equal "Point", js["geometry"]["type"]
+      assert_equal open_note.lat, js["geometry"]["coordinates"][0]
+      assert_equal open_note.lon, js["geometry"]["coordinates"][1]
+      assert_equal open_note.id, js["properties"]["id"]
+      assert_equal note_url(open_note, :format => "json"), js["properties"]["url"]
+      assert_equal comment_note_url(open_note, :format => "json"), js["properties"]["comment_url"]
+      assert_equal close_note_url(open_note, :format => "json"), js["properties"]["close_url"]
+      assert_equal open_note.created_at.to_s, js["properties"]["date_created"]
+      assert_equal open_note.status, js["properties"]["status"]
+
+      get :show, :params => { :id => open_note.id, :format => "gpx" }
+      assert_response :success
+      assert_equal "application/gpx+xml", @response.content_type
+      assert_select "gpx", :count => 1 do
+        assert_select "wpt[lat='#{open_note.lat}'][lon='#{open_note.lon}']", :count => 1 do
+          assert_select "time", :count => 1
+          assert_select "name", "Note: #{open_note.id}"
+          assert_select "desc", :count => 1
+          assert_select "link[href='http://test.host/note/#{open_note.id}']", :count => 1
+          assert_select "extensions", :count => 1 do
+            assert_select "id", open_note.id.to_s
+            assert_select "url", note_url(open_note, :format => "gpx")
+            assert_select "comment_url", comment_note_url(open_note, :format => "gpx")
+            assert_select "close_url", close_note_url(open_note, :format => "gpx")
+          end
+        end
+      end
+    end
+
+    def test_show_hidden_comment
+      note_with_hidden_comment = create(:note) do |note|
+        create(:note_comment, :note => note, :body => "Valid comment for hidden note")
+        create(:note_comment, :note => note, :visible => false)
+        create(:note_comment, :note => note, :body => "Another valid comment for hidden note")
+      end
+
+      get :show, :params => { :id => note_with_hidden_comment.id, :format => "json" }
+      assert_response :success
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "Feature", js["type"]
+      assert_equal note_with_hidden_comment.id, js["properties"]["id"]
+      assert_equal 2, js["properties"]["comments"].count
+      assert_equal "Valid comment for hidden note", js["properties"]["comments"][0]["text"]
+      assert_equal "Another valid comment for hidden note", js["properties"]["comments"][1]["text"]
+    end
+
+    def test_show_fail
+      get :show, :params => { :id => 12345 }
+      assert_response :not_found
+
+      get :show, :params => { :id => create(:note, :status => "hidden").id }
+      assert_response :gone
+    end
+
+    def test_destroy_success
+      open_note_with_comment = create(:note_with_comments)
+      user = create(:user)
+      moderator_user = create(:moderator_user)
+
+      delete :destroy, :params => { :id => open_note_with_comment.id, :text => "This is a hide comment", :format => "json" }
+      assert_response :unauthorized
+
+      basic_authorization user.email, "test"
+
+      delete :destroy, :params => { :id => open_note_with_comment.id, :text => "This is a hide comment", :format => "json" }
+      assert_response :forbidden
+
+      basic_authorization moderator_user.email, "test"
+
+      delete :destroy, :params => { :id => open_note_with_comment.id, :text => "This is a hide comment", :format => "json" }
+      assert_response :success
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "Feature", js["type"]
+      assert_equal open_note_with_comment.id, js["properties"]["id"]
+      assert_equal "hidden", js["properties"]["status"]
+      assert_equal 2, js["properties"]["comments"].count
+      assert_equal "hidden", js["properties"]["comments"].last["action"]
+      assert_equal "This is a hide comment", js["properties"]["comments"].last["text"]
+      assert_equal moderator_user.display_name, js["properties"]["comments"].last["user"]
+
+      get :show, :params => { :id => open_note_with_comment.id, :format => "json" }
+      assert_response :success
+
+      basic_authorization user.email, "test"
+      get :show, :params => { :id => open_note_with_comment.id, :format => "json" }
+      assert_response :gone
+    end
+
+    def test_destroy_fail
+      user = create(:user)
+      moderator_user = create(:moderator_user)
+
+      delete :destroy, :params => { :id => 12345, :format => "json" }
+      assert_response :unauthorized
+
+      basic_authorization user.email, "test"
+
+      delete :destroy, :params => { :id => 12345, :format => "json" }
+      assert_response :forbidden
+
+      basic_authorization moderator_user.email, "test"
+
+      delete :destroy, :params => { :id => 12345, :format => "json" }
+      assert_response :not_found
+
+      hidden_note_with_comment = create(:note_with_comments, :status => "hidden")
+
+      delete :destroy, :params => { :id => hidden_note_with_comment.id, :format => "json" }
+      assert_response :gone
+    end
+
+    def test_index_success
+      position = (1.1 * GeoRecord::SCALE).to_i
+      create(:note_with_comments, :latitude => position, :longitude => position)
+      create(:note_with_comments, :latitude => position, :longitude => position)
+
+      get :index, :params => { :bbox => "1,1,1.2,1.2", :format => "rss" }
+      assert_response :success
+      assert_equal "application/rss+xml", @response.content_type
+      assert_select "rss", :count => 1 do
+        assert_select "channel", :count => 1 do
+          assert_select "item", :count => 2
+        end
+      end
+
+      get :index, :params => { :bbox => "1,1,1.2,1.2", :format => "json" }
+      assert_response :success
+      assert_equal "application/json", @response.content_type
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "FeatureCollection", js["type"]
+      assert_equal 2, js["features"].count
+
+      get :index, :params => { :bbox => "1,1,1.2,1.2", :format => "xml" }
+      assert_response :success
+      assert_equal "application/xml", @response.content_type
+      assert_select "osm", :count => 1 do
+        assert_select "note", :count => 2
+      end
+
+      get :index, :params => { :bbox => "1,1,1.2,1.2", :format => "gpx" }
+      assert_response :success
+      assert_equal "application/gpx+xml", @response.content_type
+      assert_select "gpx", :count => 1 do
+        assert_select "wpt", :count => 2
+      end
+    end
+
+    def test_index_limit
+      position = (1.1 * GeoRecord::SCALE).to_i
+      create(:note_with_comments, :latitude => position, :longitude => position)
+      create(:note_with_comments, :latitude => position, :longitude => position)
+
+      get :index, :params => { :bbox => "1,1,1.2,1.2", :limit => 1, :format => "rss" }
+      assert_response :success
+      assert_equal "application/rss+xml", @response.content_type
+      assert_select "rss", :count => 1 do
+        assert_select "channel", :count => 1 do
+          assert_select "item", :count => 1
+        end
+      end
+
+      get :index, :params => { :bbox => "1,1,1.2,1.2", :limit => 1, :format => "json" }
+      assert_response :success
+      assert_equal "application/json", @response.content_type
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "FeatureCollection", js["type"]
+      assert_equal 1, js["features"].count
+
+      get :index, :params => { :bbox => "1,1,1.2,1.2", :limit => 1, :format => "xml" }
+      assert_response :success
+      assert_equal "application/xml", @response.content_type
+      assert_select "osm", :count => 1 do
+        assert_select "note", :count => 1
+      end
+
+      get :index, :params => { :bbox => "1,1,1.2,1.2", :limit => 1, :format => "gpx" }
+      assert_response :success
+      assert_equal "application/gpx+xml", @response.content_type
+      assert_select "gpx", :count => 1 do
+        assert_select "wpt", :count => 1
+      end
+    end
+
+    def test_index_empty_area
+      get :index, :params => { :bbox => "5,5,5.1,5.1", :format => "rss" }
+      assert_response :success
+      assert_equal "application/rss+xml", @response.content_type
+      assert_select "rss", :count => 1 do
+        assert_select "channel", :count => 1 do
+          assert_select "item", :count => 0
+        end
+      end
+
+      get :index, :params => { :bbox => "5,5,5.1,5.1", :format => "json" }
+      assert_response :success
+      assert_equal "application/json", @response.content_type
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "FeatureCollection", js["type"]
+      assert_equal 0, js["features"].count
+
+      get :index, :params => { :bbox => "5,5,5.1,5.1", :format => "xml" }
+      assert_response :success
+      assert_equal "application/xml", @response.content_type
+      assert_select "osm", :count => 1 do
+        assert_select "note", :count => 0
+      end
+
+      get :index, :params => { :bbox => "5,5,5.1,5.1", :format => "gpx" }
+      assert_response :success
+      assert_equal "application/gpx+xml", @response.content_type
+      assert_select "gpx", :count => 1 do
+        assert_select "wpt", :count => 0
+      end
+    end
+
+    def test_index_large_area
+      get :index, :params => { :bbox => "-2.5,-2.5,2.5,2.5", :format => :json }
+      assert_response :success
+      assert_equal "application/json", @response.content_type
+
+      get :index, :params => { :l => "-2.5", :b => "-2.5", :r => "2.5", :t => "2.5", :format => :json }
+      assert_response :success
+      assert_equal "application/json", @response.content_type
+
+      get :index, :params => { :bbox => "-10,-10,12,12", :format => :json }
+      assert_response :bad_request
+      assert_equal "application/json", @response.content_type
+
+      get :index, :params => { :l => "-10", :b => "-10", :r => "12", :t => "12", :format => :json }
+      assert_response :bad_request
+      assert_equal "application/json", @response.content_type
+    end
+
+    def test_index_closed
+      create(:note_with_comments, :status => "closed", :closed_at => Time.now - 5.days)
+      create(:note_with_comments, :status => "closed", :closed_at => Time.now - 100.days)
+      create(:note_with_comments, :status => "hidden")
+      create(:note_with_comments)
+
+      # Open notes + closed in last 7 days
+      get :index, :params => { :bbox => "1,1,1.7,1.7", :closed => "7", :format => "json" }
+      assert_response :success
+      assert_equal "application/json", @response.content_type
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "FeatureCollection", js["type"]
+      assert_equal 2, js["features"].count
+
+      # Only open notes
+      get :index, :params => { :bbox => "1,1,1.7,1.7", :closed => "0", :format => "json" }
+      assert_response :success
+      assert_equal "application/json", @response.content_type
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "FeatureCollection", js["type"]
+      assert_equal 1, js["features"].count
+
+      # Open notes + all closed notes
+      get :index, :params => { :bbox => "1,1,1.7,1.7", :closed => "-1", :format => "json" }
+      assert_response :success
+      assert_equal "application/json", @response.content_type
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "FeatureCollection", js["type"]
+      assert_equal 3, js["features"].count
+    end
+
+    def test_index_bad_params
+      get :index, :params => { :bbox => "-2.5,-2.5,2.5" }
+      assert_response :bad_request
+
+      get :index, :params => { :bbox => "-2.5,-2.5,2.5,2.5,2.5" }
+      assert_response :bad_request
+
+      get :index, :params => { :b => "-2.5", :r => "2.5", :t => "2.5" }
+      assert_response :bad_request
+
+      get :index, :params => { :l => "-2.5", :r => "2.5", :t => "2.5" }
+      assert_response :bad_request
+
+      get :index, :params => { :l => "-2.5", :b => "-2.5", :t => "2.5" }
+      assert_response :bad_request
+
+      get :index, :params => { :l => "-2.5", :b => "-2.5", :r => "2.5" }
+      assert_response :bad_request
+
+      get :index, :params => { :bbox => "1,1,1.7,1.7", :limit => "0", :format => "json" }
+      assert_response :bad_request
+
+      get :index, :params => { :bbox => "1,1,1.7,1.7", :limit => "10001", :format => "json" }
+      assert_response :bad_request
+    end
+
+    def test_search_success
+      create(:note_with_comments)
+
+      get :search, :params => { :q => "note comment", :format => "xml" }
+      assert_response :success
+      assert_equal "application/xml", @response.content_type
+      assert_select "osm", :count => 1 do
+        assert_select "note", :count => 1
+      end
+
+      get :search, :params => { :q => "note comment", :format => "json" }
+      assert_response :success
+      assert_equal "application/json", @response.content_type
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "FeatureCollection", js["type"]
+      assert_equal 1, js["features"].count
+
+      get :search, :params => { :q => "note comment", :format => "rss" }
+      assert_response :success
+      assert_equal "application/rss+xml", @response.content_type
+      assert_select "rss", :count => 1 do
+        assert_select "channel", :count => 1 do
+          assert_select "item", :count => 1
+        end
+      end
+
+      get :search, :params => { :q => "note comment", :format => "gpx" }
+      assert_response :success
+      assert_equal "application/gpx+xml", @response.content_type
+      assert_select "gpx", :count => 1 do
+        assert_select "wpt", :count => 1
+      end
+    end
+
+    def test_search_by_display_name_success
+      user = create(:user)
+
+      create(:note) do |note|
+        create(:note_comment, :note => note, :author => user)
+      end
+
+      get :search, :params => { :display_name => user.display_name, :format => "xml" }
+      assert_response :success
+      assert_equal "application/xml", @response.content_type
+      assert_select "osm", :count => 1 do
+        assert_select "note", :count => 1
+      end
+
+      get :search, :params => { :display_name => user.display_name, :format => "json" }
+      assert_response :success
+      assert_equal "application/json", @response.content_type
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "FeatureCollection", js["type"]
+      assert_equal 1, js["features"].count
+
+      get :search, :params => { :display_name => user.display_name, :format => "rss" }
+      assert_response :success
+      assert_equal "application/rss+xml", @response.content_type
+      assert_select "rss", :count => 1 do
+        assert_select "channel", :count => 1 do
+          assert_select "item", :count => 1
+        end
+      end
+
+      get :search, :params => { :display_name => user.display_name, :format => "gpx" }
+      assert_response :success
+      assert_equal "application/gpx+xml", @response.content_type
+      assert_select "gpx", :count => 1 do
+        assert_select "wpt", :count => 1
+      end
+    end
+
+    def test_search_by_user_success
+      user = create(:user)
+
+      create(:note) do |note|
+        create(:note_comment, :note => note, :author => user)
+      end
+
+      get :search, :params => { :user => user.id, :format => "xml" }
+      assert_response :success
+      assert_equal "application/xml", @response.content_type
+      assert_select "osm", :count => 1 do
+        assert_select "note", :count => 1
+      end
+
+      get :search, :params => { :user => user.id, :format => "json" }
+      assert_response :success
+      assert_equal "application/json", @response.content_type
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "FeatureCollection", js["type"]
+      assert_equal 1, js["features"].count
+
+      get :search, :params => { :user => user.id, :format => "rss" }
+      assert_response :success
+      assert_equal "application/rss+xml", @response.content_type
+      assert_select "rss", :count => 1 do
+        assert_select "channel", :count => 1 do
+          assert_select "item", :count => 1
+        end
+      end
+
+      get :search, :params => { :user => user.id, :format => "gpx" }
+      assert_response :success
+      assert_equal "application/gpx+xml", @response.content_type
+      assert_select "gpx", :count => 1 do
+        assert_select "wpt", :count => 1
+      end
+    end
+
+    def test_search_no_match
+      create(:note_with_comments)
+
+      get :search, :params => { :q => "no match", :format => "xml" }
+      assert_response :success
+      assert_equal "application/xml", @response.content_type
+      assert_select "osm", :count => 1 do
+        assert_select "note", :count => 0
+      end
+
+      get :search, :params => { :q => "no match", :format => "json" }
+      assert_response :success
+      assert_equal "application/json", @response.content_type
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "FeatureCollection", js["type"]
+      assert_equal 0, js["features"].count
+
+      get :search, :params => { :q => "no match", :format => "rss" }
+      assert_response :success
+      assert_equal "application/rss+xml", @response.content_type
+      assert_select "rss", :count => 1 do
+        assert_select "channel", :count => 1 do
+          assert_select "item", :count => 0
+        end
+      end
+
+      get :search, :params => { :q => "no match", :format => "gpx" }
+      assert_response :success
+      assert_equal "application/gpx+xml", @response.content_type
+      assert_select "gpx", :count => 1 do
+        assert_select "wpt", :count => 0
+      end
+    end
+
+    def test_search_by_time_no_match
+      create(:note_with_comments)
+
+      get :search, :params => { :from => "01.01.2010", :to => "01.10.2010", :format => "xml" }
+      assert_response :success
+      assert_equal "application/xml", @response.content_type
+      assert_select "osm", :count => 1 do
+        assert_select "note", :count => 0
+      end
+
+      get :search, :params => { :from => "01.01.2010", :to => "01.10.2010", :format => "json" }
+      assert_response :success
+      assert_equal "application/json", @response.content_type
+      js = ActiveSupport::JSON.decode(@response.body)
+      assert_not_nil js
+      assert_equal "FeatureCollection", js["type"]
+      assert_equal 0, js["features"].count
+
+      get :search, :params => { :from => "01.01.2010", :to => "01.10.2010", :format => "rss" }
+      assert_response :success
+      assert_equal "application/rss+xml", @response.content_type
+      assert_select "rss", :count => 1 do
+        assert_select "channel", :count => 1 do
+          assert_select "item", :count => 0
+        end
+      end
+
+      get :search, :params => { :from => "01.01.2010", :to => "01.10.2010", :format => "gpx" }
+      assert_response :success
+      assert_equal "application/gpx+xml", @response.content_type
+      assert_select "gpx", :count => 1 do
+        assert_select "wpt", :count => 0
+      end
+    end
+
+    def test_search_bad_params
+      get :search, :params => { :q => "no match", :limit => "0", :format => "json" }
+      assert_response :bad_request
+
+      get :search, :params => { :q => "no match", :limit => "10001", :format => "json" }
+      assert_response :bad_request
+
+      get :search, :params => { :display_name => "non-existent" }
+      assert_response :bad_request
+
+      get :search, :params => { :user => "-1" }
+      assert_response :bad_request
+
+      get :search, :params => { :from => "wrong-date", :to => "wrong-date" }
+      assert_response :bad_request
+
+      get :search, :params => { :from => "01.01.2010", :to => "2010.01.2010" }
+      assert_response :bad_request
+    end
+
+    def test_feed_success
+      position = (1.1 * GeoRecord::SCALE).to_i
+      create(:note_with_comments, :latitude => position, :longitude => position)
+      create(:note_with_comments, :latitude => position, :longitude => position)
+      position = (1.5 * GeoRecord::SCALE).to_i
+      create(:note_with_comments, :latitude => position, :longitude => position)
+      create(:note_with_comments, :latitude => position, :longitude => position)
+
+      get :feed, :params => { :format => "rss" }
+      assert_response :success
+      assert_equal "application/rss+xml", @response.content_type
+      assert_select "rss", :count => 1 do
+        assert_select "channel", :count => 1 do
+          assert_select "item", :count => 4
+        end
+      end
+
+      get :feed, :params => { :bbox => "1,1,1.2,1.2", :format => "rss" }
+      assert_response :success
+      assert_equal "application/rss+xml", @response.content_type
+      assert_select "rss", :count => 1 do
+        assert_select "channel", :count => 1 do
+          assert_select "item", :count => 2
+        end
+      end
+    end
+
+    def test_feed_fail
+      get :feed, :params => { :bbox => "1,1,1.2", :format => "rss" }
+      assert_response :bad_request
+
+      get :feed, :params => { :bbox => "1,1,1.2,1.2,1.2", :format => "rss" }
+      assert_response :bad_request
+
+      get :feed, :params => { :bbox => "1,1,1.2,1.2", :limit => "0", :format => "rss" }
+      assert_response :bad_request
+
+      get :feed, :params => { :bbox => "1,1,1.2,1.2", :limit => "10001", :format => "rss" }
+      assert_response :bad_request
+    end
+  end
+end
diff --git a/test/controllers/api/old_nodes_controller_test.rb b/test/controllers/api/old_nodes_controller_test.rb
new file mode 100644 (file)
index 0000000..375a553
--- /dev/null
@@ -0,0 +1,430 @@
+require "test_helper"
+
+module Api
+  class OldNodesControllerTest < ActionController::TestCase
+    #
+    # TODO: test history
+    #
+
+    ##
+    # test all routes which lead to this controller
+    def test_routes
+      assert_routing(
+        { :path => "/api/0.6/node/1/history", :method => :get },
+        { :controller => "api/old_nodes", :action => "history", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/node/1/2", :method => :get },
+        { :controller => "api/old_nodes", :action => "version", :id => "1", :version => "2" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/node/1/2/redact", :method => :post },
+        { :controller => "api/old_nodes", :action => "redact", :id => "1", :version => "2" }
+      )
+    end
+
+    ##
+    # test the version call by submitting several revisions of a new node
+    # to the API and ensuring that later calls to version return the
+    # matching versions of the object.
+    #
+    ##
+    # FIXME: Move this test to being an integration test since it spans multiple controllers
+    def test_version
+      private_user = create(:user, :data_public => false)
+      private_node = create(:node, :with_history, :version => 4, :changeset => create(:changeset, :user => private_user))
+      user = create(:user)
+      node = create(:node, :with_history, :version => 4, :changeset => create(:changeset, :user => user))
+      create_list(:node_tag, 2, :node => node)
+      # Ensure that the current tags are propagated to the history too
+      propagate_tags(node, node.old_nodes.last)
+
+      ## First try this with a non-public user
+      basic_authorization private_user.email, "test"
+
+      # setup a simple XML node
+      xml_doc = private_node.to_xml
+      xml_node = xml_doc.find("//osm/node").first
+      nodeid = private_node.id
+
+      # keep a hash of the versions => string, as we'll need something
+      # to test against later
+      versions = {}
+
+      # save a version for later checking
+      versions[xml_node["version"]] = xml_doc.to_s
+
+      # randomly move the node about
+      3.times do
+        # move the node somewhere else
+        xml_node["lat"] = precision(rand * 180 - 90).to_s
+        xml_node["lon"] = precision(rand * 360 - 180).to_s
+        with_controller(NodesController.new) do
+          put :update, :params => { :id => nodeid }, :body => xml_doc.to_s
+          assert_response :forbidden, "Should have rejected node update"
+          xml_node["version"] = @response.body.to_s
+        end
+        # save a version for later checking
+        versions[xml_node["version"]] = xml_doc.to_s
+      end
+
+      # add a bunch of random tags
+      3.times do
+        xml_tag = XML::Node.new("tag")
+        xml_tag["k"] = random_string
+        xml_tag["v"] = random_string
+        xml_node << xml_tag
+        with_controller(NodesController.new) do
+          put :update, :params => { :id => nodeid }, :body => xml_doc.to_s
+          assert_response :forbidden,
+                          "should have rejected node #{nodeid} (#{@response.body}) with forbidden"
+          xml_node["version"] = @response.body.to_s
+        end
+        # save a version for later checking
+        versions[xml_node["version"]] = xml_doc.to_s
+      end
+
+      # probably should check that they didn't get written to the database
+
+      ## Now do it with the public user
+      basic_authorization user.email, "test"
+
+      # setup a simple XML node
+
+      xml_doc = node.to_xml
+      xml_node = xml_doc.find("//osm/node").first
+      nodeid = node.id
+
+      # keep a hash of the versions => string, as we'll need something
+      # to test against later
+      versions = {}
+
+      # save a version for later checking
+      versions[xml_node["version"]] = xml_doc.to_s
+
+      # randomly move the node about
+      3.times do
+        # move the node somewhere else
+        xml_node["lat"] = precision(rand * 180 - 90).to_s
+        xml_node["lon"] = precision(rand * 360 - 180).to_s
+        with_controller(NodesController.new) do
+          put :update, :params => { :id => nodeid }, :body => xml_doc.to_s
+          assert_response :success
+          xml_node["version"] = @response.body.to_s
+        end
+        # save a version for later checking
+        versions[xml_node["version"]] = xml_doc.to_s
+      end
+
+      # add a bunch of random tags
+      3.times do
+        xml_tag = XML::Node.new("tag")
+        xml_tag["k"] = random_string
+        xml_tag["v"] = random_string
+        xml_node << xml_tag
+        with_controller(NodesController.new) do
+          put :update, :params => { :id => nodeid }, :body => xml_doc.to_s
+          assert_response :success,
+                          "couldn't update node #{nodeid} (#{@response.body})"
+          xml_node["version"] = @response.body.to_s
+        end
+        # save a version for later checking
+        versions[xml_node["version"]] = xml_doc.to_s
+      end
+
+      # check all the versions
+      versions.each_key do |key|
+        get :version, :params => { :id => nodeid, :version => key.to_i }
+
+        assert_response :success,
+                        "couldn't get version #{key.to_i} of node #{nodeid}"
+
+        check_node = Node.from_xml(versions[key])
+        api_node = Node.from_xml(@response.body.to_s)
+
+        assert_nodes_are_equal check_node, api_node
+      end
+    end
+
+    def test_not_found_version
+      check_not_found_id_version(70000, 312344)
+      check_not_found_id_version(-1, -13)
+      check_not_found_id_version(create(:node).id, 24354)
+      check_not_found_id_version(24356, create(:node).version)
+    end
+
+    def check_not_found_id_version(id, version)
+      get :version, :params => { :id => id, :version => version }
+      assert_response :not_found
+    rescue ActionController::UrlGenerationError => ex
+      assert_match(/No route matches/, ex.to_s)
+    end
+
+    ##
+    # Test that getting the current version is identical to picking
+    # that version with the version URI call.
+    def test_current_version
+      node = create(:node, :with_history)
+      used_node = create(:node, :with_history)
+      create(:way_node, :node => used_node)
+      node_used_by_relationship = create(:node, :with_history)
+      create(:relation_member, :member => node_used_by_relationship)
+      node_with_versions = create(:node, :with_history, :version => 4)
+
+      create(:node_tag, :node => node)
+      create(:node_tag, :node => used_node)
+      create(:node_tag, :node => node_used_by_relationship)
+      create(:node_tag, :node => node_with_versions)
+      propagate_tags(node, node.old_nodes.last)
+      propagate_tags(used_node, used_node.old_nodes.last)
+      propagate_tags(node_used_by_relationship, node_used_by_relationship.old_nodes.last)
+      propagate_tags(node_with_versions, node_with_versions.old_nodes.last)
+
+      check_current_version(node)
+      check_current_version(used_node)
+      check_current_version(node_used_by_relationship)
+      check_current_version(node_with_versions)
+    end
+
+    ##
+    # test the redaction of an old version of a node, while not being
+    # authorised.
+    def test_redact_node_unauthorised
+      node = create(:node, :with_history, :version => 4)
+      node_v3 = node.old_nodes.find_by(:version => 3)
+
+      do_redact_node(node_v3,
+                     create(:redaction))
+      assert_response :unauthorized, "should need to be authenticated to redact."
+    end
+
+    ##
+    # test the redaction of an old version of a node, while being
+    # authorised as a normal user.
+    def test_redact_node_normal_user
+      basic_authorization create(:user).email, "test"
+
+      node = create(:node, :with_history, :version => 4)
+      node_v3 = node.old_nodes.find_by(:version => 3)
+
+      do_redact_node(node_v3,
+                     create(:redaction))
+      assert_response :forbidden, "should need to be moderator to redact."
+    end
+
+    ##
+    # test that, even as moderator, the current version of a node
+    # can't be redacted.
+    def test_redact_node_current_version
+      basic_authorization create(:moderator_user).email, "test"
+
+      node = create(:node, :with_history, :version => 4)
+      node_v4 = node.old_nodes.find_by(:version => 4)
+
+      do_redact_node(node_v4,
+                     create(:redaction))
+      assert_response :bad_request, "shouldn't be OK to redact current version as moderator."
+    end
+
+    ##
+    # test that redacted nodes aren't visible, regardless of
+    # authorisation except as moderator...
+    def test_version_redacted
+      node = create(:node, :with_history, :version => 2)
+      node_v1 = node.old_nodes.find_by(:version => 1)
+      node_v1.redact!(create(:redaction))
+
+      get :version, :params => { :id => node_v1.node_id, :version => node_v1.version }
+      assert_response :forbidden, "Redacted node shouldn't be visible via the version API."
+
+      # not even to a logged-in user
+      basic_authorization create(:user).email, "test"
+      get :version, :params => { :id => node_v1.node_id, :version => node_v1.version }
+      assert_response :forbidden, "Redacted node shouldn't be visible via the version API, even when logged in."
+    end
+
+    ##
+    # test that redacted nodes aren't visible in the history
+    def test_history_redacted
+      node = create(:node, :with_history, :version => 2)
+      node_v1 = node.old_nodes.find_by(:version => 1)
+      node_v1.redact!(create(:redaction))
+
+      get :history, :params => { :id => node_v1.node_id }
+      assert_response :success, "Redaction shouldn't have stopped history working."
+      assert_select "osm node[id='#{node_v1.node_id}'][version='#{node_v1.version}']", 0, "redacted node #{node_v1.node_id} version #{node_v1.version} shouldn't be present in the history."
+
+      # not even to a logged-in user
+      basic_authorization create(:user).email, "test"
+      get :history, :params => { :id => node_v1.node_id }
+      assert_response :success, "Redaction shouldn't have stopped history working."
+      assert_select "osm node[id='#{node_v1.node_id}'][version='#{node_v1.version}']", 0, "redacted node #{node_v1.node_id} version #{node_v1.version} shouldn't be present in the history, even when logged in."
+    end
+
+    ##
+    # test the redaction of an old version of a node, while being
+    # authorised as a moderator.
+    def test_redact_node_moderator
+      node = create(:node, :with_history, :version => 4)
+      node_v3 = node.old_nodes.find_by(:version => 3)
+      basic_authorization create(:moderator_user).email, "test"
+
+      do_redact_node(node_v3, create(:redaction))
+      assert_response :success, "should be OK to redact old version as moderator."
+
+      # check moderator can still see the redacted data, when passing
+      # the appropriate flag
+      get :version, :params => { :id => node_v3.node_id, :version => node_v3.version }
+      assert_response :forbidden, "After redaction, node should be gone for moderator, when flag not passed."
+      get :version, :params => { :id => node_v3.node_id, :version => node_v3.version, :show_redactions => "true" }
+      assert_response :success, "After redaction, node should not be gone for moderator, when flag passed."
+
+      # and when accessed via history
+      get :history, :params => { :id => node_v3.node_id }
+      assert_response :success, "Redaction shouldn't have stopped history working."
+      assert_select "osm node[id='#{node_v3.node_id}'][version='#{node_v3.version}']", 0, "node #{node_v3.node_id} version #{node_v3.version} should not be present in the history for moderators when not passing flag."
+      get :history, :params => { :id => node_v3.node_id, :show_redactions => "true" }
+      assert_response :success, "Redaction shouldn't have stopped history working."
+      assert_select "osm node[id='#{node_v3.node_id}'][version='#{node_v3.version}']", 1, "node #{node_v3.node_id} version #{node_v3.version} should still be present in the history for moderators when passing flag."
+    end
+
+    # testing that if the moderator drops auth, he can't see the
+    # redacted stuff any more.
+    def test_redact_node_is_redacted
+      node = create(:node, :with_history, :version => 4)
+      node_v3 = node.old_nodes.find_by(:version => 3)
+      basic_authorization create(:moderator_user).email, "test"
+
+      do_redact_node(node_v3, create(:redaction))
+      assert_response :success, "should be OK to redact old version as moderator."
+
+      # re-auth as non-moderator
+      basic_authorization create(:user).email, "test"
+
+      # check can't see the redacted data
+      get :version, :params => { :id => node_v3.node_id, :version => node_v3.version }
+      assert_response :forbidden, "Redacted node shouldn't be visible via the version API."
+
+      # and when accessed via history
+      get :history, :params => { :id => node_v3.node_id }
+      assert_response :success, "Redaction shouldn't have stopped history working."
+      assert_select "osm node[id='#{node_v3.node_id}'][version='#{node_v3.version}']", 0, "redacted node #{node_v3.node_id} version #{node_v3.version} shouldn't be present in the history."
+    end
+
+    ##
+    # test the unredaction of an old version of a node, while not being
+    # authorised.
+    def test_unredact_node_unauthorised
+      node = create(:node, :with_history, :version => 2)
+      node_v1 = node.old_nodes.find_by(:version => 1)
+      node_v1.redact!(create(:redaction))
+
+      post :redact, :params => { :id => node_v1.node_id, :version => node_v1.version }
+      assert_response :unauthorized, "should need to be authenticated to unredact."
+    end
+
+    ##
+    # test the unredaction of an old version of a node, while being
+    # authorised as a normal user.
+    def test_unredact_node_normal_user
+      user = create(:user)
+      node = create(:node, :with_history, :version => 2)
+      node_v1 = node.old_nodes.find_by(:version => 1)
+      node_v1.redact!(create(:redaction))
+
+      basic_authorization user.email, "test"
+
+      post :redact, :params => { :id => node_v1.node_id, :version => node_v1.version }
+      assert_response :forbidden, "should need to be moderator to unredact."
+    end
+
+    ##
+    # test the unredaction of an old version of a node, while being
+    # authorised as a moderator.
+    def test_unredact_node_moderator
+      moderator_user = create(:moderator_user)
+      node = create(:node, :with_history, :version => 2)
+      node_v1 = node.old_nodes.find_by(:version => 1)
+      node_v1.redact!(create(:redaction))
+
+      basic_authorization moderator_user.email, "test"
+
+      post :redact, :params => { :id => node_v1.node_id, :version => node_v1.version }
+      assert_response :success, "should be OK to unredact old version as moderator."
+
+      # check moderator can now see the redacted data, when not
+      # passing the aspecial flag
+      get :version, :params => { :id => node_v1.node_id, :version => node_v1.version }
+      assert_response :success, "After unredaction, node should not be gone for moderator."
+
+      # and when accessed via history
+      get :history, :params => { :id => node_v1.node_id }
+      assert_response :success, "Unredaction shouldn't have stopped history working."
+      assert_select "osm node[id='#{node_v1.node_id}'][version='#{node_v1.version}']", 1, "node #{node_v1.node_id} version #{node_v1.version} should now be present in the history for moderators without passing flag."
+
+      basic_authorization create(:user).email, "test"
+
+      # check normal user can now see the redacted data
+      get :version, :params => { :id => node_v1.node_id, :version => node_v1.version }
+      assert_response :success, "After unredaction, node should be visible to normal users."
+
+      # and when accessed via history
+      get :history, :params => { :id => node_v1.node_id }
+      assert_response :success, "Unredaction shouldn't have stopped history working."
+      assert_select "osm node[id='#{node_v1.node_id}'][version='#{node_v1.version}']", 1, "node #{node_v1.node_id} version #{node_v1.version} should now be present in the history for normal users without passing flag."
+    end
+
+    private
+
+    def do_redact_node(node, redaction)
+      get :version, :params => { :id => node.node_id, :version => node.version }
+      assert_response :success, "should be able to get version #{node.version} of node #{node.node_id}."
+
+      # now redact it
+      post :redact, :params => { :id => node.node_id, :version => node.version, :redaction => redaction.id }
+    end
+
+    def check_current_version(node_id)
+      # get the current version of the node
+      current_node = with_controller(NodesController.new) do
+        get :show, :params => { :id => node_id }
+        assert_response :success, "cant get current node #{node_id}"
+        Node.from_xml(@response.body)
+      end
+      assert_not_nil current_node, "getting node #{node_id} returned nil"
+
+      # get the "old" version of the node from the old_node interface
+      get :version, :params => { :id => node_id, :version => current_node.version }
+      assert_response :success, "cant get old node #{node_id}, v#{current_node.version}"
+      old_node = Node.from_xml(@response.body)
+
+      # check the nodes are the same
+      assert_nodes_are_equal current_node, old_node
+    end
+
+    ##
+    # returns a 16 character long string with some nasty characters in it.
+    # this ought to stress-test the tag handling as well as the versioning.
+    def random_string
+      letters = [["!", '"', "$", "&", ";", "@"],
+                 ("a".."z").to_a,
+                 ("A".."Z").to_a,
+                 ("0".."9").to_a].flatten
+      (1..16).map { |_i| letters[rand(letters.length)] }.join
+    end
+
+    ##
+    # truncate a floating point number to the scale that it is stored in
+    # the database. otherwise rounding errors can produce failing unit
+    # tests when they shouldn't.
+    def precision(f)
+      (f * GeoRecord::SCALE).round.to_f / GeoRecord::SCALE
+    end
+
+    def propagate_tags(node, old_node)
+      node.tags.each do |k, v|
+        create(:old_node_tag, :old_node => old_node, :k => k, :v => v)
+      end
+    end
+  end
+end
diff --git a/test/controllers/api/old_relations_controller_test.rb b/test/controllers/api/old_relations_controller_test.rb
new file mode 100644 (file)
index 0000000..40a8024
--- /dev/null
@@ -0,0 +1,274 @@
+require "test_helper"
+
+module Api
+  class OldRelationsControllerTest < ActionController::TestCase
+    ##
+    # test all routes which lead to this controller
+    def test_routes
+      assert_routing(
+        { :path => "/api/0.6/relation/1/history", :method => :get },
+        { :controller => "api/old_relations", :action => "history", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/relation/1/2", :method => :get },
+        { :controller => "api/old_relations", :action => "version", :id => "1", :version => "2" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/relation/1/2/redact", :method => :post },
+        { :controller => "api/old_relations", :action => "redact", :id => "1", :version => "2" }
+      )
+    end
+
+    # -------------------------------------
+    # Test reading old relations.
+    # -------------------------------------
+    def test_history
+      # check that a visible relations is returned properly
+      get :history, :params => { :id => create(:relation, :with_history).id }
+      assert_response :success
+
+      # check chat a non-existent relations is not returned
+      get :history, :params => { :id => 0 }
+      assert_response :not_found
+    end
+
+    ##
+    # test the redaction of an old version of a relation, while not being
+    # authorised.
+    def test_redact_relation_unauthorised
+      relation = create(:relation, :with_history, :version => 4)
+      relation_v3 = relation.old_relations.find_by(:version => 3)
+
+      do_redact_relation(relation_v3, create(:redaction))
+      assert_response :unauthorized, "should need to be authenticated to redact."
+    end
+
+    ##
+    # test the redaction of an old version of a relation, while being
+    # authorised as a normal user.
+    def test_redact_relation_normal_user
+      relation = create(:relation, :with_history, :version => 4)
+      relation_v3 = relation.old_relations.find_by(:version => 3)
+
+      basic_authorization create(:user).email, "test"
+
+      do_redact_relation(relation_v3, create(:redaction))
+      assert_response :forbidden, "should need to be moderator to redact."
+    end
+
+    ##
+    # test that, even as moderator, the current version of a relation
+    # can't be redacted.
+    def test_redact_relation_current_version
+      relation = create(:relation, :with_history, :version => 4)
+      relation_latest = relation.old_relations.last
+
+      basic_authorization create(:moderator_user).email, "test"
+
+      do_redact_relation(relation_latest, create(:redaction))
+      assert_response :bad_request, "shouldn't be OK to redact current version as moderator."
+    end
+
+    ##
+    # test that redacted relations aren't visible, regardless of
+    # authorisation except as moderator...
+    def test_version_redacted
+      relation = create(:relation, :with_history, :version => 2)
+      relation_v1 = relation.old_relations.find_by(:version => 1)
+      relation_v1.redact!(create(:redaction))
+
+      get :version, :params => { :id => relation_v1.relation_id, :version => relation_v1.version }
+      assert_response :forbidden, "Redacted relation shouldn't be visible via the version API."
+
+      # not even to a logged-in user
+      basic_authorization create(:user).email, "test"
+      get :version, :params => { :id => relation_v1.relation_id, :version => relation_v1.version }
+      assert_response :forbidden, "Redacted relation shouldn't be visible via the version API, even when logged in."
+    end
+
+    ##
+    # test that redacted relations aren't visible in the history
+    def test_history_redacted
+      relation = create(:relation, :with_history, :version => 2)
+      relation_v1 = relation.old_relations.find_by(:version => 1)
+      relation_v1.redact!(create(:redaction))
+
+      get :history, :params => { :id => relation_v1.relation_id }
+      assert_response :success, "Redaction shouldn't have stopped history working."
+      assert_select "osm relation[id='#{relation_v1.relation_id}'][version='#{relation_v1.version}']", 0, "redacted relation #{relation_v1.relation_id} version #{relation_v1.version} shouldn't be present in the history."
+
+      # not even to a logged-in user
+      basic_authorization create(:user).email, "test"
+      get :version, :params => { :id => relation_v1.relation_id, :version => relation_v1.version }
+      get :history, :params => { :id => relation_v1.relation_id }
+      assert_response :success, "Redaction shouldn't have stopped history working."
+      assert_select "osm relation[id='#{relation_v1.relation_id}'][version='#{relation_v1.version}']", 0, "redacted relation #{relation_v1.relation_id} version #{relation_v1.version} shouldn't be present in the history, even when logged in."
+    end
+
+    ##
+    # test the redaction of an old version of a relation, while being
+    # authorised as a moderator.
+    def test_redact_relation_moderator
+      relation = create(:relation, :with_history, :version => 4)
+      relation_v3 = relation.old_relations.find_by(:version => 3)
+
+      basic_authorization create(:moderator_user).email, "test"
+
+      do_redact_relation(relation_v3, create(:redaction))
+      assert_response :success, "should be OK to redact old version as moderator."
+
+      # check moderator can still see the redacted data, when passing
+      # the appropriate flag
+      get :version, :params => { :id => relation_v3.relation_id, :version => relation_v3.version }
+      assert_response :forbidden, "After redaction, relation should be gone for moderator, when flag not passed."
+      get :version, :params => { :id => relation_v3.relation_id, :version => relation_v3.version, :show_redactions => "true" }
+      assert_response :success, "After redaction, relation should not be gone for moderator, when flag passed."
+
+      # and when accessed via history
+      get :history, :params => { :id => relation_v3.relation_id }
+      assert_response :success, "Redaction shouldn't have stopped history working."
+      assert_select "osm relation[id='#{relation_v3.relation_id}'][version='#{relation_v3.version}']", 0, "relation #{relation_v3.relation_id} version #{relation_v3.version} should not be present in the history for moderators when not passing flag."
+      get :history, :params => { :id => relation_v3.relation_id, :show_redactions => "true" }
+      assert_response :success, "Redaction shouldn't have stopped history working."
+      assert_select "osm relation[id='#{relation_v3.relation_id}'][version='#{relation_v3.version}']", 1, "relation #{relation_v3.relation_id} version #{relation_v3.version} should still be present in the history for moderators when passing flag."
+    end
+
+    # testing that if the moderator drops auth, he can't see the
+    # redacted stuff any more.
+    def test_redact_relation_is_redacted
+      relation = create(:relation, :with_history, :version => 4)
+      relation_v3 = relation.old_relations.find_by(:version => 3)
+
+      basic_authorization create(:moderator_user).email, "test"
+
+      do_redact_relation(relation_v3, create(:redaction))
+      assert_response :success, "should be OK to redact old version as moderator."
+
+      # re-auth as non-moderator
+      basic_authorization create(:user).email, "test"
+
+      # check can't see the redacted data
+      get :version, :params => { :id => relation_v3.relation_id, :version => relation_v3.version }
+      assert_response :forbidden, "Redacted relation shouldn't be visible via the version API."
+
+      # and when accessed via history
+      get :history, :params => { :id => relation_v3.relation_id }
+      assert_response :success, "Redaction shouldn't have stopped history working."
+      assert_select "osm relation[id='#{relation_v3.relation_id}'][version='#{relation_v3.version}']", 0, "redacted relation #{relation_v3.relation_id} version #{relation_v3.version} shouldn't be present in the history."
+    end
+
+    ##
+    # test the unredaction of an old version of a relation, while not being
+    # authorised.
+    def test_unredact_relation_unauthorised
+      relation = create(:relation, :with_history, :version => 2)
+      relation_v1 = relation.old_relations.find_by(:version => 1)
+      relation_v1.redact!(create(:redaction))
+
+      post :redact, :params => { :id => relation_v1.relation_id, :version => relation_v1.version }
+      assert_response :unauthorized, "should need to be authenticated to unredact."
+    end
+
+    ##
+    # test the unredaction of an old version of a relation, while being
+    # authorised as a normal user.
+    def test_unredact_relation_normal_user
+      relation = create(:relation, :with_history, :version => 2)
+      relation_v1 = relation.old_relations.find_by(:version => 1)
+      relation_v1.redact!(create(:redaction))
+
+      basic_authorization create(:user).email, "test"
+
+      post :redact, :params => { :id => relation_v1.relation_id, :version => relation_v1.version }
+      assert_response :forbidden, "should need to be moderator to unredact."
+    end
+
+    ##
+    # test the unredaction of an old version of a relation, while being
+    # authorised as a moderator.
+    def test_unredact_relation_moderator
+      relation = create(:relation, :with_history, :version => 2)
+      relation_v1 = relation.old_relations.find_by(:version => 1)
+      relation_v1.redact!(create(:redaction))
+
+      basic_authorization create(:moderator_user).email, "test"
+
+      post :redact, :params => { :id => relation_v1.relation_id, :version => relation_v1.version }
+      assert_response :success, "should be OK to unredact old version as moderator."
+
+      # check moderator can still see the redacted data, without passing
+      # the appropriate flag
+      get :version, :params => { :id => relation_v1.relation_id, :version => relation_v1.version }
+      assert_response :success, "After unredaction, relation should not be gone for moderator."
+
+      # and when accessed via history
+      get :history, :params => { :id => relation_v1.relation_id }
+      assert_response :success, "Redaction shouldn't have stopped history working."
+      assert_select "osm relation[id='#{relation_v1.relation_id}'][version='#{relation_v1.version}']", 1, "relation #{relation_v1.relation_id} version #{relation_v1.version} should still be present in the history for moderators."
+
+      basic_authorization create(:user).email, "test"
+
+      # check normal user can now see the redacted data
+      get :version, :params => { :id => relation_v1.relation_id, :version => relation_v1.version }
+      assert_response :success, "After redaction, node should not be gone for normal user."
+
+      # and when accessed via history
+      get :history, :params => { :id => relation_v1.relation_id }
+      assert_response :success, "Redaction shouldn't have stopped history working."
+      assert_select "osm relation[id='#{relation_v1.relation_id}'][version='#{relation_v1.version}']", 1, "relation #{relation_v1.relation_id} version #{relation_v1.version} should still be present in the history for normal users."
+    end
+
+    private
+
+    ##
+    # check that the current version of a relation is equivalent to the
+    # version which we're getting from the versions call.
+    def check_current_version(relation_id)
+      # get the current version
+      current_relation = with_controller(RelationsController.new) do
+        get :show, :params => { :id => relation_id }
+        assert_response :success, "can't get current relation #{relation_id}"
+        Relation.from_xml(@response.body)
+      end
+      assert_not_nil current_relation, "getting relation #{relation_id} returned nil"
+
+      # get the "old" version of the relation from the version method
+      get :version, :params => { :id => relation_id, :version => current_relation.version }
+      assert_response :success, "can't get old relation #{relation_id}, v#{current_relation.version}"
+      old_relation = Relation.from_xml(@response.body)
+
+      # check that the relations are identical
+      assert_relations_are_equal current_relation, old_relation
+    end
+
+    ##
+    # look at all the versions of the relation in the history and get each version from
+    # the versions call. check that they're the same.
+    def check_history_equals_versions(relation_id)
+      get :history, :params => { :id => relation_id }
+      assert_response :success, "can't get relation #{relation_id} from API"
+      history_doc = XML::Parser.string(@response.body).parse
+      assert_not_nil history_doc, "parsing relation #{relation_id} history failed"
+
+      history_doc.find("//osm/relation").each do |relation_doc|
+        history_relation = Relation.from_xml_node(relation_doc)
+        assert_not_nil history_relation, "parsing relation #{relation_id} version failed"
+
+        get :version, :params => { :id => relation_id, :version => history_relation.version }
+        assert_response :success, "couldn't get relation #{relation_id}, v#{history_relation.version}"
+        version_relation = Relation.from_xml(@response.body)
+        assert_not_nil version_relation, "failed to parse #{relation_id}, v#{history_relation.version}"
+
+        assert_relations_are_equal history_relation, version_relation
+      end
+    end
+
+    def do_redact_relation(relation, redaction)
+      get :version, :params => { :id => relation.relation_id, :version => relation.version }
+      assert_response :success, "should be able to get version #{relation.version} of relation #{relation.relation_id}."
+
+      # now redact it
+      post :redact, :params => { :id => relation.relation_id, :version => relation.version, :redaction => redaction.id }
+    end
+  end
+end
diff --git a/test/controllers/api/old_ways_controller_test.rb b/test/controllers/api/old_ways_controller_test.rb
new file mode 100644 (file)
index 0000000..73e968f
--- /dev/null
@@ -0,0 +1,320 @@
+require "test_helper"
+
+module Api
+  class OldWaysControllerTest < ActionController::TestCase
+    ##
+    # test all routes which lead to this controller
+    def test_routes
+      assert_routing(
+        { :path => "/api/0.6/way/1/history", :method => :get },
+        { :controller => "api/old_ways", :action => "history", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/way/1/2", :method => :get },
+        { :controller => "api/old_ways", :action => "version", :id => "1", :version => "2" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/way/1/2/redact", :method => :post },
+        { :controller => "api/old_ways", :action => "redact", :id => "1", :version => "2" }
+      )
+    end
+
+    # -------------------------------------
+    # Test reading old ways.
+    # -------------------------------------
+
+    def test_history_visible
+      # check that a visible way is returned properly
+      get :history, :params => { :id => create(:way, :with_history).id }
+      assert_response :success
+    end
+
+    def test_history_invisible
+      # check that an invisible way's history is returned properly
+      get :history, :params => { :id => create(:way, :with_history, :deleted).id }
+      assert_response :success
+    end
+
+    def test_history_invalid
+      # check chat a non-existent way is not returned
+      get :history, :params => { :id => 0 }
+      assert_response :not_found
+    end
+
+    ##
+    # check that we can retrieve versions of a way
+    def test_version
+      way = create(:way, :with_history)
+      used_way = create(:way, :with_history)
+      create(:relation_member, :member => used_way)
+      way_with_versions = create(:way, :with_history, :version => 4)
+
+      create(:way_tag, :way => way)
+      create(:way_tag, :way => used_way)
+      create(:way_tag, :way => way_with_versions)
+      propagate_tags(way, way.old_ways.last)
+      propagate_tags(used_way, used_way.old_ways.last)
+      propagate_tags(way_with_versions, way_with_versions.old_ways.last)
+
+      check_current_version(way.id)
+      check_current_version(used_way.id)
+      check_current_version(way_with_versions.id)
+    end
+
+    ##
+    # check that returned history is the same as getting all
+    # versions of a way from the api.
+    def test_history_equals_versions
+      way = create(:way, :with_history)
+      used_way = create(:way, :with_history)
+      create(:relation_member, :member => used_way)
+      way_with_versions = create(:way, :with_history, :version => 4)
+
+      check_history_equals_versions(way.id)
+      check_history_equals_versions(used_way.id)
+      check_history_equals_versions(way_with_versions.id)
+    end
+
+    ##
+    # test the redaction of an old version of a way, while not being
+    # authorised.
+    def test_redact_way_unauthorised
+      way = create(:way, :with_history, :version => 4)
+      way_v3 = way.old_ways.find_by(:version => 3)
+
+      do_redact_way(way_v3, create(:redaction))
+      assert_response :unauthorized, "should need to be authenticated to redact."
+    end
+
+    ##
+    # test the redaction of an old version of a way, while being
+    # authorised as a normal user.
+    def test_redact_way_normal_user
+      basic_authorization create(:user).email, "test"
+      way = create(:way, :with_history, :version => 4)
+      way_v3 = way.old_ways.find_by(:version => 3)
+
+      do_redact_way(way_v3, create(:redaction))
+      assert_response :forbidden, "should need to be moderator to redact."
+    end
+
+    ##
+    # test that, even as moderator, the current version of a way
+    # can't be redacted.
+    def test_redact_way_current_version
+      basic_authorization create(:moderator_user).email, "test"
+      way = create(:way, :with_history, :version => 4)
+      way_latest = way.old_ways.last
+
+      do_redact_way(way_latest, create(:redaction))
+      assert_response :bad_request, "shouldn't be OK to redact current version as moderator."
+    end
+
+    ##
+    # test that redacted ways aren't visible, regardless of
+    # authorisation except as moderator...
+    def test_version_redacted
+      way = create(:way, :with_history, :version => 2)
+      way_v1 = way.old_ways.find_by(:version => 1)
+      way_v1.redact!(create(:redaction))
+
+      get :version, :params => { :id => way_v1.way_id, :version => way_v1.version }
+      assert_response :forbidden, "Redacted way shouldn't be visible via the version API."
+
+      # not even to a logged-in user
+      basic_authorization create(:user).email, "test"
+      get :version, :params => { :id => way_v1.way_id, :version => way_v1.version }
+      assert_response :forbidden, "Redacted way shouldn't be visible via the version API, even when logged in."
+    end
+
+    ##
+    # test that redacted ways aren't visible in the history
+    def test_history_redacted
+      way = create(:way, :with_history, :version => 2)
+      way_v1 = way.old_ways.find_by(:version => 1)
+      way_v1.redact!(create(:redaction))
+
+      get :history, :params => { :id => way_v1.way_id }
+      assert_response :success, "Redaction shouldn't have stopped history working."
+      assert_select "osm way[id='#{way_v1.way_id}'][version='#{way_v1.version}']", 0, "redacted way #{way_v1.way_id} version #{way_v1.version} shouldn't be present in the history."
+
+      # not even to a logged-in user
+      basic_authorization create(:user).email, "test"
+      get :version, :params => { :id => way_v1.way_id, :version => way_v1.version }
+      get :history, :params => { :id => way_v1.way_id }
+      assert_response :success, "Redaction shouldn't have stopped history working."
+      assert_select "osm way[id='#{way_v1.way_id}'][version='#{way_v1.version}']", 0, "redacted node #{way_v1.way_id} version #{way_v1.version} shouldn't be present in the history, even when logged in."
+    end
+
+    ##
+    # test the redaction of an old version of a way, while being
+    # authorised as a moderator.
+    def test_redact_way_moderator
+      way = create(:way, :with_history, :version => 4)
+      way_v3 = way.old_ways.find_by(:version => 3)
+      basic_authorization create(:moderator_user).email, "test"
+
+      do_redact_way(way_v3, create(:redaction))
+      assert_response :success, "should be OK to redact old version as moderator."
+
+      # check moderator can still see the redacted data, when passing
+      # the appropriate flag
+      get :version, :params => { :id => way_v3.way_id, :version => way_v3.version }
+      assert_response :forbidden, "After redaction, node should be gone for moderator, when flag not passed."
+      get :version, :params => { :id => way_v3.way_id, :version => way_v3.version, :show_redactions => "true" }
+      assert_response :success, "After redaction, node should not be gone for moderator, when flag passed."
+
+      # and when accessed via history
+      get :history, :params => { :id => way_v3.way_id }
+      assert_response :success, "Redaction shouldn't have stopped history working."
+      assert_select "osm way[id='#{way_v3.way_id}'][version='#{way_v3.version}']", 0, "way #{way_v3.way_id} version #{way_v3.version} should not be present in the history for moderators when not passing flag."
+      get :history, :params => { :id => way_v3.way_id, :show_redactions => "true" }
+      assert_response :success, "Redaction shouldn't have stopped history working."
+      assert_select "osm way[id='#{way_v3.way_id}'][version='#{way_v3.version}']", 1, "way #{way_v3.way_id} version #{way_v3.version} should still be present in the history for moderators when passing flag."
+    end
+
+    # testing that if the moderator drops auth, he can't see the
+    # redacted stuff any more.
+    def test_redact_way_is_redacted
+      way = create(:way, :with_history, :version => 4)
+      way_v3 = way.old_ways.find_by(:version => 3)
+      basic_authorization create(:moderator_user).email, "test"
+
+      do_redact_way(way_v3, create(:redaction))
+      assert_response :success, "should be OK to redact old version as moderator."
+
+      # re-auth as non-moderator
+      basic_authorization create(:user).email, "test"
+
+      # check can't see the redacted data
+      get :version, :params => { :id => way_v3.way_id, :version => way_v3.version }
+      assert_response :forbidden, "Redacted node shouldn't be visible via the version API."
+
+      # and when accessed via history
+      get :history, :params => { :id => way_v3.way_id }
+      assert_response :success, "Redaction shouldn't have stopped history working."
+      assert_select "osm way[id='#{way_v3.way_id}'][version='#{way_v3.version}']", 0, "redacted way #{way_v3.way_id} version #{way_v3.version} shouldn't be present in the history."
+    end
+
+    ##
+    # test the unredaction of an old version of a way, while not being
+    # authorised.
+    def test_unredact_way_unauthorised
+      way = create(:way, :with_history, :version => 2)
+      way_v1 = way.old_ways.find_by(:version => 1)
+      way_v1.redact!(create(:redaction))
+
+      post :redact, :params => { :id => way_v1.way_id, :version => way_v1.version }
+      assert_response :unauthorized, "should need to be authenticated to unredact."
+    end
+
+    ##
+    # test the unredaction of an old version of a way, while being
+    # authorised as a normal user.
+    def test_unredact_way_normal_user
+      way = create(:way, :with_history, :version => 2)
+      way_v1 = way.old_ways.find_by(:version => 1)
+      way_v1.redact!(create(:redaction))
+
+      basic_authorization create(:user).email, "test"
+
+      post :redact, :params => { :id => way_v1.way_id, :version => way_v1.version }
+      assert_response :forbidden, "should need to be moderator to unredact."
+    end
+
+    ##
+    # test the unredaction of an old version of a way, while being
+    # authorised as a moderator.
+    def test_unredact_way_moderator
+      moderator_user = create(:moderator_user)
+      way = create(:way, :with_history, :version => 2)
+      way_v1 = way.old_ways.find_by(:version => 1)
+      way_v1.redact!(create(:redaction))
+
+      basic_authorization moderator_user.email, "test"
+
+      post :redact, :params => { :id => way_v1.way_id, :version => way_v1.version }
+      assert_response :success, "should be OK to unredact old version as moderator."
+
+      # check moderator can still see the unredacted data, without passing
+      # the appropriate flag
+      get :version, :params => { :id => way_v1.way_id, :version => way_v1.version }
+      assert_response :success, "After unredaction, node should not be gone for moderator."
+
+      # and when accessed via history
+      get :history, :params => { :id => way_v1.way_id }
+      assert_response :success, "Unredaction shouldn't have stopped history working."
+      assert_select "osm way[id='#{way_v1.way_id}'][version='#{way_v1.version}']", 1, "way #{way_v1.way_id} version #{way_v1.version} should still be present in the history for moderators."
+
+      basic_authorization create(:user).email, "test"
+
+      # check normal user can now see the unredacted data
+      get :version, :params => { :id => way_v1.way_id, :version => way_v1.version }
+      assert_response :success, "After redaction, node should not be gone for moderator, when flag passed."
+
+      # and when accessed via history
+      get :history, :params => { :id => way_v1.way_id }
+      assert_response :success, "Redaction shouldn't have stopped history working."
+      assert_select "osm way[id='#{way_v1.way_id}'][version='#{way_v1.version}']", 1, "way #{way_v1.way_id} version #{way_v1.version} should still be present in the history for normal users."
+    end
+
+    private
+
+    ##
+    # check that the current version of a way is equivalent to the
+    # version which we're getting from the versions call.
+    def check_current_version(way_id)
+      # get the current version
+      current_way = with_controller(WaysController.new) do
+        get :show, :params => { :id => way_id }
+        assert_response :success, "can't get current way #{way_id}"
+        Way.from_xml(@response.body)
+      end
+      assert_not_nil current_way, "getting way #{way_id} returned nil"
+
+      # get the "old" version of the way from the version method
+      get :version, :params => { :id => way_id, :version => current_way.version }
+      assert_response :success, "can't get old way #{way_id}, v#{current_way.version}"
+      old_way = Way.from_xml(@response.body)
+
+      # check that the ways are identical
+      assert_ways_are_equal current_way, old_way
+    end
+
+    ##
+    # look at all the versions of the way in the history and get each version from
+    # the versions call. check that they're the same.
+    def check_history_equals_versions(way_id)
+      get :history, :params => { :id => way_id }
+      assert_response :success, "can't get way #{way_id} from API"
+      history_doc = XML::Parser.string(@response.body).parse
+      assert_not_nil history_doc, "parsing way #{way_id} history failed"
+
+      history_doc.find("//osm/way").each do |way_doc|
+        history_way = Way.from_xml_node(way_doc)
+        assert_not_nil history_way, "parsing way #{way_id} version failed"
+
+        get :version, :params => { :id => way_id, :version => history_way.version }
+        assert_response :success, "couldn't get way #{way_id}, v#{history_way.version}"
+        version_way = Way.from_xml(@response.body)
+        assert_not_nil version_way, "failed to parse #{way_id}, v#{history_way.version}"
+
+        assert_ways_are_equal history_way, version_way
+      end
+    end
+
+    def do_redact_way(way, redaction)
+      get :version, :params => { :id => way.way_id, :version => way.version }
+      assert_response :success, "should be able to get version #{way.version} of way #{way.way_id}."
+
+      # now redact it
+      post :redact, :params => { :id => way.way_id, :version => way.version, :redaction => redaction.id }
+    end
+
+    def propagate_tags(way, old_way)
+      way.tags.each do |k, v|
+        create(:old_way_tag, :old_way => old_way, :k => k, :v => v)
+      end
+    end
+  end
+end
diff --git a/test/controllers/api/relations_controller_test.rb b/test/controllers/api/relations_controller_test.rb
new file mode 100644 (file)
index 0000000..e539092
--- /dev/null
@@ -0,0 +1,1079 @@
+require "test_helper"
+
+module Api
+  class RelationsControllerTest < ActionController::TestCase
+    ##
+    # test all routes which lead to this controller
+    def test_routes
+      assert_routing(
+        { :path => "/api/0.6/relation/create", :method => :put },
+        { :controller => "api/relations", :action => "create" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/relation/1/full", :method => :get },
+        { :controller => "api/relations", :action => "full", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/relation/1", :method => :get },
+        { :controller => "api/relations", :action => "show", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/relation/1", :method => :put },
+        { :controller => "api/relations", :action => "update", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/relation/1", :method => :delete },
+        { :controller => "api/relations", :action => "delete", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/relations", :method => :get },
+        { :controller => "api/relations", :action => "index" }
+      )
+
+      assert_routing(
+        { :path => "/api/0.6/node/1/relations", :method => :get },
+        { :controller => "api/relations", :action => "relations_for_node", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/way/1/relations", :method => :get },
+        { :controller => "api/relations", :action => "relations_for_way", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/relation/1/relations", :method => :get },
+        { :controller => "api/relations", :action => "relations_for_relation", :id => "1" }
+      )
+    end
+
+    # -------------------------------------
+    # Test showing relations.
+    # -------------------------------------
+
+    def test_show
+      # check that a visible relation is returned properly
+      get :show, :params => { :id => create(:relation).id }
+      assert_response :success
+
+      # check that an invisible relation is not returned
+      get :show, :params => { :id => create(:relation, :deleted).id }
+      assert_response :gone
+
+      # check chat a non-existent relation is not returned
+      get :show, :params => { :id => 0 }
+      assert_response :not_found
+    end
+
+    ##
+    # check that all relations containing a particular node, and no extra
+    # relations, are returned from the relations_for_node call.
+    def test_relations_for_node
+      node = create(:node)
+      # should include relations with that node as a member
+      relation_with_node = create(:relation_member, :member => node).relation
+      # should ignore relations without that node as a member
+      _relation_without_node = create(:relation_member).relation
+      # should ignore relations with the node involved indirectly, via a way
+      way = create(:way_node, :node => node).way
+      _relation_with_way = create(:relation_member, :member => way).relation
+      # should ignore relations with the node involved indirectly, via a relation
+      second_relation = create(:relation_member, :member => node).relation
+      _super_relation = create(:relation_member, :member => second_relation).relation
+      # should combine multiple relation_member references into just one relation entry
+      create(:relation_member, :member => node, :relation => relation_with_node, :sequence_id => 2)
+      # should not include deleted relations
+      deleted_relation = create(:relation, :deleted)
+      create(:relation_member, :member => node, :relation => deleted_relation)
+
+      check_relations_for_element(:relations_for_node, "node",
+                                  node.id,
+                                  [relation_with_node, second_relation])
+    end
+
+    def test_relations_for_way
+      way = create(:way)
+      # should include relations with that way as a member
+      relation_with_way = create(:relation_member, :member => way).relation
+      # should ignore relations without that way as a member
+      _relation_without_way = create(:relation_member).relation
+      # should ignore relations with the way involved indirectly, via a relation
+      second_relation = create(:relation_member, :member => way).relation
+      _super_relation = create(:relation_member, :member => second_relation).relation
+      # should combine multiple relation_member references into just one relation entry
+      create(:relation_member, :member => way, :relation => relation_with_way, :sequence_id => 2)
+      # should not include deleted relations
+      deleted_relation = create(:relation, :deleted)
+      create(:relation_member, :member => way, :relation => deleted_relation)
+
+      check_relations_for_element(:relations_for_way, "way",
+                                  way.id,
+                                  [relation_with_way, second_relation])
+    end
+
+    def test_relations_for_relation
+      relation = create(:relation)
+      # should include relations with that relation as a member
+      relation_with_relation = create(:relation_member, :member => relation).relation
+      # should ignore any relation without that relation as a member
+      _relation_without_relation = create(:relation_member).relation
+      # should ignore relations with the relation involved indirectly, via a relation
+      second_relation = create(:relation_member, :member => relation).relation
+      _super_relation = create(:relation_member, :member => second_relation).relation
+      # should combine multiple relation_member references into just one relation entry
+      create(:relation_member, :member => relation, :relation => relation_with_relation, :sequence_id => 2)
+      # should not include deleted relations
+      deleted_relation = create(:relation, :deleted)
+      create(:relation_member, :member => relation, :relation => deleted_relation)
+      check_relations_for_element(:relations_for_relation, "relation",
+                                  relation.id,
+                                  [relation_with_relation, second_relation])
+    end
+
+    def check_relations_for_element(method, type, id, expected_relations)
+      # check the "relations for relation" mode
+      get method, :params => { :id => id }
+      assert_response :success
+
+      # count one osm element
+      assert_select "osm[version='#{API_VERSION}'][generator='OpenStreetMap server']", 1
+
+      # we should have only the expected number of relations
+      assert_select "osm>relation", expected_relations.size
+
+      # and each of them should contain the element we originally searched for
+      expected_relations.each do |relation|
+        # The relation should appear once, but the element could appear multiple times
+        assert_select "osm>relation[id='#{relation.id}']", 1
+        assert_select "osm>relation[id='#{relation.id}']>member[type='#{type}'][ref='#{id}']"
+      end
+    end
+
+    def test_full
+      # check the "full" mode
+      get :full, :params => { :id => 999999 }
+      assert_response :not_found
+
+      get :full, :params => { :id => create(:relation, :deleted).id }
+      assert_response :gone
+
+      get :full, :params => { :id => create(:relation).id }
+      assert_response :success
+      # FIXME: check whether this contains the stuff we want!
+    end
+
+    ##
+    # test fetching multiple relations
+    def test_index
+      relation1 = create(:relation)
+      relation2 = create(:relation, :deleted)
+      relation3 = create(:relation, :with_history, :version => 2)
+      relation4 = create(:relation, :with_history, :version => 2)
+      relation4.old_relations.find_by(:version => 1).redact!(create(:redaction))
+
+      # check error when no parameter provided
+      get :index
+      assert_response :bad_request
+
+      # check error when no parameter value provided
+      get :index, :params => { :relations => "" }
+      assert_response :bad_request
+
+      # test a working call
+      get :index, :params => { :relations => "#{relation1.id},#{relation2.id},#{relation3.id},#{relation4.id}" }
+      assert_response :success
+      assert_select "osm" do
+        assert_select "relation", :count => 4
+        assert_select "relation[id='#{relation1.id}'][visible='true']", :count => 1
+        assert_select "relation[id='#{relation2.id}'][visible='false']", :count => 1
+        assert_select "relation[id='#{relation3.id}'][visible='true']", :count => 1
+        assert_select "relation[id='#{relation4.id}'][visible='true']", :count => 1
+      end
+
+      # check error when a non-existent relation is included
+      get :index, :params => { :relations => "#{relation1.id},#{relation2.id},#{relation3.id},#{relation4.id},0" }
+      assert_response :not_found
+    end
+
+    # -------------------------------------
+    # Test simple relation creation.
+    # -------------------------------------
+
+    def test_create
+      private_user = create(:user, :data_public => false)
+      private_changeset = create(:changeset, :user => private_user)
+      user = create(:user)
+      changeset = create(:changeset, :user => user)
+      node = create(:node)
+      way = create(:way_with_nodes, :nodes_count => 2)
+
+      basic_authorization private_user.email, "test"
+
+      # create an relation without members
+      xml = "<osm><relation changeset='#{private_changeset.id}'><tag k='test' v='yes' /></relation></osm>"
+      put :create, :body => xml
+      # hope for forbidden, due to user
+      assert_response :forbidden,
+                      "relation upload should have failed with forbidden"
+
+      ###
+      # create an relation with a node as member
+      # This time try with a role attribute in the relation
+      xml = "<osm><relation changeset='#{private_changeset.id}'>" \
+            "<member  ref='#{node.id}' type='node' role='some'/>" \
+            "<tag k='test' v='yes' /></relation></osm>"
+      put :create, :body => xml
+      # hope for forbidden due to user
+      assert_response :forbidden,
+                      "relation upload did not return forbidden status"
+
+      ###
+      # create an relation with a node as member, this time test that we don't
+      # need a role attribute to be included
+      xml = "<osm><relation changeset='#{private_changeset.id}'>" \
+            "<member  ref='#{node.id}' type='node'/>" + "<tag k='test' v='yes' /></relation></osm>"
+      put :create, :body => xml
+      # hope for forbidden due to user
+      assert_response :forbidden,
+                      "relation upload did not return forbidden status"
+
+      ###
+      # create an relation with a way and a node as members
+      xml = "<osm><relation changeset='#{private_changeset.id}'>" \
+            "<member type='node' ref='#{node.id}' role='some'/>" \
+            "<member type='way' ref='#{way.id}' role='other'/>" \
+            "<tag k='test' v='yes' /></relation></osm>"
+      put :create, :body => xml
+      # hope for forbidden, due to user
+      assert_response :forbidden,
+                      "relation upload did not return success status"
+
+      ## Now try with the public user
+      basic_authorization user.email, "test"
+
+      # create an relation without members
+      xml = "<osm><relation changeset='#{changeset.id}'><tag k='test' v='yes' /></relation></osm>"
+      put :create, :body => xml
+      # hope for success
+      assert_response :success,
+                      "relation upload did not return success status"
+      # read id of created relation and search for it
+      relationid = @response.body
+      checkrelation = Relation.find(relationid)
+      assert_not_nil checkrelation,
+                     "uploaded relation not found in data base after upload"
+      # compare values
+      assert_equal checkrelation.members.length, 0,
+                   "saved relation contains members but should not"
+      assert_equal checkrelation.tags.length, 1,
+                   "saved relation does not contain exactly one tag"
+      assert_equal changeset.id, checkrelation.changeset.id,
+                   "saved relation does not belong in the changeset it was assigned to"
+      assert_equal user.id, checkrelation.changeset.user_id,
+                   "saved relation does not belong to user that created it"
+      assert_equal true, checkrelation.visible,
+                   "saved relation is not visible"
+      # ok the relation is there but can we also retrieve it?
+      get :show, :params => { :id => relationid }
+      assert_response :success
+
+      ###
+      # create an relation with a node as member
+      # This time try with a role attribute in the relation
+      xml = "<osm><relation changeset='#{changeset.id}'>" \
+            "<member  ref='#{node.id}' type='node' role='some'/>" \
+            "<tag k='test' v='yes' /></relation></osm>"
+      put :create, :body => xml
+      # hope for success
+      assert_response :success,
+                      "relation upload did not return success status"
+      # read id of created relation and search for it
+      relationid = @response.body
+      checkrelation = Relation.find(relationid)
+      assert_not_nil checkrelation,
+                     "uploaded relation not found in data base after upload"
+      # compare values
+      assert_equal checkrelation.members.length, 1,
+                   "saved relation does not contain exactly one member"
+      assert_equal checkrelation.tags.length, 1,
+                   "saved relation does not contain exactly one tag"
+      assert_equal changeset.id, checkrelation.changeset.id,
+                   "saved relation does not belong in the changeset it was assigned to"
+      assert_equal user.id, checkrelation.changeset.user_id,
+                   "saved relation does not belong to user that created it"
+      assert_equal true, checkrelation.visible,
+                   "saved relation is not visible"
+      # ok the relation is there but can we also retrieve it?
+
+      get :show, :params => { :id => relationid }
+      assert_response :success
+
+      ###
+      # create an relation with a node as member, this time test that we don't
+      # need a role attribute to be included
+      xml = "<osm><relation changeset='#{changeset.id}'>" \
+            "<member  ref='#{node.id}' type='node'/>" + "<tag k='test' v='yes' /></relation></osm>"
+      put :create, :body => xml
+      # hope for success
+      assert_response :success,
+                      "relation upload did not return success status"
+      # read id of created relation and search for it
+      relationid = @response.body
+      checkrelation = Relation.find(relationid)
+      assert_not_nil checkrelation,
+                     "uploaded relation not found in data base after upload"
+      # compare values
+      assert_equal checkrelation.members.length, 1,
+                   "saved relation does not contain exactly one member"
+      assert_equal checkrelation.tags.length, 1,
+                   "saved relation does not contain exactly one tag"
+      assert_equal changeset.id, checkrelation.changeset.id,
+                   "saved relation does not belong in the changeset it was assigned to"
+      assert_equal user.id, checkrelation.changeset.user_id,
+                   "saved relation does not belong to user that created it"
+      assert_equal true, checkrelation.visible,
+                   "saved relation is not visible"
+      # ok the relation is there but can we also retrieve it?
+
+      get :show, :params => { :id => relationid }
+      assert_response :success
+
+      ###
+      # create an relation with a way and a node as members
+      xml = "<osm><relation changeset='#{changeset.id}'>" \
+            "<member type='node' ref='#{node.id}' role='some'/>" \
+            "<member type='way' ref='#{way.id}' role='other'/>" \
+            "<tag k='test' v='yes' /></relation></osm>"
+      put :create, :body => xml
+      # hope for success
+      assert_response :success,
+                      "relation upload did not return success status"
+      # read id of created relation and search for it
+      relationid = @response.body
+      checkrelation = Relation.find(relationid)
+      assert_not_nil checkrelation,
+                     "uploaded relation not found in data base after upload"
+      # compare values
+      assert_equal checkrelation.members.length, 2,
+                   "saved relation does not have exactly two members"
+      assert_equal checkrelation.tags.length, 1,
+                   "saved relation does not contain exactly one tag"
+      assert_equal changeset.id, checkrelation.changeset.id,
+                   "saved relation does not belong in the changeset it was assigned to"
+      assert_equal user.id, checkrelation.changeset.user_id,
+                   "saved relation does not belong to user that created it"
+      assert_equal true, checkrelation.visible,
+                   "saved relation is not visible"
+      # ok the relation is there but can we also retrieve it?
+      get :show, :params => { :id => relationid }
+      assert_response :success
+    end
+
+    # ------------------------------------
+    # Test updating relations
+    # ------------------------------------
+
+    ##
+    # test that, when tags are updated on a relation, the correct things
+    # happen to the correct tables and the API gives sensible results.
+    # this is to test a case that gregory marler noticed and posted to
+    # josm-dev.
+    ## FIXME Move this to an integration test
+    def test_update_relation_tags
+      user = create(:user)
+      changeset = create(:changeset, :user => user)
+      relation = create(:relation)
+      create_list(:relation_tag, 4, :relation => relation)
+
+      basic_authorization user.email, "test"
+
+      with_relation(relation.id) do |rel|
+        # alter one of the tags
+        tag = rel.find("//osm/relation/tag").first
+        tag["v"] = "some changed value"
+        update_changeset(rel, changeset.id)
+
+        # check that the downloaded tags are the same as the uploaded tags...
+        new_version = with_update(rel) do |new_rel|
+          assert_tags_equal rel, new_rel
+        end
+
+        # check the original one in the current_* table again
+        with_relation(relation.id) { |r| assert_tags_equal rel, r }
+
+        # now check the version in the history
+        with_relation(relation.id, new_version) { |r| assert_tags_equal rel, r }
+      end
+    end
+
+    ##
+    # test that, when tags are updated on a relation when using the diff
+    # upload function, the correct things happen to the correct tables
+    # and the API gives sensible results. this is to test a case that
+    # gregory marler noticed and posted to josm-dev.
+    def test_update_relation_tags_via_upload
+      user = create(:user)
+      changeset = create(:changeset, :user => user)
+      relation = create(:relation)
+      create_list(:relation_tag, 4, :relation => relation)
+
+      basic_authorization user.email, "test"
+
+      with_relation(relation.id) do |rel|
+        # alter one of the tags
+        tag = rel.find("//osm/relation/tag").first
+        tag["v"] = "some changed value"
+        update_changeset(rel, changeset.id)
+
+        # check that the downloaded tags are the same as the uploaded tags...
+        new_version = with_update_diff(rel) do |new_rel|
+          assert_tags_equal rel, new_rel
+        end
+
+        # check the original one in the current_* table again
+        with_relation(relation.id) { |r| assert_tags_equal rel, r }
+
+        # now check the version in the history
+        with_relation(relation.id, new_version) { |r| assert_tags_equal rel, r }
+      end
+    end
+
+    def test_update_wrong_id
+      user = create(:user)
+      changeset = create(:changeset, :user => user)
+      relation = create(:relation)
+      other_relation = create(:relation)
+
+      basic_authorization user.email, "test"
+      with_relation(relation.id) do |rel|
+        update_changeset(rel, changeset.id)
+        put :update, :params => { :id => other_relation.id }, :body => rel.to_s
+        assert_response :bad_request
+      end
+    end
+
+    # -------------------------------------
+    # Test creating some invalid relations.
+    # -------------------------------------
+
+    def test_create_invalid
+      user = create(:user)
+      changeset = create(:changeset, :user => user)
+
+      basic_authorization user.email, "test"
+
+      # create a relation with non-existing node as member
+      xml = "<osm><relation changeset='#{changeset.id}'>" \
+            "<member type='node' ref='0'/><tag k='test' v='yes' />" \
+            "</relation></osm>"
+      put :create, :body => xml
+      # expect failure
+      assert_response :precondition_failed,
+                      "relation upload with invalid node did not return 'precondition failed'"
+      assert_equal "Precondition failed: Relation with id  cannot be saved due to Node with id 0", @response.body
+    end
+
+    # -------------------------------------
+    # Test creating a relation, with some invalid XML
+    # -------------------------------------
+    def test_create_invalid_xml
+      user = create(:user)
+      changeset = create(:changeset, :user => user)
+      node = create(:node)
+
+      basic_authorization user.email, "test"
+
+      # create some xml that should return an error
+      xml = "<osm><relation changeset='#{changeset.id}'>" \
+            "<member type='type' ref='#{node.id}' role=''/>" \
+            "<tag k='tester' v='yep'/></relation></osm>"
+      put :create, :body => xml
+      # expect failure
+      assert_response :bad_request
+      assert_match(/Cannot parse valid relation from xml string/, @response.body)
+      assert_match(/The type is not allowed only, /, @response.body)
+    end
+
+    # -------------------------------------
+    # Test deleting relations.
+    # -------------------------------------
+
+    def test_delete
+      private_user = create(:user, :data_public => false)
+      private_user_closed_changeset = create(:changeset, :closed, :user => private_user)
+      user = create(:user)
+      closed_changeset = create(:changeset, :closed, :user => user)
+      changeset = create(:changeset, :user => user)
+      relation = create(:relation)
+      used_relation = create(:relation)
+      super_relation = create(:relation_member, :member => used_relation).relation
+      deleted_relation = create(:relation, :deleted)
+      multi_tag_relation = create(:relation)
+      create_list(:relation_tag, 4, :relation => multi_tag_relation)
+
+      ## First try to delete relation without auth
+      delete :delete, :params => { :id => relation.id }
+      assert_response :unauthorized
+
+      ## Then try with the private user, to make sure that you get a forbidden
+      basic_authorization private_user.email, "test"
+
+      # this shouldn't work, as we should need the payload...
+      delete :delete, :params => { :id => relation.id }
+      assert_response :forbidden
+
+      # try to delete without specifying a changeset
+      xml = "<osm><relation id='#{relation.id}'/></osm>"
+      delete :delete, :params => { :id => relation.id }, :body => xml.to_s
+      assert_response :forbidden
+
+      # try to delete with an invalid (closed) changeset
+      xml = update_changeset(relation.to_xml,
+                             private_user_closed_changeset.id)
+      delete :delete, :params => { :id => relation.id }, :body => xml.to_s
+      assert_response :forbidden
+
+      # try to delete with an invalid (non-existent) changeset
+      xml = update_changeset(relation.to_xml, 0)
+      delete :delete, :params => { :id => relation.id }, :body => xml.to_s
+      assert_response :forbidden
+
+      # this won't work because the relation is in-use by another relation
+      xml = used_relation.to_xml
+      delete :delete, :params => { :id => used_relation.id }, :body => xml.to_s
+      assert_response :forbidden
+
+      # this should work when we provide the appropriate payload...
+      xml = relation.to_xml
+      delete :delete, :params => { :id => relation.id }, :body => xml.to_s
+      assert_response :forbidden
+
+      # this won't work since the relation is already deleted
+      xml = deleted_relation.to_xml
+      delete :delete, :params => { :id => deleted_relation.id }, :body => xml.to_s
+      assert_response :forbidden
+
+      # this won't work since the relation never existed
+      delete :delete, :params => { :id => 0 }
+      assert_response :forbidden
+
+      ## now set auth for the public user
+      basic_authorization user.email, "test"
+
+      # this shouldn't work, as we should need the payload...
+      delete :delete, :params => { :id => relation.id }
+      assert_response :bad_request
+
+      # try to delete without specifying a changeset
+      xml = "<osm><relation id='#{relation.id}' version='#{relation.version}' /></osm>"
+      delete :delete, :params => { :id => relation.id }, :body => xml.to_s
+      assert_response :bad_request
+      assert_match(/Changeset id is missing/, @response.body)
+
+      # try to delete with an invalid (closed) changeset
+      xml = update_changeset(relation.to_xml,
+                             closed_changeset.id)
+      delete :delete, :params => { :id => relation.id }, :body => xml.to_s
+      assert_response :conflict
+
+      # try to delete with an invalid (non-existent) changeset
+      xml = update_changeset(relation.to_xml, 0)
+      delete :delete, :params => { :id => relation.id }, :body => xml.to_s
+      assert_response :conflict
+
+      # this won't work because the relation is in a changeset owned by someone else
+      xml = update_changeset(relation.to_xml, create(:changeset).id)
+      delete :delete, :params => { :id => relation.id }, :body => xml.to_s
+      assert_response :conflict,
+                      "shouldn't be able to delete a relation in a changeset owned by someone else (#{@response.body})"
+
+      # this won't work because the relation in the payload is different to that passed
+      xml = update_changeset(relation.to_xml, changeset.id)
+      delete :delete, :params => { :id => create(:relation).id }, :body => xml.to_s
+      assert_response :bad_request, "shouldn't be able to delete a relation when payload is different to the url"
+
+      # this won't work because the relation is in-use by another relation
+      xml = update_changeset(used_relation.to_xml, changeset.id)
+      delete :delete, :params => { :id => used_relation.id }, :body => xml.to_s
+      assert_response :precondition_failed,
+                      "shouldn't be able to delete a relation used in a relation (#{@response.body})"
+      assert_equal "Precondition failed: The relation #{used_relation.id} is used in relation #{super_relation.id}.", @response.body
+
+      # this should work when we provide the appropriate payload...
+      xml = update_changeset(multi_tag_relation.to_xml, changeset.id)
+      delete :delete, :params => { :id => multi_tag_relation.id }, :body => xml.to_s
+      assert_response :success
+
+      # valid delete should return the new version number, which should
+      # be greater than the old version number
+      assert @response.body.to_i > multi_tag_relation.version,
+             "delete request should return a new version number for relation"
+
+      # this won't work since the relation is already deleted
+      xml = update_changeset(deleted_relation.to_xml, changeset.id)
+      delete :delete, :params => { :id => deleted_relation.id }, :body => xml.to_s
+      assert_response :gone
+
+      # Public visible relation needs to be deleted
+      xml = update_changeset(super_relation.to_xml, changeset.id)
+      delete :delete, :params => { :id => super_relation.id }, :body => xml.to_s
+      assert_response :success
+
+      # this works now because the relation which was using this one
+      # has been deleted.
+      xml = update_changeset(used_relation.to_xml, changeset.id)
+      delete :delete, :params => { :id => used_relation.id }, :body => xml.to_s
+      assert_response :success,
+                      "should be able to delete a relation used in an old relation (#{@response.body})"
+
+      # this won't work since the relation never existed
+      delete :delete, :params => { :id => 0 }
+      assert_response :not_found
+    end
+
+    ##
+    # when a relation's tag is modified then it should put the bounding
+    # box of all its members into the changeset.
+    def test_tag_modify_bounding_box
+      relation = create(:relation)
+      node1 = create(:node, :lat => 3, :lon => 3)
+      node2 = create(:node, :lat => 5, :lon => 5)
+      way = create(:way)
+      create(:way_node, :way => way, :node => node1)
+      create(:relation_member, :relation => relation, :member => way)
+      create(:relation_member, :relation => relation, :member => node2)
+      # the relation contains nodes1 and node2 (node1
+      # indirectly via the way), so the bbox should be [3,3,5,5].
+      check_changeset_modify(BoundingBox.new(3, 3, 5, 5)) do |changeset_id|
+        # add a tag to an existing relation
+        relation_xml = relation.to_xml
+        relation_element = relation_xml.find("//osm/relation").first
+        new_tag = XML::Node.new("tag")
+        new_tag["k"] = "some_new_tag"
+        new_tag["v"] = "some_new_value"
+        relation_element << new_tag
+
+        # update changeset ID to point to new changeset
+        update_changeset(relation_xml, changeset_id)
+
+        # upload the change
+        put :update, :params => { :id => relation.id }, :body => relation_xml.to_s
+        assert_response :success, "can't update relation for tag/bbox test"
+      end
+    end
+
+    ##
+    # add a member to a relation and check the bounding box is only that
+    # element.
+    def test_add_member_bounding_box
+      relation = create(:relation)
+      node1 = create(:node, :lat => 4, :lon => 4)
+      node2 = create(:node, :lat => 7, :lon => 7)
+      way1 = create(:way)
+      create(:way_node, :way => way1, :node => create(:node, :lat => 8, :lon => 8))
+      way2 = create(:way)
+      create(:way_node, :way => way2, :node => create(:node, :lat => 9, :lon => 9), :sequence_id => 1)
+      create(:way_node, :way => way2, :node => create(:node, :lat => 10, :lon => 10), :sequence_id => 2)
+
+      [node1, node2, way1, way2].each do |element|
+        bbox = element.bbox.to_unscaled
+        check_changeset_modify(bbox) do |changeset_id|
+          relation_xml = Relation.find(relation.id).to_xml
+          relation_element = relation_xml.find("//osm/relation").first
+          new_member = XML::Node.new("member")
+          new_member["ref"] = element.id.to_s
+          new_member["type"] = element.class.to_s.downcase
+          new_member["role"] = "some_role"
+          relation_element << new_member
+
+          # update changeset ID to point to new changeset
+          update_changeset(relation_xml, changeset_id)
+
+          # upload the change
+          put :update, :params => { :id => relation.id }, :body => relation_xml.to_s
+          assert_response :success, "can't update relation for add #{element.class}/bbox test: #{@response.body}"
+
+          # get it back and check the ordering
+          get :show, :params => { :id => relation.id }
+          assert_response :success, "can't read back the relation: #{@response.body}"
+          check_ordering(relation_xml, @response.body)
+        end
+      end
+    end
+
+    ##
+    # remove a member from a relation and check the bounding box is
+    # only that element.
+    def test_remove_member_bounding_box
+      relation = create(:relation)
+      node1 = create(:node, :lat => 3, :lon => 3)
+      node2 = create(:node, :lat => 5, :lon => 5)
+      create(:relation_member, :relation => relation, :member => node1)
+      create(:relation_member, :relation => relation, :member => node2)
+
+      check_changeset_modify(BoundingBox.new(5, 5, 5, 5)) do |changeset_id|
+        # remove node 5 (5,5) from an existing relation
+        relation_xml = relation.to_xml
+        relation_xml
+          .find("//osm/relation/member[@type='node'][@ref='#{node2.id}']")
+          .first.remove!
+
+        # update changeset ID to point to new changeset
+        update_changeset(relation_xml, changeset_id)
+
+        # upload the change
+        put :update, :params => { :id => relation.id }, :body => relation_xml.to_s
+        assert_response :success, "can't update relation for remove node/bbox test"
+      end
+    end
+
+    ##
+    # check that relations are ordered
+    def test_relation_member_ordering
+      user = create(:user)
+      changeset = create(:changeset, :user => user)
+      node1 = create(:node)
+      node2 = create(:node)
+      node3 = create(:node)
+      way1 = create(:way_with_nodes, :nodes_count => 2)
+      way2 = create(:way_with_nodes, :nodes_count => 2)
+
+      basic_authorization user.email, "test"
+
+      doc_str = <<OSM.strip_heredoc
+        <osm>
+         <relation changeset='#{changeset.id}'>
+          <member ref='#{node1.id}' type='node' role='first'/>
+          <member ref='#{node2.id}' type='node' role='second'/>
+          <member ref='#{way1.id}' type='way' role='third'/>
+          <member ref='#{way2.id}' type='way' role='fourth'/>
+         </relation>
+        </osm>
+OSM
+      doc = XML::Parser.string(doc_str).parse
+
+      put :create, :body => doc.to_s
+      assert_response :success, "can't create a relation: #{@response.body}"
+      relation_id = @response.body.to_i
+
+      # get it back and check the ordering
+      get :show, :params => { :id => relation_id }
+      assert_response :success, "can't read back the relation: #{@response.body}"
+      check_ordering(doc, @response.body)
+
+      # insert a member at the front
+      new_member = XML::Node.new "member"
+      new_member["ref"] = node3.id.to_s
+      new_member["type"] = "node"
+      new_member["role"] = "new first"
+      doc.find("//osm/relation").first.child.prev = new_member
+      # update the version, should be 1?
+      doc.find("//osm/relation").first["id"] = relation_id.to_s
+      doc.find("//osm/relation").first["version"] = 1.to_s
+
+      # upload the next version of the relation
+      put :update, :params => { :id => relation_id }, :body => doc.to_s
+      assert_response :success, "can't update relation: #{@response.body}"
+      assert_equal 2, @response.body.to_i
+
+      # get it back again and check the ordering again
+      get :show, :params => { :id => relation_id }
+      assert_response :success, "can't read back the relation: #{@response.body}"
+      check_ordering(doc, @response.body)
+
+      # check the ordering in the history tables:
+      with_controller(OldRelationsController.new) do
+        get :version, :params => { :id => relation_id, :version => 2 }
+        assert_response :success, "can't read back version 2 of the relation #{relation_id}"
+        check_ordering(doc, @response.body)
+      end
+    end
+
+    ##
+    # check that relations can contain duplicate members
+    def test_relation_member_duplicates
+      private_user = create(:user, :data_public => false)
+      user = create(:user)
+      changeset = create(:changeset, :user => user)
+      node1 = create(:node)
+      node2 = create(:node)
+
+      doc_str = <<OSM.strip_heredoc
+        <osm>
+         <relation changeset='#{changeset.id}'>
+          <member ref='#{node1.id}' type='node' role='forward'/>
+          <member ref='#{node2.id}' type='node' role='forward'/>
+          <member ref='#{node1.id}' type='node' role='forward'/>
+          <member ref='#{node2.id}' type='node' role='forward'/>
+         </relation>
+        </osm>
+OSM
+      doc = XML::Parser.string(doc_str).parse
+
+      ## First try with the private user
+      basic_authorization private_user.email, "test"
+
+      put :create, :body => doc.to_s
+      assert_response :forbidden
+
+      ## Now try with the public user
+      basic_authorization user.email, "test"
+
+      put :create, :body => doc.to_s
+      assert_response :success, "can't create a relation: #{@response.body}"
+      relation_id = @response.body.to_i
+
+      # get it back and check the ordering
+      get :show, :params => { :id => relation_id }
+      assert_response :success, "can't read back the relation: #{relation_id}"
+      check_ordering(doc, @response.body)
+    end
+
+    ##
+    # test that the ordering of elements in the history is the same as in current.
+    def test_history_ordering
+      user = create(:user)
+      changeset = create(:changeset, :user => user)
+      node1 = create(:node)
+      node2 = create(:node)
+      node3 = create(:node)
+      node4 = create(:node)
+
+      doc_str = <<OSM.strip_heredoc
+        <osm>
+         <relation changeset='#{changeset.id}'>
+          <member ref='#{node1.id}' type='node' role='forward'/>
+          <member ref='#{node4.id}' type='node' role='forward'/>
+          <member ref='#{node3.id}' type='node' role='forward'/>
+          <member ref='#{node2.id}' type='node' role='forward'/>
+         </relation>
+        </osm>
+OSM
+      doc = XML::Parser.string(doc_str).parse
+      basic_authorization user.email, "test"
+
+      put :create, :body => doc.to_s
+      assert_response :success, "can't create a relation: #{@response.body}"
+      relation_id = @response.body.to_i
+
+      # check the ordering in the current tables:
+      get :show, :params => { :id => relation_id }
+      assert_response :success, "can't read back the relation: #{@response.body}"
+      check_ordering(doc, @response.body)
+
+      # check the ordering in the history tables:
+      with_controller(OldRelationsController.new) do
+        get :version, :params => { :id => relation_id, :version => 1 }
+        assert_response :success, "can't read back version 1 of the relation: #{@response.body}"
+        check_ordering(doc, @response.body)
+      end
+    end
+
+    ##
+    # remove all the members from a relation. the result is pretty useless, but
+    # still technically valid.
+    def test_remove_all_members
+      relation = create(:relation)
+      node1 = create(:node, :lat => 3, :lon => 3)
+      node2 = create(:node, :lat => 5, :lon => 5)
+      way = create(:way)
+      create(:way_node, :way => way, :node => node1)
+      create(:relation_member, :relation => relation, :member => way)
+      create(:relation_member, :relation => relation, :member => node2)
+
+      check_changeset_modify(BoundingBox.new(3, 3, 5, 5)) do |changeset_id|
+        relation_xml = relation.to_xml
+        relation_xml
+          .find("//osm/relation/member")
+          .each(&:remove!)
+
+        # update changeset ID to point to new changeset
+        update_changeset(relation_xml, changeset_id)
+
+        # upload the change
+        put :update, :params => { :id => relation.id }, :body => relation_xml.to_s
+        assert_response :success, "can't update relation for remove all members test"
+        checkrelation = Relation.find(relation.id)
+        assert_not_nil(checkrelation,
+                       "uploaded relation not found in database after upload")
+        assert_equal(0, checkrelation.members.length,
+                     "relation contains members but they should have all been deleted")
+      end
+    end
+
+    # ============================================================
+    # utility functions
+    # ============================================================
+
+    ##
+    # checks that the XML document and the string arguments have
+    # members in the same order.
+    def check_ordering(doc, xml)
+      new_doc = XML::Parser.string(xml).parse
+
+      doc_members = doc.find("//osm/relation/member").collect do |m|
+        [m["ref"].to_i, m["type"].to_sym, m["role"]]
+      end
+
+      new_members = new_doc.find("//osm/relation/member").collect do |m|
+        [m["ref"].to_i, m["type"].to_sym, m["role"]]
+      end
+
+      doc_members.zip(new_members).each do |d, n|
+        assert_equal d, n, "members are not equal - ordering is wrong? (#{doc}, #{xml})"
+      end
+    end
+
+    ##
+    # create a changeset and yield to the caller to set it up, then assert
+    # that the changeset bounding box is +bbox+.
+    def check_changeset_modify(bbox)
+      ## First test with the private user to check that you get a forbidden
+      basic_authorization create(:user, :data_public => false).email, "test"
+
+      # create a new changeset for this operation, so we are assured
+      # that the bounding box will be newly-generated.
+      changeset_id = with_controller(Api::ChangesetsController.new) do
+        xml = "<osm><changeset/></osm>"
+        put :create, :body => xml
+        assert_response :forbidden, "shouldn't be able to create changeset for modify test, as should get forbidden"
+      end
+
+      ## Now do the whole thing with the public user
+      basic_authorization create(:user).email, "test"
+
+      # create a new changeset for this operation, so we are assured
+      # that the bounding box will be newly-generated.
+      changeset_id = with_controller(Api::ChangesetsController.new) do
+        xml = "<osm><changeset/></osm>"
+        put :create, :body => xml
+        assert_response :success, "couldn't create changeset for modify test"
+        @response.body.to_i
+      end
+
+      # go back to the block to do the actual modifies
+      yield changeset_id
+
+      # now download the changeset to check its bounding box
+      with_controller(Api::ChangesetsController.new) do
+        get :show, :params => { :id => changeset_id }
+        assert_response :success, "can't re-read changeset for modify test"
+        assert_select "osm>changeset", 1, "Changeset element doesn't exist in #{@response.body}"
+        assert_select "osm>changeset[id='#{changeset_id}']", 1, "Changeset id=#{changeset_id} doesn't exist in #{@response.body}"
+        assert_select "osm>changeset[min_lon='#{format('%.7f', bbox.min_lon)}']", 1, "Changeset min_lon wrong in #{@response.body}"
+        assert_select "osm>changeset[min_lat='#{format('%.7f', bbox.min_lat)}']", 1, "Changeset min_lat wrong in #{@response.body}"
+        assert_select "osm>changeset[max_lon='#{format('%.7f', bbox.max_lon)}']", 1, "Changeset max_lon wrong in #{@response.body}"
+        assert_select "osm>changeset[max_lat='#{format('%.7f', bbox.max_lat)}']", 1, "Changeset max_lat wrong in #{@response.body}"
+      end
+    end
+
+    ##
+    # yields the relation with the given +id+ (and optional +version+
+    # to read from the history tables) into the block. the parsed XML
+    # doc is returned.
+    def with_relation(id, ver = nil)
+      if ver.nil?
+        get :show, :params => { :id => id }
+      else
+        with_controller(OldRelationsController.new) do
+          get :version, :params => { :id => id, :version => ver }
+        end
+      end
+      assert_response :success
+      yield xml_parse(@response.body)
+    end
+
+    ##
+    # updates the relation (XML) +rel+ and
+    # yields the new version of that relation into the block.
+    # the parsed XML doc is retured.
+    def with_update(rel)
+      rel_id = rel.find("//osm/relation").first["id"].to_i
+      put :update, :params => { :id => rel_id }, :body => rel.to_s
+      assert_response :success, "can't update relation: #{@response.body}"
+      version = @response.body.to_i
+
+      # now get the new version
+      get :show, :params => { :id => rel_id }
+      assert_response :success
+      new_rel = xml_parse(@response.body)
+
+      yield new_rel
+
+      version
+    end
+
+    ##
+    # updates the relation (XML) +rel+ via the diff-upload API and
+    # yields the new version of that relation into the block.
+    # the parsed XML doc is retured.
+    def with_update_diff(rel)
+      rel_id = rel.find("//osm/relation").first["id"].to_i
+      cs_id = rel.find("//osm/relation").first["changeset"].to_i
+      version = nil
+
+      with_controller(Api::ChangesetsController.new) do
+        doc = OSM::API.new.get_xml_doc
+        change = XML::Node.new "osmChange"
+        doc.root = change
+        modify = XML::Node.new "modify"
+        change << modify
+        modify << doc.import(rel.find("//osm/relation").first)
+
+        post :upload, :params => { :id => cs_id }, :body => doc.to_s
+        assert_response :success, "can't upload diff relation: #{@response.body}"
+        version = xml_parse(@response.body).find("//diffResult/relation").first["new_version"].to_i
+      end
+
+      # now get the new version
+      get :show, :params => { :id => rel_id }
+      assert_response :success
+      new_rel = xml_parse(@response.body)
+
+      yield new_rel
+
+      version
+    end
+
+    ##
+    # returns a k->v hash of tags from an xml doc
+    def get_tags_as_hash(a)
+      a.find("//osm/relation/tag").sort_by { |v| v["k"] }.each_with_object({}) do |v, h|
+        h[v["k"]] = v["v"]
+      end
+    end
+
+    ##
+    # assert that all tags on relation documents +a+ and +b+
+    # are equal
+    def assert_tags_equal(a, b)
+      # turn the XML doc into tags hashes
+      a_tags = get_tags_as_hash(a)
+      b_tags = get_tags_as_hash(b)
+
+      assert_equal a_tags.keys, b_tags.keys, "Tag keys should be identical."
+      a_tags.each do |k, v|
+        assert_equal v, b_tags[k],
+                     "Tags which were not altered should be the same. " \
+                     "#{a_tags.inspect} != #{b_tags.inspect}"
+      end
+    end
+
+    ##
+    # update the changeset_id of a node element
+    def update_changeset(xml, changeset_id)
+      xml_attr_rewrite(xml, "changeset", changeset_id)
+    end
+
+    ##
+    # update an attribute in the node element
+    def xml_attr_rewrite(xml, name, value)
+      xml.find("//osm/relation").first[name] = value.to_s
+      xml
+    end
+
+    ##
+    # parse some xml
+    def xml_parse(xml)
+      parser = XML::Parser.string(xml)
+      parser.parse
+    end
+  end
+end
diff --git a/test/controllers/api/search_controller_test.rb b/test/controllers/api/search_controller_test.rb
new file mode 100644 (file)
index 0000000..e11a3c7
--- /dev/null
@@ -0,0 +1,108 @@
+require "test_helper"
+
+module Api
+  class SearchControllerTest < ActionController::TestCase
+    ##
+    # test all routes which lead to this controller
+    def test_routes
+      assert_routing(
+        { :path => "/api/0.6/search", :method => :get },
+        { :controller => "api/search", :action => "search_all" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/nodes/search", :method => :get },
+        { :controller => "api/search", :action => "search_nodes" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/ways/search", :method => :get },
+        { :controller => "api/search", :action => "search_ways" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/relations/search", :method => :get },
+        { :controller => "api/search", :action => "search_relations" }
+      )
+    end
+
+    ##
+    # test searching nodes
+    def test_search_nodes
+      get :search_nodes, :params => { :type => "test" }
+      assert_response :service_unavailable
+      assert_equal "Searching of nodes is currently unavailable", response.headers["Error"]
+
+      get :search_nodes, :params => { :type => "test", :value => "yes" }
+      assert_response :service_unavailable
+      assert_equal "Searching of nodes is currently unavailable", response.headers["Error"]
+
+      get :search_nodes, :params => { :name => "Test Node" }
+      assert_response :service_unavailable
+      assert_equal "Searching of nodes is currently unavailable", response.headers["Error"]
+    end
+
+    ##
+    # test searching ways
+    def test_search_ways
+      first_way = create(:way_with_nodes, :nodes_count => 2)
+      deleted_way = create(:way_with_nodes, :deleted, :nodes_count => 2)
+      third_way = create(:way_with_nodes, :nodes_count => 2)
+
+      [first_way, deleted_way, third_way].each do |way|
+        create(:way_tag, :way => way, :k => "test", :v => "yes")
+      end
+      create(:way_tag, :way => third_way, :k => "name", :v => "Test Way")
+
+      get :search_ways, :params => { :type => "test" }
+      assert_response :service_unavailable
+      assert_equal "Searching for a key without value is currently unavailable", response.headers["Error"]
+
+      get :search_ways, :params => { :type => "test", :value => "yes" }
+      assert_response :success
+      assert_select "way", 3
+
+      get :search_ways, :params => { :name => "Test Way" }
+      assert_response :success
+      assert_select "way", 1
+    end
+
+    ##
+    # test searching relations
+    def test_search_relations
+      first_relation = create(:relation)
+      deleted_relation = create(:relation)
+      third_relation = create(:relation)
+
+      [first_relation, deleted_relation, third_relation].each do |relation|
+        create(:relation_tag, :relation => relation, :k => "test", :v => "yes")
+      end
+      create(:relation_tag, :relation => third_relation, :k => "name", :v => "Test Relation")
+
+      get :search_relations, :params => { :type => "test" }
+      assert_response :service_unavailable
+      assert_equal "Searching for a key without value is currently unavailable", response.headers["Error"]
+
+      get :search_relations, :params => { :type => "test", :value => "yes" }
+      assert_response :success
+      assert_select "relation", 3
+
+      get :search_relations, :params => { :name => "Test Relation" }
+      assert_response :success
+      assert_select "relation", 1
+    end
+
+    ##
+    # test searching nodes, ways and relations
+    def test_search_all
+      get :search_all, :params => { :type => "test" }
+      assert_response :service_unavailable
+      assert_equal "Searching of nodes is currently unavailable", response.headers["Error"]
+
+      get :search_all, :params => { :type => "test", :value => "yes" }
+      assert_response :service_unavailable
+      assert_equal "Searching of nodes is currently unavailable", response.headers["Error"]
+
+      get :search_all, :params => { :name => "Test" }
+      assert_response :service_unavailable
+      assert_equal "Searching of nodes is currently unavailable", response.headers["Error"]
+    end
+  end
+end
diff --git a/test/controllers/api/swf_controller_test.rb b/test/controllers/api/swf_controller_test.rb
new file mode 100644 (file)
index 0000000..6d7808a
--- /dev/null
@@ -0,0 +1,46 @@
+require "test_helper"
+
+module Api
+  class SwfControllerTest < ActionController::TestCase
+    ##
+    # test all routes which lead to this controller
+    def test_routes
+      assert_routing(
+        { :path => "/api/0.6/swf/trackpoints", :method => :get },
+        { :controller => "api/swf", :action => "trackpoints" }
+      )
+    end
+
+    ##
+    # basic test that trackpoints at least returns some sort of flash movie
+    def test_trackpoints
+      user = create(:user)
+      other_user = create(:user)
+      create(:trace, :visibility => "trackable", :latitude => 51.51, :longitude => -0.14, :user => user) do |trace|
+        create(:tracepoint, :trace => trace, :trackid => 1, :latitude => (51.510 * GeoRecord::SCALE).to_i, :longitude => (-0.140 * GeoRecord::SCALE).to_i)
+        create(:tracepoint, :trace => trace, :trackid => 2, :latitude => (51.511 * GeoRecord::SCALE).to_i, :longitude => (-0.141 * GeoRecord::SCALE).to_i)
+      end
+      create(:trace, :visibility => "identifiable", :latitude => 51.512, :longitude => 0.142) do |trace|
+        create(:tracepoint, :trace => trace, :latitude => (51.512 * GeoRecord::SCALE).to_i, :longitude => (0.142 * GeoRecord::SCALE).to_i)
+      end
+
+      get :trackpoints, :params => { :xmin => -1, :xmax => 1, :ymin => 51, :ymax => 52, :baselong => 0, :basey => 0, :masterscale => 1 }
+      assert_response :success
+      assert_equal "application/x-shockwave-flash", response.content_type
+      assert_match(/^FWS/, response.body)
+      assert_equal 80, response.body.length
+
+      get :trackpoints, :params => { :xmin => -1, :xmax => 1, :ymin => 51, :ymax => 52, :baselong => 0, :basey => 0, :masterscale => 1, :token => other_user.tokens.create.token }
+      assert_response :success
+      assert_equal "application/x-shockwave-flash", response.content_type
+      assert_match(/^FWS/, response.body)
+      assert_equal 67, response.body.length
+
+      get :trackpoints, :params => { :xmin => -1, :xmax => 1, :ymin => 51, :ymax => 52, :baselong => 0, :basey => 0, :masterscale => 1, :token => user.tokens.create.token }
+      assert_response :success
+      assert_equal "application/x-shockwave-flash", response.content_type
+      assert_match(/^FWS/, response.body)
+      assert_equal 74, response.body.length
+    end
+  end
+end
diff --git a/test/controllers/api/traces_controller_test.rb b/test/controllers/api/traces_controller_test.rb
new file mode 100644 (file)
index 0000000..4f28514
--- /dev/null
@@ -0,0 +1,357 @@
+require "test_helper"
+require "minitest/mock"
+
+module Api
+  class TracesControllerTest < ActionController::TestCase
+    def setup
+      @gpx_trace_dir = Object.send("remove_const", "GPX_TRACE_DIR")
+      Object.const_set("GPX_TRACE_DIR", Rails.root.join("test", "gpx", "traces"))
+
+      @gpx_image_dir = Object.send("remove_const", "GPX_IMAGE_DIR")
+      Object.const_set("GPX_IMAGE_DIR", Rails.root.join("test", "gpx", "images"))
+    end
+
+    def teardown
+      File.unlink(*Dir.glob(File.join(GPX_TRACE_DIR, "*.gpx")))
+      File.unlink(*Dir.glob(File.join(GPX_IMAGE_DIR, "*.gif")))
+
+      Object.send("remove_const", "GPX_TRACE_DIR")
+      Object.const_set("GPX_TRACE_DIR", @gpx_trace_dir)
+
+      Object.send("remove_const", "GPX_IMAGE_DIR")
+      Object.const_set("GPX_IMAGE_DIR", @gpx_image_dir)
+    end
+
+    ##
+    # test all routes which lead to this controller
+    def test_routes
+      assert_routing(
+        { :path => "/api/0.6/gpx/create", :method => :post },
+        { :controller => "api/traces", :action => "api_create" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/gpx/1", :method => :get },
+        { :controller => "api/traces", :action => "api_read", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/gpx/1", :method => :put },
+        { :controller => "api/traces", :action => "api_update", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/gpx/1", :method => :delete },
+        { :controller => "api/traces", :action => "api_delete", :id => "1" }
+      )
+      assert_recognizes(
+        { :controller => "api/traces", :action => "api_read", :id => "1" },
+        { :path => "/api/0.6/gpx/1/details", :method => :get }
+      )
+      assert_routing(
+        { :path => "/api/0.6/gpx/1/data", :method => :get },
+        { :controller => "api/traces", :action => "api_data", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/gpx/1/data.xml", :method => :get },
+        { :controller => "api/traces", :action => "api_data", :id => "1", :format => "xml" }
+      )
+    end
+
+    # Check getting a specific trace through the api
+    def test_api_read
+      public_trace_file = create(:trace, :visibility => "public")
+
+      # First with no auth
+      get :api_read, :params => { :id => public_trace_file.id }
+      assert_response :unauthorized
+
+      # Now with some other user, which should work since the trace is public
+      basic_authorization create(:user).display_name, "test"
+      get :api_read, :params => { :id => public_trace_file.id }
+      assert_response :success
+
+      # And finally we should be able to do it with the owner of the trace
+      basic_authorization public_trace_file.user.display_name, "test"
+      get :api_read, :params => { :id => public_trace_file.id }
+      assert_response :success
+    end
+
+    # Check an anoymous trace can't be specifically fetched by another user
+    def test_api_read_anon
+      anon_trace_file = create(:trace, :visibility => "private")
+
+      # First with no auth
+      get :api_read, :params => { :id => anon_trace_file.id }
+      assert_response :unauthorized
+
+      # Now try with another user, which shouldn't work since the trace is anon
+      basic_authorization create(:user).display_name, "test"
+      get :api_read, :params => { :id => anon_trace_file.id }
+      assert_response :forbidden
+
+      # And finally we should be able to get the trace details with the trace owner
+      basic_authorization anon_trace_file.user.display_name, "test"
+      get :api_read, :params => { :id => anon_trace_file.id }
+      assert_response :success
+    end
+
+    # Check the api details for a trace that doesn't exist
+    def test_api_read_not_found
+      deleted_trace_file = create(:trace, :deleted)
+
+      # Try first with no auth, as it should require it
+      get :api_read, :params => { :id => 0 }
+      assert_response :unauthorized
+
+      # Login, and try again
+      basic_authorization deleted_trace_file.user.display_name, "test"
+      get :api_read, :params => { :id => 0 }
+      assert_response :not_found
+
+      # Now try a trace which did exist but has been deleted
+      basic_authorization deleted_trace_file.user.display_name, "test"
+      get :api_read, :params => { :id => deleted_trace_file.id }
+      assert_response :not_found
+    end
+
+    # Test downloading a trace through the api
+    def test_api_data
+      public_trace_file = create(:trace, :visibility => "public", :fixture => "a")
+
+      # First with no auth
+      get :api_data, :params => { :id => public_trace_file.id }
+      assert_response :unauthorized
+
+      # Now with some other user, which should work since the trace is public
+      basic_authorization create(:user).display_name, "test"
+      get :api_data, :params => { :id => public_trace_file.id }
+      check_trace_data public_trace_file, "848caa72f2f456d1bd6a0fdf228aa1b9"
+
+      # And finally we should be able to do it with the owner of the trace
+      basic_authorization public_trace_file.user.display_name, "test"
+      get :api_data, :params => { :id => public_trace_file.id }
+      check_trace_data public_trace_file, "848caa72f2f456d1bd6a0fdf228aa1b9"
+    end
+
+    # Test downloading a compressed trace through the api
+    def test_api_data_compressed
+      identifiable_trace_file = create(:trace, :visibility => "identifiable", :fixture => "d")
+
+      # Authenticate as the owner of the trace we will be using
+      basic_authorization identifiable_trace_file.user.display_name, "test"
+
+      # First get the data as is
+      get :api_data, :params => { :id => identifiable_trace_file.id }
+      check_trace_data identifiable_trace_file, "c6422a3d8750faae49ed70e7e8a51b93", "application/x-gzip", "gpx.gz"
+
+      # Now ask explicitly for XML format
+      get :api_data, :params => { :id => identifiable_trace_file.id, :format => "xml" }
+      check_trace_data identifiable_trace_file, "abd6675fdf3024a84fc0a1deac147c0d", "application/xml", "xml"
+
+      # Now ask explicitly for GPX format
+      get :api_data, :params => { :id => identifiable_trace_file.id, :format => "gpx" }
+      check_trace_data identifiable_trace_file, "abd6675fdf3024a84fc0a1deac147c0d"
+    end
+
+    # Check an anonymous trace can't be downloaded by another user through the api
+    def test_api_data_anon
+      anon_trace_file = create(:trace, :visibility => "private", :fixture => "b")
+
+      # First with no auth
+      get :api_data, :params => { :id => anon_trace_file.id }
+      assert_response :unauthorized
+
+      # Now with some other user, which shouldn't work since the trace is anon
+      basic_authorization create(:user).display_name, "test"
+      get :api_data, :params => { :id => anon_trace_file.id }
+      assert_response :forbidden
+
+      # And finally we should be able to do it with the owner of the trace
+      basic_authorization anon_trace_file.user.display_name, "test"
+      get :api_data, :params => { :id => anon_trace_file.id }
+      check_trace_data anon_trace_file, "66179ca44f1e93d8df62e2b88cbea732"
+    end
+
+    # Test downloading a trace that doesn't exist through the api
+    def test_api_data_not_found
+      deleted_trace_file = create(:trace, :deleted)
+
+      # Try first with no auth, as it should require it
+      get :api_data, :params => { :id => 0 }
+      assert_response :unauthorized
+
+      # Login, and try again
+      basic_authorization create(:user).display_name, "test"
+      get :api_data, :params => { :id => 0 }
+      assert_response :not_found
+
+      # Now try a trace which did exist but has been deleted
+      basic_authorization deleted_trace_file.user.display_name, "test"
+      get :api_data, :params => { :id => deleted_trace_file.id }
+      assert_response :not_found
+    end
+
+    # Test creating a trace through the api
+    def test_api_create
+      # Get file to use
+      fixture = Rails.root.join("test", "gpx", "fixtures", "a.gpx")
+      file = Rack::Test::UploadedFile.new(fixture, "application/gpx+xml")
+      user = create(:user)
+
+      # First with no auth
+      post :api_create, :params => { :file => file, :description => "New Trace", :tags => "new,trace", :visibility => "trackable" }
+      assert_response :unauthorized
+
+      # Rewind the file
+      file.rewind
+
+      # Now authenticated
+      create(:user_preference, :user => user, :k => "gps.trace.visibility", :v => "identifiable")
+      assert_not_equal "trackable", user.preferences.where(:k => "gps.trace.visibility").first.v
+      basic_authorization user.display_name, "test"
+      post :api_create, :params => { :file => file, :description => "New Trace", :tags => "new,trace", :visibility => "trackable" }
+      assert_response :success
+      trace = Trace.find(response.body.to_i)
+      assert_equal "a.gpx", trace.name
+      assert_equal "New Trace", trace.description
+      assert_equal %w[new trace], trace.tags.order(:tag).collect(&:tag)
+      assert_equal "trackable", trace.visibility
+      assert_equal false, trace.inserted
+      assert_equal File.new(fixture).read, File.new(trace.trace_name).read
+      trace.destroy
+      assert_equal "trackable", user.preferences.where(:k => "gps.trace.visibility").first.v
+
+      # Rewind the file
+      file.rewind
+
+      # Now authenticated, with the legacy public flag
+      assert_not_equal "public", user.preferences.where(:k => "gps.trace.visibility").first.v
+      basic_authorization user.display_name, "test"
+      post :api_create, :params => { :file => file, :description => "New Trace", :tags => "new,trace", :public => 1 }
+      assert_response :success
+      trace = Trace.find(response.body.to_i)
+      assert_equal "a.gpx", trace.name
+      assert_equal "New Trace", trace.description
+      assert_equal %w[new trace], trace.tags.order(:tag).collect(&:tag)
+      assert_equal "public", trace.visibility
+      assert_equal false, trace.inserted
+      assert_equal File.new(fixture).read, File.new(trace.trace_name).read
+      trace.destroy
+      assert_equal "public", user.preferences.where(:k => "gps.trace.visibility").first.v
+
+      # Rewind the file
+      file.rewind
+
+      # Now authenticated, with the legacy private flag
+      second_user = create(:user)
+      assert_nil second_user.preferences.where(:k => "gps.trace.visibility").first
+      basic_authorization second_user.display_name, "test"
+      post :api_create, :params => { :file => file, :description => "New Trace", :tags => "new,trace", :public => 0 }
+      assert_response :success
+      trace = Trace.find(response.body.to_i)
+      assert_equal "a.gpx", trace.name
+      assert_equal "New Trace", trace.description
+      assert_equal %w[new trace], trace.tags.order(:tag).collect(&:tag)
+      assert_equal "private", trace.visibility
+      assert_equal false, trace.inserted
+      assert_equal File.new(fixture).read, File.new(trace.trace_name).read
+      trace.destroy
+      assert_equal "private", second_user.preferences.where(:k => "gps.trace.visibility").first.v
+    end
+
+    # Check updating a trace through the api
+    def test_api_update
+      public_trace_file = create(:trace, :visibility => "public", :fixture => "a")
+      deleted_trace_file = create(:trace, :deleted)
+      anon_trace_file = create(:trace, :visibility => "private")
+
+      # First with no auth
+      put :api_update, :params => { :id => public_trace_file.id }, :body => public_trace_file.to_xml.to_s
+      assert_response :unauthorized
+
+      # Now with some other user, which should fail
+      basic_authorization create(:user).display_name, "test"
+      put :api_update, :params => { :id => public_trace_file.id }, :body => public_trace_file.to_xml.to_s
+      assert_response :forbidden
+
+      # Now with a trace which doesn't exist
+      basic_authorization create(:user).display_name, "test"
+      put :api_update, :params => { :id => 0 }, :body => public_trace_file.to_xml.to_s
+      assert_response :not_found
+
+      # Now with a trace which did exist but has been deleted
+      basic_authorization deleted_trace_file.user.display_name, "test"
+      put :api_update, :params => { :id => deleted_trace_file.id }, :body => deleted_trace_file.to_xml.to_s
+      assert_response :not_found
+
+      # Now try an update with the wrong ID
+      basic_authorization public_trace_file.user.display_name, "test"
+      put :api_update, :params => { :id => public_trace_file.id }, :body => anon_trace_file.to_xml.to_s
+      assert_response :bad_request,
+                      "should not be able to update a trace with a different ID from the XML"
+
+      # And finally try an update that should work
+      basic_authorization public_trace_file.user.display_name, "test"
+      t = public_trace_file
+      t.description = "Changed description"
+      t.visibility = "private"
+      put :api_update, :params => { :id => t.id }, :body => t.to_xml.to_s
+      assert_response :success
+      nt = Trace.find(t.id)
+      assert_equal nt.description, t.description
+      assert_equal nt.visibility, t.visibility
+    end
+
+    # Test that updating a trace doesn't duplicate the tags
+    def test_api_update_tags
+      tracetag = create(:tracetag)
+      trace = tracetag.trace
+      basic_authorization trace.user.display_name, "test"
+
+      put :api_update, :params => { :id => trace.id }, :body => trace.to_xml.to_s
+      assert_response :success
+
+      updated = Trace.find(trace.id)
+      # Ensure there's only one tag in the database after updating
+      assert_equal Tracetag.count, 1
+      # The new tag object might have a different id, so check the string representation
+      assert_equal trace.tagstring, updated.tagstring
+    end
+
+    # Check deleting a trace through the api
+    def test_api_delete
+      public_trace_file = create(:trace, :visibility => "public")
+
+      # First with no auth
+      delete :api_delete, :params => { :id => public_trace_file.id }
+      assert_response :unauthorized
+
+      # Now with some other user, which should fail
+      basic_authorization create(:user).display_name, "test"
+      delete :api_delete, :params => { :id => public_trace_file.id }
+      assert_response :forbidden
+
+      # Now with a trace which doesn't exist
+      basic_authorization create(:user).display_name, "test"
+      delete :api_delete, :params => { :id => 0 }
+      assert_response :not_found
+
+      # And finally we should be able to do it with the owner of the trace
+      basic_authorization public_trace_file.user.display_name, "test"
+      delete :api_delete, :params => { :id => public_trace_file.id }
+      assert_response :success
+
+      # Try it a second time, which should fail
+      basic_authorization public_trace_file.user.display_name, "test"
+      delete :api_delete, :params => { :id => public_trace_file.id }
+      assert_response :not_found
+    end
+
+    private
+
+    def check_trace_data(trace, digest, content_type = "application/gpx+xml", extension = "gpx")
+      assert_response :success
+      assert_equal digest, Digest::MD5.hexdigest(response.body)
+      assert_equal content_type, response.content_type
+      assert_equal "attachment; filename=\"#{trace.id}.#{extension}\"", @response.header["Content-Disposition"]
+    end
+  end
+end
diff --git a/test/controllers/api/user_preferences_controller_test.rb b/test/controllers/api/user_preferences_controller_test.rb
new file mode 100644 (file)
index 0000000..99dad95
--- /dev/null
@@ -0,0 +1,246 @@
+require "test_helper"
+
+module Api
+  class UserPreferencesControllerTest < ActionController::TestCase
+    ##
+    # test all routes which lead to this controller
+    def test_routes
+      assert_routing(
+        { :path => "/api/0.6/user/preferences", :method => :get },
+        { :controller => "api/user_preferences", :action => "read" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/user/preferences", :method => :put },
+        { :controller => "api/user_preferences", :action => "update" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/user/preferences/key", :method => :get },
+        { :controller => "api/user_preferences", :action => "read_one", :preference_key => "key" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/user/preferences/key", :method => :put },
+        { :controller => "api/user_preferences", :action => "update_one", :preference_key => "key" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/user/preferences/key", :method => :delete },
+        { :controller => "api/user_preferences", :action => "delete_one", :preference_key => "key" }
+      )
+    end
+
+    ##
+    # test read action
+    def test_read
+      # first try without auth
+      get :read
+      assert_response :unauthorized, "should be authenticated"
+
+      # authenticate as a user with no preferences
+      basic_authorization create(:user).email, "test"
+
+      # try the read again
+      get :read
+      assert_select "osm" do
+        assert_select "preferences", :count => 1 do
+          assert_select "preference", :count => 0
+        end
+      end
+
+      # authenticate as a user with preferences
+      user = create(:user)
+      user_preference = create(:user_preference, :user => user)
+      user_preference2 = create(:user_preference, :user => user)
+      basic_authorization user.email, "test"
+
+      # try the read again
+      get :read
+      assert_response :success
+      assert_equal "application/xml", @response.content_type
+      assert_select "osm" do
+        assert_select "preferences", :count => 1 do
+          assert_select "preference", :count => 2
+          assert_select "preference[k=\"#{user_preference.k}\"][v=\"#{user_preference.v}\"]", :count => 1
+          assert_select "preference[k=\"#{user_preference2.k}\"][v=\"#{user_preference2.v}\"]", :count => 1
+        end
+      end
+    end
+
+    ##
+    # test read_one action
+    def test_read_one
+      user = create(:user)
+      create(:user_preference, :user => user, :k => "key", :v => "value")
+
+      # try a read without auth
+      get :read_one, :params => { :preference_key => "key" }
+      assert_response :unauthorized, "should be authenticated"
+
+      # authenticate as a user with preferences
+      basic_authorization user.email, "test"
+
+      # try the read again
+      get :read_one, :params => { :preference_key => "key" }
+      assert_response :success
+      assert_equal "text/plain", @response.content_type
+      assert_equal "value", @response.body
+
+      # try the read again for a non-existent key
+      get :read_one, :params => { :preference_key => "unknown_key" }
+      assert_response :not_found
+    end
+
+    ##
+    # test update action
+    def test_update
+      user = create(:user)
+      create(:user_preference, :user => user, :k => "key", :v => "value")
+      create(:user_preference, :user => user, :k => "some_key", :v => "some_value")
+
+      # try a put without auth
+      assert_no_difference "UserPreference.count" do
+        put :update, :body => "<osm><preferences><preference k='key' v='new_value'/><preference k='new_key' v='value'/></preferences></osm>"
+      end
+      assert_response :unauthorized, "should be authenticated"
+      assert_equal "value", UserPreference.find([user.id, "key"]).v
+      assert_equal "some_value", UserPreference.find([user.id, "some_key"]).v
+      assert_raises ActiveRecord::RecordNotFound do
+        UserPreference.find([user.id, "new_key"])
+      end
+
+      # authenticate as a user with preferences
+      basic_authorization user.email, "test"
+
+      # try the put again
+      assert_no_difference "UserPreference.count" do
+        put :update, :body => "<osm><preferences><preference k='key' v='new_value'/><preference k='new_key' v='value'/></preferences></osm>"
+      end
+      assert_response :success
+      assert_equal "text/plain", @response.content_type
+      assert_equal "", @response.body
+      assert_equal "new_value", UserPreference.find([user.id, "key"]).v
+      assert_equal "value", UserPreference.find([user.id, "new_key"]).v
+      assert_raises ActiveRecord::RecordNotFound do
+        UserPreference.find([user.id, "some_key"])
+      end
+
+      # try a put with duplicate keys
+      assert_no_difference "UserPreference.count" do
+        put :update, :body => "<osm><preferences><preference k='key' v='value'/><preference k='key' v='newer_value'/></preferences></osm>"
+      end
+      assert_response :bad_request
+      assert_equal "text/plain", @response.content_type
+      assert_equal "Duplicate preferences with key key", @response.body
+      assert_equal "new_value", UserPreference.find([user.id, "key"]).v
+
+      # try a put with invalid content
+      assert_no_difference "UserPreference.count" do
+        put :update, :body => "nonsense"
+      end
+      assert_response :bad_request
+    end
+
+    ##
+    # test update_one action
+    def test_update_one
+      user = create(:user)
+      create(:user_preference, :user => user)
+
+      # try a put without auth
+      assert_no_difference "UserPreference.count" do
+        put :update_one, :params => { :preference_key => "new_key" }, :body => "new_value"
+      end
+      assert_response :unauthorized, "should be authenticated"
+      assert_raises ActiveRecord::RecordNotFound do
+        UserPreference.find([user.id, "new_key"])
+      end
+
+      # authenticate as a user with preferences
+      basic_authorization user.email, "test"
+
+      # try adding a new preference
+      assert_difference "UserPreference.count", 1 do
+        put :update_one, :params => { :preference_key => "new_key" }, :body => "new_value"
+      end
+      assert_response :success
+      assert_equal "text/plain", @response.content_type
+      assert_equal "", @response.body
+      assert_equal "new_value", UserPreference.find([user.id, "new_key"]).v
+
+      # try changing the value of a preference
+      assert_no_difference "UserPreference.count" do
+        put :update_one, :params => { :preference_key => "new_key" }, :body => "newer_value"
+      end
+      assert_response :success
+      assert_equal "text/plain", @response.content_type
+      assert_equal "", @response.body
+      assert_equal "newer_value", UserPreference.find([user.id, "new_key"]).v
+    end
+
+    ##
+    # test delete_one action
+    def test_delete_one
+      user = create(:user)
+      create(:user_preference, :user => user, :k => "key", :v => "value")
+
+      # try a delete without auth
+      assert_no_difference "UserPreference.count" do
+        delete :delete_one, :params => { :preference_key => "key" }
+      end
+      assert_response :unauthorized, "should be authenticated"
+      assert_equal "value", UserPreference.find([user.id, "key"]).v
+
+      # authenticate as a user with preferences
+      basic_authorization user.email, "test"
+
+      # try the delete again
+      assert_difference "UserPreference.count", -1 do
+        get :delete_one, :params => { :preference_key => "key" }
+      end
+      assert_response :success
+      assert_equal "text/plain", @response.content_type
+      assert_equal "", @response.body
+      assert_raises ActiveRecord::RecordNotFound do
+        UserPreference.find([user.id, "key"])
+      end
+
+      # try the delete again for the same key
+      assert_no_difference "UserPreference.count" do
+        get :delete_one, :params => { :preference_key => "key" }
+      end
+      assert_response :not_found
+      assert_raises ActiveRecord::RecordNotFound do
+        UserPreference.find([user.id, "key"])
+      end
+    end
+
+    # Ensure that a valid access token with correct capabilities can be used to
+    # read preferences
+    def test_read_one_using_token
+      user = create(:user)
+      token = create(:access_token, :user => user, :allow_read_prefs => true)
+      create(:user_preference, :user => user, :k => "key", :v => "value")
+
+      # Hack together an oauth request - an alternative would be to sign the request properly
+      @request.env["oauth.version"] = 1
+      @request.env["oauth.strategies"] = [:token]
+      @request.env["oauth.token"] = token
+
+      get :read_one, :params => { :preference_key => "key" }
+      assert_response :success
+    end
+
+    # Ensure that a valid access token with incorrect capabilities can't be used
+    # to read preferences even, though the owner of that token could read them
+    # by other methods.
+    def test_read_one_using_token_fail
+      user = create(:user)
+      token = create(:access_token, :user => user, :allow_read_prefs => false)
+      create(:user_preference, :user => user, :k => "key", :v => "value")
+      @request.env["oauth.version"] = 1
+      @request.env["oauth.strategies"] = [:token]
+      @request.env["oauth.token"] = token
+
+      get :read_one, :params => { :preference_key => "key" }
+      assert_response :forbidden
+    end
+  end
+end
diff --git a/test/controllers/api/users_controller_test.rb b/test/controllers/api/users_controller_test.rb
new file mode 100644 (file)
index 0000000..5483731
--- /dev/null
@@ -0,0 +1,199 @@
+require "test_helper"
+
+module Api
+  class UsersControllerTest < ActionController::TestCase
+    def setup
+      stub_hostip_requests
+    end
+
+    ##
+    # test all routes which lead to this controller
+    def test_routes
+      assert_routing(
+        { :path => "/api/0.6/user/1", :method => :get },
+        { :controller => "api/users", :action => "api_read", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/user/details", :method => :get },
+        { :controller => "api/users", :action => "api_details" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/user/gpx_files", :method => :get },
+        { :controller => "api/users", :action => "api_gpx_files" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/users", :method => :get },
+        { :controller => "api/users", :action => "api_users" }
+      )
+    end
+
+    def test_api_read
+      user = create(:user, :description => "test", :terms_agreed => Date.yesterday)
+      # check that a visible user is returned properly
+      get :api_read, :params => { :id => user.id }
+      assert_response :success
+      assert_equal "text/xml", response.content_type
+
+      # check the data that is returned
+      assert_select "description", :count => 1, :text => "test"
+      assert_select "contributor-terms", :count => 1 do
+        assert_select "[agreed='true']"
+      end
+      assert_select "img", :count => 0
+      assert_select "roles", :count => 1 do
+        assert_select "role", :count => 0
+      end
+      assert_select "changesets", :count => 1 do
+        assert_select "[count='0']"
+      end
+      assert_select "traces", :count => 1 do
+        assert_select "[count='0']"
+      end
+      assert_select "blocks", :count => 1 do
+        assert_select "received", :count => 1 do
+          assert_select "[count='0'][active='0']"
+        end
+        assert_select "issued", :count => 0
+      end
+
+      # check that we aren't revealing private information
+      assert_select "contributor-terms[pd]", false
+      assert_select "home", false
+      assert_select "languages", false
+      assert_select "messages", false
+
+      # check that a suspended user is not returned
+      get :api_read, :params => { :id => create(:user, :suspended).id }
+      assert_response :gone
+
+      # check that a deleted user is not returned
+      get :api_read, :params => { :id => create(:user, :deleted).id }
+      assert_response :gone
+
+      # check that a non-existent user is not returned
+      get :api_read, :params => { :id => 0 }
+      assert_response :not_found
+    end
+
+    def test_api_details
+      user = create(:user, :description => "test", :terms_agreed => Date.yesterday, :home_lat => 12.1, :home_lon => 12.1, :languages => ["en"])
+      create(:message, :read, :recipient => user)
+      create(:message, :sender => user)
+
+      # check that nothing is returned when not logged in
+      get :api_details
+      assert_response :unauthorized
+
+      # check that we get a response when logged in
+      basic_authorization user.email, "test"
+      get :api_details
+      assert_response :success
+      assert_equal "text/xml", response.content_type
+
+      # check the data that is returned
+      assert_select "description", :count => 1, :text => "test"
+      assert_select "contributor-terms", :count => 1 do
+        assert_select "[agreed='true'][pd='false']"
+      end
+      assert_select "img", :count => 0
+      assert_select "roles", :count => 1 do
+        assert_select "role", :count => 0
+      end
+      assert_select "changesets", :count => 1 do
+        assert_select "[count='0']", :count => 1
+      end
+      assert_select "traces", :count => 1 do
+        assert_select "[count='0']", :count => 1
+      end
+      assert_select "blocks", :count => 1 do
+        assert_select "received", :count => 1 do
+          assert_select "[count='0'][active='0']"
+        end
+        assert_select "issued", :count => 0
+      end
+      assert_select "home", :count => 1 do
+        assert_select "[lat='12.1'][lon='12.1'][zoom='3']"
+      end
+      assert_select "languages", :count => 1 do
+        assert_select "lang", :count => 1, :text => "en"
+      end
+      assert_select "messages", :count => 1 do
+        assert_select "received", :count => 1 do
+          assert_select "[count='1'][unread='0']"
+        end
+        assert_select "sent", :count => 1 do
+          assert_select "[count='1']"
+        end
+      end
+    end
+
+    def test_api_users
+      user1 = create(:user, :description => "test1", :terms_agreed => Date.yesterday)
+      user2 = create(:user, :description => "test2", :terms_agreed => Date.yesterday)
+      user3 = create(:user, :description => "test3", :terms_agreed => Date.yesterday)
+
+      get :api_users, :params => { :users => user1.id }
+      assert_response :success
+      assert_equal "text/xml", response.content_type
+      assert_select "user", :count => 1 do
+        assert_select "user[id='#{user1.id}']", :count => 1
+        assert_select "user[id='#{user2.id}']", :count => 0
+        assert_select "user[id='#{user3.id}']", :count => 0
+      end
+
+      get :api_users, :params => { :users => user2.id }
+      assert_response :success
+      assert_equal "text/xml", response.content_type
+      assert_select "user", :count => 1 do
+        assert_select "user[id='#{user1.id}']", :count => 0
+        assert_select "user[id='#{user2.id}']", :count => 1
+        assert_select "user[id='#{user3.id}']", :count => 0
+      end
+
+      get :api_users, :params => { :users => "#{user1.id},#{user3.id}" }
+      assert_response :success
+      assert_equal "text/xml", response.content_type
+      assert_select "user", :count => 2 do
+        assert_select "user[id='#{user1.id}']", :count => 1
+        assert_select "user[id='#{user2.id}']", :count => 0
+        assert_select "user[id='#{user3.id}']", :count => 1
+      end
+
+      get :api_users, :params => { :users => create(:user, :suspended).id }
+      assert_response :not_found
+
+      get :api_users, :params => { :users => create(:user, :deleted).id }
+      assert_response :not_found
+
+      get :api_users, :params => { :users => 0 }
+      assert_response :not_found
+    end
+
+    def test_api_gpx_files
+      user = create(:user)
+      trace1 = create(:trace, :user => user) do |trace|
+        create(:tracetag, :trace => trace, :tag => "London")
+      end
+      trace2 = create(:trace, :user => user) do |trace|
+        create(:tracetag, :trace => trace, :tag => "Birmingham")
+      end
+      # check that nothing is returned when not logged in
+      get :api_gpx_files
+      assert_response :unauthorized
+
+      # check that we get a response when logged in
+      basic_authorization user.email, "test"
+      get :api_gpx_files
+      assert_response :success
+      assert_equal "application/xml", response.content_type
+
+      # check the data that is returned
+      assert_select "gpx_file[id='#{trace1.id}']", 1 do
+        assert_select "tag", "London"
+      end
+      assert_select "gpx_file[id='#{trace2.id}']", 1 do
+        assert_select "tag", "Birmingham"
+      end
+    end
+  end
+end
diff --git a/test/controllers/api/ways_controller_test.rb b/test/controllers/api/ways_controller_test.rb
new file mode 100644 (file)
index 0000000..c390e8b
--- /dev/null
@@ -0,0 +1,754 @@
+require "test_helper"
+
+module Api
+  class WaysControllerTest < ActionController::TestCase
+    ##
+    # test all routes which lead to this controller
+    def test_routes
+      assert_routing(
+        { :path => "/api/0.6/way/create", :method => :put },
+        { :controller => "api/ways", :action => "create" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/way/1/full", :method => :get },
+        { :controller => "api/ways", :action => "full", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/way/1", :method => :get },
+        { :controller => "api/ways", :action => "show", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/way/1", :method => :put },
+        { :controller => "api/ways", :action => "update", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/way/1", :method => :delete },
+        { :controller => "api/ways", :action => "delete", :id => "1" }
+      )
+      assert_routing(
+        { :path => "/api/0.6/ways", :method => :get },
+        { :controller => "api/ways", :action => "index" }
+      )
+    end
+
+    # -------------------------------------
+    # Test showing ways.
+    # -------------------------------------
+
+    def test_show
+      # check that a visible way is returned properly
+      get :show, :params => { :id => create(:way).id }
+      assert_response :success
+
+      # check that an invisible way is not returned
+      get :show, :params => { :id => create(:way, :deleted).id }
+      assert_response :gone
+
+      # check chat a non-existent way is not returned
+      get :show, :params => { :id => 0 }
+      assert_response :not_found
+    end
+
+    ##
+    # check the "full" mode
+    def test_full
+      Way.all.each do |way|
+        get :full, :params => { :id => way.id }
+
+        # full call should say "gone" for non-visible ways...
+        unless way.visible
+          assert_response :gone
+          next
+        end
+
+        # otherwise it should say success
+        assert_response :success
+
+        # Check the way is correctly returned
+        assert_select "osm way[id='#{way.id}'][version='#{way.version}'][visible='#{way.visible}']", 1
+
+        # check that each node in the way appears once in the output as a
+        # reference and as the node element.
+        way.nodes.each do |n|
+          count = (way.nodes - (way.nodes - [n])).length
+          assert_select "osm way nd[ref='#{n.id}']", count
+          assert_select "osm node[id='#{n.id}'][version='#{n.version}'][lat='#{format('%.7f', n.lat)}'][lon='#{format('%.7f', n.lon)}']", 1
+        end
+      end
+    end
+
+    ##
+    # test fetching multiple ways
+    def test_index
+      way1 = create(:way)
+      way2 = create(:way, :deleted)
+      way3 = create(:way)
+      way4 = create(:way)
+
+      # check error when no parameter provided
+      get :index
+      assert_response :bad_request
+
+      # check error when no parameter value provided
+      get :index, :params => { :ways => "" }
+      assert_response :bad_request
+
+      # test a working call
+      get :index, :params => { :ways => "#{way1.id},#{way2.id},#{way3.id},#{way4.id}" }
+      assert_response :success
+      assert_select "osm" do
+        assert_select "way", :count => 4
+        assert_select "way[id='#{way1.id}'][visible='true']", :count => 1
+        assert_select "way[id='#{way2.id}'][visible='false']", :count => 1
+        assert_select "way[id='#{way3.id}'][visible='true']", :count => 1
+        assert_select "way[id='#{way4.id}'][visible='true']", :count => 1
+      end
+
+      # check error when a non-existent way is included
+      get :index, :params => { :ways => "#{way1.id},#{way2.id},#{way3.id},#{way4.id},0" }
+      assert_response :not_found
+    end
+
+    # -------------------------------------
+    # Test simple way creation.
+    # -------------------------------------
+
+    def test_create
+      node1 = create(:node)
+      node2 = create(:node)
+      private_user = create(:user, :data_public => false)
+      private_changeset = create(:changeset, :user => private_user)
+      user = create(:user)
+      changeset = create(:changeset, :user => user)
+
+      ## First check that it fails when creating a way using a non-public user
+      basic_authorization private_user.email, "test"
+
+      # use the first user's open changeset
+      changeset_id = private_changeset.id
+
+      # create a way with pre-existing nodes
+      xml = "<osm><way changeset='#{changeset_id}'>" \
+            "<nd ref='#{node1.id}'/><nd ref='#{node2.id}'/>" \
+            "<tag k='test' v='yes' /></way></osm>"
+      put :create, :body => xml
+      # hope for failure
+      assert_response :forbidden,
+                      "way upload did not return forbidden status"
+
+      ## Now use a public user
+      basic_authorization user.email, "test"
+
+      # use the first user's open changeset
+      changeset_id = changeset.id
+
+      # create a way with pre-existing nodes
+      xml = "<osm><way changeset='#{changeset_id}'>" \
+            "<nd ref='#{node1.id}'/><nd ref='#{node2.id}'/>" \
+            "<tag k='test' v='yes' /></way></osm>"
+      put :create, :body => xml
+      # hope for success
+      assert_response :success,
+                      "way upload did not return success status"
+      # read id of created way and search for it
+      wayid = @response.body
+      checkway = Way.find(wayid)
+      assert_not_nil checkway,
+                     "uploaded way not found in data base after upload"
+      # compare values
+      assert_equal checkway.nds.length, 2,
+                   "saved way does not contain exactly one node"
+      assert_equal checkway.nds[0], node1.id,
+                   "saved way does not contain the right node on pos 0"
+      assert_equal checkway.nds[1], node2.id,
+                   "saved way does not contain the right node on pos 1"
+      assert_equal checkway.changeset_id, changeset_id,
+                   "saved way does not belong to the correct changeset"
+      assert_equal user.id, checkway.changeset.user_id,
+                   "saved way does not belong to user that created it"
+      assert_equal true, checkway.visible,
+                   "saved way is not visible"
+    end
+
+    # -------------------------------------
+    # Test creating some invalid ways.
+    # -------------------------------------
+
+    def test_create_invalid
+      node = create(:node)
+      private_user = create(:user, :data_public => false)
+      private_open_changeset = create(:changeset, :user => private_user)
+      private_closed_changeset = create(:changeset, :closed, :user => private_user)
+      user = create(:user)
+      open_changeset = create(:changeset, :user => user)
+      closed_changeset = create(:changeset, :closed, :user => user)
+
+      ## First test with a private user to make sure that they are not authorized
+      basic_authorization private_user.email, "test"
+
+      # use the first user's open changeset
+      # create a way with non-existing node
+      xml = "<osm><way changeset='#{private_open_changeset.id}'>" \
+            "<nd ref='0'/><tag k='test' v='yes' /></way></osm>"
+      put :create, :body => xml
+      # expect failure
+      assert_response :forbidden,
+                      "way upload with invalid node using a private user did not return 'forbidden'"
+
+      # create a way with no nodes
+      xml = "<osm><way changeset='#{private_open_changeset.id}'>" \
+            "<tag k='test' v='yes' /></way></osm>"
+      put :create, :body => xml
+      # expect failure
+      assert_response :forbidden,
+                      "way upload with no node using a private userdid not return 'forbidden'"
+
+      # create a way inside a closed changeset
+      xml = "<osm><way changeset='#{private_closed_changeset.id}'>" \
+            "<nd ref='#{node.id}'/></way></osm>"
+      put :create, :body => xml
+      # expect failure
+      assert_response :forbidden,
+                      "way upload to closed changeset with a private user did not return 'forbidden'"
+
+      ## Now test with a public user
+      basic_authorization user.email, "test"
+
+      # use the first user's open changeset
+      # create a way with non-existing node
+      xml = "<osm><way changeset='#{open_changeset.id}'>" \
+            "<nd ref='0'/><tag k='test' v='yes' /></way></osm>"
+      put :create, :body => xml
+      # expect failure
+      assert_response :precondition_failed,
+                      "way upload with invalid node did not return 'precondition failed'"
+      assert_equal "Precondition failed: Way  requires the nodes with id in (0), which either do not exist, or are not visible.", @response.body
+
+      # create a way with no nodes
+      xml = "<osm><way changeset='#{open_changeset.id}'>" \
+            "<tag k='test' v='yes' /></way></osm>"
+      put :create, :body => xml
+      # expect failure
+      assert_response :precondition_failed,
+                      "way upload with no node did not return 'precondition failed'"
+      assert_equal "Precondition failed: Cannot create way: data is invalid.", @response.body
+
+      # create a way inside a closed changeset
+      xml = "<osm><way changeset='#{closed_changeset.id}'>" \
+            "<nd ref='#{node.id}'/></way></osm>"
+      put :create, :body => xml
+      # expect failure
+      assert_response :conflict,
+                      "way upload to closed changeset did not return 'conflict'"
+
+      # create a way with a tag which is too long
+      xml = "<osm><way changeset='#{open_changeset.id}'>" \
+            "<nd ref='#{node.id}'/>" \
+            "<tag k='foo' v='#{'x' * 256}'/>" \
+            "</way></osm>"
+      put :create, :body => xml
+      # expect failure
+      assert_response :bad_request,
+                      "way upload to with too long tag did not return 'bad_request'"
+    end
+
+    # -------------------------------------
+    # Test deleting ways.
+    # -------------------------------------
+
+    def test_delete
+      private_user = create(:user, :data_public => false)
+      private_open_changeset = create(:changeset, :user => private_user)
+      private_closed_changeset = create(:changeset, :closed, :user => private_user)
+      private_way = create(:way, :changeset => private_open_changeset)
+      private_deleted_way = create(:way, :deleted, :changeset => private_open_changeset)
+      private_used_way = create(:way, :changeset => private_open_changeset)
+      create(:relation_member, :member => private_used_way)
+      user = create(:user)
+      open_changeset = create(:changeset, :user => user)
+      closed_changeset = create(:changeset, :closed, :user => user)
+      way = create(:way, :changeset => open_changeset)
+      deleted_way = create(:way, :deleted, :changeset => open_changeset)
+      used_way = create(:way, :changeset => open_changeset)
+      relation_member = create(:relation_member, :member => used_way)
+      relation = relation_member.relation
+
+      # first try to delete way without auth
+      delete :delete, :params => { :id => way.id }
+      assert_response :unauthorized
+
+      # now set auth using the private user
+      basic_authorization private_user.email, "test"
+
+      # this shouldn't work as with the 0.6 api we need pay load to delete
+      delete :delete, :params => { :id => private_way.id }
+      assert_response :forbidden
+
+      # Now try without having a changeset
+      xml = "<osm><way id='#{private_way.id}'/></osm>"
+      delete :delete, :params => { :id => private_way.id }, :body => xml.to_s
+      assert_response :forbidden
+
+      # try to delete with an invalid (closed) changeset
+      xml = update_changeset(private_way.to_xml, private_closed_changeset.id)
+      delete :delete, :params => { :id => private_way.id }, :body => xml.to_s
+      assert_response :forbidden
+
+      # try to delete with an invalid (non-existent) changeset
+      xml = update_changeset(private_way.to_xml, 0)
+      delete :delete, :params => { :id => private_way.id }, :body => xml.to_s
+      assert_response :forbidden
+
+      # Now try with a valid changeset
+      xml = private_way.to_xml
+      delete :delete, :params => { :id => private_way.id }, :body => xml.to_s
+      assert_response :forbidden
+
+      # check the returned value - should be the new version number
+      # valid delete should return the new version number, which should
+      # be greater than the old version number
+      # assert @response.body.to_i > current_ways(:visible_way).version,
+      #   "delete request should return a new version number for way"
+
+      # this won't work since the way is already deleted
+      xml = private_deleted_way.to_xml
+      delete :delete, :params => { :id => private_deleted_way.id }, :body => xml.to_s
+      assert_response :forbidden
+
+      # this shouldn't work as the way is used in a relation
+      xml = private_used_way.to_xml
+      delete :delete, :params => { :id => private_used_way.id }, :body => xml.to_s
+      assert_response :forbidden,
+                      "shouldn't be able to delete a way used in a relation (#{@response.body}), when done by a private user"
+
+      # this won't work since the way never existed
+      delete :delete, :params => { :id => 0 }
+      assert_response :forbidden
+
+      ### Now check with a public user
+      # now set auth
+      basic_authorization user.email, "test"
+
+      # this shouldn't work as with the 0.6 api we need pay load to delete
+      delete :delete, :params => { :id => way.id }
+      assert_response :bad_request
+
+      # Now try without having a changeset
+      xml = "<osm><way id='#{way.id}'/></osm>"
+      delete :delete, :params => { :id => way.id }, :body => xml.to_s
+      assert_response :bad_request
+
+      # try to delete with an invalid (closed) changeset
+      xml = update_changeset(way.to_xml, closed_changeset.id)
+      delete :delete, :params => { :id => way.id }, :body => xml.to_s
+      assert_response :conflict
+
+      # try to delete with an invalid (non-existent) changeset
+      xml = update_changeset(way.to_xml, 0)
+      delete :delete, :params => { :id => way.id }, :body => xml.to_s
+      assert_response :conflict
+
+      # Now try with a valid changeset
+      xml = way.to_xml
+      delete :delete, :params => { :id => way.id }, :body => xml.to_s
+      assert_response :success
+
+      # check the returned value - should be the new version number
+      # valid delete should return the new version number, which should
+      # be greater than the old version number
+      assert @response.body.to_i > way.version,
+             "delete request should return a new version number for way"
+
+      # this won't work since the way is already deleted
+      xml = deleted_way.to_xml
+      delete :delete, :params => { :id => deleted_way.id }, :body => xml.to_s
+      assert_response :gone
+
+      # this shouldn't work as the way is used in a relation
+      xml = used_way.to_xml
+      delete :delete, :params => { :id => used_way.id }, :body => xml.to_s
+      assert_response :precondition_failed,
+                      "shouldn't be able to delete a way used in a relation (#{@response.body})"
+      assert_equal "Precondition failed: Way #{used_way.id} is still used by relations #{relation.id}.", @response.body
+
+      # this won't work since the way never existed
+      delete :delete, :params => { :id => 0 }
+      assert_response :not_found
+    end
+
+    ##
+    # tests whether the API works and prevents incorrect use while trying
+    # to update ways.
+    def test_update
+      private_user = create(:user, :data_public => false)
+      private_way = create(:way, :changeset => create(:changeset, :user => private_user))
+      user = create(:user)
+      way = create(:way, :changeset => create(:changeset, :user => user))
+      node = create(:node)
+      create(:way_node, :way => private_way, :node => node)
+      create(:way_node, :way => way, :node => node)
+
+      ## First test with no user credentials
+      # try and update a way without authorisation
+      xml = way.to_xml
+      put :update, :params => { :id => way.id }, :body => xml.to_s
+      assert_response :unauthorized
+
+      ## Second test with the private user
+
+      # setup auth
+      basic_authorization private_user.email, "test"
+
+      ## trying to break changesets
+
+      # try and update in someone else's changeset
+      xml = update_changeset(private_way.to_xml,
+                             create(:changeset).id)
+      put :update, :params => { :id => private_way.id }, :body => xml.to_s
+      assert_require_public_data "update with other user's changeset should be forbidden when date isn't public"
+
+      # try and update in a closed changeset
+      xml = update_changeset(private_way.to_xml,
+                             create(:changeset, :closed, :user => private_user).id)
+      put :update, :params => { :id => private_way.id }, :body => xml.to_s
+      assert_require_public_data "update with closed changeset should be forbidden, when data isn't public"
+
+      # try and update in a non-existant changeset
+      xml = update_changeset(private_way.to_xml, 0)
+      put :update, :params => { :id => private_way.id }, :body => xml.to_s
+      assert_require_public_data("update with changeset=0 should be forbidden, when data isn't public")
+
+      ## try and submit invalid updates
+      xml = xml_replace_node(private_way.to_xml, node.id, 9999)
+      put :update, :params => { :id => private_way.id }, :body => xml.to_s
+      assert_require_public_data "way with non-existent node should be forbidden, when data isn't public"
+
+      xml = xml_replace_node(private_way.to_xml, node.id, create(:node, :deleted).id)
+      put :update, :params => { :id => private_way.id }, :body => xml.to_s
+      assert_require_public_data "way with deleted node should be forbidden, when data isn't public"
+
+      ## finally, produce a good request which will still not work
+      xml = private_way.to_xml
+      put :update, :params => { :id => private_way.id }, :body => xml.to_s
+      assert_require_public_data "should have failed with a forbidden when data isn't public"
+
+      ## Finally test with the public user
+
+      # setup auth
+      basic_authorization user.email, "test"
+
+      ## trying to break changesets
+
+      # try and update in someone else's changeset
+      xml = update_changeset(way.to_xml,
+                             create(:changeset).id)
+      put :update, :params => { :id => way.id }, :body => xml.to_s
+      assert_response :conflict, "update with other user's changeset should be rejected"
+
+      # try and update in a closed changeset
+      xml = update_changeset(way.to_xml,
+                             create(:changeset, :closed, :user => user).id)
+      put :update, :params => { :id => way.id }, :body => xml.to_s
+      assert_response :conflict, "update with closed changeset should be rejected"
+
+      # try and update in a non-existant changeset
+      xml = update_changeset(way.to_xml, 0)
+      put :update, :params => { :id => way.id }, :body => xml.to_s
+      assert_response :conflict, "update with changeset=0 should be rejected"
+
+      ## try and submit invalid updates
+      xml = xml_replace_node(way.to_xml, node.id, 9999)
+      put :update, :params => { :id => way.id }, :body => xml.to_s
+      assert_response :precondition_failed, "way with non-existent node should be rejected"
+
+      xml = xml_replace_node(way.to_xml, node.id, create(:node, :deleted).id)
+      put :update, :params => { :id => way.id }, :body => xml.to_s
+      assert_response :precondition_failed, "way with deleted node should be rejected"
+
+      ## next, attack the versioning
+      current_way_version = way.version
+
+      # try and submit a version behind
+      xml = xml_attr_rewrite(way.to_xml,
+                             "version", current_way_version - 1)
+      put :update, :params => { :id => way.id }, :body => xml.to_s
+      assert_response :conflict, "should have failed on old version number"
+
+      # try and submit a version ahead
+      xml = xml_attr_rewrite(way.to_xml,
+                             "version", current_way_version + 1)
+      put :update, :params => { :id => way.id }, :body => xml.to_s
+      assert_response :conflict, "should have failed on skipped version number"
+
+      # try and submit total crap in the version field
+      xml = xml_attr_rewrite(way.to_xml,
+                             "version", "p1r4t3s!")
+      put :update, :params => { :id => way.id }, :body => xml.to_s
+      assert_response :conflict,
+                      "should not be able to put 'p1r4at3s!' in the version field"
+
+      ## try an update with the wrong ID
+      xml = create(:way).to_xml
+      put :update, :params => { :id => way.id }, :body => xml.to_s
+      assert_response :bad_request,
+                      "should not be able to update a way with a different ID from the XML"
+
+      ## try an update with a minimal valid XML doc which isn't a well-formed OSM doc.
+      xml = "<update/>"
+      put :update, :params => { :id => way.id }, :body => xml.to_s
+      assert_response :bad_request,
+                      "should not be able to update a way with non-OSM XML doc."
+
+      ## finally, produce a good request which should work
+      xml = way.to_xml
+      put :update, :params => { :id => way.id }, :body => xml.to_s
+      assert_response :success, "a valid update request failed"
+    end
+
+    # ------------------------------------------------------------
+    # test tags handling
+    # ------------------------------------------------------------
+
+    ##
+    # Try adding a new tag to a way
+    def test_add_tags
+      private_user = create(:user, :data_public => false)
+      private_way = create(:way_with_nodes, :nodes_count => 2, :changeset => create(:changeset, :user => private_user))
+      user = create(:user)
+      way = create(:way_with_nodes, :nodes_count => 2, :changeset => create(:changeset, :user => user))
+
+      ## Try with the non-public user
+      # setup auth
+      basic_authorization private_user.email, "test"
+
+      # add an identical tag to the way
+      tag_xml = XML::Node.new("tag")
+      tag_xml["k"] = "new"
+      tag_xml["v"] = "yes"
+
+      # add the tag into the existing xml
+      way_xml = private_way.to_xml
+      way_xml.find("//osm/way").first << tag_xml
+
+      # try and upload it
+      put :update, :params => { :id => private_way.id }, :body => way_xml.to_s
+      assert_response :forbidden,
+                      "adding a duplicate tag to a way for a non-public should fail with 'forbidden'"
+
+      ## Now try with the public user
+      # setup auth
+      basic_authorization user.email, "test"
+
+      # add an identical tag to the way
+      tag_xml = XML::Node.new("tag")
+      tag_xml["k"] = "new"
+      tag_xml["v"] = "yes"
+
+      # add the tag into the existing xml
+      way_xml = way.to_xml
+      way_xml.find("//osm/way").first << tag_xml
+
+      # try and upload it
+      put :update, :params => { :id => way.id }, :body => way_xml.to_s
+      assert_response :success,
+                      "adding a new tag to a way should succeed"
+      assert_equal way.version + 1, @response.body.to_i
+    end
+
+    ##
+    # Try adding a duplicate of an existing tag to a way
+    def test_add_duplicate_tags
+      private_user = create(:user, :data_public => false)
+      private_way = create(:way, :changeset => create(:changeset, :user => private_user))
+      private_existing_tag = create(:way_tag, :way => private_way)
+      user = create(:user)
+      way = create(:way, :changeset => create(:changeset, :user => user))
+      existing_tag = create(:way_tag, :way => way)
+
+      ## Try with the non-public user
+      # setup auth
+      basic_authorization private_user.email, "test"
+
+      # add an identical tag to the way
+      tag_xml = XML::Node.new("tag")
+      tag_xml["k"] = private_existing_tag.k
+      tag_xml["v"] = private_existing_tag.v
+
+      # add the tag into the existing xml
+      way_xml = private_way.to_xml
+      way_xml.find("//osm/way").first << tag_xml
+
+      # try and upload it
+      put :update, :params => { :id => private_way.id }, :body => way_xml.to_s
+      assert_response :forbidden,
+                      "adding a duplicate tag to a way for a non-public should fail with 'forbidden'"
+
+      ## Now try with the public user
+      # setup auth
+      basic_authorization user.email, "test"
+
+      # add an identical tag to the way
+      tag_xml = XML::Node.new("tag")
+      tag_xml["k"] = existing_tag.k
+      tag_xml["v"] = existing_tag.v
+
+      # add the tag into the existing xml
+      way_xml = way.to_xml
+      way_xml.find("//osm/way").first << tag_xml
+
+      # try and upload it
+      put :update, :params => { :id => way.id }, :body => way_xml.to_s
+      assert_response :bad_request,
+                      "adding a duplicate tag to a way should fail with 'bad request'"
+      assert_equal "Element way/#{way.id} has duplicate tags with key #{existing_tag.k}", @response.body
+    end
+
+    ##
+    # Try adding a new duplicate tags to a way
+    def test_new_duplicate_tags
+      private_user = create(:user, :data_public => false)
+      private_way = create(:way, :changeset => create(:changeset, :user => private_user))
+      user = create(:user)
+      way = create(:way, :changeset => create(:changeset, :user => user))
+
+      ## First test with the non-public user so should be rejected
+      # setup auth
+      basic_authorization private_user.email, "test"
+
+      # create duplicate tag
+      tag_xml = XML::Node.new("tag")
+      tag_xml["k"] = "i_am_a_duplicate"
+      tag_xml["v"] = "foobar"
+
+      # add the tag into the existing xml
+      way_xml = private_way.to_xml
+
+      # add two copies of the tag
+      way_xml.find("//osm/way").first << tag_xml.copy(true) << tag_xml
+
+      # try and upload it
+      put :update, :params => { :id => private_way.id }, :body => way_xml.to_s
+      assert_response :forbidden,
+                      "adding new duplicate tags to a way using a non-public user should fail with 'forbidden'"
+
+      ## Now test with the public user
+      # setup auth
+      basic_authorization user.email, "test"
+
+      # create duplicate tag
+      tag_xml = XML::Node.new("tag")
+      tag_xml["k"] = "i_am_a_duplicate"
+      tag_xml["v"] = "foobar"
+
+      # add the tag into the existing xml
+      way_xml = way.to_xml
+
+      # add two copies of the tag
+      way_xml.find("//osm/way").first << tag_xml.copy(true) << tag_xml
+
+      # try and upload it
+      put :update, :params => { :id => way.id }, :body => way_xml.to_s
+      assert_response :bad_request,
+                      "adding new duplicate tags to a way should fail with 'bad request'"
+      assert_equal "Element way/#{way.id} has duplicate tags with key i_am_a_duplicate", @response.body
+    end
+
+    ##
+    # Try adding a new duplicate tags to a way.
+    # But be a bit subtle - use unicode decoding ambiguities to use different
+    # binary strings which have the same decoding.
+    def test_invalid_duplicate_tags
+      private_user = create(:user, :data_public => false)
+      private_changeset = create(:changeset, :user => private_user)
+      user = create(:user)
+      changeset = create(:changeset, :user => user)
+
+      ## First make sure that you can't with a non-public user
+      # setup auth
+      basic_authorization private_user.email, "test"
+
+      # add the tag into the existing xml
+      way_str = "<osm><way changeset='#{private_changeset.id}'>"
+      way_str << "<tag k='addr:housenumber' v='1'/>"
+      way_str << "<tag k='addr:housenumber' v='2'/>"
+      way_str << "</way></osm>"
+
+      # try and upload it
+      put :create, :body => way_str
+      assert_response :forbidden,
+                      "adding new duplicate tags to a way with a non-public user should fail with 'forbidden'"
+
+      ## Now do it with a public user
+      # setup auth
+      basic_authorization user.email, "test"
+
+      # add the tag into the existing xml
+      way_str = "<osm><way changeset='#{changeset.id}'>"
+      way_str << "<tag k='addr:housenumber' v='1'/>"
+      way_str << "<tag k='addr:housenumber' v='2'/>"
+      way_str << "</way></osm>"
+
+      # try and upload it
+      put :create, :body => way_str
+      assert_response :bad_request,
+                      "adding new duplicate tags to a way should fail with 'bad request'"
+      assert_equal "Element way/ has duplicate tags with key addr:housenumber", @response.body
+    end
+
+    ##
+    # test that a call to ways_for_node returns all ways that contain the node
+    # and none that don't.
+    def test_ways_for_node
+      node = create(:node)
+      way1 = create(:way)
+      way2 = create(:way)
+      create(:way_node, :way => way1, :node => node)
+      create(:way_node, :way => way2, :node => node)
+      # create an unrelated way
+      create(:way_with_nodes, :nodes_count => 2)
+      # create a way which used to use the node
+      way3_v1 = create(:old_way, :version => 1)
+      _way3_v2 = create(:old_way, :current_way => way3_v1.current_way, :version => 2)
+      create(:old_way_node, :old_way => way3_v1, :node => node)
+
+      get :ways_for_node, :params => { :id => node.id }
+      assert_response :success
+      ways_xml = XML::Parser.string(@response.body).parse
+      assert_not_nil ways_xml, "failed to parse ways_for_node response"
+
+      # check that the set of IDs match expectations
+      expected_way_ids = [way1.id,
+                          way2.id]
+      found_way_ids = ways_xml.find("//osm/way").collect { |w| w["id"].to_i }
+      assert_equal expected_way_ids.sort, found_way_ids.sort,
+                   "expected ways for node #{node.id} did not match found"
+
+      # check the full ways to ensure we're not missing anything
+      expected_way_ids.each do |id|
+        way_xml = ways_xml.find("//osm/way[@id='#{id}']").first
+        assert_ways_are_equal(Way.find(id),
+                              Way.from_xml_node(way_xml))
+      end
+    end
+
+    ##
+    # update the changeset_id of a way element
+    def update_changeset(xml, changeset_id)
+      xml_attr_rewrite(xml, "changeset", changeset_id)
+    end
+
+    ##
+    # update an attribute in the way element
+    def xml_attr_rewrite(xml, name, value)
+      xml.find("//osm/way").first[name] = value.to_s
+      xml
+    end
+
+    ##
+    # replace a node in a way element
+    def xml_replace_node(xml, old_node, new_node)
+      xml.find("//osm/way/nd[@ref='#{old_node}']").first["ref"] = new_node.to_s
+      xml
+    end
+  end
+end
index 33ee1deb522f6ea492d93e3d8d7410e7398740d6..2d13bd92bbbc614d1ecd6d9d267569d234c0167d 100644 (file)
@@ -4,18 +4,6 @@ class ChangesetCommentsControllerTest < ActionController::TestCase
   ##
   # test all routes which lead to this controller
   def test_routes
-    assert_routing(
-      { :path => "/api/0.6/changeset/1/comment", :method => :post },
-      { :controller => "changeset_comments", :action => "create", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/changeset/comment/1/hide", :method => :post },
-      { :controller => "changeset_comments", :action => "destroy", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/changeset/comment/1/unhide", :method => :post },
-      { :controller => "changeset_comments", :action => "restore", :id => "1" }
-    )
     assert_routing(
       { :path => "/changeset/1/comments/feed", :method => :get },
       { :controller => "changeset_comments", :action => "index", :id => "1", :format => "rss" }
@@ -26,185 +14,6 @@ class ChangesetCommentsControllerTest < ActionController::TestCase
     )
   end
 
-  ##
-  # create comment success
-  def test_create_comment_success
-    user = create(:user)
-    user2 = create(:user)
-    private_user = create(:user, :data_public => false)
-    suspended_user = create(:user, :suspended)
-    deleted_user = create(:user, :deleted)
-    private_user_closed_changeset = create(:changeset, :closed, :user => private_user)
-
-    basic_authorization user.email, "test"
-
-    assert_difference "ChangesetComment.count", 1 do
-      assert_no_difference "ActionMailer::Base.deliveries.size" do
-        perform_enqueued_jobs do
-          post :create, :params => { :id => private_user_closed_changeset.id, :text => "This is a comment" }
-        end
-      end
-    end
-    assert_response :success
-
-    changeset = create(:changeset, :closed, :user => private_user)
-    changeset.subscribers.push(private_user)
-    changeset.subscribers.push(user)
-    changeset.subscribers.push(suspended_user)
-    changeset.subscribers.push(deleted_user)
-
-    assert_difference "ChangesetComment.count", 1 do
-      assert_difference "ActionMailer::Base.deliveries.size", 1 do
-        perform_enqueued_jobs do
-          post :create, :params => { :id => changeset.id, :text => "This is a comment" }
-        end
-      end
-    end
-    assert_response :success
-
-    email = ActionMailer::Base.deliveries.first
-    assert_equal 1, email.to.length
-    assert_equal "[OpenStreetMap] #{user.display_name} has commented on one of your changesets", email.subject
-    assert_equal private_user.email, email.to.first
-
-    ActionMailer::Base.deliveries.clear
-
-    basic_authorization user2.email, "test"
-
-    assert_difference "ChangesetComment.count", 1 do
-      assert_difference "ActionMailer::Base.deliveries.size", 2 do
-        perform_enqueued_jobs do
-          post :create, :params => { :id => changeset.id, :text => "This is a comment" }
-        end
-      end
-    end
-    assert_response :success
-
-    email = ActionMailer::Base.deliveries.find { |e| e.to.first == private_user.email }
-    assert_not_nil email
-    assert_equal 1, email.to.length
-    assert_equal "[OpenStreetMap] #{user2.display_name} has commented on one of your changesets", email.subject
-
-    email = ActionMailer::Base.deliveries.find { |e| e.to.first == user.email }
-    assert_not_nil email
-    assert_equal 1, email.to.length
-    assert_equal "[OpenStreetMap] #{user2.display_name} has commented on a changeset you are interested in", email.subject
-
-    ActionMailer::Base.deliveries.clear
-  end
-
-  ##
-  # create comment fail
-  def test_create_comment_fail
-    # unauthorized
-    post :create, :params => { :id => create(:changeset, :closed).id, :text => "This is a comment" }
-    assert_response :unauthorized
-
-    basic_authorization create(:user).email, "test"
-
-    # bad changeset id
-    assert_no_difference "ChangesetComment.count" do
-      post :create, :params => { :id => 999111, :text => "This is a comment" }
-    end
-    assert_response :not_found
-
-    # not closed changeset
-    assert_no_difference "ChangesetComment.count" do
-      post :create, :params => { :id => create(:changeset).id, :text => "This is a comment" }
-    end
-    assert_response :conflict
-
-    # no text
-    assert_no_difference "ChangesetComment.count" do
-      post :create, :params => { :id => create(:changeset, :closed).id }
-    end
-    assert_response :bad_request
-
-    # empty text
-    assert_no_difference "ChangesetComment.count" do
-      post :create, :params => { :id => create(:changeset, :closed).id, :text => "" }
-    end
-    assert_response :bad_request
-  end
-
-  ##
-  # test hide comment fail
-  def test_destroy_comment_fail
-    # unauthorized
-    comment = create(:changeset_comment)
-    assert_equal true, comment.visible
-
-    post :destroy, :params => { :id => comment.id }
-    assert_response :unauthorized
-    assert_equal true, comment.reload.visible
-
-    basic_authorization create(:user).email, "test"
-
-    # not a moderator
-    post :destroy, :params => { :id => comment.id }
-    assert_response :forbidden
-    assert_equal true, comment.reload.visible
-
-    basic_authorization create(:moderator_user).email, "test"
-
-    # bad comment id
-    post :destroy, :params => { :id => 999111 }
-    assert_response :not_found
-    assert_equal true, comment.reload.visible
-  end
-
-  ##
-  # test hide comment succes
-  def test_hide_comment_success
-    comment = create(:changeset_comment)
-    assert_equal true, comment.visible
-
-    basic_authorization create(:moderator_user).email, "test"
-
-    post :destroy, :params => { :id => comment.id }
-    assert_response :success
-    assert_equal false, comment.reload.visible
-  end
-
-  ##
-  # test unhide comment fail
-  def test_restore_comment_fail
-    # unauthorized
-    comment = create(:changeset_comment, :visible => false)
-    assert_equal false, comment.visible
-
-    post :restore, :params => { :id => comment.id }
-    assert_response :unauthorized
-    assert_equal false, comment.reload.visible
-
-    basic_authorization create(:user).email, "test"
-
-    # not a moderator
-    post :restore, :params => { :id => comment.id }
-    assert_response :forbidden
-    assert_equal false, comment.reload.visible
-
-    basic_authorization create(:moderator_user).email, "test"
-
-    # bad comment id
-    post :restore, :params => { :id => 999111 }
-    assert_response :not_found
-    assert_equal false, comment.reload.visible
-  end
-
-  ##
-  # test unhide comment succes
-  def test_unhide_comment_success
-    comment = create(:changeset_comment, :visible => false)
-    assert_equal false, comment.visible
-
-    basic_authorization create(:moderator_user).email, "test"
-
-    post :restore, :params => { :id => comment.id }
-    assert_response :success
-    assert_equal true, comment.reload.visible
-  end
-
   ##
   # test comments feed
   def test_feed
@@ -248,57 +57,4 @@ class ChangesetCommentsControllerTest < ActionController::TestCase
     get :index, :params => { :format => "rss", :limit => 100001 }
     assert_response :bad_request
   end
-
-  # This test ensures that token capabilities behave correctly for a method that
-  # requires the terms to have been agreed.
-  # (This would be better as an integration or system testcase, since the changeset_comment
-  # create method is simply a stand-in for any method that requires terms agreement.
-  # But writing oauth tests is hard, and so it's easier to put in a controller test.)
-  def test_api_write_and_terms_agreed_via_token
-    user = create(:user, :terms_agreed => nil)
-    token = create(:access_token, :user => user, :allow_write_api => true)
-    changeset = create(:changeset, :closed)
-
-    # Hack together an oauth request - an alternative would be to sign the request properly
-    @request.env["oauth.version"] = 1
-    @request.env["oauth.strategies"] = [:token]
-    @request.env["oauth.token"] = token
-
-    assert_difference "ChangesetComment.count", 0 do
-      post :create, :params => { :id => changeset.id, :text => "This is a comment" }
-    end
-    assert_response :forbidden
-
-    # Try again, after agreement with the terms
-    user.terms_agreed = Time.now
-    user.save!
-
-    assert_difference "ChangesetComment.count", 1 do
-      post :create, :params => { :id => changeset.id, :text => "This is a comment" }
-    end
-    assert_response :success
-  end
-
-  # This test does the same as above, but with basic auth, to similarly test that the
-  # abilities take into account terms agreement too.
-  def test_api_write_and_terms_agreed_via_basic_auth
-    user = create(:user, :terms_agreed => nil)
-    changeset = create(:changeset, :closed)
-
-    basic_authorization user.email, "test"
-
-    assert_difference "ChangesetComment.count", 0 do
-      post :create, :params => { :id => changeset.id, :text => "This is a comment" }
-    end
-    assert_response :forbidden
-
-    # Try again, after agreement with the terms
-    user.terms_agreed = Time.now
-    user.save!
-
-    assert_difference "ChangesetComment.count", 1 do
-      post :create, :params => { :id => changeset.id, :text => "This is a comment" }
-    end
-    assert_response :success
-  end
 end
index a3c8947ca6e2eec779aa58152cd249bd559444fe..fad7a97d8387d5e5cc6977fea0f59779accc89f0 100644 (file)
@@ -4,46 +4,6 @@ class ChangesetsControllerTest < ActionController::TestCase
   ##
   # test all routes which lead to this controller
   def test_routes
-    assert_routing(
-      { :path => "/api/0.6/changeset/create", :method => :put },
-      { :controller => "changesets", :action => "create" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/changeset/1/upload", :method => :post },
-      { :controller => "changesets", :action => "upload", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/changeset/1/download", :method => :get },
-      { :controller => "changesets", :action => "download", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/changeset/1/expand_bbox", :method => :post },
-      { :controller => "changesets", :action => "expand_bbox", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/changeset/1", :method => :get },
-      { :controller => "changesets", :action => "show", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/changeset/1/subscribe", :method => :post },
-      { :controller => "changesets", :action => "subscribe", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/changeset/1/unsubscribe", :method => :post },
-      { :controller => "changesets", :action => "unsubscribe", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/changeset/1", :method => :put },
-      { :controller => "changesets", :action => "update", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/changeset/1/close", :method => :put },
-      { :controller => "changesets", :action => "close", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/changesets", :method => :get },
-      { :controller => "changesets", :action => "query" }
-    )
     assert_routing(
       { :path => "/user/name/history", :method => :get },
       { :controller => "changesets", :action => "index", :display_name => "name" }
@@ -70,1758 +30,6 @@ class ChangesetsControllerTest < ActionController::TestCase
     )
   end
 
-  # -----------------------
-  # Test simple changeset creation
-  # -----------------------
-
-  def test_create
-    basic_authorization create(:user, :data_public => false).email, "test"
-    # Create the first user's changeset
-    xml = "<osm><changeset>" \
-          "<tag k='created_by' v='osm test suite checking changesets'/>" \
-          "</changeset></osm>"
-    put :create, :body => xml
-    assert_require_public_data
-
-    basic_authorization create(:user).email, "test"
-    # Create the first user's changeset
-    xml = "<osm><changeset>" \
-          "<tag k='created_by' v='osm test suite checking changesets'/>" \
-          "</changeset></osm>"
-    put :create, :body => xml
-
-    assert_response :success, "Creation of changeset did not return sucess status"
-    newid = @response.body.to_i
-
-    # check end time, should be an hour ahead of creation time
-    cs = Changeset.find(newid)
-    duration = cs.closed_at - cs.created_at
-    # the difference can either be a rational, or a floating point number
-    # of seconds, depending on the code path taken :-(
-    if duration.class == Rational
-      assert_equal Rational(1, 24), duration, "initial idle timeout should be an hour (#{cs.created_at} -> #{cs.closed_at})"
-    else
-      # must be number of seconds...
-      assert_equal 3600, duration.round, "initial idle timeout should be an hour (#{cs.created_at} -> #{cs.closed_at})"
-    end
-
-    # checks if uploader was subscribed
-    assert_equal 1, cs.subscribers.length
-  end
-
-  def test_create_invalid
-    basic_authorization create(:user, :data_public => false).email, "test"
-    xml = "<osm><changeset></osm>"
-    put :create, :body => xml
-    assert_require_public_data
-
-    ## Try the public user
-    basic_authorization create(:user).email, "test"
-    xml = "<osm><changeset></osm>"
-    put :create, :body => xml
-    assert_response :bad_request, "creating a invalid changeset should fail"
-  end
-
-  def test_create_invalid_no_content
-    ## First check with no auth
-    put :create
-    assert_response :unauthorized, "shouldn't be able to create a changeset with no auth"
-
-    ## Now try to with a non-public user
-    basic_authorization create(:user, :data_public => false).email, "test"
-    put :create
-    assert_require_public_data
-
-    ## Try an inactive user
-    basic_authorization create(:user, :pending).email, "test"
-    put :create
-    assert_inactive_user
-
-    ## Now try to use a normal user
-    basic_authorization create(:user).email, "test"
-    put :create
-    assert_response :bad_request, "creating a changeset with no content should fail"
-  end
-
-  def test_create_wrong_method
-    basic_authorization create(:user).email, "test"
-    get :create
-    assert_response :method_not_allowed
-    post :create
-    assert_response :method_not_allowed
-  end
-
-  ##
-  # check that the changeset can be shown and returns the correct
-  # document structure.
-  def test_show
-    changeset_id = create(:changeset).id
-
-    get :show, :params => { :id => changeset_id }
-    assert_response :success, "cannot get first changeset"
-
-    assert_select "osm[version='#{API_VERSION}'][generator='OpenStreetMap server']", 1
-    assert_select "osm>changeset[id='#{changeset_id}']", 1
-    assert_select "osm>changeset>discussion", 0
-
-    get :show, :params => { :id => changeset_id, :include_discussion => true }
-    assert_response :success, "cannot get first changeset with comments"
-
-    assert_select "osm[version='#{API_VERSION}'][generator='OpenStreetMap server']", 1
-    assert_select "osm>changeset[id='#{changeset_id}']", 1
-    assert_select "osm>changeset>discussion", 1
-    assert_select "osm>changeset>discussion>comment", 0
-
-    changeset_id = create(:changeset, :closed).id
-    create_list(:changeset_comment, 3, :changeset_id => changeset_id)
-
-    get :show, :params => { :id => changeset_id, :include_discussion => true }
-    assert_response :success, "cannot get closed changeset with comments"
-
-    assert_select "osm[version='#{API_VERSION}'][generator='OpenStreetMap server']", 1
-    assert_select "osm>changeset[id='#{changeset_id}']", 1
-    assert_select "osm>changeset>discussion", 1
-    assert_select "osm>changeset>discussion>comment", 3
-  end
-
-  ##
-  # check that a changeset that doesn't exist returns an appropriate message
-  def test_show_not_found
-    [0, -32, 233455644, "afg", "213"].each do |id|
-      begin
-        get :show, :params => { :id => id }
-        assert_response :not_found, "should get a not found"
-      rescue ActionController::UrlGenerationError => ex
-        assert_match(/No route matches/, ex.to_s)
-      end
-    end
-  end
-
-  ##
-  # test that the user who opened a change can close it
-  def test_close
-    private_user = create(:user, :data_public => false)
-    private_changeset = create(:changeset, :user => private_user)
-    user = create(:user)
-    changeset = create(:changeset, :user => user)
-
-    ## Try without authentication
-    put :close, :params => { :id => changeset.id }
-    assert_response :unauthorized
-
-    ## Try using the non-public user
-    basic_authorization private_user.email, "test"
-    put :close, :params => { :id => private_changeset.id }
-    assert_require_public_data
-
-    ## The try with the public user
-    basic_authorization user.email, "test"
-
-    cs_id = changeset.id
-    put :close, :params => { :id => cs_id }
-    assert_response :success
-
-    # test that it really is closed now
-    cs = Changeset.find(cs_id)
-    assert_not(cs.is_open?,
-               "changeset should be closed now (#{cs.closed_at} > #{Time.now.getutc}.")
-  end
-
-  ##
-  # test that a different user can't close another user's changeset
-  def test_close_invalid
-    user = create(:user)
-    changeset = create(:changeset)
-
-    basic_authorization user.email, "test"
-
-    put :close, :params => { :id => changeset.id }
-    assert_response :conflict
-    assert_equal "The user doesn't own that changeset", @response.body
-  end
-
-  ##
-  # test that you can't close using another method
-  def test_close_method_invalid
-    user = create(:user)
-    changeset = create(:changeset, :user => user)
-
-    basic_authorization user.email, "test"
-
-    get :close, :params => { :id => changeset.id }
-    assert_response :method_not_allowed
-
-    post :close, :params => { :id => changeset.id }
-    assert_response :method_not_allowed
-  end
-
-  ##
-  # check that you can't close a changeset that isn't found
-  def test_close_not_found
-    cs_ids = [0, -132, "123"]
-
-    # First try to do it with no auth
-    cs_ids.each do |id|
-      begin
-        put :close, :params => { :id => id }
-        assert_response :unauthorized, "Shouldn't be able close the non-existant changeset #{id}, when not authorized"
-      rescue ActionController::UrlGenerationError => ex
-        assert_match(/No route matches/, ex.to_s)
-      end
-    end
-
-    # Now try with auth
-    basic_authorization create(:user).email, "test"
-    cs_ids.each do |id|
-      begin
-        put :close, :params => { :id => id }
-        assert_response :not_found, "The changeset #{id} doesn't exist, so can't be closed"
-      rescue ActionController::UrlGenerationError => ex
-        assert_match(/No route matches/, ex.to_s)
-      end
-    end
-  end
-
-  ##
-  # upload something simple, but valid and check that it can
-  # be read back ok
-  # Also try without auth and another user.
-  def test_upload_simple_valid
-    private_user = create(:user, :data_public => false)
-    private_changeset = create(:changeset, :user => private_user)
-    user = create(:user)
-    changeset = create(:changeset, :user => user)
-
-    node = create(:node)
-    way = create(:way)
-    relation = create(:relation)
-    other_relation = create(:relation)
-    # create some tags, since we test that they are removed later
-    create(:node_tag, :node => node)
-    create(:way_tag, :way => way)
-    create(:relation_tag, :relation => relation)
-
-    ## Try with no auth
-    changeset_id = changeset.id
-
-    # simple diff to change a node, way and relation by removing
-    # their tags
-    diff = <<CHANGESET.strip_heredoc
-      <osmChange>
-       <modify>
-        <node id='#{node.id}' lon='0' lat='0' changeset='#{changeset_id}' version='1'/>
-        <way id='#{way.id}' changeset='#{changeset_id}' version='1'>
-         <nd ref='#{node.id}'/>
-        </way>
-       </modify>
-       <modify>
-        <relation id='#{relation.id}' changeset='#{changeset_id}' version='1'>
-         <member type='way' role='some' ref='#{way.id}'/>
-         <member type='node' role='some' ref='#{node.id}'/>
-         <member type='relation' role='some' ref='#{other_relation.id}'/>
-        </relation>
-       </modify>
-      </osmChange>
-CHANGESET
-
-    # upload it
-    post :upload, :params => { :id => changeset_id }, :body => diff
-    assert_response :unauthorized,
-                    "shouldn't be able to upload a simple valid diff to changeset: #{@response.body}"
-
-    ## Now try with a private user
-    basic_authorization private_user.email, "test"
-    changeset_id = private_changeset.id
-
-    # simple diff to change a node, way and relation by removing
-    # their tags
-    diff = <<CHANGESET.strip_heredoc
-      <osmChange>
-       <modify>
-        <node id='#{node.id}' lon='0' lat='0' changeset='#{changeset_id}' version='1'/>
-        <way id='#{way.id}' changeset='#{changeset_id}' version='1'>
-         <nd ref='#{node.id}'/>
-        </way>
-       </modify>
-       <modify>
-        <relation id='#{relation.id}' changeset='#{changeset_id}' version='1'>
-         <member type='way' role='some' ref='#{way.id}'/>
-         <member type='node' role='some' ref='#{node.id}'/>
-         <member type='relation' role='some' ref='#{other_relation.id}'/>
-        </relation>
-       </modify>
-      </osmChange>
-CHANGESET
-
-    # upload it
-    post :upload, :params => { :id => changeset_id }, :body => diff
-    assert_response :forbidden,
-                    "can't upload a simple valid diff to changeset: #{@response.body}"
-
-    ## Now try with the public user
-    basic_authorization user.email, "test"
-    changeset_id = changeset.id
-
-    # simple diff to change a node, way and relation by removing
-    # their tags
-    diff = <<CHANGESET.strip_heredoc
-      <osmChange>
-       <modify>
-        <node id='#{node.id}' lon='0' lat='0' changeset='#{changeset_id}' version='1'/>
-        <way id='#{way.id}' changeset='#{changeset_id}' version='1'>
-         <nd ref='#{node.id}'/>
-        </way>
-       </modify>
-       <modify>
-        <relation id='#{relation.id}' changeset='#{changeset_id}' version='1'>
-         <member type='way' role='some' ref='#{way.id}'/>
-         <member type='node' role='some' ref='#{node.id}'/>
-         <member type='relation' role='some' ref='#{other_relation.id}'/>
-        </relation>
-       </modify>
-      </osmChange>
-CHANGESET
-
-    # upload it
-    post :upload, :params => { :id => changeset_id }, :body => diff
-    assert_response :success,
-                    "can't upload a simple valid diff to changeset: #{@response.body}"
-
-    # check that the changes made it into the database
-    assert_equal 0, Node.find(node.id).tags.size, "node #{node.id} should now have no tags"
-    assert_equal 0, Way.find(way.id).tags.size, "way #{way.id} should now have no tags"
-    assert_equal 0, Relation.find(relation.id).tags.size, "relation #{relation.id} should now have no tags"
-  end
-
-  ##
-  # upload something which creates new objects using placeholders
-  def test_upload_create_valid
-    user = create(:user)
-    changeset = create(:changeset, :user => user)
-    node = create(:node)
-    way = create(:way_with_nodes, :nodes_count => 2)
-    relation = create(:relation)
-
-    basic_authorization user.email, "test"
-
-    # simple diff to create a node way and relation using placeholders
-    diff = <<CHANGESET.strip_heredoc
-      <osmChange>
-       <create>
-        <node id='-1' lon='0' lat='0' changeset='#{changeset.id}'>
-         <tag k='foo' v='bar'/>
-         <tag k='baz' v='bat'/>
-        </node>
-        <way id='-1' changeset='#{changeset.id}'>
-         <nd ref='#{node.id}'/>
-        </way>
-       </create>
-       <create>
-        <relation id='-1' changeset='#{changeset.id}'>
-         <member type='way' role='some' ref='#{way.id}'/>
-         <member type='node' role='some' ref='#{node.id}'/>
-         <member type='relation' role='some' ref='#{relation.id}'/>
-        </relation>
-       </create>
-      </osmChange>
-CHANGESET
-
-    # upload it
-    post :upload, :params => { :id => changeset.id }, :body => diff
-    assert_response :success,
-                    "can't upload a simple valid creation to changeset: #{@response.body}"
-
-    # check the returned payload
-    assert_select "diffResult[version='#{API_VERSION}'][generator='OpenStreetMap server']", 1
-    assert_select "diffResult>node", 1
-    assert_select "diffResult>way", 1
-    assert_select "diffResult>relation", 1
-
-    # inspect the response to find out what the new element IDs are
-    doc = XML::Parser.string(@response.body).parse
-    new_node_id = doc.find("//diffResult/node").first["new_id"].to_i
-    new_way_id = doc.find("//diffResult/way").first["new_id"].to_i
-    new_rel_id = doc.find("//diffResult/relation").first["new_id"].to_i
-
-    # check the old IDs are all present and negative one
-    assert_equal(-1, doc.find("//diffResult/node").first["old_id"].to_i)
-    assert_equal(-1, doc.find("//diffResult/way").first["old_id"].to_i)
-    assert_equal(-1, doc.find("//diffResult/relation").first["old_id"].to_i)
-
-    # check the versions are present and equal one
-    assert_equal 1, doc.find("//diffResult/node").first["new_version"].to_i
-    assert_equal 1, doc.find("//diffResult/way").first["new_version"].to_i
-    assert_equal 1, doc.find("//diffResult/relation").first["new_version"].to_i
-
-    # check that the changes made it into the database
-    assert_equal 2, Node.find(new_node_id).tags.size, "new node should have two tags"
-    assert_equal 0, Way.find(new_way_id).tags.size, "new way should have no tags"
-    assert_equal 0, Relation.find(new_rel_id).tags.size, "new relation should have no tags"
-  end
-
-  ##
-  # test a complex delete where we delete elements which rely on eachother
-  # in the same transaction.
-  def test_upload_delete
-    changeset = create(:changeset)
-    super_relation = create(:relation)
-    used_relation = create(:relation)
-    used_way = create(:way)
-    used_node = create(:node)
-    create(:relation_member, :relation => super_relation, :member => used_relation)
-    create(:relation_member, :relation => super_relation, :member => used_way)
-    create(:relation_member, :relation => super_relation, :member => used_node)
-
-    basic_authorization changeset.user.display_name, "test"
-
-    diff = XML::Document.new
-    diff.root = XML::Node.new "osmChange"
-    delete = XML::Node.new "delete"
-    diff.root << delete
-    delete << super_relation.to_xml_node
-    delete << used_relation.to_xml_node
-    delete << used_way.to_xml_node
-    delete << used_node.to_xml_node
-
-    # update the changeset to one that this user owns
-    %w[node way relation].each do |type|
-      delete.find("//osmChange/delete/#{type}").each do |n|
-        n["changeset"] = changeset.id.to_s
-      end
-    end
-
-    # upload it
-    post :upload, :params => { :id => changeset.id }, :body => diff.to_s
-    assert_response :success,
-                    "can't upload a deletion diff to changeset: #{@response.body}"
-
-    # check the response is well-formed
-    assert_select "diffResult>node", 1
-    assert_select "diffResult>way", 1
-    assert_select "diffResult>relation", 2
-
-    # check that everything was deleted
-    assert_equal false, Node.find(used_node.id).visible
-    assert_equal false, Way.find(used_way.id).visible
-    assert_equal false, Relation.find(super_relation.id).visible
-    assert_equal false, Relation.find(used_relation.id).visible
-  end
-
-  ##
-  # test uploading a delete with no lat/lon, as they are optional in
-  # the osmChange spec.
-  def test_upload_nolatlon_delete
-    node = create(:node)
-    changeset = create(:changeset)
-
-    basic_authorization changeset.user.display_name, "test"
-    diff = "<osmChange><delete><node id='#{node.id}' version='#{node.version}' changeset='#{changeset.id}'/></delete></osmChange>"
-
-    # upload it
-    post :upload, :params => { :id => changeset.id }, :body => diff
-    assert_response :success,
-                    "can't upload a deletion diff to changeset: #{@response.body}"
-
-    # check the response is well-formed
-    assert_select "diffResult>node", 1
-
-    # check that everything was deleted
-    assert_equal false, Node.find(node.id).visible
-  end
-
-  def test_repeated_changeset_create
-    3.times do
-      basic_authorization create(:user).email, "test"
-
-      # create a temporary changeset
-      xml = "<osm><changeset>" \
-            "<tag k='created_by' v='osm test suite checking changesets'/>" \
-            "</changeset></osm>"
-      assert_difference "Changeset.count", 1 do
-        put :create, :body => xml
-      end
-      assert_response :success
-    end
-  end
-
-  def test_upload_large_changeset
-    basic_authorization create(:user).email, "test"
-
-    # create a changeset
-    put :create, :body => "<osm><changeset/></osm>"
-    assert_response :success, "Should be able to create a changeset: #{@response.body}"
-    changeset_id = @response.body.to_i
-
-    # upload some widely-spaced nodes, spiralling positive and negative
-    diff = <<CHANGESET.strip_heredoc
-      <osmChange>
-       <create>
-        <node id='-1' lon='-20' lat='-10' changeset='#{changeset_id}'/>
-        <node id='-10' lon='20'  lat='10' changeset='#{changeset_id}'/>
-        <node id='-2' lon='-40' lat='-20' changeset='#{changeset_id}'/>
-        <node id='-11' lon='40'  lat='20' changeset='#{changeset_id}'/>
-        <node id='-3' lon='-60' lat='-30' changeset='#{changeset_id}'/>
-        <node id='-12' lon='60'  lat='30' changeset='#{changeset_id}'/>
-        <node id='-4' lon='-80' lat='-40' changeset='#{changeset_id}'/>
-        <node id='-13' lon='80'  lat='40' changeset='#{changeset_id}'/>
-        <node id='-5' lon='-100' lat='-50' changeset='#{changeset_id}'/>
-        <node id='-14' lon='100'  lat='50' changeset='#{changeset_id}'/>
-        <node id='-6' lon='-120' lat='-60' changeset='#{changeset_id}'/>
-        <node id='-15' lon='120'  lat='60' changeset='#{changeset_id}'/>
-        <node id='-7' lon='-140' lat='-70' changeset='#{changeset_id}'/>
-        <node id='-16' lon='140'  lat='70' changeset='#{changeset_id}'/>
-        <node id='-8' lon='-160' lat='-80' changeset='#{changeset_id}'/>
-        <node id='-17' lon='160'  lat='80' changeset='#{changeset_id}'/>
-        <node id='-9' lon='-179.9' lat='-89.9' changeset='#{changeset_id}'/>
-        <node id='-18' lon='179.9'  lat='89.9' changeset='#{changeset_id}'/>
-       </create>
-      </osmChange>
-CHANGESET
-
-    # upload it, which used to cause an error like "PGError: ERROR:
-    # integer out of range" (bug #2152). but shouldn't any more.
-    post :upload, :params => { :id => changeset_id }, :body => diff
-    assert_response :success,
-                    "can't upload a spatially-large diff to changeset: #{@response.body}"
-
-    # check that the changeset bbox is within bounds
-    cs = Changeset.find(changeset_id)
-    assert cs.min_lon >= -180 * GeoRecord::SCALE, "Minimum longitude (#{cs.min_lon / GeoRecord::SCALE}) should be >= -180 to be valid."
-    assert cs.max_lon <= 180 * GeoRecord::SCALE, "Maximum longitude (#{cs.max_lon / GeoRecord::SCALE}) should be <= 180 to be valid."
-    assert cs.min_lat >= -90 * GeoRecord::SCALE, "Minimum latitude (#{cs.min_lat / GeoRecord::SCALE}) should be >= -90 to be valid."
-    assert cs.max_lat <= 90 * GeoRecord::SCALE, "Maximum latitude (#{cs.max_lat / GeoRecord::SCALE}) should be <= 90 to be valid."
-  end
-
-  ##
-  # test that deleting stuff in a transaction doesn't bypass the checks
-  # to ensure that used elements are not deleted.
-  def test_upload_delete_invalid
-    changeset = create(:changeset)
-    relation = create(:relation)
-    other_relation = create(:relation)
-    used_way = create(:way)
-    used_node = create(:node)
-    create(:relation_member, :relation => relation, :member => used_way)
-    create(:relation_member, :relation => relation, :member => used_node)
-
-    basic_authorization changeset.user.email, "test"
-
-    diff = XML::Document.new
-    diff.root = XML::Node.new "osmChange"
-    delete = XML::Node.new "delete"
-    diff.root << delete
-    delete << other_relation.to_xml_node
-    delete << used_way.to_xml_node
-    delete << used_node.to_xml_node
-
-    # update the changeset to one that this user owns
-    %w[node way relation].each do |type|
-      delete.find("//osmChange/delete/#{type}").each do |n|
-        n["changeset"] = changeset.id.to_s
-      end
-    end
-
-    # upload it
-    post :upload, :params => { :id => changeset.id }, :body => diff.to_s
-    assert_response :precondition_failed,
-                    "shouldn't be able to upload a invalid deletion diff: #{@response.body}"
-    assert_equal "Precondition failed: Way #{used_way.id} is still used by relations #{relation.id}.", @response.body
-
-    # check that nothing was, in fact, deleted
-    assert_equal true, Node.find(used_node.id).visible
-    assert_equal true, Way.find(used_way.id).visible
-    assert_equal true, Relation.find(relation.id).visible
-    assert_equal true, Relation.find(other_relation.id).visible
-  end
-
-  ##
-  # test that a conditional delete of an in use object works.
-  def test_upload_delete_if_unused
-    changeset = create(:changeset)
-    super_relation = create(:relation)
-    used_relation = create(:relation)
-    used_way = create(:way)
-    used_node = create(:node)
-    create(:relation_member, :relation => super_relation, :member => used_relation)
-    create(:relation_member, :relation => super_relation, :member => used_way)
-    create(:relation_member, :relation => super_relation, :member => used_node)
-
-    basic_authorization changeset.user.email, "test"
-
-    diff = XML::Document.new
-    diff.root = XML::Node.new "osmChange"
-    delete = XML::Node.new "delete"
-    diff.root << delete
-    delete["if-unused"] = ""
-    delete << used_relation.to_xml_node
-    delete << used_way.to_xml_node
-    delete << used_node.to_xml_node
-
-    # update the changeset to one that this user owns
-    %w[node way relation].each do |type|
-      delete.find("//osmChange/delete/#{type}").each do |n|
-        n["changeset"] = changeset.id.to_s
-      end
-    end
-
-    # upload it
-    post :upload, :params => { :id => changeset.id }, :body => diff.to_s
-    assert_response :success,
-                    "can't do a conditional delete of in use objects: #{@response.body}"
-
-    # check the returned payload
-    assert_select "diffResult[version='#{API_VERSION}'][generator='OpenStreetMap server']", 1
-    assert_select "diffResult>node", 1
-    assert_select "diffResult>way", 1
-    assert_select "diffResult>relation", 1
-
-    # parse the response
-    doc = XML::Parser.string(@response.body).parse
-
-    # check the old IDs are all present and what we expect
-    assert_equal used_node.id, doc.find("//diffResult/node").first["old_id"].to_i
-    assert_equal used_way.id, doc.find("//diffResult/way").first["old_id"].to_i
-    assert_equal used_relation.id, doc.find("//diffResult/relation").first["old_id"].to_i
-
-    # check the new IDs are all present and unchanged
-    assert_equal used_node.id, doc.find("//diffResult/node").first["new_id"].to_i
-    assert_equal used_way.id, doc.find("//diffResult/way").first["new_id"].to_i
-    assert_equal used_relation.id, doc.find("//diffResult/relation").first["new_id"].to_i
-
-    # check the new versions are all present and unchanged
-    assert_equal used_node.version, doc.find("//diffResult/node").first["new_version"].to_i
-    assert_equal used_way.version, doc.find("//diffResult/way").first["new_version"].to_i
-    assert_equal used_relation.version, doc.find("//diffResult/relation").first["new_version"].to_i
-
-    # check that nothing was, in fact, deleted
-    assert_equal true, Node.find(used_node.id).visible
-    assert_equal true, Way.find(used_way.id).visible
-    assert_equal true, Relation.find(used_relation.id).visible
-  end
-
-  ##
-  # upload an element with a really long tag value
-  def test_upload_invalid_too_long_tag
-    changeset = create(:changeset)
-
-    basic_authorization changeset.user.email, "test"
-
-    # simple diff to create a node way and relation using placeholders
-    diff = <<CHANGESET.strip_heredoc
-      <osmChange>
-       <create>
-        <node id='-1' lon='0' lat='0' changeset='#{changeset.id}'>
-         <tag k='foo' v='#{'x' * 256}'/>
-        </node>
-       </create>
-      </osmChange>
-CHANGESET
-
-    # upload it
-    post :upload, :params => { :id => changeset.id }, :body => diff
-    assert_response :bad_request,
-                    "shoudln't be able to upload too long a tag to changeset: #{@response.body}"
-  end
-
-  ##
-  # upload something which creates new objects and inserts them into
-  # existing containers using placeholders.
-  def test_upload_complex
-    way = create(:way)
-    node = create(:node)
-    relation = create(:relation)
-    create(:way_node, :way => way, :node => node)
-
-    changeset = create(:changeset)
-
-    basic_authorization changeset.user.email, "test"
-
-    # simple diff to create a node way and relation using placeholders
-    diff = <<CHANGESET.strip_heredoc
-      <osmChange>
-       <create>
-        <node id='-1' lon='0' lat='0' changeset='#{changeset.id}'>
-         <tag k='foo' v='bar'/>
-         <tag k='baz' v='bat'/>
-        </node>
-       </create>
-       <modify>
-        <way id='#{way.id}' changeset='#{changeset.id}' version='1'>
-         <nd ref='-1'/>
-         <nd ref='#{node.id}'/>
-        </way>
-        <relation id='#{relation.id}' changeset='#{changeset.id}' version='1'>
-         <member type='way' role='some' ref='#{way.id}'/>
-         <member type='node' role='some' ref='-1'/>
-         <member type='relation' role='some' ref='#{relation.id}'/>
-        </relation>
-       </modify>
-      </osmChange>
-CHANGESET
-
-    # upload it
-    post :upload, :params => { :id => changeset.id }, :body => diff
-    assert_response :success,
-                    "can't upload a complex diff to changeset: #{@response.body}"
-
-    # check the returned payload
-    assert_select "diffResult[version='#{API_VERSION}'][generator='#{GENERATOR}']", 1
-    assert_select "diffResult>node", 1
-    assert_select "diffResult>way", 1
-    assert_select "diffResult>relation", 1
-
-    # inspect the response to find out what the new element IDs are
-    doc = XML::Parser.string(@response.body).parse
-    new_node_id = doc.find("//diffResult/node").first["new_id"].to_i
-
-    # check that the changes made it into the database
-    assert_equal 2, Node.find(new_node_id).tags.size, "new node should have two tags"
-    assert_equal [new_node_id, node.id], Way.find(way.id).nds, "way nodes should match"
-    Relation.find(relation.id).members.each do |type, id, _role|
-      assert_equal new_node_id, id, "relation should contain new node" if type == "node"
-    end
-  end
-
-  ##
-  # create a diff which references several changesets, which should cause
-  # a rollback and none of the diff gets committed
-  def test_upload_invalid_changesets
-    changeset = create(:changeset)
-    other_changeset = create(:changeset, :user => changeset.user)
-    node = create(:node)
-    way = create(:way)
-    relation = create(:relation)
-    other_relation = create(:relation)
-
-    basic_authorization changeset.user.email, "test"
-
-    # simple diff to create a node way and relation using placeholders
-    diff = <<CHANGESET.strip_heredoc
-      <osmChange>
-       <modify>
-        <node id='#{node.id}' lon='0' lat='0' changeset='#{changeset.id}' version='1'/>
-        <way id='#{way.id}' changeset='#{changeset.id}' version='1'>
-         <nd ref='#{node.id}'/>
-        </way>
-       </modify>
-       <modify>
-        <relation id='#{relation.id}' changeset='#{changeset.id}' version='1'>
-         <member type='way' role='some' ref='#{way.id}'/>
-         <member type='node' role='some' ref='#{node.id}'/>
-         <member type='relation' role='some' ref='#{other_relation.id}'/>
-        </relation>
-       </modify>
-       <create>
-        <node id='-1' lon='0' lat='0' changeset='#{other_changeset.id}'>
-         <tag k='foo' v='bar'/>
-         <tag k='baz' v='bat'/>
-        </node>
-       </create>
-      </osmChange>
-CHANGESET
-
-    # upload it
-    post :upload, :params => { :id => changeset.id }, :body => diff
-    assert_response :conflict,
-                    "uploading a diff with multiple changesets should have failed"
-
-    # check that objects are unmodified
-    assert_nodes_are_equal(node, Node.find(node.id))
-    assert_ways_are_equal(way, Way.find(way.id))
-    assert_relations_are_equal(relation, Relation.find(relation.id))
-  end
-
-  ##
-  # upload multiple versions of the same element in the same diff.
-  def test_upload_multiple_valid
-    node = create(:node)
-    changeset = create(:changeset)
-    basic_authorization changeset.user.email, "test"
-
-    # change the location of a node multiple times, each time referencing
-    # the last version. doesn't this depend on version numbers being
-    # sequential?
-    diff = <<CHANGESET.strip_heredoc
-      <osmChange>
-       <modify>
-        <node id='#{node.id}' lon='0' lat='0' changeset='#{changeset.id}' version='1'/>
-        <node id='#{node.id}' lon='1' lat='0' changeset='#{changeset.id}' version='2'/>
-        <node id='#{node.id}' lon='1' lat='1' changeset='#{changeset.id}' version='3'/>
-        <node id='#{node.id}' lon='1' lat='2' changeset='#{changeset.id}' version='4'/>
-        <node id='#{node.id}' lon='2' lat='2' changeset='#{changeset.id}' version='5'/>
-        <node id='#{node.id}' lon='3' lat='2' changeset='#{changeset.id}' version='6'/>
-        <node id='#{node.id}' lon='3' lat='3' changeset='#{changeset.id}' version='7'/>
-        <node id='#{node.id}' lon='9' lat='9' changeset='#{changeset.id}' version='8'/>
-       </modify>
-      </osmChange>
-CHANGESET
-
-    # upload it
-    post :upload, :params => { :id => changeset.id }, :body => diff
-    assert_response :success,
-                    "can't upload multiple versions of an element in a diff: #{@response.body}"
-
-    # check the response is well-formed. its counter-intuitive, but the
-    # API will return multiple elements with the same ID and different
-    # version numbers for each change we made.
-    assert_select "diffResult>node", 8
-  end
-
-  ##
-  # upload multiple versions of the same element in the same diff, but
-  # keep the version numbers the same.
-  def test_upload_multiple_duplicate
-    node = create(:node)
-    changeset = create(:changeset)
-
-    basic_authorization changeset.user.email, "test"
-
-    diff = <<CHANGESET.strip_heredoc
-      <osmChange>
-       <modify>
-        <node id='#{node.id}' lon='0' lat='0' changeset='#{changeset.id}' version='1'/>
-        <node id='#{node.id}' lon='1' lat='1' changeset='#{changeset.id}' version='1'/>
-       </modify>
-      </osmChange>
-CHANGESET
-
-    # upload it
-    post :upload, :params => { :id => changeset.id }, :body => diff
-    assert_response :conflict,
-                    "shouldn't be able to upload the same element twice in a diff: #{@response.body}"
-  end
-
-  ##
-  # try to upload some elements without specifying the version
-  def test_upload_missing_version
-    changeset = create(:changeset)
-
-    basic_authorization changeset.user.email, "test"
-
-    diff = <<CHANGESET.strip_heredoc
-      <osmChange>
-       <modify>
-       <node id='1' lon='1' lat='1' changeset='#{changeset.id}'/>
-       </modify>
-      </osmChange>
-CHANGESET
-
-    # upload it
-    post :upload, :params => { :id => changeset.id }, :body => diff
-    assert_response :bad_request,
-                    "shouldn't be able to upload an element without version: #{@response.body}"
-  end
-
-  ##
-  # try to upload with commands other than create, modify, or delete
-  def test_action_upload_invalid
-    changeset = create(:changeset)
-
-    basic_authorization changeset.user.email, "test"
-
-    diff = <<CHANGESET.strip_heredoc
-      <osmChange>
-        <ping>
-         <node id='1' lon='1' lat='1' changeset='#{changeset.id}' />
-        </ping>
-      </osmChange>
-CHANGESET
-    post :upload, :params => { :id => changeset.id }, :body => diff
-    assert_response :bad_request, "Shouldn't be able to upload a diff with the action ping"
-    assert_equal @response.body, "Unknown action ping, choices are create, modify, delete"
-  end
-
-  ##
-  # upload a valid changeset which has a mixture of whitespace
-  # to check a bug reported by ivansanchez (#1565).
-  def test_upload_whitespace_valid
-    changeset = create(:changeset)
-    node = create(:node)
-    way = create(:way_with_nodes, :nodes_count => 2)
-    relation = create(:relation)
-    other_relation = create(:relation)
-    create(:relation_tag, :relation => relation)
-
-    basic_authorization changeset.user.email, "test"
-
-    diff = <<CHANGESET.strip_heredoc
-      <osmChange>
-       <modify><node id='#{node.id}' lon='0' lat='0' changeset='#{changeset.id}'
-        version='1'></node>
-        <node id='#{node.id}' lon='1' lat='1' changeset='#{changeset.id}' version='2'><tag k='k' v='v'/></node></modify>
-       <modify>
-       <relation id='#{relation.id}' changeset='#{changeset.id}' version='1'><member
-         type='way' role='some' ref='#{way.id}'/><member
-          type='node' role='some' ref='#{node.id}'/>
-         <member type='relation' role='some' ref='#{other_relation.id}'/>
-        </relation>
-       </modify></osmChange>
-CHANGESET
-
-    # upload it
-    post :upload, :params => { :id => changeset.id }, :body => diff
-    assert_response :success,
-                    "can't upload a valid diff with whitespace variations to changeset: #{@response.body}"
-
-    # check the response is well-formed
-    assert_select "diffResult>node", 2
-    assert_select "diffResult>relation", 1
-
-    # check that the changes made it into the database
-    assert_equal 1, Node.find(node.id).tags.size, "node #{node.id} should now have one tag"
-    assert_equal 0, Relation.find(relation.id).tags.size, "relation #{relation.id} should now have no tags"
-  end
-
-  ##
-  # test that a placeholder can be reused within the same upload.
-  def test_upload_reuse_placeholder_valid
-    changeset = create(:changeset)
-
-    basic_authorization changeset.user.email, "test"
-
-    diff = <<CHANGESET.strip_heredoc
-      <osmChange>
-       <create>
-        <node id='-1' lon='0' lat='0' changeset='#{changeset.id}'>
-         <tag k="foo" v="bar"/>
-        </node>
-       </create>
-       <modify>
-        <node id='-1' lon='1' lat='1' changeset='#{changeset.id}' version='1'/>
-       </modify>
-       <delete>
-        <node id='-1' lon='2' lat='2' changeset='#{changeset.id}' version='2'/>
-       </delete>
-      </osmChange>
-CHANGESET
-
-    # upload it
-    post :upload, :params => { :id => changeset.id }, :body => diff
-    assert_response :success,
-                    "can't upload a valid diff with re-used placeholders to changeset: #{@response.body}"
-
-    # check the response is well-formed
-    assert_select "diffResult>node", 3
-    assert_select "diffResult>node[old_id='-1']", 3
-  end
-
-  ##
-  # test what happens if a diff upload re-uses placeholder IDs in an
-  # illegal way.
-  def test_upload_placeholder_invalid
-    changeset = create(:changeset)
-
-    basic_authorization changeset.user.email, "test"
-
-    diff = <<CHANGESET.strip_heredoc
-      <osmChange>
-       <create>
-        <node id='-1' lon='0' lat='0' changeset='#{changeset.id}' version='1'/>
-        <node id='-1' lon='1' lat='1' changeset='#{changeset.id}' version='1'/>
-        <node id='-1' lon='2' lat='2' changeset='#{changeset.id}' version='2'/>
-       </create>
-      </osmChange>
-CHANGESET
-
-    # upload it
-    post :upload, :params => { :id => changeset.id }, :body => diff
-    assert_response :bad_request,
-                    "shouldn't be able to re-use placeholder IDs"
-  end
-
-  ##
-  # test that uploading a way referencing invalid placeholders gives a
-  # proper error, not a 500.
-  def test_upload_placeholder_invalid_way
-    changeset = create(:changeset)
-    way = create(:way)
-
-    basic_authorization changeset.user.email, "test"
-
-    diff = <<CHANGESET.strip_heredoc
-      <osmChange>
-       <create>
-        <node id="-1" lon="0" lat="0" changeset="#{changeset.id}" version="1"/>
-        <node id="-2" lon="1" lat="1" changeset="#{changeset.id}" version="1"/>
-        <node id="-3" lon="2" lat="2" changeset="#{changeset.id}" version="1"/>
-        <way id="-1" changeset="#{changeset.id}" version="1">
-         <nd ref="-1"/>
-         <nd ref="-2"/>
-         <nd ref="-3"/>
-         <nd ref="-4"/>
-        </way>
-       </create>
-      </osmChange>
-CHANGESET
-
-    # upload it
-    post :upload, :params => { :id => changeset.id }, :body => diff
-    assert_response :bad_request,
-                    "shouldn't be able to use invalid placeholder IDs"
-    assert_equal "Placeholder node not found for reference -4 in way -1", @response.body
-
-    # the same again, but this time use an existing way
-    diff = <<CHANGESET.strip_heredoc
-      <osmChange>
-       <create>
-        <node id="-1" lon="0" lat="0" changeset="#{changeset.id}" version="1"/>
-        <node id="-2" lon="1" lat="1" changeset="#{changeset.id}" version="1"/>
-        <node id="-3" lon="2" lat="2" changeset="#{changeset.id}" version="1"/>
-        <way id="#{way.id}" changeset="#{changeset.id}" version="1">
-         <nd ref="-1"/>
-         <nd ref="-2"/>
-         <nd ref="-3"/>
-         <nd ref="-4"/>
-        </way>
-       </create>
-      </osmChange>
-CHANGESET
-
-    # upload it
-    post :upload, :params => { :id => changeset.id }, :body => diff
-    assert_response :bad_request,
-                    "shouldn't be able to use invalid placeholder IDs"
-    assert_equal "Placeholder node not found for reference -4 in way #{way.id}", @response.body
-  end
-
-  ##
-  # test that uploading a relation referencing invalid placeholders gives a
-  # proper error, not a 500.
-  def test_upload_placeholder_invalid_relation
-    changeset = create(:changeset)
-    relation = create(:relation)
-
-    basic_authorization changeset.user.email, "test"
-
-    diff = <<CHANGESET.strip_heredoc
-      <osmChange>
-       <create>
-        <node id="-1" lon="0" lat="0" changeset="#{changeset.id}" version="1"/>
-        <node id="-2" lon="1" lat="1" changeset="#{changeset.id}" version="1"/>
-        <node id="-3" lon="2" lat="2" changeset="#{changeset.id}" version="1"/>
-        <relation id="-1" changeset="#{changeset.id}" version="1">
-         <member type="node" role="foo" ref="-1"/>
-         <member type="node" role="foo" ref="-2"/>
-         <member type="node" role="foo" ref="-3"/>
-         <member type="node" role="foo" ref="-4"/>
-        </relation>
-       </create>
-      </osmChange>
-CHANGESET
-
-    # upload it
-    post :upload, :params => { :id => changeset.id }, :body => diff
-    assert_response :bad_request,
-                    "shouldn't be able to use invalid placeholder IDs"
-    assert_equal "Placeholder Node not found for reference -4 in relation -1.", @response.body
-
-    # the same again, but this time use an existing relation
-    diff = <<CHANGESET.strip_heredoc
-      <osmChange>
-       <create>
-        <node id="-1" lon="0" lat="0" changeset="#{changeset.id}" version="1"/>
-        <node id="-2" lon="1" lat="1" changeset="#{changeset.id}" version="1"/>
-        <node id="-3" lon="2" lat="2" changeset="#{changeset.id}" version="1"/>
-        <relation id="#{relation.id}" changeset="#{changeset.id}" version="1">
-         <member type="node" role="foo" ref="-1"/>
-         <member type="node" role="foo" ref="-2"/>
-         <member type="node" role="foo" ref="-3"/>
-         <member type="way" role="bar" ref="-1"/>
-        </relation>
-       </create>
-      </osmChange>
-CHANGESET
-
-    # upload it
-    post :upload, :params => { :id => changeset.id }, :body => diff
-    assert_response :bad_request,
-                    "shouldn't be able to use invalid placeholder IDs"
-    assert_equal "Placeholder Way not found for reference -1 in relation #{relation.id}.", @response.body
-  end
-
-  ##
-  # test what happens if a diff is uploaded containing only a node
-  # move.
-  def test_upload_node_move
-    basic_authorization create(:user).email, "test"
-
-    xml = "<osm><changeset>" \
-          "<tag k='created_by' v='osm test suite checking changesets'/>" \
-          "</changeset></osm>"
-    put :create, :body => xml
-    assert_response :success
-    changeset_id = @response.body.to_i
-
-    old_node = create(:node, :lat => 1, :lon => 1)
-
-    diff = XML::Document.new
-    diff.root = XML::Node.new "osmChange"
-    modify = XML::Node.new "modify"
-    xml_old_node = old_node.to_xml_node
-    xml_old_node["lat"] = 2.0.to_s
-    xml_old_node["lon"] = 2.0.to_s
-    xml_old_node["changeset"] = changeset_id.to_s
-    modify << xml_old_node
-    diff.root << modify
-
-    # upload it
-    post :upload, :params => { :id => changeset_id }, :body => diff.to_s
-    assert_response :success,
-                    "diff should have uploaded OK"
-
-    # check the bbox
-    changeset = Changeset.find(changeset_id)
-    assert_equal 1 * GeoRecord::SCALE, changeset.min_lon, "min_lon should be 1 degree"
-    assert_equal 2 * GeoRecord::SCALE, changeset.max_lon, "max_lon should be 2 degrees"
-    assert_equal 1 * GeoRecord::SCALE, changeset.min_lat, "min_lat should be 1 degree"
-    assert_equal 2 * GeoRecord::SCALE, changeset.max_lat, "max_lat should be 2 degrees"
-  end
-
-  ##
-  # test what happens if a diff is uploaded adding a node to a way.
-  def test_upload_way_extend
-    basic_authorization create(:user).email, "test"
-
-    xml = "<osm><changeset>" \
-          "<tag k='created_by' v='osm test suite checking changesets'/>" \
-          "</changeset></osm>"
-    put :create, :body => xml
-    assert_response :success
-    changeset_id = @response.body.to_i
-
-    old_way = create(:way)
-    create(:way_node, :way => old_way, :node => create(:node, :lat => 1, :lon => 1))
-
-    diff = XML::Document.new
-    diff.root = XML::Node.new "osmChange"
-    modify = XML::Node.new "modify"
-    xml_old_way = old_way.to_xml_node
-    nd_ref = XML::Node.new "nd"
-    nd_ref["ref"] = create(:node, :lat => 3, :lon => 3).id.to_s
-    xml_old_way << nd_ref
-    xml_old_way["changeset"] = changeset_id.to_s
-    modify << xml_old_way
-    diff.root << modify
-
-    # upload it
-    post :upload, :params => { :id => changeset_id }, :body => diff.to_s
-    assert_response :success,
-                    "diff should have uploaded OK"
-
-    # check the bbox
-    changeset = Changeset.find(changeset_id)
-    assert_equal 1 * GeoRecord::SCALE, changeset.min_lon, "min_lon should be 1 degree"
-    assert_equal 3 * GeoRecord::SCALE, changeset.max_lon, "max_lon should be 3 degrees"
-    assert_equal 1 * GeoRecord::SCALE, changeset.min_lat, "min_lat should be 1 degree"
-    assert_equal 3 * GeoRecord::SCALE, changeset.max_lat, "max_lat should be 3 degrees"
-  end
-
-  ##
-  # test for more issues in #1568
-  def test_upload_empty_invalid
-    changeset = create(:changeset)
-
-    basic_authorization changeset.user.email, "test"
-
-    ["<osmChange/>",
-     "<osmChange></osmChange>",
-     "<osmChange><modify/></osmChange>",
-     "<osmChange><modify></modify></osmChange>"].each do |diff|
-      # upload it
-      post :upload, :params => { :id => changeset.id }, :body => diff
-      assert_response(:success, "should be able to upload " \
-                      "empty changeset: " + diff)
-    end
-  end
-
-  ##
-  # test that the X-Error-Format header works to request XML errors
-  def test_upload_xml_errors
-    changeset = create(:changeset)
-    node = create(:node)
-    create(:relation_member, :member => node)
-
-    basic_authorization changeset.user.email, "test"
-
-    # try and delete a node that is in use
-    diff = XML::Document.new
-    diff.root = XML::Node.new "osmChange"
-    delete = XML::Node.new "delete"
-    diff.root << delete
-    delete << node.to_xml_node
-
-    # upload it
-    error_format "xml"
-    post :upload, :params => { :id => changeset.id }, :body => diff.to_s
-    assert_response :success,
-                    "failed to return error in XML format"
-
-    # check the returned payload
-    assert_select "osmError[version='#{API_VERSION}'][generator='OpenStreetMap server']", 1
-    assert_select "osmError>status", 1
-    assert_select "osmError>message", 1
-  end
-
-  ##
-  # when we make some simple changes we get the same changes back from the
-  # diff download.
-  def test_diff_download_simple
-    node = create(:node)
-
-    ## First try with a non-public user, which should get a forbidden
-    basic_authorization create(:user, :data_public => false).email, "test"
-
-    # create a temporary changeset
-    xml = "<osm><changeset>" \
-          "<tag k='created_by' v='osm test suite checking changesets'/>" \
-          "</changeset></osm>"
-    put :create, :body => xml
-    assert_response :forbidden
-
-    ## Now try with a normal user
-    basic_authorization create(:user).email, "test"
-
-    # create a temporary changeset
-    xml = "<osm><changeset>" \
-          "<tag k='created_by' v='osm test suite checking changesets'/>" \
-          "</changeset></osm>"
-    put :create, :body => xml
-    assert_response :success
-    changeset_id = @response.body.to_i
-
-    # add a diff to it
-    diff = <<CHANGESET.strip_heredoc
-      <osmChange>
-       <modify>
-        <node id='#{node.id}' lon='0' lat='0' changeset='#{changeset_id}' version='1'/>
-        <node id='#{node.id}' lon='1' lat='0' changeset='#{changeset_id}' version='2'/>
-        <node id='#{node.id}' lon='1' lat='1' changeset='#{changeset_id}' version='3'/>
-        <node id='#{node.id}' lon='1' lat='2' changeset='#{changeset_id}' version='4'/>
-        <node id='#{node.id}' lon='2' lat='2' changeset='#{changeset_id}' version='5'/>
-        <node id='#{node.id}' lon='3' lat='2' changeset='#{changeset_id}' version='6'/>
-        <node id='#{node.id}' lon='3' lat='3' changeset='#{changeset_id}' version='7'/>
-        <node id='#{node.id}' lon='9' lat='9' changeset='#{changeset_id}' version='8'/>
-       </modify>
-      </osmChange>
-CHANGESET
-
-    # upload it
-    post :upload, :params => { :id => changeset_id }, :body => diff
-    assert_response :success,
-                    "can't upload multiple versions of an element in a diff: #{@response.body}"
-
-    get :download, :params => { :id => changeset_id }
-    assert_response :success
-
-    assert_select "osmChange", 1
-    assert_select "osmChange>modify", 8
-    assert_select "osmChange>modify>node", 8
-  end
-
-  ##
-  # culled this from josm to ensure that nothing in the way that josm
-  # is formatting the request is causing it to fail.
-  #
-  # NOTE: the error turned out to be something else completely!
-  def test_josm_upload
-    basic_authorization create(:user).email, "test"
-
-    # create a temporary changeset
-    xml = "<osm><changeset>" \
-          "<tag k='created_by' v='osm test suite checking changesets'/>" \
-          "</changeset></osm>"
-    put :create, :body => xml
-    assert_response :success
-    changeset_id = @response.body.to_i
-
-    diff = <<OSMFILE.strip_heredoc
-      <osmChange version="0.6" generator="JOSM">
-      <create version="0.6" generator="JOSM">
-        <node id='-1' visible='true' changeset='#{changeset_id}' lat='51.49619982187321' lon='-0.18722061869438314' />
-        <node id='-2' visible='true' changeset='#{changeset_id}' lat='51.496359883909605' lon='-0.18653093576241928' />
-        <node id='-3' visible='true' changeset='#{changeset_id}' lat='51.49598132358285' lon='-0.18719613290981638' />
-        <node id='-4' visible='true' changeset='#{changeset_id}' lat='51.4961591711078' lon='-0.18629015888084607' />
-        <node id='-5' visible='true' changeset='#{changeset_id}' lat='51.49582126021711' lon='-0.18708186591517145' />
-        <node id='-6' visible='true' changeset='#{changeset_id}' lat='51.49591018437858' lon='-0.1861432441734455' />
-        <node id='-7' visible='true' changeset='#{changeset_id}' lat='51.49560784152179' lon='-0.18694719410005425' />
-        <node id='-8' visible='true' changeset='#{changeset_id}' lat='51.49567389979617' lon='-0.1860289771788006' />
-        <node id='-9' visible='true' changeset='#{changeset_id}' lat='51.49543761398892' lon='-0.186820684213126' />
-        <way id='-10' action='modiy' visible='true' changeset='#{changeset_id}'>
-          <nd ref='-1' />
-          <nd ref='-2' />
-          <nd ref='-3' />
-          <nd ref='-4' />
-          <nd ref='-5' />
-          <nd ref='-6' />
-          <nd ref='-7' />
-          <nd ref='-8' />
-          <nd ref='-9' />
-          <tag k='highway' v='residential' />
-          <tag k='name' v='Foobar Street' />
-        </way>
-      </create>
-      </osmChange>
-OSMFILE
-
-    # upload it
-    post :upload, :params => { :id => changeset_id }, :body => diff
-    assert_response :success,
-                    "can't upload a diff from JOSM: #{@response.body}"
-
-    get :download, :params => { :id => changeset_id }
-    assert_response :success
-
-    assert_select "osmChange", 1
-    assert_select "osmChange>create>node", 9
-    assert_select "osmChange>create>way", 1
-    assert_select "osmChange>create>way>nd", 9
-    assert_select "osmChange>create>way>tag", 2
-  end
-
-  ##
-  # when we make some complex changes we get the same changes back from the
-  # diff download.
-  def test_diff_download_complex
-    node = create(:node)
-    node2 = create(:node)
-    way = create(:way)
-    basic_authorization create(:user).email, "test"
-
-    # create a temporary changeset
-    xml = "<osm><changeset>" \
-          "<tag k='created_by' v='osm test suite checking changesets'/>" \
-          "</changeset></osm>"
-    put :create, :body => xml
-    assert_response :success
-    changeset_id = @response.body.to_i
-
-    # add a diff to it
-    diff = <<CHANGESET.strip_heredoc
-      <osmChange>
-       <delete>
-        <node id='#{node.id}' lon='0' lat='0' changeset='#{changeset_id}' version='1'/>
-       </delete>
-       <create>
-        <node id='-1' lon='9' lat='9' changeset='#{changeset_id}' version='0'/>
-        <node id='-2' lon='8' lat='9' changeset='#{changeset_id}' version='0'/>
-        <node id='-3' lon='7' lat='9' changeset='#{changeset_id}' version='0'/>
-       </create>
-       <modify>
-        <node id='#{node2.id}' lon='20' lat='15' changeset='#{changeset_id}' version='1'/>
-        <way id='#{way.id}' changeset='#{changeset_id}' version='1'>
-         <nd ref='#{node2.id}'/>
-         <nd ref='-1'/>
-         <nd ref='-2'/>
-         <nd ref='-3'/>
-        </way>
-       </modify>
-      </osmChange>
-CHANGESET
-
-    # upload it
-    post :upload, :params => { :id => changeset_id }, :body => diff
-    assert_response :success,
-                    "can't upload multiple versions of an element in a diff: #{@response.body}"
-
-    get :download, :params => { :id => changeset_id }
-    assert_response :success
-
-    assert_select "osmChange", 1
-    assert_select "osmChange>create", 3
-    assert_select "osmChange>delete", 1
-    assert_select "osmChange>modify", 2
-    assert_select "osmChange>create>node", 3
-    assert_select "osmChange>delete>node", 1
-    assert_select "osmChange>modify>node", 1
-    assert_select "osmChange>modify>way", 1
-  end
-
-  def test_changeset_download
-    changeset = create(:changeset)
-    node = create(:node, :with_history, :version => 1, :changeset => changeset)
-    tag = create(:old_node_tag, :old_node => node.old_nodes.find_by(:version => 1))
-    node2 = create(:node, :with_history, :version => 1, :changeset => changeset)
-    _node3 = create(:node, :with_history, :deleted, :version => 1, :changeset => changeset)
-    _relation = create(:relation, :with_history, :version => 1, :changeset => changeset)
-    _relation2 = create(:relation, :with_history, :deleted, :version => 1, :changeset => changeset)
-
-    get :download, :params => { :id => changeset.id }
-
-    assert_response :success
-    assert_template nil
-    # print @response.body
-    # FIXME: needs more assert_select tests
-    assert_select "osmChange[version='#{API_VERSION}'][generator='#{GENERATOR}']" do
-      assert_select "create", :count => 5
-      assert_select "create>node[id='#{node.id}'][visible='#{node.visible?}'][version='#{node.version}']" do
-        assert_select "tag[k='#{tag.k}'][v='#{tag.v}']"
-      end
-      assert_select "create>node[id='#{node2.id}']"
-    end
-  end
-
-  ##
-  # check that the bounding box of a changeset gets updated correctly
-  # FIXME: This should really be moded to a integration test due to the with_controller
-  def test_changeset_bbox
-    way = create(:way)
-    create(:way_node, :way => way, :node => create(:node, :lat => 3, :lon => 3))
-
-    basic_authorization create(:user).email, "test"
-
-    # create a new changeset
-    xml = "<osm><changeset/></osm>"
-    put :create, :body => xml
-    assert_response :success, "Creating of changeset failed."
-    changeset_id = @response.body.to_i
-
-    # add a single node to it
-    with_controller(NodesController.new) do
-      xml = "<osm><node lon='1' lat='2' changeset='#{changeset_id}'/></osm>"
-      put :create, :body => xml
-      assert_response :success, "Couldn't create node."
-    end
-
-    # get the bounding box back from the changeset
-    get :show, :params => { :id => changeset_id }
-    assert_response :success, "Couldn't read back changeset."
-    assert_select "osm>changeset[min_lon='1.0000000']", 1
-    assert_select "osm>changeset[max_lon='1.0000000']", 1
-    assert_select "osm>changeset[min_lat='2.0000000']", 1
-    assert_select "osm>changeset[max_lat='2.0000000']", 1
-
-    # add another node to it
-    with_controller(NodesController.new) do
-      xml = "<osm><node lon='2' lat='1' changeset='#{changeset_id}'/></osm>"
-      put :create, :body => xml
-      assert_response :success, "Couldn't create second node."
-    end
-
-    # get the bounding box back from the changeset
-    get :show, :params => { :id => changeset_id }
-    assert_response :success, "Couldn't read back changeset for the second time."
-    assert_select "osm>changeset[min_lon='1.0000000']", 1
-    assert_select "osm>changeset[max_lon='2.0000000']", 1
-    assert_select "osm>changeset[min_lat='1.0000000']", 1
-    assert_select "osm>changeset[max_lat='2.0000000']", 1
-
-    # add (delete) a way to it, which contains a point at (3,3)
-    with_controller(WaysController.new) do
-      xml = update_changeset(way.to_xml, changeset_id)
-      put :delete, :params => { :id => way.id }, :body => xml.to_s
-      assert_response :success, "Couldn't delete a way."
-    end
-
-    # get the bounding box back from the changeset
-    get :show, :params => { :id => changeset_id }
-    assert_response :success, "Couldn't read back changeset for the third time."
-    assert_select "osm>changeset[min_lon='1.0000000']", 1
-    assert_select "osm>changeset[max_lon='3.0000000']", 1
-    assert_select "osm>changeset[min_lat='1.0000000']", 1
-    assert_select "osm>changeset[max_lat='3.0000000']", 1
-  end
-
-  ##
-  # test that the changeset :include method works as it should
-  def test_changeset_include
-    basic_authorization create(:user).display_name, "test"
-
-    # create a new changeset
-    put :create, :body => "<osm><changeset/></osm>"
-    assert_response :success, "Creating of changeset failed."
-    changeset_id = @response.body.to_i
-
-    # NOTE: the include method doesn't over-expand, like inserting
-    # a real method does. this is because we expect the client to
-    # know what it is doing!
-    check_after_include(changeset_id, 1, 1, [1, 1, 1, 1])
-    check_after_include(changeset_id, 3, 3, [1, 1, 3, 3])
-    check_after_include(changeset_id, 4, 2, [1, 1, 4, 3])
-    check_after_include(changeset_id, 2, 2, [1, 1, 4, 3])
-    check_after_include(changeset_id, -1, -1, [-1, -1, 4, 3])
-    check_after_include(changeset_id, -2, 5, [-2, -1, 4, 5])
-  end
-
-  ##
-  # test that a not found, wrong method with the expand bbox works as expected
-  def test_changeset_expand_bbox_error
-    basic_authorization create(:user).display_name, "test"
-
-    # create a new changeset
-    xml = "<osm><changeset/></osm>"
-    put :create, :body => xml
-    assert_response :success, "Creating of changeset failed."
-    changeset_id = @response.body.to_i
-
-    lon = 58.2
-    lat = -0.45
-
-    # Try and put
-    xml = "<osm><node lon='#{lon}' lat='#{lat}'/></osm>"
-    put :expand_bbox, :params => { :id => changeset_id }, :body => xml
-    assert_response :method_not_allowed, "shouldn't be able to put a bbox expand"
-
-    # Try to get the update
-    xml = "<osm><node lon='#{lon}' lat='#{lat}'/></osm>"
-    get :expand_bbox, :params => { :id => changeset_id }, :body => xml
-    assert_response :method_not_allowed, "shouldn't be able to get a bbox expand"
-
-    # Try to use a hopefully missing changeset
-    xml = "<osm><node lon='#{lon}' lat='#{lat}'/></osm>"
-    post :expand_bbox, :params => { :id => changeset_id + 13245 }, :body => xml
-    assert_response :not_found, "shouldn't be able to do a bbox expand on a nonexistant changeset"
-  end
-
-  ##
-  # test the query functionality of changesets
-  def test_query
-    private_user = create(:user, :data_public => false)
-    private_user_changeset = create(:changeset, :user => private_user)
-    private_user_closed_changeset = create(:changeset, :closed, :user => private_user)
-    user = create(:user)
-    changeset = create(:changeset, :user => user)
-    closed_changeset = create(:changeset, :closed, :user => user, :created_at => Time.utc(2008, 1, 1, 0, 0, 0), :closed_at => Time.utc(2008, 1, 2, 0, 0, 0))
-    changeset2 = create(:changeset, :min_lat => 5 * GeoRecord::SCALE, :min_lon => 5 * GeoRecord::SCALE, :max_lat => 15 * GeoRecord::SCALE, :max_lon => 15 * GeoRecord::SCALE)
-    changeset3 = create(:changeset, :min_lat => 4.5 * GeoRecord::SCALE, :min_lon => 4.5 * GeoRecord::SCALE, :max_lat => 5 * GeoRecord::SCALE, :max_lon => 5 * GeoRecord::SCALE)
-
-    get :query, :params => { :bbox => "-10,-10, 10, 10" }
-    assert_response :success, "can't get changesets in bbox"
-    assert_changesets [changeset2, changeset3]
-
-    get :query, :params => { :bbox => "4.5,4.5,4.6,4.6" }
-    assert_response :success, "can't get changesets in bbox"
-    assert_changesets [changeset3]
-
-    # not found when looking for changesets of non-existing users
-    get :query, :params => { :user => User.maximum(:id) + 1 }
-    assert_response :not_found
-    get :query, :params => { :display_name => " " }
-    assert_response :not_found
-
-    # can't get changesets of user 1 without authenticating
-    get :query, :params => { :user => private_user.id }
-    assert_response :not_found, "shouldn't be able to get changesets by non-public user (ID)"
-    get :query, :params => { :display_name => private_user.display_name }
-    assert_response :not_found, "shouldn't be able to get changesets by non-public user (name)"
-
-    # but this should work
-    basic_authorization private_user.email, "test"
-    get :query, :params => { :user => private_user.id }
-    assert_response :success, "can't get changesets by user ID"
-    assert_changesets [private_user_changeset, private_user_closed_changeset]
-
-    get :query, :params => { :display_name => private_user.display_name }
-    assert_response :success, "can't get changesets by user name"
-    assert_changesets [private_user_changeset, private_user_closed_changeset]
-
-    # check that the correct error is given when we provide both UID and name
-    get :query, :params => { :user => private_user.id,
-                             :display_name => private_user.display_name }
-    assert_response :bad_request, "should be a bad request to have both ID and name specified"
-
-    get :query, :params => { :user => private_user.id, :open => true }
-    assert_response :success, "can't get changesets by user and open"
-    assert_changesets [private_user_changeset]
-
-    get :query, :params => { :time => "2007-12-31" }
-    assert_response :success, "can't get changesets by time-since"
-    assert_changesets [private_user_changeset, private_user_closed_changeset, changeset, closed_changeset, changeset2, changeset3]
-
-    get :query, :params => { :time => "2008-01-01T12:34Z" }
-    assert_response :success, "can't get changesets by time-since with hour"
-    assert_changesets [private_user_changeset, private_user_closed_changeset, changeset, closed_changeset, changeset2, changeset3]
-
-    get :query, :params => { :time => "2007-12-31T23:59Z,2008-01-02T00:01Z" }
-    assert_response :success, "can't get changesets by time-range"
-    assert_changesets [closed_changeset]
-
-    get :query, :params => { :open => "true" }
-    assert_response :success, "can't get changesets by open-ness"
-    assert_changesets [private_user_changeset, changeset, changeset2, changeset3]
-
-    get :query, :params => { :closed => "true" }
-    assert_response :success, "can't get changesets by closed-ness"
-    assert_changesets [private_user_closed_changeset, closed_changeset]
-
-    get :query, :params => { :closed => "true", :user => private_user.id }
-    assert_response :success, "can't get changesets by closed-ness and user"
-    assert_changesets [private_user_closed_changeset]
-
-    get :query, :params => { :closed => "true", :user => user.id }
-    assert_response :success, "can't get changesets by closed-ness and user"
-    assert_changesets [closed_changeset]
-
-    get :query, :params => { :changesets => "#{private_user_changeset.id},#{changeset.id},#{closed_changeset.id}" }
-    assert_response :success, "can't get changesets by id (as comma-separated string)"
-    assert_changesets [private_user_changeset, changeset, closed_changeset]
-
-    get :query, :params => { :changesets => "" }
-    assert_response :bad_request, "should be a bad request since changesets is empty"
-  end
-
-  ##
-  # check that errors are returned if garbage is inserted
-  # into query strings
-  def test_query_invalid
-    ["abracadabra!",
-     "1,2,3,F",
-     ";drop table users;"].each do |bbox|
-      get :query, :params => { :bbox => bbox }
-      assert_response :bad_request, "'#{bbox}' isn't a bbox"
-    end
-
-    ["now()",
-     "00-00-00",
-     ";drop table users;",
-     ",",
-     "-,-"].each do |time|
-      get :query, :params => { :time => time }
-      assert_response :bad_request, "'#{time}' isn't a valid time range"
-    end
-
-    ["me",
-     "foobar",
-     "-1",
-     "0"].each do |uid|
-      get :query, :params => { :user => uid }
-      assert_response :bad_request, "'#{uid}' isn't a valid user ID"
-    end
-  end
-
-  ##
-  # check updating tags on a changeset
-  def test_changeset_update
-    private_user = create(:user, :data_public => false)
-    private_changeset = create(:changeset, :user => private_user)
-    user = create(:user)
-    changeset = create(:changeset, :user => user)
-
-    ## First try with a non-public user
-    new_changeset = private_changeset.to_xml
-    new_tag = XML::Node.new "tag"
-    new_tag["k"] = "tagtesting"
-    new_tag["v"] = "valuetesting"
-    new_changeset.find("//osm/changeset").first << new_tag
-
-    # try without any authorization
-    put :update, :params => { :id => private_changeset.id }, :body => new_changeset.to_s
-    assert_response :unauthorized
-
-    # try with the wrong authorization
-    basic_authorization create(:user).email, "test"
-    put :update, :params => { :id => private_changeset.id }, :body => new_changeset.to_s
-    assert_response :conflict
-
-    # now this should get an unauthorized
-    basic_authorization private_user.email, "test"
-    put :update, :params => { :id => private_changeset.id }, :body => new_changeset.to_s
-    assert_require_public_data "user with their data non-public, shouldn't be able to edit their changeset"
-
-    ## Now try with the public user
-    create(:changeset_tag, :changeset => changeset)
-    new_changeset = changeset.to_xml
-    new_tag = XML::Node.new "tag"
-    new_tag["k"] = "tagtesting"
-    new_tag["v"] = "valuetesting"
-    new_changeset.find("//osm/changeset").first << new_tag
-
-    # try without any authorization
-    @request.env["HTTP_AUTHORIZATION"] = nil
-    put :update, :params => { :id => changeset.id }, :body => new_changeset.to_s
-    assert_response :unauthorized
-
-    # try with the wrong authorization
-    basic_authorization create(:user).email, "test"
-    put :update, :params => { :id => changeset.id }, :body => new_changeset.to_s
-    assert_response :conflict
-
-    # now this should work...
-    basic_authorization user.email, "test"
-    put :update, :params => { :id => changeset.id }, :body => new_changeset.to_s
-    assert_response :success
-
-    assert_select "osm>changeset[id='#{changeset.id}']", 1
-    assert_select "osm>changeset>tag", 2
-    assert_select "osm>changeset>tag[k='tagtesting'][v='valuetesting']", 1
-  end
-
-  ##
-  # check that a user different from the one who opened the changeset
-  # can't modify it.
-  def test_changeset_update_invalid
-    basic_authorization create(:user).email, "test"
-
-    changeset = create(:changeset)
-    new_changeset = changeset.to_xml
-    new_tag = XML::Node.new "tag"
-    new_tag["k"] = "testing"
-    new_tag["v"] = "testing"
-    new_changeset.find("//osm/changeset").first << new_tag
-
-    put :update, :params => { :id => changeset.id }, :body => new_changeset.to_s
-    assert_response :conflict
-  end
-
-  ##
-  # check that a changeset can contain a certain max number of changes.
-  ## FIXME should be changed to an integration test due to the with_controller
-  def test_changeset_limits
-    basic_authorization create(:user).email, "test"
-
-    # open a new changeset
-    xml = "<osm><changeset/></osm>"
-    put :create, :body => xml
-    assert_response :success, "can't create a new changeset"
-    cs_id = @response.body.to_i
-
-    # start the counter just short of where the changeset should finish.
-    offset = 10
-    # alter the database to set the counter on the changeset directly,
-    # otherwise it takes about 6 minutes to fill all of them.
-    changeset = Changeset.find(cs_id)
-    changeset.num_changes = Changeset::MAX_ELEMENTS - offset
-    changeset.save!
-
-    with_controller(NodesController.new) do
-      # create a new node
-      xml = "<osm><node changeset='#{cs_id}' lat='0.0' lon='0.0'/></osm>"
-      put :create, :body => xml
-      assert_response :success, "can't create a new node"
-      node_id = @response.body.to_i
-
-      get :show, :params => { :id => node_id }
-      assert_response :success, "can't read back new node"
-      node_doc = XML::Parser.string(@response.body).parse
-      node_xml = node_doc.find("//osm/node").first
-
-      # loop until we fill the changeset with nodes
-      offset.times do |i|
-        node_xml["lat"] = rand.to_s
-        node_xml["lon"] = rand.to_s
-        node_xml["version"] = (i + 1).to_s
-
-        put :update, :params => { :id => node_id }, :body => node_doc.to_s
-        assert_response :success, "attempt #{i} should have succeeded"
-      end
-
-      # trying again should fail
-      node_xml["lat"] = rand.to_s
-      node_xml["lon"] = rand.to_s
-      node_xml["version"] = offset.to_s
-
-      put :update, :params => { :id => node_id }, :body => node_doc.to_s
-      assert_response :conflict, "final attempt should have failed"
-    end
-
-    changeset = Changeset.find(cs_id)
-    assert_equal Changeset::MAX_ELEMENTS + 1, changeset.num_changes
-
-    # check that the changeset is now closed as well
-    assert_not(changeset.is_open?,
-               "changeset should have been auto-closed by exceeding " \
-               "element limit.")
-  end
-
   ##
   # This should display the last 20 changesets closed
   def test_index
@@ -2062,167 +270,8 @@ CHANGESET
     assert_redirected_to :action => :feed
   end
 
-  ##
-  # check that the changeset download for a changeset with a redacted
-  # element in it doesn't contain that element.
-  def test_diff_download_redacted
-    changeset = create(:changeset)
-    node = create(:node, :with_history, :version => 2, :changeset => changeset)
-    node_v1 = node.old_nodes.find_by(:version => 1)
-    node_v1.redact!(create(:redaction))
-
-    get :download, :params => { :id => changeset.id }
-    assert_response :success
-
-    assert_select "osmChange", 1
-    # this changeset contains the node in versions 1 & 2, but 1 should
-    # be hidden.
-    assert_select "osmChange node[id='#{node.id}']", 1
-    assert_select "osmChange node[id='#{node.id}'][version='1']", 0
-  end
-
-  ##
-  # test subscribe success
-  def test_subscribe_success
-    basic_authorization create(:user).email, "test"
-    changeset = create(:changeset, :closed)
-
-    assert_difference "changeset.subscribers.count", 1 do
-      post :subscribe, :params => { :id => changeset.id }
-    end
-    assert_response :success
-
-    # not closed changeset
-    changeset = create(:changeset)
-    assert_difference "changeset.subscribers.count", 1 do
-      post :subscribe, :params => { :id => changeset.id }
-    end
-    assert_response :success
-  end
-
-  ##
-  # test subscribe fail
-  def test_subscribe_fail
-    user = create(:user)
-
-    # unauthorized
-    changeset = create(:changeset, :closed)
-    assert_no_difference "changeset.subscribers.count" do
-      post :subscribe, :params => { :id => changeset.id }
-    end
-    assert_response :unauthorized
-
-    basic_authorization user.email, "test"
-
-    # bad changeset id
-    assert_no_difference "changeset.subscribers.count" do
-      post :subscribe, :params => { :id => 999111 }
-    end
-    assert_response :not_found
-
-    # trying to subscribe when already subscribed
-    changeset = create(:changeset, :closed)
-    changeset.subscribers.push(user)
-    assert_no_difference "changeset.subscribers.count" do
-      post :subscribe, :params => { :id => changeset.id }
-    end
-    assert_response :conflict
-  end
-
-  ##
-  # test unsubscribe success
-  def test_unsubscribe_success
-    user = create(:user)
-    basic_authorization user.email, "test"
-    changeset = create(:changeset, :closed)
-    changeset.subscribers.push(user)
-
-    assert_difference "changeset.subscribers.count", -1 do
-      post :unsubscribe, :params => { :id => changeset.id }
-    end
-    assert_response :success
-
-    # not closed changeset
-    changeset = create(:changeset)
-    changeset.subscribers.push(user)
-
-    assert_difference "changeset.subscribers.count", -1 do
-      post :unsubscribe, :params => { :id => changeset.id }
-    end
-    assert_response :success
-  end
-
-  ##
-  # test unsubscribe fail
-  def test_unsubscribe_fail
-    # unauthorized
-    changeset = create(:changeset, :closed)
-    assert_no_difference "changeset.subscribers.count" do
-      post :unsubscribe, :params => { :id => changeset.id }
-    end
-    assert_response :unauthorized
-
-    basic_authorization create(:user).email, "test"
-
-    # bad changeset id
-    assert_no_difference "changeset.subscribers.count" do
-      post :unsubscribe, :params => { :id => 999111 }
-    end
-    assert_response :not_found
-
-    # trying to unsubscribe when not subscribed
-    changeset = create(:changeset, :closed)
-    assert_no_difference "changeset.subscribers.count" do
-      post :unsubscribe, :params => { :id => changeset.id }
-    end
-    assert_response :not_found
-  end
-
   private
 
-  ##
-  # boilerplate for checking that certain changesets exist in the
-  # output.
-  def assert_changesets(changesets)
-    assert_select "osm>changeset", changesets.size
-    changesets.each do |changeset|
-      assert_select "osm>changeset[id='#{changeset.id}']", 1
-    end
-  end
-
-  ##
-  # call the include method and assert properties of the bbox
-  def check_after_include(changeset_id, lon, lat, bbox)
-    xml = "<osm><node lon='#{lon}' lat='#{lat}'/></osm>"
-    post :expand_bbox, :params => { :id => changeset_id }, :body => xml
-    assert_response :success, "Setting include of changeset failed: #{@response.body}"
-
-    # check exactly one changeset
-    assert_select "osm>changeset", 1
-    assert_select "osm>changeset[id='#{changeset_id}']", 1
-
-    # check the bbox
-    doc = XML::Parser.string(@response.body).parse
-    changeset = doc.find("//osm/changeset").first
-    assert_equal bbox[0], changeset["min_lon"].to_f, "min lon"
-    assert_equal bbox[1], changeset["min_lat"].to_f, "min lat"
-    assert_equal bbox[2], changeset["max_lon"].to_f, "max lon"
-    assert_equal bbox[3], changeset["max_lat"].to_f, "max lat"
-  end
-
-  ##
-  # update the changeset_id of a way element
-  def update_changeset(xml, changeset_id)
-    xml_attr_rewrite(xml, "changeset", changeset_id)
-  end
-
-  ##
-  # update an attribute in a way element
-  def xml_attr_rewrite(xml, name, value)
-    xml.find("//osm/way").first[name] = value.to_s
-    xml
-  end
-
   ##
   # check the result of a index
   def check_index_result(changesets)
diff --git a/test/controllers/nodes_controller_test.rb b/test/controllers/nodes_controller_test.rb
deleted file mode 100644 (file)
index e63f04e..0000000
+++ /dev/null
@@ -1,550 +0,0 @@
-require "test_helper"
-
-class NodesControllerTest < ActionController::TestCase
-  ##
-  # test all routes which lead to this controller
-  def test_routes
-    assert_routing(
-      { :path => "/api/0.6/node/create", :method => :put },
-      { :controller => "nodes", :action => "create" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/node/1", :method => :get },
-      { :controller => "nodes", :action => "show", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/node/1", :method => :put },
-      { :controller => "nodes", :action => "update", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/node/1", :method => :delete },
-      { :controller => "nodes", :action => "delete", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/nodes", :method => :get },
-      { :controller => "nodes", :action => "index" }
-    )
-  end
-
-  def test_create
-    private_user = create(:user, :data_public => false)
-    private_changeset = create(:changeset, :user => private_user)
-    user = create(:user)
-    changeset = create(:changeset, :user => user)
-
-    # create a node with random lat/lon
-    lat = rand(-50..50) + rand
-    lon = rand(-50..50) + rand
-
-    ## First try with no auth
-    # create a minimal xml file
-    xml = "<osm><node lat='#{lat}' lon='#{lon}' changeset='#{changeset.id}'/></osm>"
-    assert_difference("OldNode.count", 0) do
-      put :create, :body => xml
-    end
-    # hope for unauthorized
-    assert_response :unauthorized, "node upload did not return unauthorized status"
-
-    ## Now try with the user which doesn't have their data public
-    basic_authorization private_user.email, "test"
-
-    # create a minimal xml file
-    xml = "<osm><node lat='#{lat}' lon='#{lon}' changeset='#{private_changeset.id}'/></osm>"
-    assert_difference("Node.count", 0) do
-      put :create, :body => xml
-    end
-    # hope for success
-    assert_require_public_data "node create did not return forbidden status"
-
-    ## Now try with the user that has the public data
-    basic_authorization user.email, "test"
-
-    # create a minimal xml file
-    xml = "<osm><node lat='#{lat}' lon='#{lon}' changeset='#{changeset.id}'/></osm>"
-    put :create, :body => xml
-    # hope for success
-    assert_response :success, "node upload did not return success status"
-
-    # read id of created node and search for it
-    nodeid = @response.body
-    checknode = Node.find(nodeid)
-    assert_not_nil checknode, "uploaded node not found in data base after upload"
-    # compare values
-    assert_in_delta lat * 10000000, checknode.latitude, 1, "saved node does not match requested latitude"
-    assert_in_delta lon * 10000000, checknode.longitude, 1, "saved node does not match requested longitude"
-    assert_equal changeset.id, checknode.changeset_id, "saved node does not belong to changeset that it was created in"
-    assert_equal true, checknode.visible, "saved node is not visible"
-  end
-
-  def test_create_invalid_xml
-    ## Only test public user here, as test_create should cover what's the forbiddens
-    ## that would occur here
-
-    user = create(:user)
-    changeset = create(:changeset, :user => user)
-
-    basic_authorization user.email, "test"
-    lat = 3.434
-    lon = 3.23
-
-    # test that the upload is rejected when xml is valid, but osm doc isn't
-    xml = "<create/>"
-    put :create, :body => xml
-    assert_response :bad_request, "node upload did not return bad_request status"
-    assert_equal "Cannot parse valid node from xml string <create/>. XML doesn't contain an osm/node element.", @response.body
-
-    # test that the upload is rejected when no lat is supplied
-    # create a minimal xml file
-    xml = "<osm><node lon='#{lon}' changeset='#{changeset.id}'/></osm>"
-    put :create, :body => xml
-    # hope for success
-    assert_response :bad_request, "node upload did not return bad_request status"
-    assert_equal "Cannot parse valid node from xml string <node lon=\"3.23\" changeset=\"#{changeset.id}\"/>. lat missing", @response.body
-
-    # test that the upload is rejected when no lon is supplied
-    # create a minimal xml file
-    xml = "<osm><node lat='#{lat}' changeset='#{changeset.id}'/></osm>"
-    put :create, :body => xml
-    # hope for success
-    assert_response :bad_request, "node upload did not return bad_request status"
-    assert_equal "Cannot parse valid node from xml string <node lat=\"3.434\" changeset=\"#{changeset.id}\"/>. lon missing", @response.body
-
-    # test that the upload is rejected when lat is non-numeric
-    # create a minimal xml file
-    xml = "<osm><node lat='abc' lon='#{lon}' changeset='#{changeset.id}'/></osm>"
-    put :create, :body => xml
-    # hope for success
-    assert_response :bad_request, "node upload did not return bad_request status"
-    assert_equal "Cannot parse valid node from xml string <node lat=\"abc\" lon=\"#{lon}\" changeset=\"#{changeset.id}\"/>. lat not a number", @response.body
-
-    # test that the upload is rejected when lon is non-numeric
-    # create a minimal xml file
-    xml = "<osm><node lat='#{lat}' lon='abc' changeset='#{changeset.id}'/></osm>"
-    put :create, :body => xml
-    # hope for success
-    assert_response :bad_request, "node upload did not return bad_request status"
-    assert_equal "Cannot parse valid node from xml string <node lat=\"#{lat}\" lon=\"abc\" changeset=\"#{changeset.id}\"/>. lon not a number", @response.body
-
-    # test that the upload is rejected when we have a tag which is too long
-    xml = "<osm><node lat='#{lat}' lon='#{lon}' changeset='#{changeset.id}'><tag k='foo' v='#{'x' * 256}'/></node></osm>"
-    put :create, :body => xml
-    assert_response :bad_request, "node upload did not return bad_request status"
-    assert_equal ["NodeTag ", " v: is too long (maximum is 255 characters) (\"#{'x' * 256}\")"], @response.body.split(/[0-9]+,foo:/)
-  end
-
-  def test_show
-    # check that a visible node is returned properly
-    get :show, :params => { :id => create(:node).id }
-    assert_response :success
-
-    # check that an deleted node is not returned
-    get :show, :params => { :id => create(:node, :deleted).id }
-    assert_response :gone
-
-    # check chat a non-existent node is not returned
-    get :show, :params => { :id => 0 }
-    assert_response :not_found
-  end
-
-  # this tests deletion restrictions - basic deletion is tested in the unit
-  # tests for node!
-  def test_delete
-    private_user = create(:user, :data_public => false)
-    private_user_changeset = create(:changeset, :user => private_user)
-    private_user_closed_changeset = create(:changeset, :closed, :user => private_user)
-    private_node = create(:node, :changeset => private_user_changeset)
-    private_deleted_node = create(:node, :deleted, :changeset => private_user_changeset)
-
-    ## first try to delete node without auth
-    delete :delete, :params => { :id => private_node.id }
-    assert_response :unauthorized
-
-    ## now set auth for the non-data public user
-    basic_authorization private_user.email, "test"
-
-    # try to delete with an invalid (closed) changeset
-    xml = update_changeset(private_node.to_xml, private_user_closed_changeset.id)
-    delete :delete, :params => { :id => private_node.id }, :body => xml.to_s
-    assert_require_public_data("non-public user shouldn't be able to delete node")
-
-    # try to delete with an invalid (non-existent) changeset
-    xml = update_changeset(private_node.to_xml, 0)
-    delete :delete, :params => { :id => private_node.id }, :body => xml.to_s
-    assert_require_public_data("shouldn't be able to delete node, when user's data is private")
-
-    # valid delete now takes a payload
-    xml = private_node.to_xml
-    delete :delete, :params => { :id => private_node.id }, :body => xml.to_s
-    assert_require_public_data("shouldn't be able to delete node when user's data isn't public'")
-
-    # this won't work since the node is already deleted
-    xml = private_deleted_node.to_xml
-    delete :delete, :params => { :id => private_deleted_node.id }, :body => xml.to_s
-    assert_require_public_data
-
-    # this won't work since the node never existed
-    delete :delete, :params => { :id => 0 }
-    assert_require_public_data
-
-    ## these test whether nodes which are in-use can be deleted:
-    # in a way...
-    private_used_node = create(:node, :changeset => private_user_changeset)
-    create(:way_node, :node => private_used_node)
-
-    xml = private_used_node.to_xml
-    delete :delete, :params => { :id => private_used_node.id }, :body => xml.to_s
-    assert_require_public_data "shouldn't be able to delete a node used in a way (#{@response.body})"
-
-    # in a relation...
-    private_used_node2 = create(:node, :changeset => private_user_changeset)
-    create(:relation_member, :member => private_used_node2)
-
-    xml = private_used_node2.to_xml
-    delete :delete, :params => { :id => private_used_node2.id }, :body => xml.to_s
-    assert_require_public_data "shouldn't be able to delete a node used in a relation (#{@response.body})"
-
-    ## now setup for the public data user
-    user = create(:user, :data_public => true)
-    changeset = create(:changeset, :user => user)
-    closed_changeset = create(:changeset, :closed, :user => user)
-    node = create(:node, :changeset => changeset)
-    basic_authorization user.email, "test"
-
-    # try to delete with an invalid (closed) changeset
-    xml = update_changeset(node.to_xml, closed_changeset.id)
-    delete :delete, :params => { :id => node.id }, :body => xml.to_s
-    assert_response :conflict
-
-    # try to delete with an invalid (non-existent) changeset
-    xml = update_changeset(node.to_xml, 0)
-    delete :delete, :params => { :id => node.id }, :body => xml.to_s
-    assert_response :conflict
-
-    # try to delete a node with a different ID
-    other_node = create(:node)
-    xml = other_node.to_xml
-    delete :delete, :params => { :id => node.id }, :body => xml.to_s
-    assert_response :bad_request,
-                    "should not be able to delete a node with a different ID from the XML"
-
-    # try to delete a node rubbish in the payloads
-    xml = "<delete/>"
-    delete :delete, :params => { :id => node.id }, :body => xml.to_s
-    assert_response :bad_request,
-                    "should not be able to delete a node without a valid XML payload"
-
-    # valid delete now takes a payload
-    xml = node.to_xml
-    delete :delete, :params => { :id => node.id }, :body => xml.to_s
-    assert_response :success
-
-    # valid delete should return the new version number, which should
-    # be greater than the old version number
-    assert @response.body.to_i > node.version,
-           "delete request should return a new version number for node"
-
-    # deleting the same node twice doesn't work
-    xml = node.to_xml
-    delete :delete, :params => { :id => node.id }, :body => xml.to_s
-    assert_response :gone
-
-    # this won't work since the node never existed
-    delete :delete, :params => { :id => 0 }
-    assert_response :not_found
-
-    ## these test whether nodes which are in-use can be deleted:
-    # in a way...
-    used_node = create(:node, :changeset => create(:changeset, :user => user))
-    way_node = create(:way_node, :node => used_node)
-    way_node2 = create(:way_node, :node => used_node)
-
-    xml = used_node.to_xml
-    delete :delete, :params => { :id => used_node.id }, :body => xml.to_s
-    assert_response :precondition_failed,
-                    "shouldn't be able to delete a node used in a way (#{@response.body})"
-    assert_equal "Precondition failed: Node #{used_node.id} is still used by ways #{way_node.way.id},#{way_node2.way.id}.", @response.body
-
-    # in a relation...
-    used_node2 = create(:node, :changeset => create(:changeset, :user => user))
-    relation_member = create(:relation_member, :member => used_node2)
-    relation_member2 = create(:relation_member, :member => used_node2)
-
-    xml = used_node2.to_xml
-    delete :delete, :params => { :id => used_node2.id }, :body => xml.to_s
-    assert_response :precondition_failed,
-                    "shouldn't be able to delete a node used in a relation (#{@response.body})"
-    assert_equal "Precondition failed: Node #{used_node2.id} is still used by relations #{relation_member.relation.id},#{relation_member2.relation.id}.", @response.body
-  end
-
-  ##
-  # tests whether the API works and prevents incorrect use while trying
-  # to update nodes.
-  def test_update
-    ## First test with no user credentials
-    # try and update a node without authorisation
-    # first try to delete node without auth
-    private_user = create(:user, :data_public => false)
-    private_node = create(:node, :changeset => create(:changeset, :user => private_user))
-    user = create(:user)
-    node = create(:node, :changeset => create(:changeset, :user => user))
-
-    xml = node.to_xml
-    put :update, :params => { :id => node.id }, :body => xml.to_s
-    assert_response :unauthorized
-
-    ## Second test with the private user
-
-    # setup auth
-    basic_authorization private_user.email, "test"
-
-    ## trying to break changesets
-
-    # try and update in someone else's changeset
-    xml = update_changeset(private_node.to_xml,
-                           create(:changeset).id)
-    put :update, :params => { :id => private_node.id }, :body => xml.to_s
-    assert_require_public_data "update with other user's changeset should be forbidden when data isn't public"
-
-    # try and update in a closed changeset
-    xml = update_changeset(private_node.to_xml,
-                           create(:changeset, :closed, :user => private_user).id)
-    put :update, :params => { :id => private_node.id }, :body => xml.to_s
-    assert_require_public_data "update with closed changeset should be forbidden, when data isn't public"
-
-    # try and update in a non-existant changeset
-    xml = update_changeset(private_node.to_xml, 0)
-    put :update, :params => { :id => private_node.id }, :body => xml.to_s
-    assert_require_public_data "update with changeset=0 should be forbidden, when data isn't public"
-
-    ## try and submit invalid updates
-    xml = xml_attr_rewrite(private_node.to_xml, "lat", 91.0)
-    put :update, :params => { :id => private_node.id }, :body => xml.to_s
-    assert_require_public_data "node at lat=91 should be forbidden, when data isn't public"
-
-    xml = xml_attr_rewrite(private_node.to_xml, "lat", -91.0)
-    put :update, :params => { :id => private_node.id }, :body => xml.to_s
-    assert_require_public_data "node at lat=-91 should be forbidden, when data isn't public"
-
-    xml = xml_attr_rewrite(private_node.to_xml, "lon", 181.0)
-    put :update, :params => { :id => private_node.id }, :body => xml.to_s
-    assert_require_public_data "node at lon=181 should be forbidden, when data isn't public"
-
-    xml = xml_attr_rewrite(private_node.to_xml, "lon", -181.0)
-    put :update, :params => { :id => private_node.id }, :body => xml.to_s
-    assert_require_public_data "node at lon=-181 should be forbidden, when data isn't public"
-
-    ## finally, produce a good request which still won't work
-    xml = private_node.to_xml
-    put :update, :params => { :id => private_node.id }, :body => xml.to_s
-    assert_require_public_data "should have failed with a forbidden when data isn't public"
-
-    ## Finally test with the public user
-
-    # try and update a node without authorisation
-    # first try to update node without auth
-    xml = node.to_xml
-    put :update, :params => { :id => node.id }, :body => xml.to_s
-    assert_response :forbidden
-
-    # setup auth
-    basic_authorization user.email, "test"
-
-    ## trying to break changesets
-
-    # try and update in someone else's changeset
-    xml = update_changeset(node.to_xml,
-                           create(:changeset).id)
-    put :update, :params => { :id => node.id }, :body => xml.to_s
-    assert_response :conflict, "update with other user's changeset should be rejected"
-
-    # try and update in a closed changeset
-    xml = update_changeset(node.to_xml,
-                           create(:changeset, :closed, :user => user).id)
-    put :update, :params => { :id => node.id }, :body => xml.to_s
-    assert_response :conflict, "update with closed changeset should be rejected"
-
-    # try and update in a non-existant changeset
-    xml = update_changeset(node.to_xml, 0)
-    put :update, :params => { :id => node.id }, :body => xml.to_s
-    assert_response :conflict, "update with changeset=0 should be rejected"
-
-    ## try and submit invalid updates
-    xml = xml_attr_rewrite(node.to_xml, "lat", 91.0)
-    put :update, :params => { :id => node.id }, :body => xml.to_s
-    assert_response :bad_request, "node at lat=91 should be rejected"
-
-    xml = xml_attr_rewrite(node.to_xml, "lat", -91.0)
-    put :update, :params => { :id => node.id }, :body => xml.to_s
-    assert_response :bad_request, "node at lat=-91 should be rejected"
-
-    xml = xml_attr_rewrite(node.to_xml, "lon", 181.0)
-    put :update, :params => { :id => node.id }, :body => xml.to_s
-    assert_response :bad_request, "node at lon=181 should be rejected"
-
-    xml = xml_attr_rewrite(node.to_xml, "lon", -181.0)
-    put :update, :params => { :id => node.id }, :body => xml.to_s
-    assert_response :bad_request, "node at lon=-181 should be rejected"
-
-    ## next, attack the versioning
-    current_node_version = node.version
-
-    # try and submit a version behind
-    xml = xml_attr_rewrite(node.to_xml,
-                           "version", current_node_version - 1)
-    put :update, :params => { :id => node.id }, :body => xml.to_s
-    assert_response :conflict, "should have failed on old version number"
-
-    # try and submit a version ahead
-    xml = xml_attr_rewrite(node.to_xml,
-                           "version", current_node_version + 1)
-    put :update, :params => { :id => node.id }, :body => xml.to_s
-    assert_response :conflict, "should have failed on skipped version number"
-
-    # try and submit total crap in the version field
-    xml = xml_attr_rewrite(node.to_xml,
-                           "version", "p1r4t3s!")
-    put :update, :params => { :id => node.id }, :body => xml.to_s
-    assert_response :conflict,
-                    "should not be able to put 'p1r4at3s!' in the version field"
-
-    ## try an update with the wrong ID
-    xml = create(:node).to_xml
-    put :update, :params => { :id => node.id }, :body => xml.to_s
-    assert_response :bad_request,
-                    "should not be able to update a node with a different ID from the XML"
-
-    ## try an update with a minimal valid XML doc which isn't a well-formed OSM doc.
-    xml = "<update/>"
-    put :update, :params => { :id => node.id }, :body => xml.to_s
-    assert_response :bad_request,
-                    "should not be able to update a node with non-OSM XML doc."
-
-    ## finally, produce a good request which should work
-    xml = node.to_xml
-    put :update, :params => { :id => node.id }, :body => xml.to_s
-    assert_response :success, "a valid update request failed"
-  end
-
-  ##
-  # test fetching multiple nodes
-  def test_index
-    node1 = create(:node)
-    node2 = create(:node, :deleted)
-    node3 = create(:node)
-    node4 = create(:node, :with_history, :version => 2)
-    node5 = create(:node, :deleted, :with_history, :version => 2)
-
-    # check error when no parameter provided
-    get :index
-    assert_response :bad_request
-
-    # check error when no parameter value provided
-    get :index, :params => { :nodes => "" }
-    assert_response :bad_request
-
-    # test a working call
-    get :index, :params => { :nodes => "#{node1.id},#{node2.id},#{node3.id},#{node4.id},#{node5.id}" }
-    assert_response :success
-    assert_select "osm" do
-      assert_select "node", :count => 5
-      assert_select "node[id='#{node1.id}'][visible='true']", :count => 1
-      assert_select "node[id='#{node2.id}'][visible='false']", :count => 1
-      assert_select "node[id='#{node3.id}'][visible='true']", :count => 1
-      assert_select "node[id='#{node4.id}'][visible='true']", :count => 1
-      assert_select "node[id='#{node5.id}'][visible='false']", :count => 1
-    end
-
-    # check error when a non-existent node is included
-    get :index, :params => { :nodes => "#{node1.id},#{node2.id},#{node3.id},#{node4.id},#{node5.id},0" }
-    assert_response :not_found
-  end
-
-  ##
-  # test adding tags to a node
-  def test_duplicate_tags
-    existing_tag = create(:node_tag)
-    assert_equal true, existing_tag.node.changeset.user.data_public
-    # setup auth
-    basic_authorization existing_tag.node.changeset.user.email, "test"
-
-    # add an identical tag to the node
-    tag_xml = XML::Node.new("tag")
-    tag_xml["k"] = existing_tag.k
-    tag_xml["v"] = existing_tag.v
-
-    # add the tag into the existing xml
-    node_xml = existing_tag.node.to_xml
-    node_xml.find("//osm/node").first << tag_xml
-
-    # try and upload it
-    put :update, :params => { :id => existing_tag.node.id }, :body => node_xml.to_s
-    assert_response :bad_request,
-                    "adding duplicate tags to a node should fail with 'bad request'"
-    assert_equal "Element node/#{existing_tag.node.id} has duplicate tags with key #{existing_tag.k}", @response.body
-  end
-
-  # test whether string injection is possible
-  def test_string_injection
-    private_user = create(:user, :data_public => false)
-    private_changeset = create(:changeset, :user => private_user)
-    user = create(:user)
-    changeset = create(:changeset, :user => user)
-
-    ## First try with the non-data public user
-    basic_authorization private_user.email, "test"
-
-    # try and put something into a string that the API might
-    # use unquoted and therefore allow code injection...
-    xml = "<osm><node lat='0' lon='0' changeset='#{private_changeset.id}'>" \
-          '<tag k="#{@user.inspect}" v="0"/>' \
-          "</node></osm>"
-    put :create, :body => xml
-    assert_require_public_data "Shouldn't be able to create with non-public user"
-
-    ## Then try with the public data user
-    basic_authorization user.email, "test"
-
-    # try and put something into a string that the API might
-    # use unquoted and therefore allow code injection...
-    xml = "<osm><node lat='0' lon='0' changeset='#{changeset.id}'>" \
-          '<tag k="#{@user.inspect}" v="0"/>' \
-          "</node></osm>"
-    put :create, :body => xml
-    assert_response :success
-    nodeid = @response.body
-
-    # find the node in the database
-    checknode = Node.find(nodeid)
-    assert_not_nil checknode, "node not found in data base after upload"
-
-    # and grab it using the api
-    get :show, :params => { :id => nodeid }
-    assert_response :success
-    apinode = Node.from_xml(@response.body)
-    assert_not_nil apinode, "downloaded node is nil, but shouldn't be"
-
-    # check the tags are not corrupted
-    assert_equal checknode.tags, apinode.tags
-    assert apinode.tags.include?("\#{@user.inspect}")
-  end
-
-  ##
-  # update the changeset_id of a node element
-  def update_changeset(xml, changeset_id)
-    xml_attr_rewrite(xml, "changeset", changeset_id)
-  end
-
-  ##
-  # update an attribute in the node element
-  def xml_attr_rewrite(xml, name, value)
-    xml.find("//osm/node").first[name] = value.to_s
-    xml
-  end
-
-  ##
-  # parse some xml
-  def xml_parse(xml)
-    parser = XML::Parser.string(xml)
-    parser.parse
-  end
-end
index a1c32333224337f95e238c024d540fa222d1fb42..82821de6c0725db74b7e0864706e79e2fd96ec78 100644 (file)
@@ -10,1087 +10,12 @@ class NotesControllerTest < ActionController::TestCase
   ##
   # test all routes which lead to this controller
   def test_routes
-    assert_routing(
-      { :path => "/api/0.6/notes", :method => :post },
-      { :controller => "notes", :action => "create", :format => "xml" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/notes/1", :method => :get },
-      { :controller => "notes", :action => "show", :id => "1", :format => "xml" }
-    )
-    assert_recognizes(
-      { :controller => "notes", :action => "show", :id => "1", :format => "xml" },
-      { :path => "/api/0.6/notes/1.xml", :method => :get }
-    )
-    assert_routing(
-      { :path => "/api/0.6/notes/1.rss", :method => :get },
-      { :controller => "notes", :action => "show", :id => "1", :format => "rss" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/notes/1.json", :method => :get },
-      { :controller => "notes", :action => "show", :id => "1", :format => "json" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/notes/1.gpx", :method => :get },
-      { :controller => "notes", :action => "show", :id => "1", :format => "gpx" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/notes/1/comment", :method => :post },
-      { :controller => "notes", :action => "comment", :id => "1", :format => "xml" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/notes/1/close", :method => :post },
-      { :controller => "notes", :action => "close", :id => "1", :format => "xml" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/notes/1/reopen", :method => :post },
-      { :controller => "notes", :action => "reopen", :id => "1", :format => "xml" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/notes/1", :method => :delete },
-      { :controller => "notes", :action => "destroy", :id => "1", :format => "xml" }
-    )
-
-    assert_routing(
-      { :path => "/api/0.6/notes", :method => :get },
-      { :controller => "notes", :action => "index", :format => "xml" }
-    )
-    assert_recognizes(
-      { :controller => "notes", :action => "index", :format => "xml" },
-      { :path => "/api/0.6/notes.xml", :method => :get }
-    )
-    assert_routing(
-      { :path => "/api/0.6/notes.rss", :method => :get },
-      { :controller => "notes", :action => "index", :format => "rss" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/notes.json", :method => :get },
-      { :controller => "notes", :action => "index", :format => "json" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/notes.gpx", :method => :get },
-      { :controller => "notes", :action => "index", :format => "gpx" }
-    )
-
-    assert_routing(
-      { :path => "/api/0.6/notes/search", :method => :get },
-      { :controller => "notes", :action => "search", :format => "xml" }
-    )
-    assert_recognizes(
-      { :controller => "notes", :action => "search", :format => "xml" },
-      { :path => "/api/0.6/notes/search.xml", :method => :get }
-    )
-    assert_routing(
-      { :path => "/api/0.6/notes/search.rss", :method => :get },
-      { :controller => "notes", :action => "search", :format => "rss" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/notes/search.json", :method => :get },
-      { :controller => "notes", :action => "search", :format => "json" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/notes/search.gpx", :method => :get },
-      { :controller => "notes", :action => "search", :format => "gpx" }
-    )
-
-    assert_routing(
-      { :path => "/api/0.6/notes/feed", :method => :get },
-      { :controller => "notes", :action => "feed", :format => "rss" }
-    )
-
-    assert_recognizes(
-      { :controller => "notes", :action => "create" },
-      { :path => "/api/0.6/notes/addPOIexec", :method => :post }
-    )
-    assert_recognizes(
-      { :controller => "notes", :action => "close" },
-      { :path => "/api/0.6/notes/closePOIexec", :method => :post }
-    )
-    assert_recognizes(
-      { :controller => "notes", :action => "comment" },
-      { :path => "/api/0.6/notes/editPOIexec", :method => :post }
-    )
-    assert_recognizes(
-      { :controller => "notes", :action => "index", :format => "gpx" },
-      { :path => "/api/0.6/notes/getGPX", :method => :get }
-    )
-    assert_recognizes(
-      { :controller => "notes", :action => "feed", :format => "rss" },
-      { :path => "/api/0.6/notes/getRSSfeed", :method => :get }
-    )
-
     assert_routing(
       { :path => "/user/username/notes", :method => :get },
       { :controller => "notes", :action => "mine", :display_name => "username" }
     )
   end
 
-  def test_create_success
-    assert_difference "Note.count", 1 do
-      assert_difference "NoteComment.count", 1 do
-        post :create, :params => { :lat => -1.0, :lon => -1.0, :text => "This is a comment", :format => "json" }
-      end
-    end
-    assert_response :success
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "Feature", js["type"]
-    assert_equal "Point", js["geometry"]["type"]
-    assert_equal [-1.0, -1.0], js["geometry"]["coordinates"]
-    assert_equal "open", js["properties"]["status"]
-    assert_equal 1, js["properties"]["comments"].count
-    assert_equal "opened", js["properties"]["comments"].last["action"]
-    assert_equal "This is a comment", js["properties"]["comments"].last["text"]
-    assert_nil js["properties"]["comments"].last["user"]
-    id = js["properties"]["id"]
-
-    get :show, :params => { :id => id, :format => "json" }
-    assert_response :success
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "Feature", js["type"]
-    assert_equal "Point", js["geometry"]["type"]
-    assert_equal [-1.0, -1.0], js["geometry"]["coordinates"]
-    assert_equal id, js["properties"]["id"]
-    assert_equal "open", js["properties"]["status"]
-    assert_equal 1, js["properties"]["comments"].count
-    assert_equal "opened", js["properties"]["comments"].last["action"]
-    assert_equal "This is a comment", js["properties"]["comments"].last["text"]
-    assert_nil js["properties"]["comments"].last["user"]
-  end
-
-  def test_create_fail
-    assert_no_difference "Note.count" do
-      assert_no_difference "NoteComment.count" do
-        post :create, :params => { :lon => -1.0, :text => "This is a comment" }
-      end
-    end
-    assert_response :bad_request
-
-    assert_no_difference "Note.count" do
-      assert_no_difference "NoteComment.count" do
-        post :create, :params => { :lat => -1.0, :text => "This is a comment" }
-      end
-    end
-    assert_response :bad_request
-
-    assert_no_difference "Note.count" do
-      assert_no_difference "NoteComment.count" do
-        post :create, :params => { :lat => -1.0, :lon => -1.0 }
-      end
-    end
-    assert_response :bad_request
-
-    assert_no_difference "Note.count" do
-      assert_no_difference "NoteComment.count" do
-        post :create, :params => { :lat => -1.0, :lon => -1.0, :text => "" }
-      end
-    end
-    assert_response :bad_request
-
-    assert_no_difference "Note.count" do
-      assert_no_difference "NoteComment.count" do
-        post :create, :params => { :lat => -100.0, :lon => -1.0, :text => "This is a comment" }
-      end
-    end
-    assert_response :bad_request
-
-    assert_no_difference "Note.count" do
-      assert_no_difference "NoteComment.count" do
-        post :create, :params => { :lat => -1.0, :lon => -200.0, :text => "This is a comment" }
-      end
-    end
-    assert_response :bad_request
-
-    assert_no_difference "Note.count" do
-      assert_no_difference "NoteComment.count" do
-        post :create, :params => { :lat => "abc", :lon => -1.0, :text => "This is a comment" }
-      end
-    end
-    assert_response :bad_request
-
-    assert_no_difference "Note.count" do
-      assert_no_difference "NoteComment.count" do
-        post :create, :params => { :lat => -1.0, :lon => "abc", :text => "This is a comment" }
-      end
-    end
-    assert_response :bad_request
-
-    assert_no_difference "Note.count" do
-      assert_no_difference "NoteComment.count" do
-        post :create, :params => { :lat => -1.0, :lon => -1.0, :text => "x\u0000y" }
-      end
-    end
-    assert_response :bad_request
-  end
-
-  def test_comment_success
-    open_note_with_comment = create(:note_with_comments)
-    assert_difference "NoteComment.count", 1 do
-      assert_no_difference "ActionMailer::Base.deliveries.size" do
-        perform_enqueued_jobs do
-          post :comment, :params => { :id => open_note_with_comment.id, :text => "This is an additional comment", :format => "json" }
-        end
-      end
-    end
-    assert_response :success
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "Feature", js["type"]
-    assert_equal open_note_with_comment.id, js["properties"]["id"]
-    assert_equal "open", js["properties"]["status"]
-    assert_equal 2, js["properties"]["comments"].count
-    assert_equal "commented", js["properties"]["comments"].last["action"]
-    assert_equal "This is an additional comment", js["properties"]["comments"].last["text"]
-    assert_nil js["properties"]["comments"].last["user"]
-
-    get :show, :params => { :id => open_note_with_comment.id, :format => "json" }
-    assert_response :success
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "Feature", js["type"]
-    assert_equal open_note_with_comment.id, js["properties"]["id"]
-    assert_equal "open", js["properties"]["status"]
-    assert_equal 2, js["properties"]["comments"].count
-    assert_equal "commented", js["properties"]["comments"].last["action"]
-    assert_equal "This is an additional comment", js["properties"]["comments"].last["text"]
-    assert_nil js["properties"]["comments"].last["user"]
-
-    # Ensure that emails are sent to users
-    first_user = create(:user)
-    second_user = create(:user)
-    third_user = create(:user)
-
-    note_with_comments_by_users = create(:note) do |note|
-      create(:note_comment, :note => note, :author => first_user)
-      create(:note_comment, :note => note, :author => second_user)
-    end
-    assert_difference "NoteComment.count", 1 do
-      assert_difference "ActionMailer::Base.deliveries.size", 2 do
-        perform_enqueued_jobs do
-          post :comment, :params => { :id => note_with_comments_by_users.id, :text => "This is an additional comment", :format => "json" }
-        end
-      end
-    end
-    assert_response :success
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "Feature", js["type"]
-    assert_equal note_with_comments_by_users.id, js["properties"]["id"]
-    assert_equal "open", js["properties"]["status"]
-    assert_equal 3, js["properties"]["comments"].count
-    assert_equal "commented", js["properties"]["comments"].last["action"]
-    assert_equal "This is an additional comment", js["properties"]["comments"].last["text"]
-    assert_nil js["properties"]["comments"].last["user"]
-
-    email = ActionMailer::Base.deliveries.find { |e| e.to.first == first_user.email }
-    assert_not_nil email
-    assert_equal 1, email.to.length
-    assert_equal "[OpenStreetMap] An anonymous user has commented on one of your notes", email.subject
-
-    email = ActionMailer::Base.deliveries.find { |e| e.to.first == second_user.email }
-    assert_not_nil email
-    assert_equal 1, email.to.length
-    assert_equal "[OpenStreetMap] An anonymous user has commented on a note you are interested in", email.subject
-
-    get :show, :params => { :id => note_with_comments_by_users.id, :format => "json" }
-    assert_response :success
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "Feature", js["type"]
-    assert_equal note_with_comments_by_users.id, js["properties"]["id"]
-    assert_equal "open", js["properties"]["status"]
-    assert_equal 3, js["properties"]["comments"].count
-    assert_equal "commented", js["properties"]["comments"].last["action"]
-    assert_equal "This is an additional comment", js["properties"]["comments"].last["text"]
-    assert_nil js["properties"]["comments"].last["user"]
-
-    ActionMailer::Base.deliveries.clear
-
-    basic_authorization third_user.email, "test"
-
-    assert_difference "NoteComment.count", 1 do
-      assert_difference "ActionMailer::Base.deliveries.size", 2 do
-        perform_enqueued_jobs do
-          post :comment, :params => { :id => note_with_comments_by_users.id, :text => "This is an additional comment", :format => "json" }
-        end
-      end
-    end
-    assert_response :success
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "Feature", js["type"]
-    assert_equal note_with_comments_by_users.id, js["properties"]["id"]
-    assert_equal "open", js["properties"]["status"]
-    assert_equal 4, js["properties"]["comments"].count
-    assert_equal "commented", js["properties"]["comments"].last["action"]
-    assert_equal "This is an additional comment", js["properties"]["comments"].last["text"]
-    assert_equal third_user.display_name, js["properties"]["comments"].last["user"]
-
-    email = ActionMailer::Base.deliveries.find { |e| e.to.first == first_user.email }
-    assert_not_nil email
-    assert_equal 1, email.to.length
-    assert_equal "[OpenStreetMap] #{third_user.display_name} has commented on one of your notes", email.subject
-    assert_equal first_user.email, email.to.first
-
-    email = ActionMailer::Base.deliveries.find { |e| e.to.first == second_user.email }
-    assert_not_nil email
-    assert_equal 1, email.to.length
-    assert_equal "[OpenStreetMap] #{third_user.display_name} has commented on a note you are interested in", email.subject
-
-    get :show, :params => { :id => note_with_comments_by_users.id, :format => "json" }
-    assert_response :success
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "Feature", js["type"]
-    assert_equal note_with_comments_by_users.id, js["properties"]["id"]
-    assert_equal "open", js["properties"]["status"]
-    assert_equal 4, js["properties"]["comments"].count
-    assert_equal "commented", js["properties"]["comments"].last["action"]
-    assert_equal "This is an additional comment", js["properties"]["comments"].last["text"]
-    assert_equal third_user.display_name, js["properties"]["comments"].last["user"]
-
-    ActionMailer::Base.deliveries.clear
-  end
-
-  def test_comment_fail
-    open_note_with_comment = create(:note_with_comments)
-
-    assert_no_difference "NoteComment.count" do
-      post :comment, :params => { :text => "This is an additional comment" }
-    end
-    assert_response :bad_request
-
-    assert_no_difference "NoteComment.count" do
-      post :comment, :params => { :id => open_note_with_comment.id }
-    end
-    assert_response :bad_request
-
-    assert_no_difference "NoteComment.count" do
-      post :comment, :params => { :id => open_note_with_comment.id, :text => "" }
-    end
-    assert_response :bad_request
-
-    assert_no_difference "NoteComment.count" do
-      post :comment, :params => { :id => 12345, :text => "This is an additional comment" }
-    end
-    assert_response :not_found
-
-    hidden_note_with_comment = create(:note_with_comments, :status => "hidden")
-
-    assert_no_difference "NoteComment.count" do
-      post :comment, :params => { :id => hidden_note_with_comment.id, :text => "This is an additional comment" }
-    end
-    assert_response :gone
-
-    closed_note_with_comment = create(:note_with_comments, :status => "closed", :closed_at => Time.now)
-
-    assert_no_difference "NoteComment.count" do
-      post :comment, :params => { :id => closed_note_with_comment.id, :text => "This is an additional comment" }
-    end
-    assert_response :conflict
-
-    assert_no_difference "NoteComment.count" do
-      post :comment, :params => { :id => open_note_with_comment.id, :text => "x\u0000y" }
-    end
-    assert_response :bad_request
-  end
-
-  def test_close_success
-    open_note_with_comment = create(:note_with_comments)
-    user = create(:user)
-
-    post :close, :params => { :id => open_note_with_comment.id, :text => "This is a close comment", :format => "json" }
-    assert_response :unauthorized
-
-    basic_authorization user.email, "test"
-
-    post :close, :params => { :id => open_note_with_comment.id, :text => "This is a close comment", :format => "json" }
-    assert_response :success
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "Feature", js["type"]
-    assert_equal open_note_with_comment.id, js["properties"]["id"]
-    assert_equal "closed", js["properties"]["status"]
-    assert_equal 2, js["properties"]["comments"].count
-    assert_equal "closed", js["properties"]["comments"].last["action"]
-    assert_equal "This is a close comment", js["properties"]["comments"].last["text"]
-    assert_equal user.display_name, js["properties"]["comments"].last["user"]
-
-    get :show, :params => { :id => open_note_with_comment.id, :format => "json" }
-    assert_response :success
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "Feature", js["type"]
-    assert_equal open_note_with_comment.id, js["properties"]["id"]
-    assert_equal "closed", js["properties"]["status"]
-    assert_equal 2, js["properties"]["comments"].count
-    assert_equal "closed", js["properties"]["comments"].last["action"]
-    assert_equal "This is a close comment", js["properties"]["comments"].last["text"]
-    assert_equal user.display_name, js["properties"]["comments"].last["user"]
-  end
-
-  def test_close_fail
-    post :close
-    assert_response :unauthorized
-
-    basic_authorization create(:user).email, "test"
-
-    post :close
-    assert_response :bad_request
-
-    post :close, :params => { :id => 12345 }
-    assert_response :not_found
-
-    hidden_note_with_comment = create(:note_with_comments, :status => "hidden")
-
-    post :close, :params => { :id => hidden_note_with_comment.id }
-    assert_response :gone
-
-    closed_note_with_comment = create(:note_with_comments, :status => "closed", :closed_at => Time.now)
-
-    post :close, :params => { :id => closed_note_with_comment.id }
-    assert_response :conflict
-  end
-
-  def test_reopen_success
-    closed_note_with_comment = create(:note_with_comments, :status => "closed", :closed_at => Time.now)
-    user = create(:user)
-
-    post :reopen, :params => { :id => closed_note_with_comment.id, :text => "This is a reopen comment", :format => "json" }
-    assert_response :unauthorized
-
-    basic_authorization user.email, "test"
-
-    post :reopen, :params => { :id => closed_note_with_comment.id, :text => "This is a reopen comment", :format => "json" }
-    assert_response :success
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "Feature", js["type"]
-    assert_equal closed_note_with_comment.id, js["properties"]["id"]
-    assert_equal "open", js["properties"]["status"]
-    assert_equal 2, js["properties"]["comments"].count
-    assert_equal "reopened", js["properties"]["comments"].last["action"]
-    assert_equal "This is a reopen comment", js["properties"]["comments"].last["text"]
-    assert_equal user.display_name, js["properties"]["comments"].last["user"]
-
-    get :show, :params => { :id => closed_note_with_comment.id, :format => "json" }
-    assert_response :success
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "Feature", js["type"]
-    assert_equal closed_note_with_comment.id, js["properties"]["id"]
-    assert_equal "open", js["properties"]["status"]
-    assert_equal 2, js["properties"]["comments"].count
-    assert_equal "reopened", js["properties"]["comments"].last["action"]
-    assert_equal "This is a reopen comment", js["properties"]["comments"].last["text"]
-    assert_equal user.display_name, js["properties"]["comments"].last["user"]
-  end
-
-  def test_reopen_fail
-    hidden_note_with_comment = create(:note_with_comments, :status => "hidden")
-
-    post :reopen, :params => { :id => hidden_note_with_comment.id }
-    assert_response :unauthorized
-
-    basic_authorization create(:user).email, "test"
-
-    post :reopen, :params => { :id => 12345 }
-    assert_response :not_found
-
-    post :reopen, :params => { :id => hidden_note_with_comment.id }
-    assert_response :gone
-
-    open_note_with_comment = create(:note_with_comments)
-
-    post :reopen, :params => { :id => open_note_with_comment.id }
-    assert_response :conflict
-  end
-
-  def test_show_success
-    open_note = create(:note_with_comments)
-
-    get :show, :params => { :id => open_note.id, :format => "xml" }
-    assert_response :success
-    assert_equal "application/xml", @response.content_type
-    assert_select "osm", :count => 1 do
-      assert_select "note[lat='#{open_note.lat}'][lon='#{open_note.lon}']", :count => 1 do
-        assert_select "id", open_note.id.to_s
-        assert_select "url", note_url(open_note, :format => "xml")
-        assert_select "comment_url", comment_note_url(open_note, :format => "xml")
-        assert_select "close_url", close_note_url(open_note, :format => "xml")
-        assert_select "date_created", open_note.created_at.to_s
-        assert_select "status", open_note.status
-        assert_select "comments", :count => 1 do
-          assert_select "comment", :count => 1
-        end
-      end
-    end
-
-    get :show, :params => { :id => open_note.id, :format => "rss" }
-    assert_response :success
-    assert_equal "application/rss+xml", @response.content_type
-    assert_select "rss", :count => 1 do
-      assert_select "channel", :count => 1 do
-        assert_select "item", :count => 1 do
-          assert_select "link", browse_note_url(open_note)
-          assert_select "guid", note_url(open_note)
-          assert_select "pubDate", open_note.created_at.to_s(:rfc822)
-          #          assert_select "geo:lat", open_note.lat.to_s
-          #          assert_select "geo:long", open_note.lon
-          #          assert_select "georss:point", "#{open_note.lon} #{open_note.lon}"
-        end
-      end
-    end
-
-    get :show, :params => { :id => open_note.id, :format => "json" }
-    assert_response :success
-    assert_equal "application/json", @response.content_type
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "Feature", js["type"]
-    assert_equal "Point", js["geometry"]["type"]
-    assert_equal open_note.lat, js["geometry"]["coordinates"][0]
-    assert_equal open_note.lon, js["geometry"]["coordinates"][1]
-    assert_equal open_note.id, js["properties"]["id"]
-    assert_equal note_url(open_note, :format => "json"), js["properties"]["url"]
-    assert_equal comment_note_url(open_note, :format => "json"), js["properties"]["comment_url"]
-    assert_equal close_note_url(open_note, :format => "json"), js["properties"]["close_url"]
-    assert_equal open_note.created_at.to_s, js["properties"]["date_created"]
-    assert_equal open_note.status, js["properties"]["status"]
-
-    get :show, :params => { :id => open_note.id, :format => "gpx" }
-    assert_response :success
-    assert_equal "application/gpx+xml", @response.content_type
-    assert_select "gpx", :count => 1 do
-      assert_select "wpt[lat='#{open_note.lat}'][lon='#{open_note.lon}']", :count => 1 do
-        assert_select "time", :count => 1
-        assert_select "name", "Note: #{open_note.id}"
-        assert_select "desc", :count => 1
-        assert_select "link[href='http://test.host/note/#{open_note.id}']", :count => 1
-        assert_select "extensions", :count => 1 do
-          assert_select "id", open_note.id.to_s
-          assert_select "url", note_url(open_note, :format => "gpx")
-          assert_select "comment_url", comment_note_url(open_note, :format => "gpx")
-          assert_select "close_url", close_note_url(open_note, :format => "gpx")
-        end
-      end
-    end
-  end
-
-  def test_show_hidden_comment
-    note_with_hidden_comment = create(:note) do |note|
-      create(:note_comment, :note => note, :body => "Valid comment for hidden note")
-      create(:note_comment, :note => note, :visible => false)
-      create(:note_comment, :note => note, :body => "Another valid comment for hidden note")
-    end
-
-    get :show, :params => { :id => note_with_hidden_comment.id, :format => "json" }
-    assert_response :success
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "Feature", js["type"]
-    assert_equal note_with_hidden_comment.id, js["properties"]["id"]
-    assert_equal 2, js["properties"]["comments"].count
-    assert_equal "Valid comment for hidden note", js["properties"]["comments"][0]["text"]
-    assert_equal "Another valid comment for hidden note", js["properties"]["comments"][1]["text"]
-  end
-
-  def test_show_fail
-    get :show, :params => { :id => 12345 }
-    assert_response :not_found
-
-    get :show, :params => { :id => create(:note, :status => "hidden").id }
-    assert_response :gone
-  end
-
-  def test_destroy_success
-    open_note_with_comment = create(:note_with_comments)
-    user = create(:user)
-    moderator_user = create(:moderator_user)
-
-    delete :destroy, :params => { :id => open_note_with_comment.id, :text => "This is a hide comment", :format => "json" }
-    assert_response :unauthorized
-
-    basic_authorization user.email, "test"
-
-    delete :destroy, :params => { :id => open_note_with_comment.id, :text => "This is a hide comment", :format => "json" }
-    assert_response :forbidden
-
-    basic_authorization moderator_user.email, "test"
-
-    delete :destroy, :params => { :id => open_note_with_comment.id, :text => "This is a hide comment", :format => "json" }
-    assert_response :success
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "Feature", js["type"]
-    assert_equal open_note_with_comment.id, js["properties"]["id"]
-    assert_equal "hidden", js["properties"]["status"]
-    assert_equal 2, js["properties"]["comments"].count
-    assert_equal "hidden", js["properties"]["comments"].last["action"]
-    assert_equal "This is a hide comment", js["properties"]["comments"].last["text"]
-    assert_equal moderator_user.display_name, js["properties"]["comments"].last["user"]
-
-    get :show, :params => { :id => open_note_with_comment.id, :format => "json" }
-    assert_response :success
-
-    basic_authorization user.email, "test"
-    get :show, :params => { :id => open_note_with_comment.id, :format => "json" }
-    assert_response :gone
-  end
-
-  def test_destroy_fail
-    user = create(:user)
-    moderator_user = create(:moderator_user)
-
-    delete :destroy, :params => { :id => 12345, :format => "json" }
-    assert_response :unauthorized
-
-    basic_authorization user.email, "test"
-
-    delete :destroy, :params => { :id => 12345, :format => "json" }
-    assert_response :forbidden
-
-    basic_authorization moderator_user.email, "test"
-
-    delete :destroy, :params => { :id => 12345, :format => "json" }
-    assert_response :not_found
-
-    hidden_note_with_comment = create(:note_with_comments, :status => "hidden")
-
-    delete :destroy, :params => { :id => hidden_note_with_comment.id, :format => "json" }
-    assert_response :gone
-  end
-
-  def test_index_success
-    position = (1.1 * GeoRecord::SCALE).to_i
-    create(:note_with_comments, :latitude => position, :longitude => position)
-    create(:note_with_comments, :latitude => position, :longitude => position)
-
-    get :index, :params => { :bbox => "1,1,1.2,1.2", :format => "rss" }
-    assert_response :success
-    assert_equal "application/rss+xml", @response.content_type
-    assert_select "rss", :count => 1 do
-      assert_select "channel", :count => 1 do
-        assert_select "item", :count => 2
-      end
-    end
-
-    get :index, :params => { :bbox => "1,1,1.2,1.2", :format => "json" }
-    assert_response :success
-    assert_equal "application/json", @response.content_type
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "FeatureCollection", js["type"]
-    assert_equal 2, js["features"].count
-
-    get :index, :params => { :bbox => "1,1,1.2,1.2", :format => "xml" }
-    assert_response :success
-    assert_equal "application/xml", @response.content_type
-    assert_select "osm", :count => 1 do
-      assert_select "note", :count => 2
-    end
-
-    get :index, :params => { :bbox => "1,1,1.2,1.2", :format => "gpx" }
-    assert_response :success
-    assert_equal "application/gpx+xml", @response.content_type
-    assert_select "gpx", :count => 1 do
-      assert_select "wpt", :count => 2
-    end
-  end
-
-  def test_index_limit
-    position = (1.1 * GeoRecord::SCALE).to_i
-    create(:note_with_comments, :latitude => position, :longitude => position)
-    create(:note_with_comments, :latitude => position, :longitude => position)
-
-    get :index, :params => { :bbox => "1,1,1.2,1.2", :limit => 1, :format => "rss" }
-    assert_response :success
-    assert_equal "application/rss+xml", @response.content_type
-    assert_select "rss", :count => 1 do
-      assert_select "channel", :count => 1 do
-        assert_select "item", :count => 1
-      end
-    end
-
-    get :index, :params => { :bbox => "1,1,1.2,1.2", :limit => 1, :format => "json" }
-    assert_response :success
-    assert_equal "application/json", @response.content_type
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "FeatureCollection", js["type"]
-    assert_equal 1, js["features"].count
-
-    get :index, :params => { :bbox => "1,1,1.2,1.2", :limit => 1, :format => "xml" }
-    assert_response :success
-    assert_equal "application/xml", @response.content_type
-    assert_select "osm", :count => 1 do
-      assert_select "note", :count => 1
-    end
-
-    get :index, :params => { :bbox => "1,1,1.2,1.2", :limit => 1, :format => "gpx" }
-    assert_response :success
-    assert_equal "application/gpx+xml", @response.content_type
-    assert_select "gpx", :count => 1 do
-      assert_select "wpt", :count => 1
-    end
-  end
-
-  def test_index_empty_area
-    get :index, :params => { :bbox => "5,5,5.1,5.1", :format => "rss" }
-    assert_response :success
-    assert_equal "application/rss+xml", @response.content_type
-    assert_select "rss", :count => 1 do
-      assert_select "channel", :count => 1 do
-        assert_select "item", :count => 0
-      end
-    end
-
-    get :index, :params => { :bbox => "5,5,5.1,5.1", :format => "json" }
-    assert_response :success
-    assert_equal "application/json", @response.content_type
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "FeatureCollection", js["type"]
-    assert_equal 0, js["features"].count
-
-    get :index, :params => { :bbox => "5,5,5.1,5.1", :format => "xml" }
-    assert_response :success
-    assert_equal "application/xml", @response.content_type
-    assert_select "osm", :count => 1 do
-      assert_select "note", :count => 0
-    end
-
-    get :index, :params => { :bbox => "5,5,5.1,5.1", :format => "gpx" }
-    assert_response :success
-    assert_equal "application/gpx+xml", @response.content_type
-    assert_select "gpx", :count => 1 do
-      assert_select "wpt", :count => 0
-    end
-  end
-
-  def test_index_large_area
-    get :index, :params => { :bbox => "-2.5,-2.5,2.5,2.5", :format => :json }
-    assert_response :success
-    assert_equal "application/json", @response.content_type
-
-    get :index, :params => { :l => "-2.5", :b => "-2.5", :r => "2.5", :t => "2.5", :format => :json }
-    assert_response :success
-    assert_equal "application/json", @response.content_type
-
-    get :index, :params => { :bbox => "-10,-10,12,12", :format => :json }
-    assert_response :bad_request
-    assert_equal "application/json", @response.content_type
-
-    get :index, :params => { :l => "-10", :b => "-10", :r => "12", :t => "12", :format => :json }
-    assert_response :bad_request
-    assert_equal "application/json", @response.content_type
-  end
-
-  def test_index_closed
-    create(:note_with_comments, :status => "closed", :closed_at => Time.now - 5.days)
-    create(:note_with_comments, :status => "closed", :closed_at => Time.now - 100.days)
-    create(:note_with_comments, :status => "hidden")
-    create(:note_with_comments)
-
-    # Open notes + closed in last 7 days
-    get :index, :params => { :bbox => "1,1,1.7,1.7", :closed => "7", :format => "json" }
-    assert_response :success
-    assert_equal "application/json", @response.content_type
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "FeatureCollection", js["type"]
-    assert_equal 2, js["features"].count
-
-    # Only open notes
-    get :index, :params => { :bbox => "1,1,1.7,1.7", :closed => "0", :format => "json" }
-    assert_response :success
-    assert_equal "application/json", @response.content_type
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "FeatureCollection", js["type"]
-    assert_equal 1, js["features"].count
-
-    # Open notes + all closed notes
-    get :index, :params => { :bbox => "1,1,1.7,1.7", :closed => "-1", :format => "json" }
-    assert_response :success
-    assert_equal "application/json", @response.content_type
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "FeatureCollection", js["type"]
-    assert_equal 3, js["features"].count
-  end
-
-  def test_index_bad_params
-    get :index, :params => { :bbox => "-2.5,-2.5,2.5" }
-    assert_response :bad_request
-
-    get :index, :params => { :bbox => "-2.5,-2.5,2.5,2.5,2.5" }
-    assert_response :bad_request
-
-    get :index, :params => { :b => "-2.5", :r => "2.5", :t => "2.5" }
-    assert_response :bad_request
-
-    get :index, :params => { :l => "-2.5", :r => "2.5", :t => "2.5" }
-    assert_response :bad_request
-
-    get :index, :params => { :l => "-2.5", :b => "-2.5", :t => "2.5" }
-    assert_response :bad_request
-
-    get :index, :params => { :l => "-2.5", :b => "-2.5", :r => "2.5" }
-    assert_response :bad_request
-
-    get :index, :params => { :bbox => "1,1,1.7,1.7", :limit => "0", :format => "json" }
-    assert_response :bad_request
-
-    get :index, :params => { :bbox => "1,1,1.7,1.7", :limit => "10001", :format => "json" }
-    assert_response :bad_request
-  end
-
-  def test_search_success
-    create(:note_with_comments)
-
-    get :search, :params => { :q => "note comment", :format => "xml" }
-    assert_response :success
-    assert_equal "application/xml", @response.content_type
-    assert_select "osm", :count => 1 do
-      assert_select "note", :count => 1
-    end
-
-    get :search, :params => { :q => "note comment", :format => "json" }
-    assert_response :success
-    assert_equal "application/json", @response.content_type
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "FeatureCollection", js["type"]
-    assert_equal 1, js["features"].count
-
-    get :search, :params => { :q => "note comment", :format => "rss" }
-    assert_response :success
-    assert_equal "application/rss+xml", @response.content_type
-    assert_select "rss", :count => 1 do
-      assert_select "channel", :count => 1 do
-        assert_select "item", :count => 1
-      end
-    end
-
-    get :search, :params => { :q => "note comment", :format => "gpx" }
-    assert_response :success
-    assert_equal "application/gpx+xml", @response.content_type
-    assert_select "gpx", :count => 1 do
-      assert_select "wpt", :count => 1
-    end
-  end
-
-  def test_search_by_display_name_success
-    user = create(:user)
-
-    create(:note) do |note|
-      create(:note_comment, :note => note, :author => user)
-    end
-
-    get :search, :params => { :display_name => user.display_name, :format => "xml" }
-    assert_response :success
-    assert_equal "application/xml", @response.content_type
-    assert_select "osm", :count => 1 do
-      assert_select "note", :count => 1
-    end
-
-    get :search, :params => { :display_name => user.display_name, :format => "json" }
-    assert_response :success
-    assert_equal "application/json", @response.content_type
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "FeatureCollection", js["type"]
-    assert_equal 1, js["features"].count
-
-    get :search, :params => { :display_name => user.display_name, :format => "rss" }
-    assert_response :success
-    assert_equal "application/rss+xml", @response.content_type
-    assert_select "rss", :count => 1 do
-      assert_select "channel", :count => 1 do
-        assert_select "item", :count => 1
-      end
-    end
-
-    get :search, :params => { :display_name => user.display_name, :format => "gpx" }
-    assert_response :success
-    assert_equal "application/gpx+xml", @response.content_type
-    assert_select "gpx", :count => 1 do
-      assert_select "wpt", :count => 1
-    end
-  end
-
-  def test_search_by_user_success
-    user = create(:user)
-
-    create(:note) do |note|
-      create(:note_comment, :note => note, :author => user)
-    end
-
-    get :search, :params => { :user => user.id, :format => "xml" }
-    assert_response :success
-    assert_equal "application/xml", @response.content_type
-    assert_select "osm", :count => 1 do
-      assert_select "note", :count => 1
-    end
-
-    get :search, :params => { :user => user.id, :format => "json" }
-    assert_response :success
-    assert_equal "application/json", @response.content_type
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "FeatureCollection", js["type"]
-    assert_equal 1, js["features"].count
-
-    get :search, :params => { :user => user.id, :format => "rss" }
-    assert_response :success
-    assert_equal "application/rss+xml", @response.content_type
-    assert_select "rss", :count => 1 do
-      assert_select "channel", :count => 1 do
-        assert_select "item", :count => 1
-      end
-    end
-
-    get :search, :params => { :user => user.id, :format => "gpx" }
-    assert_response :success
-    assert_equal "application/gpx+xml", @response.content_type
-    assert_select "gpx", :count => 1 do
-      assert_select "wpt", :count => 1
-    end
-  end
-
-  def test_search_no_match
-    create(:note_with_comments)
-
-    get :search, :params => { :q => "no match", :format => "xml" }
-    assert_response :success
-    assert_equal "application/xml", @response.content_type
-    assert_select "osm", :count => 1 do
-      assert_select "note", :count => 0
-    end
-
-    get :search, :params => { :q => "no match", :format => "json" }
-    assert_response :success
-    assert_equal "application/json", @response.content_type
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "FeatureCollection", js["type"]
-    assert_equal 0, js["features"].count
-
-    get :search, :params => { :q => "no match", :format => "rss" }
-    assert_response :success
-    assert_equal "application/rss+xml", @response.content_type
-    assert_select "rss", :count => 1 do
-      assert_select "channel", :count => 1 do
-        assert_select "item", :count => 0
-      end
-    end
-
-    get :search, :params => { :q => "no match", :format => "gpx" }
-    assert_response :success
-    assert_equal "application/gpx+xml", @response.content_type
-    assert_select "gpx", :count => 1 do
-      assert_select "wpt", :count => 0
-    end
-  end
-
-  def test_search_by_time_no_match
-    create(:note_with_comments)
-
-    get :search, :params => { :from => "01.01.2010", :to => "01.10.2010", :format => "xml" }
-    assert_response :success
-    assert_equal "application/xml", @response.content_type
-    assert_select "osm", :count => 1 do
-      assert_select "note", :count => 0
-    end
-
-    get :search, :params => { :from => "01.01.2010", :to => "01.10.2010", :format => "json" }
-    assert_response :success
-    assert_equal "application/json", @response.content_type
-    js = ActiveSupport::JSON.decode(@response.body)
-    assert_not_nil js
-    assert_equal "FeatureCollection", js["type"]
-    assert_equal 0, js["features"].count
-
-    get :search, :params => { :from => "01.01.2010", :to => "01.10.2010", :format => "rss" }
-    assert_response :success
-    assert_equal "application/rss+xml", @response.content_type
-    assert_select "rss", :count => 1 do
-      assert_select "channel", :count => 1 do
-        assert_select "item", :count => 0
-      end
-    end
-
-    get :search, :params => { :from => "01.01.2010", :to => "01.10.2010", :format => "gpx" }
-    assert_response :success
-    assert_equal "application/gpx+xml", @response.content_type
-    assert_select "gpx", :count => 1 do
-      assert_select "wpt", :count => 0
-    end
-  end
-
-  def test_search_bad_params
-    get :search, :params => { :q => "no match", :limit => "0", :format => "json" }
-    assert_response :bad_request
-
-    get :search, :params => { :q => "no match", :limit => "10001", :format => "json" }
-    assert_response :bad_request
-
-    get :search, :params => { :display_name => "non-existent" }
-    assert_response :bad_request
-
-    get :search, :params => { :user => "-1" }
-    assert_response :bad_request
-
-    get :search, :params => { :from => "wrong-date", :to => "wrong-date" }
-    assert_response :bad_request
-
-    get :search, :params => { :from => "01.01.2010", :to => "2010.01.2010" }
-    assert_response :bad_request
-  end
-
-  def test_feed_success
-    position = (1.1 * GeoRecord::SCALE).to_i
-    create(:note_with_comments, :latitude => position, :longitude => position)
-    create(:note_with_comments, :latitude => position, :longitude => position)
-    position = (1.5 * GeoRecord::SCALE).to_i
-    create(:note_with_comments, :latitude => position, :longitude => position)
-    create(:note_with_comments, :latitude => position, :longitude => position)
-
-    get :feed, :params => { :format => "rss" }
-    assert_response :success
-    assert_equal "application/rss+xml", @response.content_type
-    assert_select "rss", :count => 1 do
-      assert_select "channel", :count => 1 do
-        assert_select "item", :count => 4
-      end
-    end
-
-    get :feed, :params => { :bbox => "1,1,1.2,1.2", :format => "rss" }
-    assert_response :success
-    assert_equal "application/rss+xml", @response.content_type
-    assert_select "rss", :count => 1 do
-      assert_select "channel", :count => 1 do
-        assert_select "item", :count => 2
-      end
-    end
-  end
-
-  def test_feed_fail
-    get :feed, :params => { :bbox => "1,1,1.2", :format => "rss" }
-    assert_response :bad_request
-
-    get :feed, :params => { :bbox => "1,1,1.2,1.2,1.2", :format => "rss" }
-    assert_response :bad_request
-
-    get :feed, :params => { :bbox => "1,1,1.2,1.2", :limit => "0", :format => "rss" }
-    assert_response :bad_request
-
-    get :feed, :params => { :bbox => "1,1,1.2,1.2", :limit => "10001", :format => "rss" }
-    assert_response :bad_request
-  end
-
   def test_mine_success
     first_user = create(:user)
     second_user = create(:user)
diff --git a/test/controllers/old_nodes_controller_test.rb b/test/controllers/old_nodes_controller_test.rb
deleted file mode 100644 (file)
index 94d16c8..0000000
+++ /dev/null
@@ -1,428 +0,0 @@
-require "test_helper"
-
-class OldNodesControllerTest < ActionController::TestCase
-  #
-  # TODO: test history
-  #
-
-  ##
-  # test all routes which lead to this controller
-  def test_routes
-    assert_routing(
-      { :path => "/api/0.6/node/1/history", :method => :get },
-      { :controller => "old_nodes", :action => "history", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/node/1/2", :method => :get },
-      { :controller => "old_nodes", :action => "version", :id => "1", :version => "2" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/node/1/2/redact", :method => :post },
-      { :controller => "old_nodes", :action => "redact", :id => "1", :version => "2" }
-    )
-  end
-
-  ##
-  # test the version call by submitting several revisions of a new node
-  # to the API and ensuring that later calls to version return the
-  # matching versions of the object.
-  #
-  ##
-  # FIXME: Move this test to being an integration test since it spans multiple controllers
-  def test_version
-    private_user = create(:user, :data_public => false)
-    private_node = create(:node, :with_history, :version => 4, :changeset => create(:changeset, :user => private_user))
-    user = create(:user)
-    node = create(:node, :with_history, :version => 4, :changeset => create(:changeset, :user => user))
-    create_list(:node_tag, 2, :node => node)
-    # Ensure that the current tags are propagated to the history too
-    propagate_tags(node, node.old_nodes.last)
-
-    ## First try this with a non-public user
-    basic_authorization private_user.email, "test"
-
-    # setup a simple XML node
-    xml_doc = private_node.to_xml
-    xml_node = xml_doc.find("//osm/node").first
-    nodeid = private_node.id
-
-    # keep a hash of the versions => string, as we'll need something
-    # to test against later
-    versions = {}
-
-    # save a version for later checking
-    versions[xml_node["version"]] = xml_doc.to_s
-
-    # randomly move the node about
-    3.times do
-      # move the node somewhere else
-      xml_node["lat"] = precision(rand * 180 - 90).to_s
-      xml_node["lon"] = precision(rand * 360 - 180).to_s
-      with_controller(NodesController.new) do
-        put :update, :params => { :id => nodeid }, :body => xml_doc.to_s
-        assert_response :forbidden, "Should have rejected node update"
-        xml_node["version"] = @response.body.to_s
-      end
-      # save a version for later checking
-      versions[xml_node["version"]] = xml_doc.to_s
-    end
-
-    # add a bunch of random tags
-    3.times do
-      xml_tag = XML::Node.new("tag")
-      xml_tag["k"] = random_string
-      xml_tag["v"] = random_string
-      xml_node << xml_tag
-      with_controller(NodesController.new) do
-        put :update, :params => { :id => nodeid }, :body => xml_doc.to_s
-        assert_response :forbidden,
-                        "should have rejected node #{nodeid} (#{@response.body}) with forbidden"
-        xml_node["version"] = @response.body.to_s
-      end
-      # save a version for later checking
-      versions[xml_node["version"]] = xml_doc.to_s
-    end
-
-    # probably should check that they didn't get written to the database
-
-    ## Now do it with the public user
-    basic_authorization user.email, "test"
-
-    # setup a simple XML node
-
-    xml_doc = node.to_xml
-    xml_node = xml_doc.find("//osm/node").first
-    nodeid = node.id
-
-    # keep a hash of the versions => string, as we'll need something
-    # to test against later
-    versions = {}
-
-    # save a version for later checking
-    versions[xml_node["version"]] = xml_doc.to_s
-
-    # randomly move the node about
-    3.times do
-      # move the node somewhere else
-      xml_node["lat"] = precision(rand * 180 - 90).to_s
-      xml_node["lon"] = precision(rand * 360 - 180).to_s
-      with_controller(NodesController.new) do
-        put :update, :params => { :id => nodeid }, :body => xml_doc.to_s
-        assert_response :success
-        xml_node["version"] = @response.body.to_s
-      end
-      # save a version for later checking
-      versions[xml_node["version"]] = xml_doc.to_s
-    end
-
-    # add a bunch of random tags
-    3.times do
-      xml_tag = XML::Node.new("tag")
-      xml_tag["k"] = random_string
-      xml_tag["v"] = random_string
-      xml_node << xml_tag
-      with_controller(NodesController.new) do
-        put :update, :params => { :id => nodeid }, :body => xml_doc.to_s
-        assert_response :success,
-                        "couldn't update node #{nodeid} (#{@response.body})"
-        xml_node["version"] = @response.body.to_s
-      end
-      # save a version for later checking
-      versions[xml_node["version"]] = xml_doc.to_s
-    end
-
-    # check all the versions
-    versions.each_key do |key|
-      get :version, :params => { :id => nodeid, :version => key.to_i }
-
-      assert_response :success,
-                      "couldn't get version #{key.to_i} of node #{nodeid}"
-
-      check_node = Node.from_xml(versions[key])
-      api_node = Node.from_xml(@response.body.to_s)
-
-      assert_nodes_are_equal check_node, api_node
-    end
-  end
-
-  def test_not_found_version
-    check_not_found_id_version(70000, 312344)
-    check_not_found_id_version(-1, -13)
-    check_not_found_id_version(create(:node).id, 24354)
-    check_not_found_id_version(24356, create(:node).version)
-  end
-
-  def check_not_found_id_version(id, version)
-    get :version, :params => { :id => id, :version => version }
-    assert_response :not_found
-  rescue ActionController::UrlGenerationError => ex
-    assert_match(/No route matches/, ex.to_s)
-  end
-
-  ##
-  # Test that getting the current version is identical to picking
-  # that version with the version URI call.
-  def test_current_version
-    node = create(:node, :with_history)
-    used_node = create(:node, :with_history)
-    create(:way_node, :node => used_node)
-    node_used_by_relationship = create(:node, :with_history)
-    create(:relation_member, :member => node_used_by_relationship)
-    node_with_versions = create(:node, :with_history, :version => 4)
-
-    create(:node_tag, :node => node)
-    create(:node_tag, :node => used_node)
-    create(:node_tag, :node => node_used_by_relationship)
-    create(:node_tag, :node => node_with_versions)
-    propagate_tags(node, node.old_nodes.last)
-    propagate_tags(used_node, used_node.old_nodes.last)
-    propagate_tags(node_used_by_relationship, node_used_by_relationship.old_nodes.last)
-    propagate_tags(node_with_versions, node_with_versions.old_nodes.last)
-
-    check_current_version(node)
-    check_current_version(used_node)
-    check_current_version(node_used_by_relationship)
-    check_current_version(node_with_versions)
-  end
-
-  ##
-  # test the redaction of an old version of a node, while not being
-  # authorised.
-  def test_redact_node_unauthorised
-    node = create(:node, :with_history, :version => 4)
-    node_v3 = node.old_nodes.find_by(:version => 3)
-
-    do_redact_node(node_v3,
-                   create(:redaction))
-    assert_response :unauthorized, "should need to be authenticated to redact."
-  end
-
-  ##
-  # test the redaction of an old version of a node, while being
-  # authorised as a normal user.
-  def test_redact_node_normal_user
-    basic_authorization create(:user).email, "test"
-
-    node = create(:node, :with_history, :version => 4)
-    node_v3 = node.old_nodes.find_by(:version => 3)
-
-    do_redact_node(node_v3,
-                   create(:redaction))
-    assert_response :forbidden, "should need to be moderator to redact."
-  end
-
-  ##
-  # test that, even as moderator, the current version of a node
-  # can't be redacted.
-  def test_redact_node_current_version
-    basic_authorization create(:moderator_user).email, "test"
-
-    node = create(:node, :with_history, :version => 4)
-    node_v4 = node.old_nodes.find_by(:version => 4)
-
-    do_redact_node(node_v4,
-                   create(:redaction))
-    assert_response :bad_request, "shouldn't be OK to redact current version as moderator."
-  end
-
-  ##
-  # test that redacted nodes aren't visible, regardless of
-  # authorisation except as moderator...
-  def test_version_redacted
-    node = create(:node, :with_history, :version => 2)
-    node_v1 = node.old_nodes.find_by(:version => 1)
-    node_v1.redact!(create(:redaction))
-
-    get :version, :params => { :id => node_v1.node_id, :version => node_v1.version }
-    assert_response :forbidden, "Redacted node shouldn't be visible via the version API."
-
-    # not even to a logged-in user
-    basic_authorization create(:user).email, "test"
-    get :version, :params => { :id => node_v1.node_id, :version => node_v1.version }
-    assert_response :forbidden, "Redacted node shouldn't be visible via the version API, even when logged in."
-  end
-
-  ##
-  # test that redacted nodes aren't visible in the history
-  def test_history_redacted
-    node = create(:node, :with_history, :version => 2)
-    node_v1 = node.old_nodes.find_by(:version => 1)
-    node_v1.redact!(create(:redaction))
-
-    get :history, :params => { :id => node_v1.node_id }
-    assert_response :success, "Redaction shouldn't have stopped history working."
-    assert_select "osm node[id='#{node_v1.node_id}'][version='#{node_v1.version}']", 0, "redacted node #{node_v1.node_id} version #{node_v1.version} shouldn't be present in the history."
-
-    # not even to a logged-in user
-    basic_authorization create(:user).email, "test"
-    get :history, :params => { :id => node_v1.node_id }
-    assert_response :success, "Redaction shouldn't have stopped history working."
-    assert_select "osm node[id='#{node_v1.node_id}'][version='#{node_v1.version}']", 0, "redacted node #{node_v1.node_id} version #{node_v1.version} shouldn't be present in the history, even when logged in."
-  end
-
-  ##
-  # test the redaction of an old version of a node, while being
-  # authorised as a moderator.
-  def test_redact_node_moderator
-    node = create(:node, :with_history, :version => 4)
-    node_v3 = node.old_nodes.find_by(:version => 3)
-    basic_authorization create(:moderator_user).email, "test"
-
-    do_redact_node(node_v3, create(:redaction))
-    assert_response :success, "should be OK to redact old version as moderator."
-
-    # check moderator can still see the redacted data, when passing
-    # the appropriate flag
-    get :version, :params => { :id => node_v3.node_id, :version => node_v3.version }
-    assert_response :forbidden, "After redaction, node should be gone for moderator, when flag not passed."
-    get :version, :params => { :id => node_v3.node_id, :version => node_v3.version, :show_redactions => "true" }
-    assert_response :success, "After redaction, node should not be gone for moderator, when flag passed."
-
-    # and when accessed via history
-    get :history, :params => { :id => node_v3.node_id }
-    assert_response :success, "Redaction shouldn't have stopped history working."
-    assert_select "osm node[id='#{node_v3.node_id}'][version='#{node_v3.version}']", 0, "node #{node_v3.node_id} version #{node_v3.version} should not be present in the history for moderators when not passing flag."
-    get :history, :params => { :id => node_v3.node_id, :show_redactions => "true" }
-    assert_response :success, "Redaction shouldn't have stopped history working."
-    assert_select "osm node[id='#{node_v3.node_id}'][version='#{node_v3.version}']", 1, "node #{node_v3.node_id} version #{node_v3.version} should still be present in the history for moderators when passing flag."
-  end
-
-  # testing that if the moderator drops auth, he can't see the
-  # redacted stuff any more.
-  def test_redact_node_is_redacted
-    node = create(:node, :with_history, :version => 4)
-    node_v3 = node.old_nodes.find_by(:version => 3)
-    basic_authorization create(:moderator_user).email, "test"
-
-    do_redact_node(node_v3, create(:redaction))
-    assert_response :success, "should be OK to redact old version as moderator."
-
-    # re-auth as non-moderator
-    basic_authorization create(:user).email, "test"
-
-    # check can't see the redacted data
-    get :version, :params => { :id => node_v3.node_id, :version => node_v3.version }
-    assert_response :forbidden, "Redacted node shouldn't be visible via the version API."
-
-    # and when accessed via history
-    get :history, :params => { :id => node_v3.node_id }
-    assert_response :success, "Redaction shouldn't have stopped history working."
-    assert_select "osm node[id='#{node_v3.node_id}'][version='#{node_v3.version}']", 0, "redacted node #{node_v3.node_id} version #{node_v3.version} shouldn't be present in the history."
-  end
-
-  ##
-  # test the unredaction of an old version of a node, while not being
-  # authorised.
-  def test_unredact_node_unauthorised
-    node = create(:node, :with_history, :version => 2)
-    node_v1 = node.old_nodes.find_by(:version => 1)
-    node_v1.redact!(create(:redaction))
-
-    post :redact, :params => { :id => node_v1.node_id, :version => node_v1.version }
-    assert_response :unauthorized, "should need to be authenticated to unredact."
-  end
-
-  ##
-  # test the unredaction of an old version of a node, while being
-  # authorised as a normal user.
-  def test_unredact_node_normal_user
-    user = create(:user)
-    node = create(:node, :with_history, :version => 2)
-    node_v1 = node.old_nodes.find_by(:version => 1)
-    node_v1.redact!(create(:redaction))
-
-    basic_authorization user.email, "test"
-
-    post :redact, :params => { :id => node_v1.node_id, :version => node_v1.version }
-    assert_response :forbidden, "should need to be moderator to unredact."
-  end
-
-  ##
-  # test the unredaction of an old version of a node, while being
-  # authorised as a moderator.
-  def test_unredact_node_moderator
-    moderator_user = create(:moderator_user)
-    node = create(:node, :with_history, :version => 2)
-    node_v1 = node.old_nodes.find_by(:version => 1)
-    node_v1.redact!(create(:redaction))
-
-    basic_authorization moderator_user.email, "test"
-
-    post :redact, :params => { :id => node_v1.node_id, :version => node_v1.version }
-    assert_response :success, "should be OK to unredact old version as moderator."
-
-    # check moderator can now see the redacted data, when not
-    # passing the aspecial flag
-    get :version, :params => { :id => node_v1.node_id, :version => node_v1.version }
-    assert_response :success, "After unredaction, node should not be gone for moderator."
-
-    # and when accessed via history
-    get :history, :params => { :id => node_v1.node_id }
-    assert_response :success, "Unredaction shouldn't have stopped history working."
-    assert_select "osm node[id='#{node_v1.node_id}'][version='#{node_v1.version}']", 1, "node #{node_v1.node_id} version #{node_v1.version} should now be present in the history for moderators without passing flag."
-
-    basic_authorization create(:user).email, "test"
-
-    # check normal user can now see the redacted data
-    get :version, :params => { :id => node_v1.node_id, :version => node_v1.version }
-    assert_response :success, "After unredaction, node should be visible to normal users."
-
-    # and when accessed via history
-    get :history, :params => { :id => node_v1.node_id }
-    assert_response :success, "Unredaction shouldn't have stopped history working."
-    assert_select "osm node[id='#{node_v1.node_id}'][version='#{node_v1.version}']", 1, "node #{node_v1.node_id} version #{node_v1.version} should now be present in the history for normal users without passing flag."
-  end
-
-  private
-
-  def do_redact_node(node, redaction)
-    get :version, :params => { :id => node.node_id, :version => node.version }
-    assert_response :success, "should be able to get version #{node.version} of node #{node.node_id}."
-
-    # now redact it
-    post :redact, :params => { :id => node.node_id, :version => node.version, :redaction => redaction.id }
-  end
-
-  def check_current_version(node_id)
-    # get the current version of the node
-    current_node = with_controller(NodesController.new) do
-      get :show, :params => { :id => node_id }
-      assert_response :success, "cant get current node #{node_id}"
-      Node.from_xml(@response.body)
-    end
-    assert_not_nil current_node, "getting node #{node_id} returned nil"
-
-    # get the "old" version of the node from the old_node interface
-    get :version, :params => { :id => node_id, :version => current_node.version }
-    assert_response :success, "cant get old node #{node_id}, v#{current_node.version}"
-    old_node = Node.from_xml(@response.body)
-
-    # check the nodes are the same
-    assert_nodes_are_equal current_node, old_node
-  end
-
-  ##
-  # returns a 16 character long string with some nasty characters in it.
-  # this ought to stress-test the tag handling as well as the versioning.
-  def random_string
-    letters = [["!", '"', "$", "&", ";", "@"],
-               ("a".."z").to_a,
-               ("A".."Z").to_a,
-               ("0".."9").to_a].flatten
-    (1..16).map { |_i| letters[rand(letters.length)] }.join
-  end
-
-  ##
-  # truncate a floating point number to the scale that it is stored in
-  # the database. otherwise rounding errors can produce failing unit
-  # tests when they shouldn't.
-  def precision(f)
-    (f * GeoRecord::SCALE).round.to_f / GeoRecord::SCALE
-  end
-
-  def propagate_tags(node, old_node)
-    node.tags.each do |k, v|
-      create(:old_node_tag, :old_node => old_node, :k => k, :v => v)
-    end
-  end
-end
diff --git a/test/controllers/old_relations_controller_test.rb b/test/controllers/old_relations_controller_test.rb
deleted file mode 100644 (file)
index 9dd9a71..0000000
+++ /dev/null
@@ -1,272 +0,0 @@
-require "test_helper"
-
-class OldRelationsControllerTest < ActionController::TestCase
-  ##
-  # test all routes which lead to this controller
-  def test_routes
-    assert_routing(
-      { :path => "/api/0.6/relation/1/history", :method => :get },
-      { :controller => "old_relations", :action => "history", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/relation/1/2", :method => :get },
-      { :controller => "old_relations", :action => "version", :id => "1", :version => "2" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/relation/1/2/redact", :method => :post },
-      { :controller => "old_relations", :action => "redact", :id => "1", :version => "2" }
-    )
-  end
-
-  # -------------------------------------
-  # Test reading old relations.
-  # -------------------------------------
-  def test_history
-    # check that a visible relations is returned properly
-    get :history, :params => { :id => create(:relation, :with_history).id }
-    assert_response :success
-
-    # check chat a non-existent relations is not returned
-    get :history, :params => { :id => 0 }
-    assert_response :not_found
-  end
-
-  ##
-  # test the redaction of an old version of a relation, while not being
-  # authorised.
-  def test_redact_relation_unauthorised
-    relation = create(:relation, :with_history, :version => 4)
-    relation_v3 = relation.old_relations.find_by(:version => 3)
-
-    do_redact_relation(relation_v3, create(:redaction))
-    assert_response :unauthorized, "should need to be authenticated to redact."
-  end
-
-  ##
-  # test the redaction of an old version of a relation, while being
-  # authorised as a normal user.
-  def test_redact_relation_normal_user
-    relation = create(:relation, :with_history, :version => 4)
-    relation_v3 = relation.old_relations.find_by(:version => 3)
-
-    basic_authorization create(:user).email, "test"
-
-    do_redact_relation(relation_v3, create(:redaction))
-    assert_response :forbidden, "should need to be moderator to redact."
-  end
-
-  ##
-  # test that, even as moderator, the current version of a relation
-  # can't be redacted.
-  def test_redact_relation_current_version
-    relation = create(:relation, :with_history, :version => 4)
-    relation_latest = relation.old_relations.last
-
-    basic_authorization create(:moderator_user).email, "test"
-
-    do_redact_relation(relation_latest, create(:redaction))
-    assert_response :bad_request, "shouldn't be OK to redact current version as moderator."
-  end
-
-  ##
-  # test that redacted relations aren't visible, regardless of
-  # authorisation except as moderator...
-  def test_version_redacted
-    relation = create(:relation, :with_history, :version => 2)
-    relation_v1 = relation.old_relations.find_by(:version => 1)
-    relation_v1.redact!(create(:redaction))
-
-    get :version, :params => { :id => relation_v1.relation_id, :version => relation_v1.version }
-    assert_response :forbidden, "Redacted relation shouldn't be visible via the version API."
-
-    # not even to a logged-in user
-    basic_authorization create(:user).email, "test"
-    get :version, :params => { :id => relation_v1.relation_id, :version => relation_v1.version }
-    assert_response :forbidden, "Redacted relation shouldn't be visible via the version API, even when logged in."
-  end
-
-  ##
-  # test that redacted relations aren't visible in the history
-  def test_history_redacted
-    relation = create(:relation, :with_history, :version => 2)
-    relation_v1 = relation.old_relations.find_by(:version => 1)
-    relation_v1.redact!(create(:redaction))
-
-    get :history, :params => { :id => relation_v1.relation_id }
-    assert_response :success, "Redaction shouldn't have stopped history working."
-    assert_select "osm relation[id='#{relation_v1.relation_id}'][version='#{relation_v1.version}']", 0, "redacted relation #{relation_v1.relation_id} version #{relation_v1.version} shouldn't be present in the history."
-
-    # not even to a logged-in user
-    basic_authorization create(:user).email, "test"
-    get :version, :params => { :id => relation_v1.relation_id, :version => relation_v1.version }
-    get :history, :params => { :id => relation_v1.relation_id }
-    assert_response :success, "Redaction shouldn't have stopped history working."
-    assert_select "osm relation[id='#{relation_v1.relation_id}'][version='#{relation_v1.version}']", 0, "redacted relation #{relation_v1.relation_id} version #{relation_v1.version} shouldn't be present in the history, even when logged in."
-  end
-
-  ##
-  # test the redaction of an old version of a relation, while being
-  # authorised as a moderator.
-  def test_redact_relation_moderator
-    relation = create(:relation, :with_history, :version => 4)
-    relation_v3 = relation.old_relations.find_by(:version => 3)
-
-    basic_authorization create(:moderator_user).email, "test"
-
-    do_redact_relation(relation_v3, create(:redaction))
-    assert_response :success, "should be OK to redact old version as moderator."
-
-    # check moderator can still see the redacted data, when passing
-    # the appropriate flag
-    get :version, :params => { :id => relation_v3.relation_id, :version => relation_v3.version }
-    assert_response :forbidden, "After redaction, relation should be gone for moderator, when flag not passed."
-    get :version, :params => { :id => relation_v3.relation_id, :version => relation_v3.version, :show_redactions => "true" }
-    assert_response :success, "After redaction, relation should not be gone for moderator, when flag passed."
-
-    # and when accessed via history
-    get :history, :params => { :id => relation_v3.relation_id }
-    assert_response :success, "Redaction shouldn't have stopped history working."
-    assert_select "osm relation[id='#{relation_v3.relation_id}'][version='#{relation_v3.version}']", 0, "relation #{relation_v3.relation_id} version #{relation_v3.version} should not be present in the history for moderators when not passing flag."
-    get :history, :params => { :id => relation_v3.relation_id, :show_redactions => "true" }
-    assert_response :success, "Redaction shouldn't have stopped history working."
-    assert_select "osm relation[id='#{relation_v3.relation_id}'][version='#{relation_v3.version}']", 1, "relation #{relation_v3.relation_id} version #{relation_v3.version} should still be present in the history for moderators when passing flag."
-  end
-
-  # testing that if the moderator drops auth, he can't see the
-  # redacted stuff any more.
-  def test_redact_relation_is_redacted
-    relation = create(:relation, :with_history, :version => 4)
-    relation_v3 = relation.old_relations.find_by(:version => 3)
-
-    basic_authorization create(:moderator_user).email, "test"
-
-    do_redact_relation(relation_v3, create(:redaction))
-    assert_response :success, "should be OK to redact old version as moderator."
-
-    # re-auth as non-moderator
-    basic_authorization create(:user).email, "test"
-
-    # check can't see the redacted data
-    get :version, :params => { :id => relation_v3.relation_id, :version => relation_v3.version }
-    assert_response :forbidden, "Redacted relation shouldn't be visible via the version API."
-
-    # and when accessed via history
-    get :history, :params => { :id => relation_v3.relation_id }
-    assert_response :success, "Redaction shouldn't have stopped history working."
-    assert_select "osm relation[id='#{relation_v3.relation_id}'][version='#{relation_v3.version}']", 0, "redacted relation #{relation_v3.relation_id} version #{relation_v3.version} shouldn't be present in the history."
-  end
-
-  ##
-  # test the unredaction of an old version of a relation, while not being
-  # authorised.
-  def test_unredact_relation_unauthorised
-    relation = create(:relation, :with_history, :version => 2)
-    relation_v1 = relation.old_relations.find_by(:version => 1)
-    relation_v1.redact!(create(:redaction))
-
-    post :redact, :params => { :id => relation_v1.relation_id, :version => relation_v1.version }
-    assert_response :unauthorized, "should need to be authenticated to unredact."
-  end
-
-  ##
-  # test the unredaction of an old version of a relation, while being
-  # authorised as a normal user.
-  def test_unredact_relation_normal_user
-    relation = create(:relation, :with_history, :version => 2)
-    relation_v1 = relation.old_relations.find_by(:version => 1)
-    relation_v1.redact!(create(:redaction))
-
-    basic_authorization create(:user).email, "test"
-
-    post :redact, :params => { :id => relation_v1.relation_id, :version => relation_v1.version }
-    assert_response :forbidden, "should need to be moderator to unredact."
-  end
-
-  ##
-  # test the unredaction of an old version of a relation, while being
-  # authorised as a moderator.
-  def test_unredact_relation_moderator
-    relation = create(:relation, :with_history, :version => 2)
-    relation_v1 = relation.old_relations.find_by(:version => 1)
-    relation_v1.redact!(create(:redaction))
-
-    basic_authorization create(:moderator_user).email, "test"
-
-    post :redact, :params => { :id => relation_v1.relation_id, :version => relation_v1.version }
-    assert_response :success, "should be OK to unredact old version as moderator."
-
-    # check moderator can still see the redacted data, without passing
-    # the appropriate flag
-    get :version, :params => { :id => relation_v1.relation_id, :version => relation_v1.version }
-    assert_response :success, "After unredaction, relation should not be gone for moderator."
-
-    # and when accessed via history
-    get :history, :params => { :id => relation_v1.relation_id }
-    assert_response :success, "Redaction shouldn't have stopped history working."
-    assert_select "osm relation[id='#{relation_v1.relation_id}'][version='#{relation_v1.version}']", 1, "relation #{relation_v1.relation_id} version #{relation_v1.version} should still be present in the history for moderators."
-
-    basic_authorization create(:user).email, "test"
-
-    # check normal user can now see the redacted data
-    get :version, :params => { :id => relation_v1.relation_id, :version => relation_v1.version }
-    assert_response :success, "After redaction, node should not be gone for normal user."
-
-    # and when accessed via history
-    get :history, :params => { :id => relation_v1.relation_id }
-    assert_response :success, "Redaction shouldn't have stopped history working."
-    assert_select "osm relation[id='#{relation_v1.relation_id}'][version='#{relation_v1.version}']", 1, "relation #{relation_v1.relation_id} version #{relation_v1.version} should still be present in the history for normal users."
-  end
-
-  private
-
-  ##
-  # check that the current version of a relation is equivalent to the
-  # version which we're getting from the versions call.
-  def check_current_version(relation_id)
-    # get the current version
-    current_relation = with_controller(RelationsController.new) do
-      get :show, :params => { :id => relation_id }
-      assert_response :success, "can't get current relation #{relation_id}"
-      Relation.from_xml(@response.body)
-    end
-    assert_not_nil current_relation, "getting relation #{relation_id} returned nil"
-
-    # get the "old" version of the relation from the version method
-    get :version, :params => { :id => relation_id, :version => current_relation.version }
-    assert_response :success, "can't get old relation #{relation_id}, v#{current_relation.version}"
-    old_relation = Relation.from_xml(@response.body)
-
-    # check that the relations are identical
-    assert_relations_are_equal current_relation, old_relation
-  end
-
-  ##
-  # look at all the versions of the relation in the history and get each version from
-  # the versions call. check that they're the same.
-  def check_history_equals_versions(relation_id)
-    get :history, :params => { :id => relation_id }
-    assert_response :success, "can't get relation #{relation_id} from API"
-    history_doc = XML::Parser.string(@response.body).parse
-    assert_not_nil history_doc, "parsing relation #{relation_id} history failed"
-
-    history_doc.find("//osm/relation").each do |relation_doc|
-      history_relation = Relation.from_xml_node(relation_doc)
-      assert_not_nil history_relation, "parsing relation #{relation_id} version failed"
-
-      get :version, :params => { :id => relation_id, :version => history_relation.version }
-      assert_response :success, "couldn't get relation #{relation_id}, v#{history_relation.version}"
-      version_relation = Relation.from_xml(@response.body)
-      assert_not_nil version_relation, "failed to parse #{relation_id}, v#{history_relation.version}"
-
-      assert_relations_are_equal history_relation, version_relation
-    end
-  end
-
-  def do_redact_relation(relation, redaction)
-    get :version, :params => { :id => relation.relation_id, :version => relation.version }
-    assert_response :success, "should be able to get version #{relation.version} of relation #{relation.relation_id}."
-
-    # now redact it
-    post :redact, :params => { :id => relation.relation_id, :version => relation.version, :redaction => redaction.id }
-  end
-end
diff --git a/test/controllers/old_ways_controller_test.rb b/test/controllers/old_ways_controller_test.rb
deleted file mode 100644 (file)
index 737ca1f..0000000
+++ /dev/null
@@ -1,318 +0,0 @@
-require "test_helper"
-
-class OldWaysControllerTest < ActionController::TestCase
-  ##
-  # test all routes which lead to this controller
-  def test_routes
-    assert_routing(
-      { :path => "/api/0.6/way/1/history", :method => :get },
-      { :controller => "old_ways", :action => "history", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/way/1/2", :method => :get },
-      { :controller => "old_ways", :action => "version", :id => "1", :version => "2" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/way/1/2/redact", :method => :post },
-      { :controller => "old_ways", :action => "redact", :id => "1", :version => "2" }
-    )
-  end
-
-  # -------------------------------------
-  # Test reading old ways.
-  # -------------------------------------
-
-  def test_history_visible
-    # check that a visible way is returned properly
-    get :history, :params => { :id => create(:way, :with_history).id }
-    assert_response :success
-  end
-
-  def test_history_invisible
-    # check that an invisible way's history is returned properly
-    get :history, :params => { :id => create(:way, :with_history, :deleted).id }
-    assert_response :success
-  end
-
-  def test_history_invalid
-    # check chat a non-existent way is not returned
-    get :history, :params => { :id => 0 }
-    assert_response :not_found
-  end
-
-  ##
-  # check that we can retrieve versions of a way
-  def test_version
-    way = create(:way, :with_history)
-    used_way = create(:way, :with_history)
-    create(:relation_member, :member => used_way)
-    way_with_versions = create(:way, :with_history, :version => 4)
-
-    create(:way_tag, :way => way)
-    create(:way_tag, :way => used_way)
-    create(:way_tag, :way => way_with_versions)
-    propagate_tags(way, way.old_ways.last)
-    propagate_tags(used_way, used_way.old_ways.last)
-    propagate_tags(way_with_versions, way_with_versions.old_ways.last)
-
-    check_current_version(way.id)
-    check_current_version(used_way.id)
-    check_current_version(way_with_versions.id)
-  end
-
-  ##
-  # check that returned history is the same as getting all
-  # versions of a way from the api.
-  def test_history_equals_versions
-    way = create(:way, :with_history)
-    used_way = create(:way, :with_history)
-    create(:relation_member, :member => used_way)
-    way_with_versions = create(:way, :with_history, :version => 4)
-
-    check_history_equals_versions(way.id)
-    check_history_equals_versions(used_way.id)
-    check_history_equals_versions(way_with_versions.id)
-  end
-
-  ##
-  # test the redaction of an old version of a way, while not being
-  # authorised.
-  def test_redact_way_unauthorised
-    way = create(:way, :with_history, :version => 4)
-    way_v3 = way.old_ways.find_by(:version => 3)
-
-    do_redact_way(way_v3, create(:redaction))
-    assert_response :unauthorized, "should need to be authenticated to redact."
-  end
-
-  ##
-  # test the redaction of an old version of a way, while being
-  # authorised as a normal user.
-  def test_redact_way_normal_user
-    basic_authorization create(:user).email, "test"
-    way = create(:way, :with_history, :version => 4)
-    way_v3 = way.old_ways.find_by(:version => 3)
-
-    do_redact_way(way_v3, create(:redaction))
-    assert_response :forbidden, "should need to be moderator to redact."
-  end
-
-  ##
-  # test that, even as moderator, the current version of a way
-  # can't be redacted.
-  def test_redact_way_current_version
-    basic_authorization create(:moderator_user).email, "test"
-    way = create(:way, :with_history, :version => 4)
-    way_latest = way.old_ways.last
-
-    do_redact_way(way_latest, create(:redaction))
-    assert_response :bad_request, "shouldn't be OK to redact current version as moderator."
-  end
-
-  ##
-  # test that redacted ways aren't visible, regardless of
-  # authorisation except as moderator...
-  def test_version_redacted
-    way = create(:way, :with_history, :version => 2)
-    way_v1 = way.old_ways.find_by(:version => 1)
-    way_v1.redact!(create(:redaction))
-
-    get :version, :params => { :id => way_v1.way_id, :version => way_v1.version }
-    assert_response :forbidden, "Redacted way shouldn't be visible via the version API."
-
-    # not even to a logged-in user
-    basic_authorization create(:user).email, "test"
-    get :version, :params => { :id => way_v1.way_id, :version => way_v1.version }
-    assert_response :forbidden, "Redacted way shouldn't be visible via the version API, even when logged in."
-  end
-
-  ##
-  # test that redacted ways aren't visible in the history
-  def test_history_redacted
-    way = create(:way, :with_history, :version => 2)
-    way_v1 = way.old_ways.find_by(:version => 1)
-    way_v1.redact!(create(:redaction))
-
-    get :history, :params => { :id => way_v1.way_id }
-    assert_response :success, "Redaction shouldn't have stopped history working."
-    assert_select "osm way[id='#{way_v1.way_id}'][version='#{way_v1.version}']", 0, "redacted way #{way_v1.way_id} version #{way_v1.version} shouldn't be present in the history."
-
-    # not even to a logged-in user
-    basic_authorization create(:user).email, "test"
-    get :version, :params => { :id => way_v1.way_id, :version => way_v1.version }
-    get :history, :params => { :id => way_v1.way_id }
-    assert_response :success, "Redaction shouldn't have stopped history working."
-    assert_select "osm way[id='#{way_v1.way_id}'][version='#{way_v1.version}']", 0, "redacted node #{way_v1.way_id} version #{way_v1.version} shouldn't be present in the history, even when logged in."
-  end
-
-  ##
-  # test the redaction of an old version of a way, while being
-  # authorised as a moderator.
-  def test_redact_way_moderator
-    way = create(:way, :with_history, :version => 4)
-    way_v3 = way.old_ways.find_by(:version => 3)
-    basic_authorization create(:moderator_user).email, "test"
-
-    do_redact_way(way_v3, create(:redaction))
-    assert_response :success, "should be OK to redact old version as moderator."
-
-    # check moderator can still see the redacted data, when passing
-    # the appropriate flag
-    get :version, :params => { :id => way_v3.way_id, :version => way_v3.version }
-    assert_response :forbidden, "After redaction, node should be gone for moderator, when flag not passed."
-    get :version, :params => { :id => way_v3.way_id, :version => way_v3.version, :show_redactions => "true" }
-    assert_response :success, "After redaction, node should not be gone for moderator, when flag passed."
-
-    # and when accessed via history
-    get :history, :params => { :id => way_v3.way_id }
-    assert_response :success, "Redaction shouldn't have stopped history working."
-    assert_select "osm way[id='#{way_v3.way_id}'][version='#{way_v3.version}']", 0, "way #{way_v3.way_id} version #{way_v3.version} should not be present in the history for moderators when not passing flag."
-    get :history, :params => { :id => way_v3.way_id, :show_redactions => "true" }
-    assert_response :success, "Redaction shouldn't have stopped history working."
-    assert_select "osm way[id='#{way_v3.way_id}'][version='#{way_v3.version}']", 1, "way #{way_v3.way_id} version #{way_v3.version} should still be present in the history for moderators when passing flag."
-  end
-
-  # testing that if the moderator drops auth, he can't see the
-  # redacted stuff any more.
-  def test_redact_way_is_redacted
-    way = create(:way, :with_history, :version => 4)
-    way_v3 = way.old_ways.find_by(:version => 3)
-    basic_authorization create(:moderator_user).email, "test"
-
-    do_redact_way(way_v3, create(:redaction))
-    assert_response :success, "should be OK to redact old version as moderator."
-
-    # re-auth as non-moderator
-    basic_authorization create(:user).email, "test"
-
-    # check can't see the redacted data
-    get :version, :params => { :id => way_v3.way_id, :version => way_v3.version }
-    assert_response :forbidden, "Redacted node shouldn't be visible via the version API."
-
-    # and when accessed via history
-    get :history, :params => { :id => way_v3.way_id }
-    assert_response :success, "Redaction shouldn't have stopped history working."
-    assert_select "osm way[id='#{way_v3.way_id}'][version='#{way_v3.version}']", 0, "redacted way #{way_v3.way_id} version #{way_v3.version} shouldn't be present in the history."
-  end
-
-  ##
-  # test the unredaction of an old version of a way, while not being
-  # authorised.
-  def test_unredact_way_unauthorised
-    way = create(:way, :with_history, :version => 2)
-    way_v1 = way.old_ways.find_by(:version => 1)
-    way_v1.redact!(create(:redaction))
-
-    post :redact, :params => { :id => way_v1.way_id, :version => way_v1.version }
-    assert_response :unauthorized, "should need to be authenticated to unredact."
-  end
-
-  ##
-  # test the unredaction of an old version of a way, while being
-  # authorised as a normal user.
-  def test_unredact_way_normal_user
-    way = create(:way, :with_history, :version => 2)
-    way_v1 = way.old_ways.find_by(:version => 1)
-    way_v1.redact!(create(:redaction))
-
-    basic_authorization create(:user).email, "test"
-
-    post :redact, :params => { :id => way_v1.way_id, :version => way_v1.version }
-    assert_response :forbidden, "should need to be moderator to unredact."
-  end
-
-  ##
-  # test the unredaction of an old version of a way, while being
-  # authorised as a moderator.
-  def test_unredact_way_moderator
-    moderator_user = create(:moderator_user)
-    way = create(:way, :with_history, :version => 2)
-    way_v1 = way.old_ways.find_by(:version => 1)
-    way_v1.redact!(create(:redaction))
-
-    basic_authorization moderator_user.email, "test"
-
-    post :redact, :params => { :id => way_v1.way_id, :version => way_v1.version }
-    assert_response :success, "should be OK to unredact old version as moderator."
-
-    # check moderator can still see the unredacted data, without passing
-    # the appropriate flag
-    get :version, :params => { :id => way_v1.way_id, :version => way_v1.version }
-    assert_response :success, "After unredaction, node should not be gone for moderator."
-
-    # and when accessed via history
-    get :history, :params => { :id => way_v1.way_id }
-    assert_response :success, "Unredaction shouldn't have stopped history working."
-    assert_select "osm way[id='#{way_v1.way_id}'][version='#{way_v1.version}']", 1, "way #{way_v1.way_id} version #{way_v1.version} should still be present in the history for moderators."
-
-    basic_authorization create(:user).email, "test"
-
-    # check normal user can now see the unredacted data
-    get :version, :params => { :id => way_v1.way_id, :version => way_v1.version }
-    assert_response :success, "After redaction, node should not be gone for moderator, when flag passed."
-
-    # and when accessed via history
-    get :history, :params => { :id => way_v1.way_id }
-    assert_response :success, "Redaction shouldn't have stopped history working."
-    assert_select "osm way[id='#{way_v1.way_id}'][version='#{way_v1.version}']", 1, "way #{way_v1.way_id} version #{way_v1.version} should still be present in the history for normal users."
-  end
-
-  private
-
-  ##
-  # check that the current version of a way is equivalent to the
-  # version which we're getting from the versions call.
-  def check_current_version(way_id)
-    # get the current version
-    current_way = with_controller(WaysController.new) do
-      get :show, :params => { :id => way_id }
-      assert_response :success, "can't get current way #{way_id}"
-      Way.from_xml(@response.body)
-    end
-    assert_not_nil current_way, "getting way #{way_id} returned nil"
-
-    # get the "old" version of the way from the version method
-    get :version, :params => { :id => way_id, :version => current_way.version }
-    assert_response :success, "can't get old way #{way_id}, v#{current_way.version}"
-    old_way = Way.from_xml(@response.body)
-
-    # check that the ways are identical
-    assert_ways_are_equal current_way, old_way
-  end
-
-  ##
-  # look at all the versions of the way in the history and get each version from
-  # the versions call. check that they're the same.
-  def check_history_equals_versions(way_id)
-    get :history, :params => { :id => way_id }
-    assert_response :success, "can't get way #{way_id} from API"
-    history_doc = XML::Parser.string(@response.body).parse
-    assert_not_nil history_doc, "parsing way #{way_id} history failed"
-
-    history_doc.find("//osm/way").each do |way_doc|
-      history_way = Way.from_xml_node(way_doc)
-      assert_not_nil history_way, "parsing way #{way_id} version failed"
-
-      get :version, :params => { :id => way_id, :version => history_way.version }
-      assert_response :success, "couldn't get way #{way_id}, v#{history_way.version}"
-      version_way = Way.from_xml(@response.body)
-      assert_not_nil version_way, "failed to parse #{way_id}, v#{history_way.version}"
-
-      assert_ways_are_equal history_way, version_way
-    end
-  end
-
-  def do_redact_way(way, redaction)
-    get :version, :params => { :id => way.way_id, :version => way.version }
-    assert_response :success, "should be able to get version #{way.version} of way #{way.way_id}."
-
-    # now redact it
-    post :redact, :params => { :id => way.way_id, :version => way.version, :redaction => redaction.id }
-  end
-
-  def propagate_tags(way, old_way)
-    way.tags.each do |k, v|
-      create(:old_way_tag, :old_way => old_way, :k => k, :v => v)
-    end
-  end
-end
diff --git a/test/controllers/relations_controller_test.rb b/test/controllers/relations_controller_test.rb
deleted file mode 100644 (file)
index a8b0ed2..0000000
+++ /dev/null
@@ -1,1077 +0,0 @@
-require "test_helper"
-
-class RelationsControllerTest < ActionController::TestCase
-  ##
-  # test all routes which lead to this controller
-  def test_routes
-    assert_routing(
-      { :path => "/api/0.6/relation/create", :method => :put },
-      { :controller => "relations", :action => "create" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/relation/1/full", :method => :get },
-      { :controller => "relations", :action => "full", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/relation/1", :method => :get },
-      { :controller => "relations", :action => "show", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/relation/1", :method => :put },
-      { :controller => "relations", :action => "update", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/relation/1", :method => :delete },
-      { :controller => "relations", :action => "delete", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/relations", :method => :get },
-      { :controller => "relations", :action => "index" }
-    )
-
-    assert_routing(
-      { :path => "/api/0.6/node/1/relations", :method => :get },
-      { :controller => "relations", :action => "relations_for_node", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/way/1/relations", :method => :get },
-      { :controller => "relations", :action => "relations_for_way", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/relation/1/relations", :method => :get },
-      { :controller => "relations", :action => "relations_for_relation", :id => "1" }
-    )
-  end
-
-  # -------------------------------------
-  # Test showing relations.
-  # -------------------------------------
-
-  def test_show
-    # check that a visible relation is returned properly
-    get :show, :params => { :id => create(:relation).id }
-    assert_response :success
-
-    # check that an invisible relation is not returned
-    get :show, :params => { :id => create(:relation, :deleted).id }
-    assert_response :gone
-
-    # check chat a non-existent relation is not returned
-    get :show, :params => { :id => 0 }
-    assert_response :not_found
-  end
-
-  ##
-  # check that all relations containing a particular node, and no extra
-  # relations, are returned from the relations_for_node call.
-  def test_relations_for_node
-    node = create(:node)
-    # should include relations with that node as a member
-    relation_with_node = create(:relation_member, :member => node).relation
-    # should ignore relations without that node as a member
-    _relation_without_node = create(:relation_member).relation
-    # should ignore relations with the node involved indirectly, via a way
-    way = create(:way_node, :node => node).way
-    _relation_with_way = create(:relation_member, :member => way).relation
-    # should ignore relations with the node involved indirectly, via a relation
-    second_relation = create(:relation_member, :member => node).relation
-    _super_relation = create(:relation_member, :member => second_relation).relation
-    # should combine multiple relation_member references into just one relation entry
-    create(:relation_member, :member => node, :relation => relation_with_node, :sequence_id => 2)
-    # should not include deleted relations
-    deleted_relation = create(:relation, :deleted)
-    create(:relation_member, :member => node, :relation => deleted_relation)
-
-    check_relations_for_element(:relations_for_node, "node",
-                                node.id,
-                                [relation_with_node, second_relation])
-  end
-
-  def test_relations_for_way
-    way = create(:way)
-    # should include relations with that way as a member
-    relation_with_way = create(:relation_member, :member => way).relation
-    # should ignore relations without that way as a member
-    _relation_without_way = create(:relation_member).relation
-    # should ignore relations with the way involved indirectly, via a relation
-    second_relation = create(:relation_member, :member => way).relation
-    _super_relation = create(:relation_member, :member => second_relation).relation
-    # should combine multiple relation_member references into just one relation entry
-    create(:relation_member, :member => way, :relation => relation_with_way, :sequence_id => 2)
-    # should not include deleted relations
-    deleted_relation = create(:relation, :deleted)
-    create(:relation_member, :member => way, :relation => deleted_relation)
-
-    check_relations_for_element(:relations_for_way, "way",
-                                way.id,
-                                [relation_with_way, second_relation])
-  end
-
-  def test_relations_for_relation
-    relation = create(:relation)
-    # should include relations with that relation as a member
-    relation_with_relation = create(:relation_member, :member => relation).relation
-    # should ignore any relation without that relation as a member
-    _relation_without_relation = create(:relation_member).relation
-    # should ignore relations with the relation involved indirectly, via a relation
-    second_relation = create(:relation_member, :member => relation).relation
-    _super_relation = create(:relation_member, :member => second_relation).relation
-    # should combine multiple relation_member references into just one relation entry
-    create(:relation_member, :member => relation, :relation => relation_with_relation, :sequence_id => 2)
-    # should not include deleted relations
-    deleted_relation = create(:relation, :deleted)
-    create(:relation_member, :member => relation, :relation => deleted_relation)
-    check_relations_for_element(:relations_for_relation, "relation",
-                                relation.id,
-                                [relation_with_relation, second_relation])
-  end
-
-  def check_relations_for_element(method, type, id, expected_relations)
-    # check the "relations for relation" mode
-    get method, :params => { :id => id }
-    assert_response :success
-
-    # count one osm element
-    assert_select "osm[version='#{API_VERSION}'][generator='OpenStreetMap server']", 1
-
-    # we should have only the expected number of relations
-    assert_select "osm>relation", expected_relations.size
-
-    # and each of them should contain the element we originally searched for
-    expected_relations.each do |relation|
-      # The relation should appear once, but the element could appear multiple times
-      assert_select "osm>relation[id='#{relation.id}']", 1
-      assert_select "osm>relation[id='#{relation.id}']>member[type='#{type}'][ref='#{id}']"
-    end
-  end
-
-  def test_full
-    # check the "full" mode
-    get :full, :params => { :id => 999999 }
-    assert_response :not_found
-
-    get :full, :params => { :id => create(:relation, :deleted).id }
-    assert_response :gone
-
-    get :full, :params => { :id => create(:relation).id }
-    assert_response :success
-    # FIXME: check whether this contains the stuff we want!
-  end
-
-  ##
-  # test fetching multiple relations
-  def test_index
-    relation1 = create(:relation)
-    relation2 = create(:relation, :deleted)
-    relation3 = create(:relation, :with_history, :version => 2)
-    relation4 = create(:relation, :with_history, :version => 2)
-    relation4.old_relations.find_by(:version => 1).redact!(create(:redaction))
-
-    # check error when no parameter provided
-    get :index
-    assert_response :bad_request
-
-    # check error when no parameter value provided
-    get :index, :params => { :relations => "" }
-    assert_response :bad_request
-
-    # test a working call
-    get :index, :params => { :relations => "#{relation1.id},#{relation2.id},#{relation3.id},#{relation4.id}" }
-    assert_response :success
-    assert_select "osm" do
-      assert_select "relation", :count => 4
-      assert_select "relation[id='#{relation1.id}'][visible='true']", :count => 1
-      assert_select "relation[id='#{relation2.id}'][visible='false']", :count => 1
-      assert_select "relation[id='#{relation3.id}'][visible='true']", :count => 1
-      assert_select "relation[id='#{relation4.id}'][visible='true']", :count => 1
-    end
-
-    # check error when a non-existent relation is included
-    get :index, :params => { :relations => "#{relation1.id},#{relation2.id},#{relation3.id},#{relation4.id},0" }
-    assert_response :not_found
-  end
-
-  # -------------------------------------
-  # Test simple relation creation.
-  # -------------------------------------
-
-  def test_create
-    private_user = create(:user, :data_public => false)
-    private_changeset = create(:changeset, :user => private_user)
-    user = create(:user)
-    changeset = create(:changeset, :user => user)
-    node = create(:node)
-    way = create(:way_with_nodes, :nodes_count => 2)
-
-    basic_authorization private_user.email, "test"
-
-    # create an relation without members
-    xml = "<osm><relation changeset='#{private_changeset.id}'><tag k='test' v='yes' /></relation></osm>"
-    put :create, :body => xml
-    # hope for forbidden, due to user
-    assert_response :forbidden,
-                    "relation upload should have failed with forbidden"
-
-    ###
-    # create an relation with a node as member
-    # This time try with a role attribute in the relation
-    xml = "<osm><relation changeset='#{private_changeset.id}'>" \
-          "<member  ref='#{node.id}' type='node' role='some'/>" \
-          "<tag k='test' v='yes' /></relation></osm>"
-    put :create, :body => xml
-    # hope for forbidden due to user
-    assert_response :forbidden,
-                    "relation upload did not return forbidden status"
-
-    ###
-    # create an relation with a node as member, this time test that we don't
-    # need a role attribute to be included
-    xml = "<osm><relation changeset='#{private_changeset.id}'>" \
-          "<member  ref='#{node.id}' type='node'/>" + "<tag k='test' v='yes' /></relation></osm>"
-    put :create, :body => xml
-    # hope for forbidden due to user
-    assert_response :forbidden,
-                    "relation upload did not return forbidden status"
-
-    ###
-    # create an relation with a way and a node as members
-    xml = "<osm><relation changeset='#{private_changeset.id}'>" \
-          "<member type='node' ref='#{node.id}' role='some'/>" \
-          "<member type='way' ref='#{way.id}' role='other'/>" \
-          "<tag k='test' v='yes' /></relation></osm>"
-    put :create, :body => xml
-    # hope for forbidden, due to user
-    assert_response :forbidden,
-                    "relation upload did not return success status"
-
-    ## Now try with the public user
-    basic_authorization user.email, "test"
-
-    # create an relation without members
-    xml = "<osm><relation changeset='#{changeset.id}'><tag k='test' v='yes' /></relation></osm>"
-    put :create, :body => xml
-    # hope for success
-    assert_response :success,
-                    "relation upload did not return success status"
-    # read id of created relation and search for it
-    relationid = @response.body
-    checkrelation = Relation.find(relationid)
-    assert_not_nil checkrelation,
-                   "uploaded relation not found in data base after upload"
-    # compare values
-    assert_equal checkrelation.members.length, 0,
-                 "saved relation contains members but should not"
-    assert_equal checkrelation.tags.length, 1,
-                 "saved relation does not contain exactly one tag"
-    assert_equal changeset.id, checkrelation.changeset.id,
-                 "saved relation does not belong in the changeset it was assigned to"
-    assert_equal user.id, checkrelation.changeset.user_id,
-                 "saved relation does not belong to user that created it"
-    assert_equal true, checkrelation.visible,
-                 "saved relation is not visible"
-    # ok the relation is there but can we also retrieve it?
-    get :show, :params => { :id => relationid }
-    assert_response :success
-
-    ###
-    # create an relation with a node as member
-    # This time try with a role attribute in the relation
-    xml = "<osm><relation changeset='#{changeset.id}'>" \
-          "<member  ref='#{node.id}' type='node' role='some'/>" \
-          "<tag k='test' v='yes' /></relation></osm>"
-    put :create, :body => xml
-    # hope for success
-    assert_response :success,
-                    "relation upload did not return success status"
-    # read id of created relation and search for it
-    relationid = @response.body
-    checkrelation = Relation.find(relationid)
-    assert_not_nil checkrelation,
-                   "uploaded relation not found in data base after upload"
-    # compare values
-    assert_equal checkrelation.members.length, 1,
-                 "saved relation does not contain exactly one member"
-    assert_equal checkrelation.tags.length, 1,
-                 "saved relation does not contain exactly one tag"
-    assert_equal changeset.id, checkrelation.changeset.id,
-                 "saved relation does not belong in the changeset it was assigned to"
-    assert_equal user.id, checkrelation.changeset.user_id,
-                 "saved relation does not belong to user that created it"
-    assert_equal true, checkrelation.visible,
-                 "saved relation is not visible"
-    # ok the relation is there but can we also retrieve it?
-
-    get :show, :params => { :id => relationid }
-    assert_response :success
-
-    ###
-    # create an relation with a node as member, this time test that we don't
-    # need a role attribute to be included
-    xml = "<osm><relation changeset='#{changeset.id}'>" \
-          "<member  ref='#{node.id}' type='node'/>" + "<tag k='test' v='yes' /></relation></osm>"
-    put :create, :body => xml
-    # hope for success
-    assert_response :success,
-                    "relation upload did not return success status"
-    # read id of created relation and search for it
-    relationid = @response.body
-    checkrelation = Relation.find(relationid)
-    assert_not_nil checkrelation,
-                   "uploaded relation not found in data base after upload"
-    # compare values
-    assert_equal checkrelation.members.length, 1,
-                 "saved relation does not contain exactly one member"
-    assert_equal checkrelation.tags.length, 1,
-                 "saved relation does not contain exactly one tag"
-    assert_equal changeset.id, checkrelation.changeset.id,
-                 "saved relation does not belong in the changeset it was assigned to"
-    assert_equal user.id, checkrelation.changeset.user_id,
-                 "saved relation does not belong to user that created it"
-    assert_equal true, checkrelation.visible,
-                 "saved relation is not visible"
-    # ok the relation is there but can we also retrieve it?
-
-    get :show, :params => { :id => relationid }
-    assert_response :success
-
-    ###
-    # create an relation with a way and a node as members
-    xml = "<osm><relation changeset='#{changeset.id}'>" \
-          "<member type='node' ref='#{node.id}' role='some'/>" \
-          "<member type='way' ref='#{way.id}' role='other'/>" \
-          "<tag k='test' v='yes' /></relation></osm>"
-    put :create, :body => xml
-    # hope for success
-    assert_response :success,
-                    "relation upload did not return success status"
-    # read id of created relation and search for it
-    relationid = @response.body
-    checkrelation = Relation.find(relationid)
-    assert_not_nil checkrelation,
-                   "uploaded relation not found in data base after upload"
-    # compare values
-    assert_equal checkrelation.members.length, 2,
-                 "saved relation does not have exactly two members"
-    assert_equal checkrelation.tags.length, 1,
-                 "saved relation does not contain exactly one tag"
-    assert_equal changeset.id, checkrelation.changeset.id,
-                 "saved relation does not belong in the changeset it was assigned to"
-    assert_equal user.id, checkrelation.changeset.user_id,
-                 "saved relation does not belong to user that created it"
-    assert_equal true, checkrelation.visible,
-                 "saved relation is not visible"
-    # ok the relation is there but can we also retrieve it?
-    get :show, :params => { :id => relationid }
-    assert_response :success
-  end
-
-  # ------------------------------------
-  # Test updating relations
-  # ------------------------------------
-
-  ##
-  # test that, when tags are updated on a relation, the correct things
-  # happen to the correct tables and the API gives sensible results.
-  # this is to test a case that gregory marler noticed and posted to
-  # josm-dev.
-  ## FIXME Move this to an integration test
-  def test_update_relation_tags
-    user = create(:user)
-    changeset = create(:changeset, :user => user)
-    relation = create(:relation)
-    create_list(:relation_tag, 4, :relation => relation)
-
-    basic_authorization user.email, "test"
-
-    with_relation(relation.id) do |rel|
-      # alter one of the tags
-      tag = rel.find("//osm/relation/tag").first
-      tag["v"] = "some changed value"
-      update_changeset(rel, changeset.id)
-
-      # check that the downloaded tags are the same as the uploaded tags...
-      new_version = with_update(rel) do |new_rel|
-        assert_tags_equal rel, new_rel
-      end
-
-      # check the original one in the current_* table again
-      with_relation(relation.id) { |r| assert_tags_equal rel, r }
-
-      # now check the version in the history
-      with_relation(relation.id, new_version) { |r| assert_tags_equal rel, r }
-    end
-  end
-
-  ##
-  # test that, when tags are updated on a relation when using the diff
-  # upload function, the correct things happen to the correct tables
-  # and the API gives sensible results. this is to test a case that
-  # gregory marler noticed and posted to josm-dev.
-  def test_update_relation_tags_via_upload
-    user = create(:user)
-    changeset = create(:changeset, :user => user)
-    relation = create(:relation)
-    create_list(:relation_tag, 4, :relation => relation)
-
-    basic_authorization user.email, "test"
-
-    with_relation(relation.id) do |rel|
-      # alter one of the tags
-      tag = rel.find("//osm/relation/tag").first
-      tag["v"] = "some changed value"
-      update_changeset(rel, changeset.id)
-
-      # check that the downloaded tags are the same as the uploaded tags...
-      new_version = with_update_diff(rel) do |new_rel|
-        assert_tags_equal rel, new_rel
-      end
-
-      # check the original one in the current_* table again
-      with_relation(relation.id) { |r| assert_tags_equal rel, r }
-
-      # now check the version in the history
-      with_relation(relation.id, new_version) { |r| assert_tags_equal rel, r }
-    end
-  end
-
-  def test_update_wrong_id
-    user = create(:user)
-    changeset = create(:changeset, :user => user)
-    relation = create(:relation)
-    other_relation = create(:relation)
-
-    basic_authorization user.email, "test"
-    with_relation(relation.id) do |rel|
-      update_changeset(rel, changeset.id)
-      put :update, :params => { :id => other_relation.id }, :body => rel.to_s
-      assert_response :bad_request
-    end
-  end
-
-  # -------------------------------------
-  # Test creating some invalid relations.
-  # -------------------------------------
-
-  def test_create_invalid
-    user = create(:user)
-    changeset = create(:changeset, :user => user)
-
-    basic_authorization user.email, "test"
-
-    # create a relation with non-existing node as member
-    xml = "<osm><relation changeset='#{changeset.id}'>" \
-          "<member type='node' ref='0'/><tag k='test' v='yes' />" \
-          "</relation></osm>"
-    put :create, :body => xml
-    # expect failure
-    assert_response :precondition_failed,
-                    "relation upload with invalid node did not return 'precondition failed'"
-    assert_equal "Precondition failed: Relation with id  cannot be saved due to Node with id 0", @response.body
-  end
-
-  # -------------------------------------
-  # Test creating a relation, with some invalid XML
-  # -------------------------------------
-  def test_create_invalid_xml
-    user = create(:user)
-    changeset = create(:changeset, :user => user)
-    node = create(:node)
-
-    basic_authorization user.email, "test"
-
-    # create some xml that should return an error
-    xml = "<osm><relation changeset='#{changeset.id}'>" \
-          "<member type='type' ref='#{node.id}' role=''/>" \
-          "<tag k='tester' v='yep'/></relation></osm>"
-    put :create, :body => xml
-    # expect failure
-    assert_response :bad_request
-    assert_match(/Cannot parse valid relation from xml string/, @response.body)
-    assert_match(/The type is not allowed only, /, @response.body)
-  end
-
-  # -------------------------------------
-  # Test deleting relations.
-  # -------------------------------------
-
-  def test_delete
-    private_user = create(:user, :data_public => false)
-    private_user_closed_changeset = create(:changeset, :closed, :user => private_user)
-    user = create(:user)
-    closed_changeset = create(:changeset, :closed, :user => user)
-    changeset = create(:changeset, :user => user)
-    relation = create(:relation)
-    used_relation = create(:relation)
-    super_relation = create(:relation_member, :member => used_relation).relation
-    deleted_relation = create(:relation, :deleted)
-    multi_tag_relation = create(:relation)
-    create_list(:relation_tag, 4, :relation => multi_tag_relation)
-
-    ## First try to delete relation without auth
-    delete :delete, :params => { :id => relation.id }
-    assert_response :unauthorized
-
-    ## Then try with the private user, to make sure that you get a forbidden
-    basic_authorization private_user.email, "test"
-
-    # this shouldn't work, as we should need the payload...
-    delete :delete, :params => { :id => relation.id }
-    assert_response :forbidden
-
-    # try to delete without specifying a changeset
-    xml = "<osm><relation id='#{relation.id}'/></osm>"
-    delete :delete, :params => { :id => relation.id }, :body => xml.to_s
-    assert_response :forbidden
-
-    # try to delete with an invalid (closed) changeset
-    xml = update_changeset(relation.to_xml,
-                           private_user_closed_changeset.id)
-    delete :delete, :params => { :id => relation.id }, :body => xml.to_s
-    assert_response :forbidden
-
-    # try to delete with an invalid (non-existent) changeset
-    xml = update_changeset(relation.to_xml, 0)
-    delete :delete, :params => { :id => relation.id }, :body => xml.to_s
-    assert_response :forbidden
-
-    # this won't work because the relation is in-use by another relation
-    xml = used_relation.to_xml
-    delete :delete, :params => { :id => used_relation.id }, :body => xml.to_s
-    assert_response :forbidden
-
-    # this should work when we provide the appropriate payload...
-    xml = relation.to_xml
-    delete :delete, :params => { :id => relation.id }, :body => xml.to_s
-    assert_response :forbidden
-
-    # this won't work since the relation is already deleted
-    xml = deleted_relation.to_xml
-    delete :delete, :params => { :id => deleted_relation.id }, :body => xml.to_s
-    assert_response :forbidden
-
-    # this won't work since the relation never existed
-    delete :delete, :params => { :id => 0 }
-    assert_response :forbidden
-
-    ## now set auth for the public user
-    basic_authorization user.email, "test"
-
-    # this shouldn't work, as we should need the payload...
-    delete :delete, :params => { :id => relation.id }
-    assert_response :bad_request
-
-    # try to delete without specifying a changeset
-    xml = "<osm><relation id='#{relation.id}' version='#{relation.version}' /></osm>"
-    delete :delete, :params => { :id => relation.id }, :body => xml.to_s
-    assert_response :bad_request
-    assert_match(/Changeset id is missing/, @response.body)
-
-    # try to delete with an invalid (closed) changeset
-    xml = update_changeset(relation.to_xml,
-                           closed_changeset.id)
-    delete :delete, :params => { :id => relation.id }, :body => xml.to_s
-    assert_response :conflict
-
-    # try to delete with an invalid (non-existent) changeset
-    xml = update_changeset(relation.to_xml, 0)
-    delete :delete, :params => { :id => relation.id }, :body => xml.to_s
-    assert_response :conflict
-
-    # this won't work because the relation is in a changeset owned by someone else
-    xml = update_changeset(relation.to_xml, create(:changeset).id)
-    delete :delete, :params => { :id => relation.id }, :body => xml.to_s
-    assert_response :conflict,
-                    "shouldn't be able to delete a relation in a changeset owned by someone else (#{@response.body})"
-
-    # this won't work because the relation in the payload is different to that passed
-    xml = update_changeset(relation.to_xml, changeset.id)
-    delete :delete, :params => { :id => create(:relation).id }, :body => xml.to_s
-    assert_response :bad_request, "shouldn't be able to delete a relation when payload is different to the url"
-
-    # this won't work because the relation is in-use by another relation
-    xml = update_changeset(used_relation.to_xml, changeset.id)
-    delete :delete, :params => { :id => used_relation.id }, :body => xml.to_s
-    assert_response :precondition_failed,
-                    "shouldn't be able to delete a relation used in a relation (#{@response.body})"
-    assert_equal "Precondition failed: The relation #{used_relation.id} is used in relation #{super_relation.id}.", @response.body
-
-    # this should work when we provide the appropriate payload...
-    xml = update_changeset(multi_tag_relation.to_xml, changeset.id)
-    delete :delete, :params => { :id => multi_tag_relation.id }, :body => xml.to_s
-    assert_response :success
-
-    # valid delete should return the new version number, which should
-    # be greater than the old version number
-    assert @response.body.to_i > multi_tag_relation.version,
-           "delete request should return a new version number for relation"
-
-    # this won't work since the relation is already deleted
-    xml = update_changeset(deleted_relation.to_xml, changeset.id)
-    delete :delete, :params => { :id => deleted_relation.id }, :body => xml.to_s
-    assert_response :gone
-
-    # Public visible relation needs to be deleted
-    xml = update_changeset(super_relation.to_xml, changeset.id)
-    delete :delete, :params => { :id => super_relation.id }, :body => xml.to_s
-    assert_response :success
-
-    # this works now because the relation which was using this one
-    # has been deleted.
-    xml = update_changeset(used_relation.to_xml, changeset.id)
-    delete :delete, :params => { :id => used_relation.id }, :body => xml.to_s
-    assert_response :success,
-                    "should be able to delete a relation used in an old relation (#{@response.body})"
-
-    # this won't work since the relation never existed
-    delete :delete, :params => { :id => 0 }
-    assert_response :not_found
-  end
-
-  ##
-  # when a relation's tag is modified then it should put the bounding
-  # box of all its members into the changeset.
-  def test_tag_modify_bounding_box
-    relation = create(:relation)
-    node1 = create(:node, :lat => 3, :lon => 3)
-    node2 = create(:node, :lat => 5, :lon => 5)
-    way = create(:way)
-    create(:way_node, :way => way, :node => node1)
-    create(:relation_member, :relation => relation, :member => way)
-    create(:relation_member, :relation => relation, :member => node2)
-    # the relation contains nodes1 and node2 (node1
-    # indirectly via the way), so the bbox should be [3,3,5,5].
-    check_changeset_modify(BoundingBox.new(3, 3, 5, 5)) do |changeset_id|
-      # add a tag to an existing relation
-      relation_xml = relation.to_xml
-      relation_element = relation_xml.find("//osm/relation").first
-      new_tag = XML::Node.new("tag")
-      new_tag["k"] = "some_new_tag"
-      new_tag["v"] = "some_new_value"
-      relation_element << new_tag
-
-      # update changeset ID to point to new changeset
-      update_changeset(relation_xml, changeset_id)
-
-      # upload the change
-      put :update, :params => { :id => relation.id }, :body => relation_xml.to_s
-      assert_response :success, "can't update relation for tag/bbox test"
-    end
-  end
-
-  ##
-  # add a member to a relation and check the bounding box is only that
-  # element.
-  def test_add_member_bounding_box
-    relation = create(:relation)
-    node1 = create(:node, :lat => 4, :lon => 4)
-    node2 = create(:node, :lat => 7, :lon => 7)
-    way1 = create(:way)
-    create(:way_node, :way => way1, :node => create(:node, :lat => 8, :lon => 8))
-    way2 = create(:way)
-    create(:way_node, :way => way2, :node => create(:node, :lat => 9, :lon => 9), :sequence_id => 1)
-    create(:way_node, :way => way2, :node => create(:node, :lat => 10, :lon => 10), :sequence_id => 2)
-
-    [node1, node2, way1, way2].each do |element|
-      bbox = element.bbox.to_unscaled
-      check_changeset_modify(bbox) do |changeset_id|
-        relation_xml = Relation.find(relation.id).to_xml
-        relation_element = relation_xml.find("//osm/relation").first
-        new_member = XML::Node.new("member")
-        new_member["ref"] = element.id.to_s
-        new_member["type"] = element.class.to_s.downcase
-        new_member["role"] = "some_role"
-        relation_element << new_member
-
-        # update changeset ID to point to new changeset
-        update_changeset(relation_xml, changeset_id)
-
-        # upload the change
-        put :update, :params => { :id => relation.id }, :body => relation_xml.to_s
-        assert_response :success, "can't update relation for add #{element.class}/bbox test: #{@response.body}"
-
-        # get it back and check the ordering
-        get :show, :params => { :id => relation.id }
-        assert_response :success, "can't read back the relation: #{@response.body}"
-        check_ordering(relation_xml, @response.body)
-      end
-    end
-  end
-
-  ##
-  # remove a member from a relation and check the bounding box is
-  # only that element.
-  def test_remove_member_bounding_box
-    relation = create(:relation)
-    node1 = create(:node, :lat => 3, :lon => 3)
-    node2 = create(:node, :lat => 5, :lon => 5)
-    create(:relation_member, :relation => relation, :member => node1)
-    create(:relation_member, :relation => relation, :member => node2)
-
-    check_changeset_modify(BoundingBox.new(5, 5, 5, 5)) do |changeset_id|
-      # remove node 5 (5,5) from an existing relation
-      relation_xml = relation.to_xml
-      relation_xml
-        .find("//osm/relation/member[@type='node'][@ref='#{node2.id}']")
-        .first.remove!
-
-      # update changeset ID to point to new changeset
-      update_changeset(relation_xml, changeset_id)
-
-      # upload the change
-      put :update, :params => { :id => relation.id }, :body => relation_xml.to_s
-      assert_response :success, "can't update relation for remove node/bbox test"
-    end
-  end
-
-  ##
-  # check that relations are ordered
-  def test_relation_member_ordering
-    user = create(:user)
-    changeset = create(:changeset, :user => user)
-    node1 = create(:node)
-    node2 = create(:node)
-    node3 = create(:node)
-    way1 = create(:way_with_nodes, :nodes_count => 2)
-    way2 = create(:way_with_nodes, :nodes_count => 2)
-
-    basic_authorization user.email, "test"
-
-    doc_str = <<OSM.strip_heredoc
-      <osm>
-       <relation changeset='#{changeset.id}'>
-        <member ref='#{node1.id}' type='node' role='first'/>
-        <member ref='#{node2.id}' type='node' role='second'/>
-        <member ref='#{way1.id}' type='way' role='third'/>
-        <member ref='#{way2.id}' type='way' role='fourth'/>
-       </relation>
-      </osm>
-OSM
-    doc = XML::Parser.string(doc_str).parse
-
-    put :create, :body => doc.to_s
-    assert_response :success, "can't create a relation: #{@response.body}"
-    relation_id = @response.body.to_i
-
-    # get it back and check the ordering
-    get :show, :params => { :id => relation_id }
-    assert_response :success, "can't read back the relation: #{@response.body}"
-    check_ordering(doc, @response.body)
-
-    # insert a member at the front
-    new_member = XML::Node.new "member"
-    new_member["ref"] = node3.id.to_s
-    new_member["type"] = "node"
-    new_member["role"] = "new first"
-    doc.find("//osm/relation").first.child.prev = new_member
-    # update the version, should be 1?
-    doc.find("//osm/relation").first["id"] = relation_id.to_s
-    doc.find("//osm/relation").first["version"] = 1.to_s
-
-    # upload the next version of the relation
-    put :update, :params => { :id => relation_id }, :body => doc.to_s
-    assert_response :success, "can't update relation: #{@response.body}"
-    assert_equal 2, @response.body.to_i
-
-    # get it back again and check the ordering again
-    get :show, :params => { :id => relation_id }
-    assert_response :success, "can't read back the relation: #{@response.body}"
-    check_ordering(doc, @response.body)
-
-    # check the ordering in the history tables:
-    with_controller(OldRelationsController.new) do
-      get :version, :params => { :id => relation_id, :version => 2 }
-      assert_response :success, "can't read back version 2 of the relation #{relation_id}"
-      check_ordering(doc, @response.body)
-    end
-  end
-
-  ##
-  # check that relations can contain duplicate members
-  def test_relation_member_duplicates
-    private_user = create(:user, :data_public => false)
-    user = create(:user)
-    changeset = create(:changeset, :user => user)
-    node1 = create(:node)
-    node2 = create(:node)
-
-    doc_str = <<OSM.strip_heredoc
-      <osm>
-       <relation changeset='#{changeset.id}'>
-        <member ref='#{node1.id}' type='node' role='forward'/>
-        <member ref='#{node2.id}' type='node' role='forward'/>
-        <member ref='#{node1.id}' type='node' role='forward'/>
-        <member ref='#{node2.id}' type='node' role='forward'/>
-       </relation>
-      </osm>
-OSM
-    doc = XML::Parser.string(doc_str).parse
-
-    ## First try with the private user
-    basic_authorization private_user.email, "test"
-
-    put :create, :body => doc.to_s
-    assert_response :forbidden
-
-    ## Now try with the public user
-    basic_authorization user.email, "test"
-
-    put :create, :body => doc.to_s
-    assert_response :success, "can't create a relation: #{@response.body}"
-    relation_id = @response.body.to_i
-
-    # get it back and check the ordering
-    get :show, :params => { :id => relation_id }
-    assert_response :success, "can't read back the relation: #{relation_id}"
-    check_ordering(doc, @response.body)
-  end
-
-  ##
-  # test that the ordering of elements in the history is the same as in current.
-  def test_history_ordering
-    user = create(:user)
-    changeset = create(:changeset, :user => user)
-    node1 = create(:node)
-    node2 = create(:node)
-    node3 = create(:node)
-    node4 = create(:node)
-
-    doc_str = <<OSM.strip_heredoc
-      <osm>
-       <relation changeset='#{changeset.id}'>
-        <member ref='#{node1.id}' type='node' role='forward'/>
-        <member ref='#{node4.id}' type='node' role='forward'/>
-        <member ref='#{node3.id}' type='node' role='forward'/>
-        <member ref='#{node2.id}' type='node' role='forward'/>
-       </relation>
-      </osm>
-OSM
-    doc = XML::Parser.string(doc_str).parse
-    basic_authorization user.email, "test"
-
-    put :create, :body => doc.to_s
-    assert_response :success, "can't create a relation: #{@response.body}"
-    relation_id = @response.body.to_i
-
-    # check the ordering in the current tables:
-    get :show, :params => { :id => relation_id }
-    assert_response :success, "can't read back the relation: #{@response.body}"
-    check_ordering(doc, @response.body)
-
-    # check the ordering in the history tables:
-    with_controller(OldRelationsController.new) do
-      get :version, :params => { :id => relation_id, :version => 1 }
-      assert_response :success, "can't read back version 1 of the relation: #{@response.body}"
-      check_ordering(doc, @response.body)
-    end
-  end
-
-  ##
-  # remove all the members from a relation. the result is pretty useless, but
-  # still technically valid.
-  def test_remove_all_members
-    relation = create(:relation)
-    node1 = create(:node, :lat => 3, :lon => 3)
-    node2 = create(:node, :lat => 5, :lon => 5)
-    way = create(:way)
-    create(:way_node, :way => way, :node => node1)
-    create(:relation_member, :relation => relation, :member => way)
-    create(:relation_member, :relation => relation, :member => node2)
-
-    check_changeset_modify(BoundingBox.new(3, 3, 5, 5)) do |changeset_id|
-      relation_xml = relation.to_xml
-      relation_xml
-        .find("//osm/relation/member")
-        .each(&:remove!)
-
-      # update changeset ID to point to new changeset
-      update_changeset(relation_xml, changeset_id)
-
-      # upload the change
-      put :update, :params => { :id => relation.id }, :body => relation_xml.to_s
-      assert_response :success, "can't update relation for remove all members test"
-      checkrelation = Relation.find(relation.id)
-      assert_not_nil(checkrelation,
-                     "uploaded relation not found in database after upload")
-      assert_equal(0, checkrelation.members.length,
-                   "relation contains members but they should have all been deleted")
-    end
-  end
-
-  # ============================================================
-  # utility functions
-  # ============================================================
-
-  ##
-  # checks that the XML document and the string arguments have
-  # members in the same order.
-  def check_ordering(doc, xml)
-    new_doc = XML::Parser.string(xml).parse
-
-    doc_members = doc.find("//osm/relation/member").collect do |m|
-      [m["ref"].to_i, m["type"].to_sym, m["role"]]
-    end
-
-    new_members = new_doc.find("//osm/relation/member").collect do |m|
-      [m["ref"].to_i, m["type"].to_sym, m["role"]]
-    end
-
-    doc_members.zip(new_members).each do |d, n|
-      assert_equal d, n, "members are not equal - ordering is wrong? (#{doc}, #{xml})"
-    end
-  end
-
-  ##
-  # create a changeset and yield to the caller to set it up, then assert
-  # that the changeset bounding box is +bbox+.
-  def check_changeset_modify(bbox)
-    ## First test with the private user to check that you get a forbidden
-    basic_authorization create(:user, :data_public => false).email, "test"
-
-    # create a new changeset for this operation, so we are assured
-    # that the bounding box will be newly-generated.
-    changeset_id = with_controller(ChangesetsController.new) do
-      xml = "<osm><changeset/></osm>"
-      put :create, :body => xml
-      assert_response :forbidden, "shouldn't be able to create changeset for modify test, as should get forbidden"
-    end
-
-    ## Now do the whole thing with the public user
-    basic_authorization create(:user).email, "test"
-
-    # create a new changeset for this operation, so we are assured
-    # that the bounding box will be newly-generated.
-    changeset_id = with_controller(ChangesetsController.new) do
-      xml = "<osm><changeset/></osm>"
-      put :create, :body => xml
-      assert_response :success, "couldn't create changeset for modify test"
-      @response.body.to_i
-    end
-
-    # go back to the block to do the actual modifies
-    yield changeset_id
-
-    # now download the changeset to check its bounding box
-    with_controller(ChangesetsController.new) do
-      get :show, :params => { :id => changeset_id }
-      assert_response :success, "can't re-read changeset for modify test"
-      assert_select "osm>changeset", 1, "Changeset element doesn't exist in #{@response.body}"
-      assert_select "osm>changeset[id='#{changeset_id}']", 1, "Changeset id=#{changeset_id} doesn't exist in #{@response.body}"
-      assert_select "osm>changeset[min_lon='#{format('%.7f', bbox.min_lon)}']", 1, "Changeset min_lon wrong in #{@response.body}"
-      assert_select "osm>changeset[min_lat='#{format('%.7f', bbox.min_lat)}']", 1, "Changeset min_lat wrong in #{@response.body}"
-      assert_select "osm>changeset[max_lon='#{format('%.7f', bbox.max_lon)}']", 1, "Changeset max_lon wrong in #{@response.body}"
-      assert_select "osm>changeset[max_lat='#{format('%.7f', bbox.max_lat)}']", 1, "Changeset max_lat wrong in #{@response.body}"
-    end
-  end
-
-  ##
-  # yields the relation with the given +id+ (and optional +version+
-  # to read from the history tables) into the block. the parsed XML
-  # doc is returned.
-  def with_relation(id, ver = nil)
-    if ver.nil?
-      get :show, :params => { :id => id }
-    else
-      with_controller(OldRelationsController.new) do
-        get :version, :params => { :id => id, :version => ver }
-      end
-    end
-    assert_response :success
-    yield xml_parse(@response.body)
-  end
-
-  ##
-  # updates the relation (XML) +rel+ and
-  # yields the new version of that relation into the block.
-  # the parsed XML doc is retured.
-  def with_update(rel)
-    rel_id = rel.find("//osm/relation").first["id"].to_i
-    put :update, :params => { :id => rel_id }, :body => rel.to_s
-    assert_response :success, "can't update relation: #{@response.body}"
-    version = @response.body.to_i
-
-    # now get the new version
-    get :show, :params => { :id => rel_id }
-    assert_response :success
-    new_rel = xml_parse(@response.body)
-
-    yield new_rel
-
-    version
-  end
-
-  ##
-  # updates the relation (XML) +rel+ via the diff-upload API and
-  # yields the new version of that relation into the block.
-  # the parsed XML doc is retured.
-  def with_update_diff(rel)
-    rel_id = rel.find("//osm/relation").first["id"].to_i
-    cs_id = rel.find("//osm/relation").first["changeset"].to_i
-    version = nil
-
-    with_controller(ChangesetsController.new) do
-      doc = OSM::API.new.get_xml_doc
-      change = XML::Node.new "osmChange"
-      doc.root = change
-      modify = XML::Node.new "modify"
-      change << modify
-      modify << doc.import(rel.find("//osm/relation").first)
-
-      post :upload, :params => { :id => cs_id }, :body => doc.to_s
-      assert_response :success, "can't upload diff relation: #{@response.body}"
-      version = xml_parse(@response.body).find("//diffResult/relation").first["new_version"].to_i
-    end
-
-    # now get the new version
-    get :show, :params => { :id => rel_id }
-    assert_response :success
-    new_rel = xml_parse(@response.body)
-
-    yield new_rel
-
-    version
-  end
-
-  ##
-  # returns a k->v hash of tags from an xml doc
-  def get_tags_as_hash(a)
-    a.find("//osm/relation/tag").sort_by { |v| v["k"] }.each_with_object({}) do |v, h|
-      h[v["k"]] = v["v"]
-    end
-  end
-
-  ##
-  # assert that all tags on relation documents +a+ and +b+
-  # are equal
-  def assert_tags_equal(a, b)
-    # turn the XML doc into tags hashes
-    a_tags = get_tags_as_hash(a)
-    b_tags = get_tags_as_hash(b)
-
-    assert_equal a_tags.keys, b_tags.keys, "Tag keys should be identical."
-    a_tags.each do |k, v|
-      assert_equal v, b_tags[k],
-                   "Tags which were not altered should be the same. " \
-                   "#{a_tags.inspect} != #{b_tags.inspect}"
-    end
-  end
-
-  ##
-  # update the changeset_id of a node element
-  def update_changeset(xml, changeset_id)
-    xml_attr_rewrite(xml, "changeset", changeset_id)
-  end
-
-  ##
-  # update an attribute in the node element
-  def xml_attr_rewrite(xml, name, value)
-    xml.find("//osm/relation").first[name] = value.to_s
-    xml
-  end
-
-  ##
-  # parse some xml
-  def xml_parse(xml)
-    parser = XML::Parser.string(xml)
-    parser.parse
-  end
-end
diff --git a/test/controllers/search_controller_test.rb b/test/controllers/search_controller_test.rb
deleted file mode 100644 (file)
index 49a70f1..0000000
+++ /dev/null
@@ -1,106 +0,0 @@
-require "test_helper"
-
-class SearchControllerTest < ActionController::TestCase
-  ##
-  # test all routes which lead to this controller
-  def test_routes
-    assert_routing(
-      { :path => "/api/0.6/search", :method => :get },
-      { :controller => "search", :action => "search_all" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/nodes/search", :method => :get },
-      { :controller => "search", :action => "search_nodes" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/ways/search", :method => :get },
-      { :controller => "search", :action => "search_ways" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/relations/search", :method => :get },
-      { :controller => "search", :action => "search_relations" }
-    )
-  end
-
-  ##
-  # test searching nodes
-  def test_search_nodes
-    get :search_nodes, :params => { :type => "test" }
-    assert_response :service_unavailable
-    assert_equal "Searching of nodes is currently unavailable", response.headers["Error"]
-
-    get :search_nodes, :params => { :type => "test", :value => "yes" }
-    assert_response :service_unavailable
-    assert_equal "Searching of nodes is currently unavailable", response.headers["Error"]
-
-    get :search_nodes, :params => { :name => "Test Node" }
-    assert_response :service_unavailable
-    assert_equal "Searching of nodes is currently unavailable", response.headers["Error"]
-  end
-
-  ##
-  # test searching ways
-  def test_search_ways
-    first_way = create(:way_with_nodes, :nodes_count => 2)
-    deleted_way = create(:way_with_nodes, :deleted, :nodes_count => 2)
-    third_way = create(:way_with_nodes, :nodes_count => 2)
-
-    [first_way, deleted_way, third_way].each do |way|
-      create(:way_tag, :way => way, :k => "test", :v => "yes")
-    end
-    create(:way_tag, :way => third_way, :k => "name", :v => "Test Way")
-
-    get :search_ways, :params => { :type => "test" }
-    assert_response :service_unavailable
-    assert_equal "Searching for a key without value is currently unavailable", response.headers["Error"]
-
-    get :search_ways, :params => { :type => "test", :value => "yes" }
-    assert_response :success
-    assert_select "way", 3
-
-    get :search_ways, :params => { :name => "Test Way" }
-    assert_response :success
-    assert_select "way", 1
-  end
-
-  ##
-  # test searching relations
-  def test_search_relations
-    first_relation = create(:relation)
-    deleted_relation = create(:relation)
-    third_relation = create(:relation)
-
-    [first_relation, deleted_relation, third_relation].each do |relation|
-      create(:relation_tag, :relation => relation, :k => "test", :v => "yes")
-    end
-    create(:relation_tag, :relation => third_relation, :k => "name", :v => "Test Relation")
-
-    get :search_relations, :params => { :type => "test" }
-    assert_response :service_unavailable
-    assert_equal "Searching for a key without value is currently unavailable", response.headers["Error"]
-
-    get :search_relations, :params => { :type => "test", :value => "yes" }
-    assert_response :success
-    assert_select "relation", 3
-
-    get :search_relations, :params => { :name => "Test Relation" }
-    assert_response :success
-    assert_select "relation", 1
-  end
-
-  ##
-  # test searching nodes, ways and relations
-  def test_search_all
-    get :search_all, :params => { :type => "test" }
-    assert_response :service_unavailable
-    assert_equal "Searching of nodes is currently unavailable", response.headers["Error"]
-
-    get :search_all, :params => { :type => "test", :value => "yes" }
-    assert_response :service_unavailable
-    assert_equal "Searching of nodes is currently unavailable", response.headers["Error"]
-
-    get :search_all, :params => { :name => "Test" }
-    assert_response :service_unavailable
-    assert_equal "Searching of nodes is currently unavailable", response.headers["Error"]
-  end
-end
diff --git a/test/controllers/swf_controller_test.rb b/test/controllers/swf_controller_test.rb
deleted file mode 100644 (file)
index 2b8a19b..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-require "test_helper"
-
-class SwfControllerTest < ActionController::TestCase
-  ##
-  # test all routes which lead to this controller
-  def test_routes
-    assert_routing(
-      { :path => "/api/0.6/swf/trackpoints", :method => :get },
-      { :controller => "swf", :action => "trackpoints" }
-    )
-  end
-
-  ##
-  # basic test that trackpoints at least returns some sort of flash movie
-  def test_trackpoints
-    user = create(:user)
-    other_user = create(:user)
-    create(:trace, :visibility => "trackable", :latitude => 51.51, :longitude => -0.14, :user => user) do |trace|
-      create(:tracepoint, :trace => trace, :trackid => 1, :latitude => (51.510 * GeoRecord::SCALE).to_i, :longitude => (-0.140 * GeoRecord::SCALE).to_i)
-      create(:tracepoint, :trace => trace, :trackid => 2, :latitude => (51.511 * GeoRecord::SCALE).to_i, :longitude => (-0.141 * GeoRecord::SCALE).to_i)
-    end
-    create(:trace, :visibility => "identifiable", :latitude => 51.512, :longitude => 0.142) do |trace|
-      create(:tracepoint, :trace => trace, :latitude => (51.512 * GeoRecord::SCALE).to_i, :longitude => (0.142 * GeoRecord::SCALE).to_i)
-    end
-
-    get :trackpoints, :params => { :xmin => -1, :xmax => 1, :ymin => 51, :ymax => 52, :baselong => 0, :basey => 0, :masterscale => 1 }
-    assert_response :success
-    assert_equal "application/x-shockwave-flash", response.content_type
-    assert_match(/^FWS/, response.body)
-    assert_equal 80, response.body.length
-
-    get :trackpoints, :params => { :xmin => -1, :xmax => 1, :ymin => 51, :ymax => 52, :baselong => 0, :basey => 0, :masterscale => 1, :token => other_user.tokens.create.token }
-    assert_response :success
-    assert_equal "application/x-shockwave-flash", response.content_type
-    assert_match(/^FWS/, response.body)
-    assert_equal 67, response.body.length
-
-    get :trackpoints, :params => { :xmin => -1, :xmax => 1, :ymin => 51, :ymax => 52, :baselong => 0, :basey => 0, :masterscale => 1, :token => user.tokens.create.token }
-    assert_response :success
-    assert_equal "application/x-shockwave-flash", response.content_type
-    assert_match(/^FWS/, response.body)
-    assert_equal 74, response.body.length
-  end
-end
index 179070e005d4463154bd5374852bdf8b792610f4..84469437ac8524b7be304df60073430fed9f5642 100644 (file)
@@ -24,35 +24,6 @@ class TracesControllerTest < ActionController::TestCase
   ##
   # test all routes which lead to this controller
   def test_routes
-    assert_routing(
-      { :path => "/api/0.6/gpx/create", :method => :post },
-      { :controller => "traces", :action => "api_create" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/gpx/1", :method => :get },
-      { :controller => "traces", :action => "api_read", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/gpx/1", :method => :put },
-      { :controller => "traces", :action => "api_update", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/gpx/1", :method => :delete },
-      { :controller => "traces", :action => "api_delete", :id => "1" }
-    )
-    assert_recognizes(
-      { :controller => "traces", :action => "api_read", :id => "1" },
-      { :path => "/api/0.6/gpx/1/details", :method => :get }
-    )
-    assert_routing(
-      { :path => "/api/0.6/gpx/1/data", :method => :get },
-      { :controller => "traces", :action => "api_data", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/gpx/1/data.xml", :method => :get },
-      { :controller => "traces", :action => "api_data", :id => "1", :format => "xml" }
-    )
-
     assert_routing(
       { :path => "/traces", :method => :get },
       { :controller => "traces", :action => "index" }
@@ -719,296 +690,6 @@ class TracesControllerTest < ActionController::TestCase
     assert_equal false, trace.visible
   end
 
-  # Check getting a specific trace through the api
-  def test_api_read
-    public_trace_file = create(:trace, :visibility => "public")
-
-    # First with no auth
-    get :api_read, :params => { :id => public_trace_file.id }
-    assert_response :unauthorized
-
-    # Now with some other user, which should work since the trace is public
-    basic_authorization create(:user).display_name, "test"
-    get :api_read, :params => { :id => public_trace_file.id }
-    assert_response :success
-
-    # And finally we should be able to do it with the owner of the trace
-    basic_authorization public_trace_file.user.display_name, "test"
-    get :api_read, :params => { :id => public_trace_file.id }
-    assert_response :success
-  end
-
-  # Check an anoymous trace can't be specifically fetched by another user
-  def test_api_read_anon
-    anon_trace_file = create(:trace, :visibility => "private")
-
-    # First with no auth
-    get :api_read, :params => { :id => anon_trace_file.id }
-    assert_response :unauthorized
-
-    # Now try with another user, which shouldn't work since the trace is anon
-    basic_authorization create(:user).display_name, "test"
-    get :api_read, :params => { :id => anon_trace_file.id }
-    assert_response :forbidden
-
-    # And finally we should be able to get the trace details with the trace owner
-    basic_authorization anon_trace_file.user.display_name, "test"
-    get :api_read, :params => { :id => anon_trace_file.id }
-    assert_response :success
-  end
-
-  # Check the api details for a trace that doesn't exist
-  def test_api_read_not_found
-    deleted_trace_file = create(:trace, :deleted)
-
-    # Try first with no auth, as it should require it
-    get :api_read, :params => { :id => 0 }
-    assert_response :unauthorized
-
-    # Login, and try again
-    basic_authorization deleted_trace_file.user.display_name, "test"
-    get :api_read, :params => { :id => 0 }
-    assert_response :not_found
-
-    # Now try a trace which did exist but has been deleted
-    basic_authorization deleted_trace_file.user.display_name, "test"
-    get :api_read, :params => { :id => deleted_trace_file.id }
-    assert_response :not_found
-  end
-
-  # Test downloading a trace through the api
-  def test_api_data
-    public_trace_file = create(:trace, :visibility => "public", :fixture => "a")
-
-    # First with no auth
-    get :api_data, :params => { :id => public_trace_file.id }
-    assert_response :unauthorized
-
-    # Now with some other user, which should work since the trace is public
-    basic_authorization create(:user).display_name, "test"
-    get :api_data, :params => { :id => public_trace_file.id }
-    check_trace_data public_trace_file, "848caa72f2f456d1bd6a0fdf228aa1b9"
-
-    # And finally we should be able to do it with the owner of the trace
-    basic_authorization public_trace_file.user.display_name, "test"
-    get :api_data, :params => { :id => public_trace_file.id }
-    check_trace_data public_trace_file, "848caa72f2f456d1bd6a0fdf228aa1b9"
-  end
-
-  # Test downloading a compressed trace through the api
-  def test_api_data_compressed
-    identifiable_trace_file = create(:trace, :visibility => "identifiable", :fixture => "d")
-
-    # Authenticate as the owner of the trace we will be using
-    basic_authorization identifiable_trace_file.user.display_name, "test"
-
-    # First get the data as is
-    get :api_data, :params => { :id => identifiable_trace_file.id }
-    check_trace_data identifiable_trace_file, "c6422a3d8750faae49ed70e7e8a51b93", "application/x-gzip", "gpx.gz"
-
-    # Now ask explicitly for XML format
-    get :api_data, :params => { :id => identifiable_trace_file.id, :format => "xml" }
-    check_trace_data identifiable_trace_file, "abd6675fdf3024a84fc0a1deac147c0d", "application/xml", "xml"
-
-    # Now ask explicitly for GPX format
-    get :api_data, :params => { :id => identifiable_trace_file.id, :format => "gpx" }
-    check_trace_data identifiable_trace_file, "abd6675fdf3024a84fc0a1deac147c0d"
-  end
-
-  # Check an anonymous trace can't be downloaded by another user through the api
-  def test_api_data_anon
-    anon_trace_file = create(:trace, :visibility => "private", :fixture => "b")
-
-    # First with no auth
-    get :api_data, :params => { :id => anon_trace_file.id }
-    assert_response :unauthorized
-
-    # Now with some other user, which shouldn't work since the trace is anon
-    basic_authorization create(:user).display_name, "test"
-    get :api_data, :params => { :id => anon_trace_file.id }
-    assert_response :forbidden
-
-    # And finally we should be able to do it with the owner of the trace
-    basic_authorization anon_trace_file.user.display_name, "test"
-    get :api_data, :params => { :id => anon_trace_file.id }
-    check_trace_data anon_trace_file, "66179ca44f1e93d8df62e2b88cbea732"
-  end
-
-  # Test downloading a trace that doesn't exist through the api
-  def test_api_data_not_found
-    deleted_trace_file = create(:trace, :deleted)
-
-    # Try first with no auth, as it should require it
-    get :api_data, :params => { :id => 0 }
-    assert_response :unauthorized
-
-    # Login, and try again
-    basic_authorization create(:user).display_name, "test"
-    get :api_data, :params => { :id => 0 }
-    assert_response :not_found
-
-    # Now try a trace which did exist but has been deleted
-    basic_authorization deleted_trace_file.user.display_name, "test"
-    get :api_data, :params => { :id => deleted_trace_file.id }
-    assert_response :not_found
-  end
-
-  # Test creating a trace through the api
-  def test_api_create
-    # Get file to use
-    fixture = Rails.root.join("test", "gpx", "fixtures", "a.gpx")
-    file = Rack::Test::UploadedFile.new(fixture, "application/gpx+xml")
-    user = create(:user)
-
-    # First with no auth
-    post :api_create, :params => { :file => file, :description => "New Trace", :tags => "new,trace", :visibility => "trackable" }
-    assert_response :unauthorized
-
-    # Rewind the file
-    file.rewind
-
-    # Now authenticated
-    create(:user_preference, :user => user, :k => "gps.trace.visibility", :v => "identifiable")
-    assert_not_equal "trackable", user.preferences.where(:k => "gps.trace.visibility").first.v
-    basic_authorization user.display_name, "test"
-    post :api_create, :params => { :file => file, :description => "New Trace", :tags => "new,trace", :visibility => "trackable" }
-    assert_response :success
-    trace = Trace.find(response.body.to_i)
-    assert_equal "a.gpx", trace.name
-    assert_equal "New Trace", trace.description
-    assert_equal %w[new trace], trace.tags.order(:tag).collect(&:tag)
-    assert_equal "trackable", trace.visibility
-    assert_equal false, trace.inserted
-    assert_equal File.new(fixture).read, File.new(trace.trace_name).read
-    trace.destroy
-    assert_equal "trackable", user.preferences.where(:k => "gps.trace.visibility").first.v
-
-    # Rewind the file
-    file.rewind
-
-    # Now authenticated, with the legacy public flag
-    assert_not_equal "public", user.preferences.where(:k => "gps.trace.visibility").first.v
-    basic_authorization user.display_name, "test"
-    post :api_create, :params => { :file => file, :description => "New Trace", :tags => "new,trace", :public => 1 }
-    assert_response :success
-    trace = Trace.find(response.body.to_i)
-    assert_equal "a.gpx", trace.name
-    assert_equal "New Trace", trace.description
-    assert_equal %w[new trace], trace.tags.order(:tag).collect(&:tag)
-    assert_equal "public", trace.visibility
-    assert_equal false, trace.inserted
-    assert_equal File.new(fixture).read, File.new(trace.trace_name).read
-    trace.destroy
-    assert_equal "public", user.preferences.where(:k => "gps.trace.visibility").first.v
-
-    # Rewind the file
-    file.rewind
-
-    # Now authenticated, with the legacy private flag
-    second_user = create(:user)
-    assert_nil second_user.preferences.where(:k => "gps.trace.visibility").first
-    basic_authorization second_user.display_name, "test"
-    post :api_create, :params => { :file => file, :description => "New Trace", :tags => "new,trace", :public => 0 }
-    assert_response :success
-    trace = Trace.find(response.body.to_i)
-    assert_equal "a.gpx", trace.name
-    assert_equal "New Trace", trace.description
-    assert_equal %w[new trace], trace.tags.order(:tag).collect(&:tag)
-    assert_equal "private", trace.visibility
-    assert_equal false, trace.inserted
-    assert_equal File.new(fixture).read, File.new(trace.trace_name).read
-    trace.destroy
-    assert_equal "private", second_user.preferences.where(:k => "gps.trace.visibility").first.v
-  end
-
-  # Check updating a trace through the api
-  def test_api_update
-    public_trace_file = create(:trace, :visibility => "public", :fixture => "a")
-    deleted_trace_file = create(:trace, :deleted)
-    anon_trace_file = create(:trace, :visibility => "private")
-
-    # First with no auth
-    put :api_update, :params => { :id => public_trace_file.id }, :body => public_trace_file.to_xml.to_s
-    assert_response :unauthorized
-
-    # Now with some other user, which should fail
-    basic_authorization create(:user).display_name, "test"
-    put :api_update, :params => { :id => public_trace_file.id }, :body => public_trace_file.to_xml.to_s
-    assert_response :forbidden
-
-    # Now with a trace which doesn't exist
-    basic_authorization create(:user).display_name, "test"
-    put :api_update, :params => { :id => 0 }, :body => public_trace_file.to_xml.to_s
-    assert_response :not_found
-
-    # Now with a trace which did exist but has been deleted
-    basic_authorization deleted_trace_file.user.display_name, "test"
-    put :api_update, :params => { :id => deleted_trace_file.id }, :body => deleted_trace_file.to_xml.to_s
-    assert_response :not_found
-
-    # Now try an update with the wrong ID
-    basic_authorization public_trace_file.user.display_name, "test"
-    put :api_update, :params => { :id => public_trace_file.id }, :body => anon_trace_file.to_xml.to_s
-    assert_response :bad_request,
-                    "should not be able to update a trace with a different ID from the XML"
-
-    # And finally try an update that should work
-    basic_authorization public_trace_file.user.display_name, "test"
-    t = public_trace_file
-    t.description = "Changed description"
-    t.visibility = "private"
-    put :api_update, :params => { :id => t.id }, :body => t.to_xml.to_s
-    assert_response :success
-    nt = Trace.find(t.id)
-    assert_equal nt.description, t.description
-    assert_equal nt.visibility, t.visibility
-  end
-
-  # Test that updating a trace doesn't duplicate the tags
-  def test_api_update_tags
-    tracetag = create(:tracetag)
-    trace = tracetag.trace
-    basic_authorization trace.user.display_name, "test"
-
-    put :api_update, :params => { :id => trace.id }, :body => trace.to_xml.to_s
-    assert_response :success
-
-    updated = Trace.find(trace.id)
-    # Ensure there's only one tag in the database after updating
-    assert_equal Tracetag.count, 1
-    # The new tag object might have a different id, so check the string representation
-    assert_equal trace.tagstring, updated.tagstring
-  end
-
-  # Check deleting a trace through the api
-  def test_api_delete
-    public_trace_file = create(:trace, :visibility => "public")
-
-    # First with no auth
-    delete :api_delete, :params => { :id => public_trace_file.id }
-    assert_response :unauthorized
-
-    # Now with some other user, which should fail
-    basic_authorization create(:user).display_name, "test"
-    delete :api_delete, :params => { :id => public_trace_file.id }
-    assert_response :forbidden
-
-    # Now with a trace which doesn't exist
-    basic_authorization create(:user).display_name, "test"
-    delete :api_delete, :params => { :id => 0 }
-    assert_response :not_found
-
-    # And finally we should be able to do it with the owner of the trace
-    basic_authorization public_trace_file.user.display_name, "test"
-    delete :api_delete, :params => { :id => public_trace_file.id }
-    assert_response :success
-
-    # Try it a second time, which should fail
-    basic_authorization public_trace_file.user.display_name, "test"
-    delete :api_delete, :params => { :id => public_trace_file.id }
-    assert_response :not_found
-  end
-
   private
 
   def check_trace_feed(traces)
diff --git a/test/controllers/user_preferences_controller_test.rb b/test/controllers/user_preferences_controller_test.rb
deleted file mode 100644 (file)
index 99b40d5..0000000
+++ /dev/null
@@ -1,244 +0,0 @@
-require "test_helper"
-
-class UserPreferencesControllerTest < ActionController::TestCase
-  ##
-  # test all routes which lead to this controller
-  def test_routes
-    assert_routing(
-      { :path => "/api/0.6/user/preferences", :method => :get },
-      { :controller => "user_preferences", :action => "read" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/user/preferences", :method => :put },
-      { :controller => "user_preferences", :action => "update" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/user/preferences/key", :method => :get },
-      { :controller => "user_preferences", :action => "read_one", :preference_key => "key" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/user/preferences/key", :method => :put },
-      { :controller => "user_preferences", :action => "update_one", :preference_key => "key" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/user/preferences/key", :method => :delete },
-      { :controller => "user_preferences", :action => "delete_one", :preference_key => "key" }
-    )
-  end
-
-  ##
-  # test read action
-  def test_read
-    # first try without auth
-    get :read
-    assert_response :unauthorized, "should be authenticated"
-
-    # authenticate as a user with no preferences
-    basic_authorization create(:user).email, "test"
-
-    # try the read again
-    get :read
-    assert_select "osm" do
-      assert_select "preferences", :count => 1 do
-        assert_select "preference", :count => 0
-      end
-    end
-
-    # authenticate as a user with preferences
-    user = create(:user)
-    user_preference = create(:user_preference, :user => user)
-    user_preference2 = create(:user_preference, :user => user)
-    basic_authorization user.email, "test"
-
-    # try the read again
-    get :read
-    assert_response :success
-    assert_equal "application/xml", @response.content_type
-    assert_select "osm" do
-      assert_select "preferences", :count => 1 do
-        assert_select "preference", :count => 2
-        assert_select "preference[k=\"#{user_preference.k}\"][v=\"#{user_preference.v}\"]", :count => 1
-        assert_select "preference[k=\"#{user_preference2.k}\"][v=\"#{user_preference2.v}\"]", :count => 1
-      end
-    end
-  end
-
-  ##
-  # test read_one action
-  def test_read_one
-    user = create(:user)
-    create(:user_preference, :user => user, :k => "key", :v => "value")
-
-    # try a read without auth
-    get :read_one, :params => { :preference_key => "key" }
-    assert_response :unauthorized, "should be authenticated"
-
-    # authenticate as a user with preferences
-    basic_authorization user.email, "test"
-
-    # try the read again
-    get :read_one, :params => { :preference_key => "key" }
-    assert_response :success
-    assert_equal "text/plain", @response.content_type
-    assert_equal "value", @response.body
-
-    # try the read again for a non-existent key
-    get :read_one, :params => { :preference_key => "unknown_key" }
-    assert_response :not_found
-  end
-
-  ##
-  # test update action
-  def test_update
-    user = create(:user)
-    create(:user_preference, :user => user, :k => "key", :v => "value")
-    create(:user_preference, :user => user, :k => "some_key", :v => "some_value")
-
-    # try a put without auth
-    assert_no_difference "UserPreference.count" do
-      put :update, :body => "<osm><preferences><preference k='key' v='new_value'/><preference k='new_key' v='value'/></preferences></osm>"
-    end
-    assert_response :unauthorized, "should be authenticated"
-    assert_equal "value", UserPreference.find([user.id, "key"]).v
-    assert_equal "some_value", UserPreference.find([user.id, "some_key"]).v
-    assert_raises ActiveRecord::RecordNotFound do
-      UserPreference.find([user.id, "new_key"])
-    end
-
-    # authenticate as a user with preferences
-    basic_authorization user.email, "test"
-
-    # try the put again
-    assert_no_difference "UserPreference.count" do
-      put :update, :body => "<osm><preferences><preference k='key' v='new_value'/><preference k='new_key' v='value'/></preferences></osm>"
-    end
-    assert_response :success
-    assert_equal "text/plain", @response.content_type
-    assert_equal "", @response.body
-    assert_equal "new_value", UserPreference.find([user.id, "key"]).v
-    assert_equal "value", UserPreference.find([user.id, "new_key"]).v
-    assert_raises ActiveRecord::RecordNotFound do
-      UserPreference.find([user.id, "some_key"])
-    end
-
-    # try a put with duplicate keys
-    assert_no_difference "UserPreference.count" do
-      put :update, :body => "<osm><preferences><preference k='key' v='value'/><preference k='key' v='newer_value'/></preferences></osm>"
-    end
-    assert_response :bad_request
-    assert_equal "text/plain", @response.content_type
-    assert_equal "Duplicate preferences with key key", @response.body
-    assert_equal "new_value", UserPreference.find([user.id, "key"]).v
-
-    # try a put with invalid content
-    assert_no_difference "UserPreference.count" do
-      put :update, :body => "nonsense"
-    end
-    assert_response :bad_request
-  end
-
-  ##
-  # test update_one action
-  def test_update_one
-    user = create(:user)
-    create(:user_preference, :user => user)
-
-    # try a put without auth
-    assert_no_difference "UserPreference.count" do
-      put :update_one, :params => { :preference_key => "new_key" }, :body => "new_value"
-    end
-    assert_response :unauthorized, "should be authenticated"
-    assert_raises ActiveRecord::RecordNotFound do
-      UserPreference.find([user.id, "new_key"])
-    end
-
-    # authenticate as a user with preferences
-    basic_authorization user.email, "test"
-
-    # try adding a new preference
-    assert_difference "UserPreference.count", 1 do
-      put :update_one, :params => { :preference_key => "new_key" }, :body => "new_value"
-    end
-    assert_response :success
-    assert_equal "text/plain", @response.content_type
-    assert_equal "", @response.body
-    assert_equal "new_value", UserPreference.find([user.id, "new_key"]).v
-
-    # try changing the value of a preference
-    assert_no_difference "UserPreference.count" do
-      put :update_one, :params => { :preference_key => "new_key" }, :body => "newer_value"
-    end
-    assert_response :success
-    assert_equal "text/plain", @response.content_type
-    assert_equal "", @response.body
-    assert_equal "newer_value", UserPreference.find([user.id, "new_key"]).v
-  end
-
-  ##
-  # test delete_one action
-  def test_delete_one
-    user = create(:user)
-    create(:user_preference, :user => user, :k => "key", :v => "value")
-
-    # try a delete without auth
-    assert_no_difference "UserPreference.count" do
-      delete :delete_one, :params => { :preference_key => "key" }
-    end
-    assert_response :unauthorized, "should be authenticated"
-    assert_equal "value", UserPreference.find([user.id, "key"]).v
-
-    # authenticate as a user with preferences
-    basic_authorization user.email, "test"
-
-    # try the delete again
-    assert_difference "UserPreference.count", -1 do
-      get :delete_one, :params => { :preference_key => "key" }
-    end
-    assert_response :success
-    assert_equal "text/plain", @response.content_type
-    assert_equal "", @response.body
-    assert_raises ActiveRecord::RecordNotFound do
-      UserPreference.find([user.id, "key"])
-    end
-
-    # try the delete again for the same key
-    assert_no_difference "UserPreference.count" do
-      get :delete_one, :params => { :preference_key => "key" }
-    end
-    assert_response :not_found
-    assert_raises ActiveRecord::RecordNotFound do
-      UserPreference.find([user.id, "key"])
-    end
-  end
-
-  # Ensure that a valid access token with correct capabilities can be used to
-  # read preferences
-  def test_read_one_using_token
-    user = create(:user)
-    token = create(:access_token, :user => user, :allow_read_prefs => true)
-    create(:user_preference, :user => user, :k => "key", :v => "value")
-
-    # Hack together an oauth request - an alternative would be to sign the request properly
-    @request.env["oauth.version"] = 1
-    @request.env["oauth.strategies"] = [:token]
-    @request.env["oauth.token"] = token
-
-    get :read_one, :params => { :preference_key => "key" }
-    assert_response :success
-  end
-
-  # Ensure that a valid access token with incorrect capabilities can't be used
-  # to read preferences even, though the owner of that token could read them
-  # by other methods.
-  def test_read_one_using_token_fail
-    user = create(:user)
-    token = create(:access_token, :user => user, :allow_read_prefs => false)
-    create(:user_preference, :user => user, :k => "key", :v => "value")
-    @request.env["oauth.version"] = 1
-    @request.env["oauth.strategies"] = [:token]
-    @request.env["oauth.token"] = token
-
-    get :read_one, :params => { :preference_key => "key" }
-    assert_response :forbidden
-  end
-end
index b85dcf65b0cdcc93c3671a1a6509482c94a97e28..1b875ca97b5d1c643c3489c62374003abfcb69b5 100644 (file)
@@ -8,23 +8,6 @@ class UsersControllerTest < ActionController::TestCase
   ##
   # test all routes which lead to this controller
   def test_routes
-    assert_routing(
-      { :path => "/api/0.6/user/1", :method => :get },
-      { :controller => "users", :action => "api_read", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/user/details", :method => :get },
-      { :controller => "users", :action => "api_details" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/user/gpx_files", :method => :get },
-      { :controller => "users", :action => "api_gpx_files" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/users", :method => :get },
-      { :controller => "users", :action => "api_users" }
-    )
-
     assert_routing(
       { :path => "/login", :method => :get },
       { :controller => "users", :action => "login" }
@@ -1123,175 +1106,6 @@ class UsersControllerTest < ActionController::TestCase
     end
   end
 
-  def test_api_read
-    user = create(:user, :description => "test", :terms_agreed => Date.yesterday)
-    # check that a visible user is returned properly
-    get :api_read, :params => { :id => user.id }
-    assert_response :success
-    assert_equal "text/xml", response.content_type
-
-    # check the data that is returned
-    assert_select "description", :count => 1, :text => "test"
-    assert_select "contributor-terms", :count => 1 do
-      assert_select "[agreed='true']"
-    end
-    assert_select "img", :count => 0
-    assert_select "roles", :count => 1 do
-      assert_select "role", :count => 0
-    end
-    assert_select "changesets", :count => 1 do
-      assert_select "[count='0']"
-    end
-    assert_select "traces", :count => 1 do
-      assert_select "[count='0']"
-    end
-    assert_select "blocks", :count => 1 do
-      assert_select "received", :count => 1 do
-        assert_select "[count='0'][active='0']"
-      end
-      assert_select "issued", :count => 0
-    end
-
-    # check that we aren't revealing private information
-    assert_select "contributor-terms[pd]", false
-    assert_select "home", false
-    assert_select "languages", false
-    assert_select "messages", false
-
-    # check that a suspended user is not returned
-    get :api_read, :params => { :id => create(:user, :suspended).id }
-    assert_response :gone
-
-    # check that a deleted user is not returned
-    get :api_read, :params => { :id => create(:user, :deleted).id }
-    assert_response :gone
-
-    # check that a non-existent user is not returned
-    get :api_read, :params => { :id => 0 }
-    assert_response :not_found
-  end
-
-  def test_api_details
-    user = create(:user, :description => "test", :terms_agreed => Date.yesterday, :home_lat => 12.1, :home_lon => 12.1, :languages => ["en"])
-    create(:message, :read, :recipient => user)
-    create(:message, :sender => user)
-
-    # check that nothing is returned when not logged in
-    get :api_details
-    assert_response :unauthorized
-
-    # check that we get a response when logged in
-    basic_authorization user.email, "test"
-    get :api_details
-    assert_response :success
-    assert_equal "text/xml", response.content_type
-
-    # check the data that is returned
-    assert_select "description", :count => 1, :text => "test"
-    assert_select "contributor-terms", :count => 1 do
-      assert_select "[agreed='true'][pd='false']"
-    end
-    assert_select "img", :count => 0
-    assert_select "roles", :count => 1 do
-      assert_select "role", :count => 0
-    end
-    assert_select "changesets", :count => 1 do
-      assert_select "[count='0']", :count => 1
-    end
-    assert_select "traces", :count => 1 do
-      assert_select "[count='0']", :count => 1
-    end
-    assert_select "blocks", :count => 1 do
-      assert_select "received", :count => 1 do
-        assert_select "[count='0'][active='0']"
-      end
-      assert_select "issued", :count => 0
-    end
-    assert_select "home", :count => 1 do
-      assert_select "[lat='12.1'][lon='12.1'][zoom='3']"
-    end
-    assert_select "languages", :count => 1 do
-      assert_select "lang", :count => 1, :text => "en"
-    end
-    assert_select "messages", :count => 1 do
-      assert_select "received", :count => 1 do
-        assert_select "[count='1'][unread='0']"
-      end
-      assert_select "sent", :count => 1 do
-        assert_select "[count='1']"
-      end
-    end
-  end
-
-  def test_api_users
-    user1 = create(:user, :description => "test1", :terms_agreed => Date.yesterday)
-    user2 = create(:user, :description => "test2", :terms_agreed => Date.yesterday)
-    user3 = create(:user, :description => "test3", :terms_agreed => Date.yesterday)
-
-    get :api_users, :params => { :users => user1.id }
-    assert_response :success
-    assert_equal "text/xml", response.content_type
-    assert_select "user", :count => 1 do
-      assert_select "user[id='#{user1.id}']", :count => 1
-      assert_select "user[id='#{user2.id}']", :count => 0
-      assert_select "user[id='#{user3.id}']", :count => 0
-    end
-
-    get :api_users, :params => { :users => user2.id }
-    assert_response :success
-    assert_equal "text/xml", response.content_type
-    assert_select "user", :count => 1 do
-      assert_select "user[id='#{user1.id}']", :count => 0
-      assert_select "user[id='#{user2.id}']", :count => 1
-      assert_select "user[id='#{user3.id}']", :count => 0
-    end
-
-    get :api_users, :params => { :users => "#{user1.id},#{user3.id}" }
-    assert_response :success
-    assert_equal "text/xml", response.content_type
-    assert_select "user", :count => 2 do
-      assert_select "user[id='#{user1.id}']", :count => 1
-      assert_select "user[id='#{user2.id}']", :count => 0
-      assert_select "user[id='#{user3.id}']", :count => 1
-    end
-
-    get :api_users, :params => { :users => create(:user, :suspended).id }
-    assert_response :not_found
-
-    get :api_users, :params => { :users => create(:user, :deleted).id }
-    assert_response :not_found
-
-    get :api_users, :params => { :users => 0 }
-    assert_response :not_found
-  end
-
-  def test_api_gpx_files
-    user = create(:user)
-    trace1 = create(:trace, :user => user) do |trace|
-      create(:tracetag, :trace => trace, :tag => "London")
-    end
-    trace2 = create(:trace, :user => user) do |trace|
-      create(:tracetag, :trace => trace, :tag => "Birmingham")
-    end
-    # check that nothing is returned when not logged in
-    get :api_gpx_files
-    assert_response :unauthorized
-
-    # check that we get a response when logged in
-    basic_authorization user.email, "test"
-    get :api_gpx_files
-    assert_response :success
-    assert_equal "application/xml", response.content_type
-
-    # check the data that is returned
-    assert_select "gpx_file[id='#{trace1.id}']", 1 do
-      assert_select "tag", "London"
-    end
-    assert_select "gpx_file[id='#{trace2.id}']", 1 do
-      assert_select "tag", "Birmingham"
-    end
-  end
-
   def test_make_friend
     # Get users to work with
     user = create(:user)
diff --git a/test/controllers/ways_controller_test.rb b/test/controllers/ways_controller_test.rb
deleted file mode 100644 (file)
index 3c141dc..0000000
+++ /dev/null
@@ -1,752 +0,0 @@
-require "test_helper"
-
-class WaysControllerTest < ActionController::TestCase
-  ##
-  # test all routes which lead to this controller
-  def test_routes
-    assert_routing(
-      { :path => "/api/0.6/way/create", :method => :put },
-      { :controller => "ways", :action => "create" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/way/1/full", :method => :get },
-      { :controller => "ways", :action => "full", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/way/1", :method => :get },
-      { :controller => "ways", :action => "show", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/way/1", :method => :put },
-      { :controller => "ways", :action => "update", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/way/1", :method => :delete },
-      { :controller => "ways", :action => "delete", :id => "1" }
-    )
-    assert_routing(
-      { :path => "/api/0.6/ways", :method => :get },
-      { :controller => "ways", :action => "index" }
-    )
-  end
-
-  # -------------------------------------
-  # Test showing ways.
-  # -------------------------------------
-
-  def test_show
-    # check that a visible way is returned properly
-    get :show, :params => { :id => create(:way).id }
-    assert_response :success
-
-    # check that an invisible way is not returned
-    get :show, :params => { :id => create(:way, :deleted).id }
-    assert_response :gone
-
-    # check chat a non-existent way is not returned
-    get :show, :params => { :id => 0 }
-    assert_response :not_found
-  end
-
-  ##
-  # check the "full" mode
-  def test_full
-    Way.all.each do |way|
-      get :full, :params => { :id => way.id }
-
-      # full call should say "gone" for non-visible ways...
-      unless way.visible
-        assert_response :gone
-        next
-      end
-
-      # otherwise it should say success
-      assert_response :success
-
-      # Check the way is correctly returned
-      assert_select "osm way[id='#{way.id}'][version='#{way.version}'][visible='#{way.visible}']", 1
-
-      # check that each node in the way appears once in the output as a
-      # reference and as the node element.
-      way.nodes.each do |n|
-        count = (way.nodes - (way.nodes - [n])).length
-        assert_select "osm way nd[ref='#{n.id}']", count
-        assert_select "osm node[id='#{n.id}'][version='#{n.version}'][lat='#{format('%.7f', n.lat)}'][lon='#{format('%.7f', n.lon)}']", 1
-      end
-    end
-  end
-
-  ##
-  # test fetching multiple ways
-  def test_index
-    way1 = create(:way)
-    way2 = create(:way, :deleted)
-    way3 = create(:way)
-    way4 = create(:way)
-
-    # check error when no parameter provided
-    get :index
-    assert_response :bad_request
-
-    # check error when no parameter value provided
-    get :index, :params => { :ways => "" }
-    assert_response :bad_request
-
-    # test a working call
-    get :index, :params => { :ways => "#{way1.id},#{way2.id},#{way3.id},#{way4.id}" }
-    assert_response :success
-    assert_select "osm" do
-      assert_select "way", :count => 4
-      assert_select "way[id='#{way1.id}'][visible='true']", :count => 1
-      assert_select "way[id='#{way2.id}'][visible='false']", :count => 1
-      assert_select "way[id='#{way3.id}'][visible='true']", :count => 1
-      assert_select "way[id='#{way4.id}'][visible='true']", :count => 1
-    end
-
-    # check error when a non-existent way is included
-    get :index, :params => { :ways => "#{way1.id},#{way2.id},#{way3.id},#{way4.id},0" }
-    assert_response :not_found
-  end
-
-  # -------------------------------------
-  # Test simple way creation.
-  # -------------------------------------
-
-  def test_create
-    node1 = create(:node)
-    node2 = create(:node)
-    private_user = create(:user, :data_public => false)
-    private_changeset = create(:changeset, :user => private_user)
-    user = create(:user)
-    changeset = create(:changeset, :user => user)
-
-    ## First check that it fails when creating a way using a non-public user
-    basic_authorization private_user.email, "test"
-
-    # use the first user's open changeset
-    changeset_id = private_changeset.id
-
-    # create a way with pre-existing nodes
-    xml = "<osm><way changeset='#{changeset_id}'>" \
-          "<nd ref='#{node1.id}'/><nd ref='#{node2.id}'/>" \
-          "<tag k='test' v='yes' /></way></osm>"
-    put :create, :body => xml
-    # hope for failure
-    assert_response :forbidden,
-                    "way upload did not return forbidden status"
-
-    ## Now use a public user
-    basic_authorization user.email, "test"
-
-    # use the first user's open changeset
-    changeset_id = changeset.id
-
-    # create a way with pre-existing nodes
-    xml = "<osm><way changeset='#{changeset_id}'>" \
-          "<nd ref='#{node1.id}'/><nd ref='#{node2.id}'/>" \
-          "<tag k='test' v='yes' /></way></osm>"
-    put :create, :body => xml
-    # hope for success
-    assert_response :success,
-                    "way upload did not return success status"
-    # read id of created way and search for it
-    wayid = @response.body
-    checkway = Way.find(wayid)
-    assert_not_nil checkway,
-                   "uploaded way not found in data base after upload"
-    # compare values
-    assert_equal checkway.nds.length, 2,
-                 "saved way does not contain exactly one node"
-    assert_equal checkway.nds[0], node1.id,
-                 "saved way does not contain the right node on pos 0"
-    assert_equal checkway.nds[1], node2.id,
-                 "saved way does not contain the right node on pos 1"
-    assert_equal checkway.changeset_id, changeset_id,
-                 "saved way does not belong to the correct changeset"
-    assert_equal user.id, checkway.changeset.user_id,
-                 "saved way does not belong to user that created it"
-    assert_equal true, checkway.visible,
-                 "saved way is not visible"
-  end
-
-  # -------------------------------------
-  # Test creating some invalid ways.
-  # -------------------------------------
-
-  def test_create_invalid
-    node = create(:node)
-    private_user = create(:user, :data_public => false)
-    private_open_changeset = create(:changeset, :user => private_user)
-    private_closed_changeset = create(:changeset, :closed, :user => private_user)
-    user = create(:user)
-    open_changeset = create(:changeset, :user => user)
-    closed_changeset = create(:changeset, :closed, :user => user)
-
-    ## First test with a private user to make sure that they are not authorized
-    basic_authorization private_user.email, "test"
-
-    # use the first user's open changeset
-    # create a way with non-existing node
-    xml = "<osm><way changeset='#{private_open_changeset.id}'>" \
-          "<nd ref='0'/><tag k='test' v='yes' /></way></osm>"
-    put :create, :body => xml
-    # expect failure
-    assert_response :forbidden,
-                    "way upload with invalid node using a private user did not return 'forbidden'"
-
-    # create a way with no nodes
-    xml = "<osm><way changeset='#{private_open_changeset.id}'>" \
-          "<tag k='test' v='yes' /></way></osm>"
-    put :create, :body => xml
-    # expect failure
-    assert_response :forbidden,
-                    "way upload with no node using a private userdid not return 'forbidden'"
-
-    # create a way inside a closed changeset
-    xml = "<osm><way changeset='#{private_closed_changeset.id}'>" \
-          "<nd ref='#{node.id}'/></way></osm>"
-    put :create, :body => xml
-    # expect failure
-    assert_response :forbidden,
-                    "way upload to closed changeset with a private user did not return 'forbidden'"
-
-    ## Now test with a public user
-    basic_authorization user.email, "test"
-
-    # use the first user's open changeset
-    # create a way with non-existing node
-    xml = "<osm><way changeset='#{open_changeset.id}'>" \
-          "<nd ref='0'/><tag k='test' v='yes' /></way></osm>"
-    put :create, :body => xml
-    # expect failure
-    assert_response :precondition_failed,
-                    "way upload with invalid node did not return 'precondition failed'"
-    assert_equal "Precondition failed: Way  requires the nodes with id in (0), which either do not exist, or are not visible.", @response.body
-
-    # create a way with no nodes
-    xml = "<osm><way changeset='#{open_changeset.id}'>" \
-          "<tag k='test' v='yes' /></way></osm>"
-    put :create, :body => xml
-    # expect failure
-    assert_response :precondition_failed,
-                    "way upload with no node did not return 'precondition failed'"
-    assert_equal "Precondition failed: Cannot create way: data is invalid.", @response.body
-
-    # create a way inside a closed changeset
-    xml = "<osm><way changeset='#{closed_changeset.id}'>" \
-          "<nd ref='#{node.id}'/></way></osm>"
-    put :create, :body => xml
-    # expect failure
-    assert_response :conflict,
-                    "way upload to closed changeset did not return 'conflict'"
-
-    # create a way with a tag which is too long
-    xml = "<osm><way changeset='#{open_changeset.id}'>" \
-          "<nd ref='#{node.id}'/>" \
-          "<tag k='foo' v='#{'x' * 256}'/>" \
-          "</way></osm>"
-    put :create, :body => xml
-    # expect failure
-    assert_response :bad_request,
-                    "way upload to with too long tag did not return 'bad_request'"
-  end
-
-  # -------------------------------------
-  # Test deleting ways.
-  # -------------------------------------
-
-  def test_delete
-    private_user = create(:user, :data_public => false)
-    private_open_changeset = create(:changeset, :user => private_user)
-    private_closed_changeset = create(:changeset, :closed, :user => private_user)
-    private_way = create(:way, :changeset => private_open_changeset)
-    private_deleted_way = create(:way, :deleted, :changeset => private_open_changeset)
-    private_used_way = create(:way, :changeset => private_open_changeset)
-    create(:relation_member, :member => private_used_way)
-    user = create(:user)
-    open_changeset = create(:changeset, :user => user)
-    closed_changeset = create(:changeset, :closed, :user => user)
-    way = create(:way, :changeset => open_changeset)
-    deleted_way = create(:way, :deleted, :changeset => open_changeset)
-    used_way = create(:way, :changeset => open_changeset)
-    relation_member = create(:relation_member, :member => used_way)
-    relation = relation_member.relation
-
-    # first try to delete way without auth
-    delete :delete, :params => { :id => way.id }
-    assert_response :unauthorized
-
-    # now set auth using the private user
-    basic_authorization private_user.email, "test"
-
-    # this shouldn't work as with the 0.6 api we need pay load to delete
-    delete :delete, :params => { :id => private_way.id }
-    assert_response :forbidden
-
-    # Now try without having a changeset
-    xml = "<osm><way id='#{private_way.id}'/></osm>"
-    delete :delete, :params => { :id => private_way.id }, :body => xml.to_s
-    assert_response :forbidden
-
-    # try to delete with an invalid (closed) changeset
-    xml = update_changeset(private_way.to_xml, private_closed_changeset.id)
-    delete :delete, :params => { :id => private_way.id }, :body => xml.to_s
-    assert_response :forbidden
-
-    # try to delete with an invalid (non-existent) changeset
-    xml = update_changeset(private_way.to_xml, 0)
-    delete :delete, :params => { :id => private_way.id }, :body => xml.to_s
-    assert_response :forbidden
-
-    # Now try with a valid changeset
-    xml = private_way.to_xml
-    delete :delete, :params => { :id => private_way.id }, :body => xml.to_s
-    assert_response :forbidden
-
-    # check the returned value - should be the new version number
-    # valid delete should return the new version number, which should
-    # be greater than the old version number
-    # assert @response.body.to_i > current_ways(:visible_way).version,
-    #   "delete request should return a new version number for way"
-
-    # this won't work since the way is already deleted
-    xml = private_deleted_way.to_xml
-    delete :delete, :params => { :id => private_deleted_way.id }, :body => xml.to_s
-    assert_response :forbidden
-
-    # this shouldn't work as the way is used in a relation
-    xml = private_used_way.to_xml
-    delete :delete, :params => { :id => private_used_way.id }, :body => xml.to_s
-    assert_response :forbidden,
-                    "shouldn't be able to delete a way used in a relation (#{@response.body}), when done by a private user"
-
-    # this won't work since the way never existed
-    delete :delete, :params => { :id => 0 }
-    assert_response :forbidden
-
-    ### Now check with a public user
-    # now set auth
-    basic_authorization user.email, "test"
-
-    # this shouldn't work as with the 0.6 api we need pay load to delete
-    delete :delete, :params => { :id => way.id }
-    assert_response :bad_request
-
-    # Now try without having a changeset
-    xml = "<osm><way id='#{way.id}'/></osm>"
-    delete :delete, :params => { :id => way.id }, :body => xml.to_s
-    assert_response :bad_request
-
-    # try to delete with an invalid (closed) changeset
-    xml = update_changeset(way.to_xml, closed_changeset.id)
-    delete :delete, :params => { :id => way.id }, :body => xml.to_s
-    assert_response :conflict
-
-    # try to delete with an invalid (non-existent) changeset
-    xml = update_changeset(way.to_xml, 0)
-    delete :delete, :params => { :id => way.id }, :body => xml.to_s
-    assert_response :conflict
-
-    # Now try with a valid changeset
-    xml = way.to_xml
-    delete :delete, :params => { :id => way.id }, :body => xml.to_s
-    assert_response :success
-
-    # check the returned value - should be the new version number
-    # valid delete should return the new version number, which should
-    # be greater than the old version number
-    assert @response.body.to_i > way.version,
-           "delete request should return a new version number for way"
-
-    # this won't work since the way is already deleted
-    xml = deleted_way.to_xml
-    delete :delete, :params => { :id => deleted_way.id }, :body => xml.to_s
-    assert_response :gone
-
-    # this shouldn't work as the way is used in a relation
-    xml = used_way.to_xml
-    delete :delete, :params => { :id => used_way.id }, :body => xml.to_s
-    assert_response :precondition_failed,
-                    "shouldn't be able to delete a way used in a relation (#{@response.body})"
-    assert_equal "Precondition failed: Way #{used_way.id} is still used by relations #{relation.id}.", @response.body
-
-    # this won't work since the way never existed
-    delete :delete, :params => { :id => 0 }
-    assert_response :not_found
-  end
-
-  ##
-  # tests whether the API works and prevents incorrect use while trying
-  # to update ways.
-  def test_update
-    private_user = create(:user, :data_public => false)
-    private_way = create(:way, :changeset => create(:changeset, :user => private_user))
-    user = create(:user)
-    way = create(:way, :changeset => create(:changeset, :user => user))
-    node = create(:node)
-    create(:way_node, :way => private_way, :node => node)
-    create(:way_node, :way => way, :node => node)
-
-    ## First test with no user credentials
-    # try and update a way without authorisation
-    xml = way.to_xml
-    put :update, :params => { :id => way.id }, :body => xml.to_s
-    assert_response :unauthorized
-
-    ## Second test with the private user
-
-    # setup auth
-    basic_authorization private_user.email, "test"
-
-    ## trying to break changesets
-
-    # try and update in someone else's changeset
-    xml = update_changeset(private_way.to_xml,
-                           create(:changeset).id)
-    put :update, :params => { :id => private_way.id }, :body => xml.to_s
-    assert_require_public_data "update with other user's changeset should be forbidden when date isn't public"
-
-    # try and update in a closed changeset
-    xml = update_changeset(private_way.to_xml,
-                           create(:changeset, :closed, :user => private_user).id)
-    put :update, :params => { :id => private_way.id }, :body => xml.to_s
-    assert_require_public_data "update with closed changeset should be forbidden, when data isn't public"
-
-    # try and update in a non-existant changeset
-    xml = update_changeset(private_way.to_xml, 0)
-    put :update, :params => { :id => private_way.id }, :body => xml.to_s
-    assert_require_public_data("update with changeset=0 should be forbidden, when data isn't public")
-
-    ## try and submit invalid updates
-    xml = xml_replace_node(private_way.to_xml, node.id, 9999)
-    put :update, :params => { :id => private_way.id }, :body => xml.to_s
-    assert_require_public_data "way with non-existent node should be forbidden, when data isn't public"
-
-    xml = xml_replace_node(private_way.to_xml, node.id, create(:node, :deleted).id)
-    put :update, :params => { :id => private_way.id }, :body => xml.to_s
-    assert_require_public_data "way with deleted node should be forbidden, when data isn't public"
-
-    ## finally, produce a good request which will still not work
-    xml = private_way.to_xml
-    put :update, :params => { :id => private_way.id }, :body => xml.to_s
-    assert_require_public_data "should have failed with a forbidden when data isn't public"
-
-    ## Finally test with the public user
-
-    # setup auth
-    basic_authorization user.email, "test"
-
-    ## trying to break changesets
-
-    # try and update in someone else's changeset
-    xml = update_changeset(way.to_xml,
-                           create(:changeset).id)
-    put :update, :params => { :id => way.id }, :body => xml.to_s
-    assert_response :conflict, "update with other user's changeset should be rejected"
-
-    # try and update in a closed changeset
-    xml = update_changeset(way.to_xml,
-                           create(:changeset, :closed, :user => user).id)
-    put :update, :params => { :id => way.id }, :body => xml.to_s
-    assert_response :conflict, "update with closed changeset should be rejected"
-
-    # try and update in a non-existant changeset
-    xml = update_changeset(way.to_xml, 0)
-    put :update, :params => { :id => way.id }, :body => xml.to_s
-    assert_response :conflict, "update with changeset=0 should be rejected"
-
-    ## try and submit invalid updates
-    xml = xml_replace_node(way.to_xml, node.id, 9999)
-    put :update, :params => { :id => way.id }, :body => xml.to_s
-    assert_response :precondition_failed, "way with non-existent node should be rejected"
-
-    xml = xml_replace_node(way.to_xml, node.id, create(:node, :deleted).id)
-    put :update, :params => { :id => way.id }, :body => xml.to_s
-    assert_response :precondition_failed, "way with deleted node should be rejected"
-
-    ## next, attack the versioning
-    current_way_version = way.version
-
-    # try and submit a version behind
-    xml = xml_attr_rewrite(way.to_xml,
-                           "version", current_way_version - 1)
-    put :update, :params => { :id => way.id }, :body => xml.to_s
-    assert_response :conflict, "should have failed on old version number"
-
-    # try and submit a version ahead
-    xml = xml_attr_rewrite(way.to_xml,
-                           "version", current_way_version + 1)
-    put :update, :params => { :id => way.id }, :body => xml.to_s
-    assert_response :conflict, "should have failed on skipped version number"
-
-    # try and submit total crap in the version field
-    xml = xml_attr_rewrite(way.to_xml,
-                           "version", "p1r4t3s!")
-    put :update, :params => { :id => way.id }, :body => xml.to_s
-    assert_response :conflict,
-                    "should not be able to put 'p1r4at3s!' in the version field"
-
-    ## try an update with the wrong ID
-    xml = create(:way).to_xml
-    put :update, :params => { :id => way.id }, :body => xml.to_s
-    assert_response :bad_request,
-                    "should not be able to update a way with a different ID from the XML"
-
-    ## try an update with a minimal valid XML doc which isn't a well-formed OSM doc.
-    xml = "<update/>"
-    put :update, :params => { :id => way.id }, :body => xml.to_s
-    assert_response :bad_request,
-                    "should not be able to update a way with non-OSM XML doc."
-
-    ## finally, produce a good request which should work
-    xml = way.to_xml
-    put :update, :params => { :id => way.id }, :body => xml.to_s
-    assert_response :success, "a valid update request failed"
-  end
-
-  # ------------------------------------------------------------
-  # test tags handling
-  # ------------------------------------------------------------
-
-  ##
-  # Try adding a new tag to a way
-  def test_add_tags
-    private_user = create(:user, :data_public => false)
-    private_way = create(:way_with_nodes, :nodes_count => 2, :changeset => create(:changeset, :user => private_user))
-    user = create(:user)
-    way = create(:way_with_nodes, :nodes_count => 2, :changeset => create(:changeset, :user => user))
-
-    ## Try with the non-public user
-    # setup auth
-    basic_authorization private_user.email, "test"
-
-    # add an identical tag to the way
-    tag_xml = XML::Node.new("tag")
-    tag_xml["k"] = "new"
-    tag_xml["v"] = "yes"
-
-    # add the tag into the existing xml
-    way_xml = private_way.to_xml
-    way_xml.find("//osm/way").first << tag_xml
-
-    # try and upload it
-    put :update, :params => { :id => private_way.id }, :body => way_xml.to_s
-    assert_response :forbidden,
-                    "adding a duplicate tag to a way for a non-public should fail with 'forbidden'"
-
-    ## Now try with the public user
-    # setup auth
-    basic_authorization user.email, "test"
-
-    # add an identical tag to the way
-    tag_xml = XML::Node.new("tag")
-    tag_xml["k"] = "new"
-    tag_xml["v"] = "yes"
-
-    # add the tag into the existing xml
-    way_xml = way.to_xml
-    way_xml.find("//osm/way").first << tag_xml
-
-    # try and upload it
-    put :update, :params => { :id => way.id }, :body => way_xml.to_s
-    assert_response :success,
-                    "adding a new tag to a way should succeed"
-    assert_equal way.version + 1, @response.body.to_i
-  end
-
-  ##
-  # Try adding a duplicate of an existing tag to a way
-  def test_add_duplicate_tags
-    private_user = create(:user, :data_public => false)
-    private_way = create(:way, :changeset => create(:changeset, :user => private_user))
-    private_existing_tag = create(:way_tag, :way => private_way)
-    user = create(:user)
-    way = create(:way, :changeset => create(:changeset, :user => user))
-    existing_tag = create(:way_tag, :way => way)
-
-    ## Try with the non-public user
-    # setup auth
-    basic_authorization private_user.email, "test"
-
-    # add an identical tag to the way
-    tag_xml = XML::Node.new("tag")
-    tag_xml["k"] = private_existing_tag.k
-    tag_xml["v"] = private_existing_tag.v
-
-    # add the tag into the existing xml
-    way_xml = private_way.to_xml
-    way_xml.find("//osm/way").first << tag_xml
-
-    # try and upload it
-    put :update, :params => { :id => private_way.id }, :body => way_xml.to_s
-    assert_response :forbidden,
-                    "adding a duplicate tag to a way for a non-public should fail with 'forbidden'"
-
-    ## Now try with the public user
-    # setup auth
-    basic_authorization user.email, "test"
-
-    # add an identical tag to the way
-    tag_xml = XML::Node.new("tag")
-    tag_xml["k"] = existing_tag.k
-    tag_xml["v"] = existing_tag.v
-
-    # add the tag into the existing xml
-    way_xml = way.to_xml
-    way_xml.find("//osm/way").first << tag_xml
-
-    # try and upload it
-    put :update, :params => { :id => way.id }, :body => way_xml.to_s
-    assert_response :bad_request,
-                    "adding a duplicate tag to a way should fail with 'bad request'"
-    assert_equal "Element way/#{way.id} has duplicate tags with key #{existing_tag.k}", @response.body
-  end
-
-  ##
-  # Try adding a new duplicate tags to a way
-  def test_new_duplicate_tags
-    private_user = create(:user, :data_public => false)
-    private_way = create(:way, :changeset => create(:changeset, :user => private_user))
-    user = create(:user)
-    way = create(:way, :changeset => create(:changeset, :user => user))
-
-    ## First test with the non-public user so should be rejected
-    # setup auth
-    basic_authorization private_user.email, "test"
-
-    # create duplicate tag
-    tag_xml = XML::Node.new("tag")
-    tag_xml["k"] = "i_am_a_duplicate"
-    tag_xml["v"] = "foobar"
-
-    # add the tag into the existing xml
-    way_xml = private_way.to_xml
-
-    # add two copies of the tag
-    way_xml.find("//osm/way").first << tag_xml.copy(true) << tag_xml
-
-    # try and upload it
-    put :update, :params => { :id => private_way.id }, :body => way_xml.to_s
-    assert_response :forbidden,
-                    "adding new duplicate tags to a way using a non-public user should fail with 'forbidden'"
-
-    ## Now test with the public user
-    # setup auth
-    basic_authorization user.email, "test"
-
-    # create duplicate tag
-    tag_xml = XML::Node.new("tag")
-    tag_xml["k"] = "i_am_a_duplicate"
-    tag_xml["v"] = "foobar"
-
-    # add the tag into the existing xml
-    way_xml = way.to_xml
-
-    # add two copies of the tag
-    way_xml.find("//osm/way").first << tag_xml.copy(true) << tag_xml
-
-    # try and upload it
-    put :update, :params => { :id => way.id }, :body => way_xml.to_s
-    assert_response :bad_request,
-                    "adding new duplicate tags to a way should fail with 'bad request'"
-    assert_equal "Element way/#{way.id} has duplicate tags with key i_am_a_duplicate", @response.body
-  end
-
-  ##
-  # Try adding a new duplicate tags to a way.
-  # But be a bit subtle - use unicode decoding ambiguities to use different
-  # binary strings which have the same decoding.
-  def test_invalid_duplicate_tags
-    private_user = create(:user, :data_public => false)
-    private_changeset = create(:changeset, :user => private_user)
-    user = create(:user)
-    changeset = create(:changeset, :user => user)
-
-    ## First make sure that you can't with a non-public user
-    # setup auth
-    basic_authorization private_user.email, "test"
-
-    # add the tag into the existing xml
-    way_str = "<osm><way changeset='#{private_changeset.id}'>"
-    way_str << "<tag k='addr:housenumber' v='1'/>"
-    way_str << "<tag k='addr:housenumber' v='2'/>"
-    way_str << "</way></osm>"
-
-    # try and upload it
-    put :create, :body => way_str
-    assert_response :forbidden,
-                    "adding new duplicate tags to a way with a non-public user should fail with 'forbidden'"
-
-    ## Now do it with a public user
-    # setup auth
-    basic_authorization user.email, "test"
-
-    # add the tag into the existing xml
-    way_str = "<osm><way changeset='#{changeset.id}'>"
-    way_str << "<tag k='addr:housenumber' v='1'/>"
-    way_str << "<tag k='addr:housenumber' v='2'/>"
-    way_str << "</way></osm>"
-
-    # try and upload it
-    put :create, :body => way_str
-    assert_response :bad_request,
-                    "adding new duplicate tags to a way should fail with 'bad request'"
-    assert_equal "Element way/ has duplicate tags with key addr:housenumber", @response.body
-  end
-
-  ##
-  # test that a call to ways_for_node returns all ways that contain the node
-  # and none that don't.
-  def test_ways_for_node
-    node = create(:node)
-    way1 = create(:way)
-    way2 = create(:way)
-    create(:way_node, :way => way1, :node => node)
-    create(:way_node, :way => way2, :node => node)
-    # create an unrelated way
-    create(:way_with_nodes, :nodes_count => 2)
-    # create a way which used to use the node
-    way3_v1 = create(:old_way, :version => 1)
-    _way3_v2 = create(:old_way, :current_way => way3_v1.current_way, :version => 2)
-    create(:old_way_node, :old_way => way3_v1, :node => node)
-
-    get :ways_for_node, :params => { :id => node.id }
-    assert_response :success
-    ways_xml = XML::Parser.string(@response.body).parse
-    assert_not_nil ways_xml, "failed to parse ways_for_node response"
-
-    # check that the set of IDs match expectations
-    expected_way_ids = [way1.id,
-                        way2.id]
-    found_way_ids = ways_xml.find("//osm/way").collect { |w| w["id"].to_i }
-    assert_equal expected_way_ids.sort, found_way_ids.sort,
-                 "expected ways for node #{node.id} did not match found"
-
-    # check the full ways to ensure we're not missing anything
-    expected_way_ids.each do |id|
-      way_xml = ways_xml.find("//osm/way[@id='#{id}']").first
-      assert_ways_are_equal(Way.find(id),
-                            Way.from_xml_node(way_xml))
-    end
-  end
-
-  ##
-  # update the changeset_id of a way element
-  def update_changeset(xml, changeset_id)
-    xml_attr_rewrite(xml, "changeset", changeset_id)
-  end
-
-  ##
-  # update an attribute in the way element
-  def xml_attr_rewrite(xml, name, value)
-    xml.find("//osm/way").first[name] = value.to_s
-    xml
-  end
-
-  ##
-  # replace a node in a way element
-  def xml_replace_node(xml, old_node, new_node)
-    xml.find("//osm/way/nd[@ref='#{old_node}']").first["ref"] = new_node.to_s
-    xml
-  end
-end