From 34e3e51456774127d43408b7ab65c24f41373f62 Mon Sep 17 00:00:00 2001 From: Tom Hughes Date: Mon, 16 Feb 2015 18:52:25 +0000 Subject: [PATCH] Cleanup trailing whitespace --- .rubocop_todo.yml | 11 -- Vagrantfile | 2 +- app/controllers/amf_controller.rb | 127 ++++++------ app/controllers/api_controller.rb | 30 +-- app/controllers/application_controller.rb | 48 ++--- app/controllers/browse_controller.rb | 4 +- app/controllers/diary_entry_controller.rb | 2 +- app/controllers/node_controller.rb | 8 +- app/controllers/notes_controller.rb | 38 ++-- app/controllers/old_controller.rb | 18 +- app/controllers/old_node_controller.rb | 2 +- app/controllers/old_relation_controller.rb | 2 +- app/controllers/old_way_controller.rb | 2 +- app/controllers/redactions_controller.rb | 12 +- app/controllers/relation_controller.rb | 30 +-- app/controllers/swf_controller.rb | 64 +++--- app/controllers/user_blocks_controller.rb | 12 +- app/controllers/user_preference_controller.rb | 2 +- app/controllers/user_roles_controller.rb | 2 +- app/controllers/way_controller.rb | 16 +- app/helpers/user_blocks_helper.rb | 4 +- app/helpers/user_roles_helper.rb | 2 +- app/models/access_token.rb | 6 +- app/models/changeset.rb | 4 +- app/models/changeset_comment.rb | 2 +- app/models/client_application.rb | 12 +- app/models/language.rb | 2 +- app/models/node.rb | 42 ++-- app/models/node_tag.rb | 2 +- app/models/oauth_token.rb | 12 +- app/models/old_node.rb | 30 +-- app/models/old_relation.rb | 6 +- app/models/old_relation_tag.rb | 2 +- app/models/old_way.rb | 8 +- app/models/redaction.rb | 6 +- app/models/relation.rb | 52 ++--- app/models/trace.rb | 10 +- app/models/user_preference.rb | 4 +- app/models/way.rb | 30 +-- app/models/way_tag.rb | 2 +- config/initializers/abstract_adapter.rb | 2 +- config/initializers/action_mailer.rb | 2 +- config/initializers/memory_limits.rb | 8 +- config/initializers/r2.rb | 2 +- config/routes.rb | 2 +- db/migrate/001_create_osm_db.rb | 2 +- db/migrate/002_cleanup_osm_db.rb | 6 +- db/migrate/006_tile_nodes.rb | 2 +- db/migrate/008_remove_segments.rb | 2 +- .../020_populate_node_tags_and_remove.rb | 2 +- db/migrate/021_move_to_innodb.rb | 4 +- db/migrate/023_add_changesets.rb | 10 +- db/migrate/024_order_relation_members.rb | 4 +- db/migrate/025_add_end_time_to_changesets.rb | 6 +- db/migrate/040_create_oauth_tables.rb | 8 +- db/migrate/053_add_map_bug_tables.rb | 8 +- db/migrate/054_refactor_map_bug_tables.rb | 4 +- db/migrate/056_add_date_closed.rb | 2 +- db/migrate/20100516124737_add_open_id.rb | 2 +- .../20110322001319_add_terms_seen_to_user.rb | 2 +- lib/classic_pagination/pagination.rb | 68 +++---- lib/classic_pagination/pagination_helper.rb | 24 +-- lib/consistency_validations.rb | 10 +- lib/daemons/gpx_import.rb | 4 +- lib/diff_reader.rb | 24 +-- lib/editors.rb | 2 +- lib/geo_record.rb | 6 +- lib/output_compression/output_compression.rb | 116 +++++------ lib/potlatch.rb | 35 ++-- lib/quova.rb | 3 +- lib/redactable.rb | 2 +- lib/rich_text.rb | 2 +- lib/session_persistence.rb | 2 +- lib/short_link.rb | 14 +- lib/tasks/add_version_to_nodes.rake | 12 +- lib/tasks/testing.rake | 2 +- lib/validators.rb | 4 +- script/daemons | 2 +- script/locale/po2yaml | 2 +- script/statistics | 2 +- test/controllers/amf_controller_test.rb | 92 ++++----- test/controllers/api_controller_test.rb | 48 ++--- test/controllers/changeset_controller_test.rb | 4 +- .../diary_entry_controller_test.rb | 38 ++-- test/controllers/export_controller_test.rb | 2 +- test/controllers/node_controller_test.rb | 78 ++++---- test/controllers/notes_controller_test.rb | 4 +- .../oauth_clients_controller_test.rb | 8 +- test/controllers/old_node_controller_test.rb | 40 ++-- .../old_relation_controller_test.rb | 16 +- test/controllers/old_way_controller_test.rb | 24 +-- test/controllers/relation_controller_test.rb | 186 +++++++++--------- test/controllers/trace_controller_test.rb | 2 +- test/controllers/user_controller_test.rb | 16 +- .../user_preference_controller_test.rb | 2 +- test/controllers/way_controller_test.rb | 96 ++++----- test/helpers/application_helper_test.rb | 4 +- test/integration/oauth_test.rb | 24 +-- .../user_changeset_comments_test.rb | 4 +- test/integration/user_diaries_test.rb | 6 +- test/integration/user_terms_seen_test.rb | 2 +- test/lib/short_link_test.rb | 16 +- test/models/changeset_comment_test.rb | 2 +- test/models/changeset_tag_test.rb | 12 +- test/models/diary_comment_test.rb | 2 +- test/models/diary_entry_test.rb | 10 +- test/models/friend_test.rb | 2 +- test/models/message_test.rb | 10 +- test/models/node_tag_test.rb | 16 +- test/models/node_test.rb | 56 +++--- test/models/oauth_nonce_test.rb | 2 +- test/models/old_node_tag_test.rb | 12 +- test/models/old_node_test.rb | 30 +-- test/models/old_relation_tag_test.rb | 14 +- test/models/old_relation_test.rb | 4 +- test/models/old_way_tag_test.rb | 14 +- test/models/old_way_test.rb | 4 +- test/models/relation_member_test.rb | 2 +- test/models/relation_tag_test.rb | 18 +- test/models/relation_test.rb | 20 +- test/models/trace_test.rb | 2 +- test/models/tracepoint_test.rb | 4 +- test/models/tracetag_test.rb | 2 +- test/models/user_preference_test.rb | 4 +- test/models/user_test.rb | 32 +-- test/models/user_token_test.rb | 2 +- test/models/way_tag_test.rb | 14 +- test/models/way_test.rb | 22 +-- test/test_helper.rb | 18 +- 129 files changed, 1054 insertions(+), 1074 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index ac10d78c9..0c09cb1b7 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -626,23 +626,12 @@ Style/SymbolProc: Style/Tab: Enabled: false -# Offense count: 6 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles. -Style/TrailingBlankLines: - Enabled: false - # Offense count: 4 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyleForMultiline, SupportedStyles. Style/TrailingComma: Enabled: false -# Offense count: 1052 -# Cop supports --auto-correct. -Style/TrailingWhitespace: - Enabled: false - # Offense count: 13 # Cop supports --auto-correct. # Configuration parameters: ExactNameMatch, AllowPredicates, AllowDSLWriters, Whitelist. diff --git a/Vagrantfile b/Vagrantfile index 5489192f4..69ec5256d 100644 --- a/Vagrantfile +++ b/Vagrantfile @@ -4,7 +4,7 @@ Vagrant.configure("2") do |config| config.vm.box = "precise64" config.vm.box_url = "http://files.vagrantup.com/precise64.box" - + # port forward for webrick on 3000 config.vm.network :forwarded_port, guest: 3000, host: 3000 diff --git a/app/controllers/amf_controller.rb b/app/controllers/amf_controller.rb index 9dd0e909e..19b7d5de8 100644 --- a/app/controllers/amf_controller.rb +++ b/app/controllers/amf_controller.rb @@ -1,6 +1,6 @@ -# 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 +# 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 @@ -11,25 +11,25 @@ # == 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. +# 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) +# (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: @@ -43,7 +43,7 @@ class AmfController < ApplicationController # 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 @@ -63,7 +63,7 @@ class AmfController < ApplicationController when 'findrelations'; result = findrelations(*args) when 'getpoi'; result = getpoi(*args) end - + result end end @@ -128,7 +128,7 @@ class AmfController < ApplicationController # 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) @@ -156,14 +156,14 @@ class AmfController < ApplicationController cs.save_with_tags! end end - + # open a new changeset if opennew!=0 cs = Changeset.new cs.tags = cstags cs.user_id = user.id - if !closecomment.empty? - cs.tags['comment']=closecomment + if !closecomment.empty? + cs.tags['comment']=closecomment # in case closecomment has chars not allowed in xml cs.tags = strip_non_xml_chars cs.tags end @@ -234,10 +234,10 @@ class AmfController < ApplicationController ## # 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. + # in a given bounding box. Nodes are returned in full; ways and relations + # are IDs only. # - # return is of the form: + # return is of the form: # [success_code, success_message, # [[way_id, way_version], ...], # [[node_id, lat, lon, [tags, ...], node_version], ...], @@ -265,7 +265,7 @@ class AmfController < ApplicationController else # find the way ids in an area nodes_in_area = Node.bbox(bbox).visible.includes(:ways) - ways = nodes_in_area.inject([]) { |sum, node| + ways = nodes_in_area.inject([]) { |sum, node| visible_ways = node.ways.select { |w| w.visible? } sum + visible_ways.collect { |w| [w.id,w.version] } }.uniq @@ -339,22 +339,22 @@ class AmfController < ApplicationController [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 + # 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, + # 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) #:doc: amf_handle_error_with_timeout("'getway_old' #{id}, #{timestamp}", 'way',id) do if timestamp == '' @@ -387,15 +387,15 @@ class AmfController < ApplicationController 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; + # 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 + # sort and collapse list (to within 2 seconds); trim all dates before the # start date of the way. def getway_history(wayid) #:doc: @@ -431,11 +431,11 @@ class AmfController < ApplicationController return ['way', wayid, []] end end - + # Find history of a node. Returns 'node', id, and an array of previous versions as above. def getnode_history(nodeid) #:doc: - begin + begin 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 @@ -454,7 +454,7 @@ class AmfController < ApplicationController # 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) @@ -482,7 +482,7 @@ class AmfController < ApplicationController # 3. hash of tags, # 4. list of members, # 5. version. - + def getrelation(relid) #:doc: amf_handle_error("'getrelation' #{relid}" ,'relation',relid) do rel = Relation.where(:id => relid).first @@ -494,7 +494,7 @@ class AmfController < ApplicationController # Find relations with specified name/id. # Returns array of relations, each in same form as getrelation. - + def findrelations(searchterm) rels = [] if searchterm.to_i>0 then @@ -575,7 +575,7 @@ class AmfController < ApplicationController relation.delete_with_history!(new_relation, user) end end # transaction - + if relid <= 0 return [0, '', relid, new_relation.id, new_relation.version] else @@ -586,7 +586,7 @@ class AmfController < ApplicationController # 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) @@ -597,7 +597,7 @@ class AmfController < ApplicationController # 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, @@ -610,7 +610,7 @@ class AmfController < ApplicationController def putway(renumberednodes, usertoken, changeset_id, wayversion, originalway, pointlist, attributes, nodes, deletednodes) #:doc: amf_handle_error("'putway' #{originalway}" ,'way',originalway) do # -- Initialise - + user = getuser(usertoken) if !user then return -1,"You are not logged in, so the way could not be saved." end if user.blocks.active.exists? then return -1,t('application.setup_user_auth.blocked') end @@ -748,7 +748,7 @@ class AmfController < ApplicationController new_node.lat = lat new_node.lon = lon new_node.tags = tags - if id <= 0 + if id <= 0 # We're creating the node new_node.create_with_history(user) elsif visible @@ -767,7 +767,7 @@ class AmfController < ApplicationController return [0, '', id, new_node.id, new_node.version] else return [0, '', id, node.id, node.version] - end + end end end @@ -799,7 +799,7 @@ class AmfController < ApplicationController # * 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 + # * 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. @@ -809,7 +809,7 @@ class AmfController < ApplicationController unless user then return -1,"You are not logged in, so the way could not be deleted." end if user.blocks.active.exists? then return -1,t('application.setup_user_auth.blocked') end if REQUIRE_TERMS_AGREED and user.terms_agreed.nil? then return -1,"You must accept the contributor terms before you can edit." end - + way_id = way_id.to_i nodeversions = {} old_way=nil # returned, so scope it outside the transaction @@ -853,7 +853,7 @@ class AmfController < ApplicationController # Authenticate token # (can also be of form user:pass) - # When we are writing to the api, we need the actual user model, + # When we are writing to the api, we need the actual user model, # not just the id, hence this abstraction def getuser(token) #:doc: @@ -868,7 +868,7 @@ class AmfController < ApplicationController def getlocales Dir.glob("#{Rails.root}/config/potlatch/locales/*").collect { |f| File.basename(f, ".yml") } end - + ## # check that all key-value pairs are valid UTF-8. def tags_ok(tags) @@ -903,19 +903,19 @@ class AmfController < ApplicationController 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 + WHERE current_nodes.visible=TRUE + AND current_ways.visible=TRUE AND #{OSM.sql_for_area(bbox, "current_nodes.")} EOF return 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=<<-EOF - 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 + 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.")} @@ -929,15 +929,15 @@ class AmfController < ApplicationController 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=<<-EOF - SELECT DISTINCT cr.id AS relid,cr.version AS version + 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' + 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.")} EOF unless way_ids.empty? @@ -946,20 +946,20 @@ class AmfController < ApplicationController 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' + WHERE crm.member_type='Way' AND crm.member_id IN (#{way_ids.join(',')}) EOF 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=<<-EOF - 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 + 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 EOF @@ -973,7 +973,7 @@ class AmfController < ApplicationController 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| @@ -990,4 +990,3 @@ class AmfController < ApplicationController 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_controller.rb b/app/controllers/api_controller.rb index 2f630c6d6..36bb0bff3 100644 --- a/app/controllers/api_controller.rb +++ b/app/controllers/api_controller.rb @@ -40,7 +40,7 @@ class ApiController < ApplicationController root['version'] = '1.0' root['creator'] = 'OpenStreetMap.org' root['xmlns'] = "http://www.topografix.com/GPX/1/0" - + doc.root = root # initialise these variables outside of the loop so that they @@ -75,21 +75,21 @@ class ApiController < ApplicationController # use the anonymous track segment if the user hasn't allowed # their GPX points to be tracked. timestamps = false - if anon_track.nil? + if anon_track.nil? anon_track = XML::Node.new 'trk' doc.root << anon_track end track = anon_track end end - + if trackid != point.trackid if gpx_file.trackable? trkseg = XML::Node.new 'trkseg' track << trkseg trackid = point.trackid else - if anon_trkseg.nil? + if anon_trkseg.nil? anon_trkseg = XML::Node.new 'trkseg' anon_track << anon_trkseg end @@ -105,14 +105,14 @@ class ApiController < ApplicationController render :text => doc.to_s, :content_type => "text/xml" end - # This is probably the most common call of all. It is used for getting the + # This is probably the most common call of all. It is used for getting the # OSM data for a specified bounding box, usually for editing. First the - # bounding box (bbox) is checked to make sure that it is sane. All nodes + # bounding box (bbox) is checked to make sure that it is sane. All nodes # are searched, then all the ways that reference those nodes are found. # All Nodes that are referenced by those ways are fetched and added to the list # of nodes. # Then all the relations that reference the already found nodes and ways are - # fetched. All the nodes and ways that are referenced by those ways are then + # fetched. All the nodes and ways that are referenced by those ways are then # fetched. Finally all the xml is returned. def map # Figure out the bbox @@ -185,15 +185,15 @@ class ApiController < ApplicationController doc.root << way.to_xml_node(visible_nodes, changeset_cache, user_display_name_cache) way_ids << way.id end - end + end relations = Relation.nodes(visible_nodes.keys).visible + Relation.ways(way_ids).visible - # we do not normally return the "other" partners referenced by an relation, - # e.g. if we return a way A that is referenced by relation X, and there's - # another way B also referenced, that is not returned. But we do make - # an exception for cases where an relation references another *relation*; + # we do not normally return the "other" partners referenced by an relation, + # e.g. if we return a way A that is referenced by relation X, and there's + # another way B also referenced, that is not returned. But we do make + # an exception for cases where an relation references another *relation*; # in that case we return that as well (but we don't go recursive here) relations += Relation.relations(relations.collect { |r| r.id }).visible @@ -254,8 +254,8 @@ class ApiController < ApplicationController end end - # External apps that use the api are able to query the api to find out some - # parameters of the API. It currently returns: + # External apps that use the api are able to query the api to find out some + # parameters of the API. It currently returns: # * minimum and maximum API versions that can be used. # * maximum area that can be requested in a bbox request in square degrees # * number of tracepoints that are returned in each tracepoints page @@ -290,7 +290,7 @@ class ApiController < ApplicationController doc.root << api policy = XML::Node.new 'policy' blacklist = XML::Node.new 'imagery' - IMAGERY_BLACKLIST.each do |url_regex| + IMAGERY_BLACKLIST.each do |url_regex| xnd = XML::Node.new 'blacklist' xnd['regex'] = url_regex.to_s blacklist << xnd diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index bd4a62948..c335dcaf4 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -51,8 +51,8 @@ class ApplicationController < ActionController::Base end ## - # requires the user to be logged in by the token or HTTP methods, or have an - # OAuth token with the right capability. this method is a bit of a pain to call + # requires the user to be logged in by the token or HTTP methods, or have an + # OAuth token with the right capability. this method is a bit of a pain to call # directly, since it's cumbersome to call filters with arguments in rails. to # make it easier to read and write the code, there are some utility methods # below. @@ -161,18 +161,18 @@ class ApplicationController < ActionController::Base end end - def authorize(realm='Web Password', errormessage="Couldn't authenticate you") + def authorize(realm='Web Password', errormessage="Couldn't authenticate you") # make the @user object from any auth sources we have setup_user_auth # handle authenticate pass/fail unless @user # no auth, the user does not exist or the password was wrong - response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\"" + response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\"" render :text => errormessage, :status => :unauthorized return false - end - end + end + end ## # to be used as a before_filter *after* authorize. this checks that @@ -180,15 +180,15 @@ class ApplicationController < ActionController::Base # # NOTE: this isn't a very good way of doing it - it duplicates logic # from require_moderator - but what we really need to do is a fairly - # drastic refactoring based on :format and respond_to? but not a + # drastic refactoring based on :format and respond_to? but not a # good idea to do that in this branch. - def authorize_moderator(errormessage="Access restricted to moderators") + def authorize_moderator(errormessage="Access restricted to moderators") # check user is a moderator unless @user.moderator? render :text => errormessage, :status => :forbidden return false - end - end + end + end def check_database_readable(need_api = false) if STATUS == :database_offline or (need_api and STATUS == :api_offline) @@ -230,7 +230,7 @@ class ApplicationController < ActionController::Base :offline elsif STATUS == :database_readonly :readonly - else + else :online end end @@ -264,7 +264,7 @@ class ApplicationController < ActionController::Base # Report and error to the user # (If anyone ever fixes Rails so it can set a http status "reason phrase", - # rather than only a status code and having the web engine make up a + # rather than only a status code and having the web engine make up a # phrase from that, we can also put the error message into the status # message. For now, rails won't let us) def report_error(message, status = :bad_request) @@ -283,7 +283,7 @@ class ApplicationController < ActionController::Base render :text => message, :status => status, :content_type => "text/plain" end end - + def set_locale response.header['Vary'] = 'Accept-Language' @@ -448,23 +448,23 @@ class ApplicationController < ActionController::Base helper_method :preferred_editor -private +private # extract authorisation credentials from headers, returns user = nil if none - def get_auth_data - if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it - authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split - elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION' # mod_fcgi - authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split + def get_auth_data + if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it + authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split + elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION' # mod_fcgi + authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split elsif request.env.has_key? 'HTTP_AUTHORIZATION' # regular location authdata = request.env['HTTP_AUTHORIZATION'].to_s.split - end + end # only basic authentication supported - if authdata and authdata[0] == 'Basic' + if authdata and authdata[0] == 'Basic' user, pass = Base64.decode64(authdata[1]).split(':',2) - end - return [user, pass] - end + end + return [user, pass] + end # used by oauth plugin to get the current user def current_user diff --git a/app/controllers/browse_controller.rb b/app/controllers/browse_controller.rb index f60957ff7..d3a474c14 100644 --- a/app/controllers/browse_controller.rb +++ b/app/controllers/browse_controller.rb @@ -1,8 +1,8 @@ class BrowseController < ApplicationController layout :map_layout - before_filter :authorize_web - before_filter :set_locale + before_filter :authorize_web + before_filter :set_locale before_filter :except => [ :query ] { |c| c.check_database_readable(true) } before_filter :require_oauth around_filter :web_timeout diff --git a/app/controllers/diary_entry_controller.rb b/app/controllers/diary_entry_controller.rb index 741ff1500..a611c19e9 100644 --- a/app/controllers/diary_entry_controller.rb +++ b/app/controllers/diary_entry_controller.rb @@ -98,7 +98,7 @@ class DiaryEntryController < ApplicationController end else @entries = DiaryEntry.joins(:user).where(:users => { :status => ["active", "confirmed"] }) - + if params[:language] @title = t 'diary_entry.list.in_language_title', :language => Language.find(params[:language]).english_name @entries = @entries.where(:language_code => params[:language]) diff --git a/app/controllers/node_controller.rb b/app/controllers/node_controller.rb index 1e34bc10d..597aa4a44 100644 --- a/app/controllers/node_controller.rb +++ b/app/controllers/node_controller.rb @@ -35,12 +35,12 @@ class NodeController < ApplicationController render :text => "", :status => :gone end end - + # Update a node from given XML def update node = Node.find(params[:id]) new_node = Node.from_xml(request.raw_post) - + unless new_node and new_node.id == node.id raise OSM::APIBadUserInput.new("The id in the url (#{node.id}) is not the same as provided in the xml (#{new_node.id})") end @@ -48,13 +48,13 @@ class NodeController < ApplicationController render :text => node.version.to_s, :content_type => "text/plain" end - # Delete a node. Doesn't actually delete it, but retains its history + # 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) - + unless new_node and new_node.id == node.id raise OSM::APIBadUserInput.new("The id in the url (#{node.id}) is not the same as provided in the xml (#{new_node.id})") end diff --git a/app/controllers/notes_controller.rb b/app/controllers/notes_controller.rb index 7584daf62..e4782449b 100644 --- a/app/controllers/notes_controller.rb +++ b/app/controllers/notes_controller.rb @@ -146,7 +146,7 @@ class NotesController < ApplicationController format.xml { render :action => :show } format.json { render :action => :show } end - end + end ## # Reopen a note @@ -176,7 +176,7 @@ class NotesController < ApplicationController format.xml { render :action => :show } format.json { render :action => :show } end - end + end ## # Get a feed of recent notes and comments @@ -278,33 +278,33 @@ class NotesController < ApplicationController ## # Display a list of notes by a specified user def mine - if params[:display_name] + if params[:display_name] if @this_user = User.active.find_by_display_name(params[:display_name]) - @title = t 'note.mine.title', :user => @this_user.display_name - @heading = t 'note.mine.heading', :user => @this_user.display_name + @title = t 'note.mine.title', :user => @this_user.display_name + @heading = t 'note.mine.heading', :user => @this_user.display_name @description = t 'note.mine.subheading', :user => render_to_string(:partial => "user", :object => @this_user) - @page = (params[:page] || 1).to_i + @page = (params[:page] || 1).to_i @page_size = 10 @notes = @this_user.notes.order("updated_at DESC, id").uniq.offset((@page - 1) * @page_size).limit(@page_size).preload(:comments => :author).to_a else - @title = t 'user.no_such_user.title' - @not_found_user = params[:display_name] + @title = t 'user.no_such_user.title' + @not_found_user = params[:display_name] - render :template => 'user/no_such_user', :status => :not_found - end + render :template => 'user/no_such_user', :status => :not_found + end end end -private - #------------------------------------------------------------ - # utility functions below. - #------------------------------------------------------------ - +private + #------------------------------------------------------------ + # utility functions below. + #------------------------------------------------------------ + ## # Render an OK response def render_ok if params[:format] == "js" - render :text => "osbResponse();", :content_type => "text/javascript" + render :text => "osbResponse();", :content_type => "text/javascript" else render :text => "ok " + @note.id.to_s + "\n", :content_type => "text/plain" if @note render :text => "ok\n", :content_type => "text/plain" unless @note @@ -334,7 +334,7 @@ private else closed_since = 7 end - + if closed_since < 0 notes = notes.where("status != 'hidden'") elsif closed_since > 0 @@ -351,9 +351,9 @@ private def add_comment(note, text, event, notify = true) attributes = { :visible => true, :event => event, :body => text } - if @user + if @user attributes[:author_id] = @user.id - else + else attributes[:author_ip] = request.remote_ip end diff --git a/app/controllers/old_controller.rb b/app/controllers/old_controller.rb index a542a9bde..82669f504 100644 --- a/app/controllers/old_controller.rb +++ b/app/controllers/old_controller.rb @@ -18,12 +18,12 @@ class OldController < ApplicationController 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 + # call won't throw an error if no records are found, so we have # to do that ourselves. raise OSM::APINotFoundError.new if @elements.empty? doc = OSM::API.new.get_xml_doc - + visible_elements = if show_redactions? @elements else @@ -33,20 +33,20 @@ class OldController < ApplicationController visible_elements.each do |element| doc.root << element.to_xml_node end - + render :text => doc.to_s, :content_type => "text/xml" end - + def version if @old_element.redacted? and not show_redactions? render :text => "", :status => :forbidden else response.last_modified = @old_element.timestamp - + doc = OSM::API.new.get_xml_doc doc.root << @old_element.to_xml_node - + render :text => doc.to_s, :content_type => "text/xml" end end @@ -58,19 +58,19 @@ class OldController < ApplicationController # be redacted in that redaction. redaction = Redaction.find(redaction_id.to_i) @old_element.redact!(redaction) - + else # if no redaction ID was provided, then this is an unredact # operation. @old_element.redact!(nil) end - + # just return an empty 200 OK for success render :text => "" end private - + def show_redactions? @user and @user.moderator? and params[:show_redactions] == "true" end diff --git a/app/controllers/old_node_controller.rb b/app/controllers/old_node_controller.rb index 16f33013e..75be576d0 100644 --- a/app/controllers/old_node_controller.rb +++ b/app/controllers/old_node_controller.rb @@ -1,7 +1,7 @@ class OldNodeController < OldController private - + def lookup_old_element @old_element = OldNode.find([params[:id], params[:version]]) end diff --git a/app/controllers/old_relation_controller.rb b/app/controllers/old_relation_controller.rb index 0cb3b2747..abf37452f 100644 --- a/app/controllers/old_relation_controller.rb +++ b/app/controllers/old_relation_controller.rb @@ -1,7 +1,7 @@ class OldRelationController < OldController private - + def lookup_old_element @old_element = OldRelation.find([params[:id], params[:version]]) end diff --git a/app/controllers/old_way_controller.rb b/app/controllers/old_way_controller.rb index f6f282309..64fe5b6a7 100644 --- a/app/controllers/old_way_controller.rb +++ b/app/controllers/old_way_controller.rb @@ -1,7 +1,7 @@ class OldWayController < OldController private - + def lookup_old_element @old_element = OldWay.find([params[:id], params[:version]]) end diff --git a/app/controllers/redactions_controller.rb b/app/controllers/redactions_controller.rb index d0f902717..6dbe53937 100644 --- a/app/controllers/redactions_controller.rb +++ b/app/controllers/redactions_controller.rb @@ -1,6 +1,6 @@ class RedactionsController < ApplicationController layout 'site' - + before_filter :authorize_web before_filter :set_locale before_filter :require_user, :only => [:new, :create, :edit, :update, :destroy] @@ -16,7 +16,7 @@ class RedactionsController < ApplicationController def new @redaction = Redaction.new end - + def create @redaction = Redaction.new @redaction.user = @user @@ -31,13 +31,13 @@ class RedactionsController < ApplicationController render :action => 'new' end end - + def show end - + def edit end - + def update # note - don't update the user ID @redaction.title = params[:redaction][:title] @@ -50,7 +50,7 @@ class RedactionsController < ApplicationController render :action => 'edit' end end - + def destroy unless @redaction.old_nodes.empty? and @redaction.old_ways.empty? and diff --git a/app/controllers/relation_controller.rb b/app/controllers/relation_controller.rb index 9e7466a4a..454e0ef58 100644 --- a/app/controllers/relation_controller.rb +++ b/app/controllers/relation_controller.rb @@ -14,8 +14,8 @@ class RelationController < ApplicationController assert_method :put relation = Relation.from_xml(request.raw_post, true) - - # We assume that an exception has been thrown if there was an error + + # We assume that an exception has been thrown if there was an error # generating the relation #if relation relation.create_with_history @user @@ -40,7 +40,7 @@ class RelationController < ApplicationController relation = Relation.find(params[:id]) new_relation = Relation.from_xml(request.raw_post) - + if new_relation and new_relation.id == relation.id relation.update_from new_relation, @user render :text => relation.version.to_s, :content_type => "text/plain" @@ -62,7 +62,7 @@ class RelationController < ApplicationController # ----------------------------------------------------------------- # full - # + # # input parameters: id # # returns XML representation of one relation object plus all its @@ -70,37 +70,37 @@ class RelationController < ApplicationController # ----------------------------------------------------------------- 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' and 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 + + # now additionally collect nodes referenced by ways. Note how we # recursively evaluate ways but NOT relations. - + way_node_ids = ways.collect { |way| way.way_nodes.collect { |way_node| way_node.node_id } } 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 = {} visible_members = { "Node" => {}, "Way" => {}, "Relation" => {} } changeset_cache = {} user_display_name_cache = {} - + nodes.each do |node| if node.visible? # should be unnecessary if data is consistent. doc.root << node.to_xml_node(changeset_cache, user_display_name_cache) @@ -123,7 +123,7 @@ class RelationController < ApplicationController # finally add self and output doc.root << relation.to_xml_node(visible_members, changeset_cache, user_display_name_cache) render :text => doc.to_s, :content_type => "text/xml" - + else render :text => "", :status => :gone end diff --git a/app/controllers/swf_controller.rb b/app/controllers/swf_controller.rb index 5097aa8c3..02e43a87d 100644 --- a/app/controllers/swf_controller.rb +++ b/app/controllers/swf_controller.rb @@ -10,23 +10,23 @@ class SwfController < ApplicationController # ==================================================================== # Public methods - + # ---- trackpoints compile SWF of trackpoints - def 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 @@ -38,13 +38,13 @@ class SwfController < ApplicationController 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,"+ @@ -66,9 +66,9 @@ class SwfController < ApplicationController "LIMIT 10000 OFFSET #{start}" end gpslist=ActiveRecord::Base.connection.select_all sql - + # - Draw GPS trace lines - + r=startShape() gpslist.each do |row| xs=(long2coord(row['lon'].to_f,baselong,masterscale)*20).floor @@ -88,24 +88,24 @@ class SwfController < ApplicationController r+=[b.slice!(0...80)].pack("B*") end end - + # (Unwayed segments removed) - + # - Write shape - + b+=endShape() r+=[b].pack("B*") m+=swfRecord(2,packUI16(1) + packRect(xl,xr,yb,yt) + r) m+=swfRecord(4,packUI16(1) + packUI16(1)) - + # - Create Flash header and write to browser - + m+=swfRecord(1,'') # Show frame m+=swfRecord(0,'') # End - + m=packRect(bounds_left,bounds_right,bounds_bottom,bounds_top) + 0.chr + 12.chr + packUI16(1) + m m='FWS' + 6.chr + packUI32(m.length+8) + m - + render :text => m, :content_type => "application/x-shockwave-flash" end @@ -113,7 +113,7 @@ class SwfController < ApplicationController # ======================================================================= # SWF functions - + # ----------------------------------------------------------------------- # Line-drawing @@ -125,18 +125,18 @@ class SwfController < ApplicationController s+=34.chr # 2 fill, 2 line index bits s end - + def endShape '000000' end - + def startAndMove(x,y,col) d='001001' # Line style change, moveTo l =[lengthSB(x),lengthSB(y)].max d+=sprintf("%05b%0#{l}b%0#{l}b",l,x,y) d+=col # Select line style end - + def drawTo(absx,absy,x,y) dx=x-absx dy=y-absy @@ -154,7 +154,7 @@ class SwfController < ApplicationController end d end - + def drawSection(x1,y1,x2,y2) d='11' # TypeFlag, EdgeFlag dx=x2-x1 @@ -195,33 +195,33 @@ class SwfController < ApplicationController # ----------------------------------------------------------------------- # Generic pack functions - + def packUI16(n) [n.floor].pack("v") end - + def packUI32(n) [n.floor].pack("V") end - + # Find number of bits required to store arbitrary-length binary - + def lengthSB(n) Math.frexp(n+ (n==0?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 diff --git a/app/controllers/user_blocks_controller.rb b/app/controllers/user_blocks_controller.rb index 2284174be..f530eec91 100644 --- a/app/controllers/user_blocks_controller.rb +++ b/app/controllers/user_blocks_controller.rb @@ -34,7 +34,7 @@ class UserBlocksController < ApplicationController end def create - if @valid_params + if @valid_params @user_block = UserBlock.new( :user_id => @this_user.id, :creator_id => @user.id, @@ -42,7 +42,7 @@ class UserBlocksController < ApplicationController :ends_at => Time.now.getutc() + @block_period.hours, :needs_view => params[:user_block][:needs_view] ) - + if @user_block.save flash[:notice] = t('user_block.create.flash', :name => @this_user.display_name) redirect_to @user_block @@ -54,8 +54,8 @@ class UserBlocksController < ApplicationController end end - def update - if @valid_params + def update + if @valid_params if @user_block.creator_id != @user.id flash[:error] = t('user_block.update.only_creator_can_edit') redirect_to :action => "edit" @@ -125,10 +125,10 @@ class UserBlocksController < ApplicationController if !UserBlock::PERIODS.include?(@block_period) flash[:error] = t('user_block.filter.block_period') - + elsif @user_block and !@user_block.active? flash[:error] = t('user_block.filter.block_expired') - + else @valid_params = true end diff --git a/app/controllers/user_preference_controller.rb b/app/controllers/user_preference_controller.rb index a3face30d..7d6fc8e23 100644 --- a/app/controllers/user_preference_controller.rb +++ b/app/controllers/user_preference_controller.rb @@ -70,7 +70,7 @@ class UserPreferenceController < ApplicationController def update_one begin pref = UserPreference.find([@user.id, params[:preference_key]]) - rescue ActiveRecord::RecordNotFound + rescue ActiveRecord::RecordNotFound pref = UserPreference.new pref.user = @user pref.k = params[:preference_key] diff --git a/app/controllers/user_roles_controller.rb b/app/controllers/user_roles_controller.rb index 8f623a04d..2c83971e7 100644 --- a/app/controllers/user_roles_controller.rb +++ b/app/controllers/user_roles_controller.rb @@ -31,7 +31,7 @@ class UserRolesController < ApplicationController end ## - # require that the given role is valid. the role is a URL + # require that the given role is valid. the role is a URL # parameter, so should always be present. def require_valid_role @role = params[:role] diff --git a/app/controllers/way_controller.rb b/app/controllers/way_controller.rb index 2ce49b7e8..3291ce8b7 100644 --- a/app/controllers/way_controller.rb +++ b/app/controllers/way_controller.rb @@ -14,7 +14,7 @@ class WayController < ApplicationController assert_method :put way = Way.from_xml(request.raw_post, true) - + if way way.create_with_history @user render :text => way.id.to_s, :content_type => "text/plain" @@ -25,9 +25,9 @@ class WayController < ApplicationController def read way = Way.find(params[:id]) - + response.last_modified = way.timestamp - + if way.visible render :text => way.to_xml.to_s, :content_type => "text/xml" else @@ -38,7 +38,7 @@ class WayController < ApplicationController def update way = Way.find(params[:id]) new_way = Way.from_xml(request.raw_post) - + if new_way and new_way.id == way.id way.update_from(new_way, @user) render :text => way.version.to_s, :content_type => "text/plain" @@ -51,7 +51,7 @@ class WayController < ApplicationController def delete way = Way.find(params[:id]) new_way = Way.from_xml(request.raw_post) - + if new_way and new_way.id == way.id way.delete_with_history!(new_way, @user) render :text => way.version.to_s, :content_type => "text/plain" @@ -62,7 +62,7 @@ class WayController < ApplicationController def full way = Way.includes(:nodes => :node_tags).find(params[:id]) - + if way.visible visible_nodes = {} changeset_cache = {} @@ -76,7 +76,7 @@ class WayController < ApplicationController end end doc.root << way.to_xml_node(visible_nodes, changeset_cache, user_display_name_cache) - + render :text => doc.to_s, :content_type => "text/xml" else render :text => "", :status => :gone @@ -104,7 +104,7 @@ class WayController < ApplicationController end ## - # returns all the ways which are currently using the node given in the + # 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 diff --git a/app/helpers/user_blocks_helper.rb b/app/helpers/user_blocks_helper.rb index 3cd9373c1..f645d360b 100644 --- a/app/helpers/user_blocks_helper.rb +++ b/app/helpers/user_blocks_helper.rb @@ -1,6 +1,6 @@ module UserBlocksHelper ## - # returns a translated string representing the status of the + # returns a translated string representing the status of the # user block (i.e: whether it's active, what the expiry time is) def block_status(block) if block.active? @@ -11,7 +11,7 @@ module UserBlocksHelper end else # the max of the last update time or the ends_at time is when this block finished - # either because the user viewed the block (updated_at) or it expired or was + # either because the user viewed the block (updated_at) or it expired or was # revoked (ends_at) last_time = [block.ends_at, block.updated_at].max I18n.t('user_block.helper.time_past', :time => distance_of_time_in_words_to_now(last_time)) diff --git a/app/helpers/user_roles_helper.rb b/app/helpers/user_roles_helper.rb index 369efca5a..37fbf8634 100644 --- a/app/helpers/user_roles_helper.rb +++ b/app/helpers/user_roles_helper.rb @@ -18,7 +18,7 @@ module UserRolesHelper url = grant_role_path(:display_name => user.display_name, :role => role) confirm = t("user_role.grant.are_you_sure", :name => user.display_name, :role => role) end - elsif user.has_role?(role) + elsif user.has_role?(role) image = "roles/#{role}.png" alt = t("user.view.role.#{role}") title = t("user.view.role.#{role}") diff --git a/app/models/access_token.rb b/app/models/access_token.rb index 3aa6f9daf..6e48c996d 100644 --- a/app/models/access_token.rb +++ b/app/models/access_token.rb @@ -7,9 +7,9 @@ class AccessToken < OauthToken validates_presence_of :user, :secret before_create :set_authorized_at - -protected - + +protected + def set_authorized_at self.authorized_at = Time.now end diff --git a/app/models/changeset.rb b/app/models/changeset.rb index ab6e05ccf..926e82ab6 100644 --- a/app/models/changeset.rb +++ b/app/models/changeset.rb @@ -11,7 +11,7 @@ class Changeset < ActiveRecord::Base has_many :old_nodes has_many :old_ways has_many :old_relations - + has_many :comments, -> { where(:visible => true).order(:created_at) }, :class_name => "ChangesetComment" has_and_belongs_to_many :subscribers, :class_name => 'User', :join_table => 'changesets_subscribers', :association_foreign_key => 'subscriber_id' @@ -107,7 +107,7 @@ class Changeset < ActiveRecord::Base # suggested on the wiki page by kleptog. def update_bbox!(bbox_update) bbox.expand!(bbox_update, EXPAND) - + # update active record. rails 2.1's dirty handling should take care of # whether this object needs saving or not. self.min_lon, self.min_lat, self.max_lon, self.max_lat = @bbox.to_a if bbox.complete? diff --git a/app/models/changeset_comment.rb b/app/models/changeset_comment.rb index a010674a3..1f037d667 100644 --- a/app/models/changeset_comment.rb +++ b/app/models/changeset_comment.rb @@ -9,7 +9,7 @@ class ChangesetComment < ActiveRecord::Base validates_presence_of :author validates_associated :author validates :visible, :inclusion => { :in => [true,false] } - + # Return the comment text def body RichText.new("text", read_attribute(:body)) diff --git a/app/models/client_application.rb b/app/models/client_application.rb index ff031d62b..fd382629a 100644 --- a/app/models/client_application.rb +++ b/app/models/client_application.rb @@ -16,7 +16,7 @@ class ClientApplication < ActiveRecord::Base before_validation :generate_keys, :on => :create attr_accessor :token_callback_url - + def self.find_token(token_key) token = OauthToken.find_by_token(token_key, :include => :client_application) if token && token.authorized? @@ -36,7 +36,7 @@ class ClientApplication < ActiveRecord::Base false end end - + def self.all_permissions PERMISSIONS end @@ -44,11 +44,11 @@ class ClientApplication < ActiveRecord::Base def oauth_server @oauth_server ||= OAuth::Server.new("http://" + SERVER_URL) end - + def credentials @oauth_client ||= OAuth::Consumer.new(key, secret) end - + def create_request_token(params={}) params = { :client_application => self, :callback_url => self.token_callback_url } permissions.each do |p| @@ -67,7 +67,7 @@ class ClientApplication < ActiveRecord::Base token = access_tokens.create(params) end - + token end @@ -77,7 +77,7 @@ class ClientApplication < ActiveRecord::Base end protected - + # this is the set of permissions that the client can ask for. clients # have to say up-front what permissions they want and when users sign up they # can agree or not agree to each of them. diff --git a/app/models/language.rb b/app/models/language.rb index 3a63176f6..fdcb7bacb 100644 --- a/app/models/language.rb +++ b/app/models/language.rb @@ -23,5 +23,5 @@ class Language < ActiveRecord::Base name = english_name name += " (#{native_name})" unless native_name.nil? name - end + end end diff --git a/app/models/node.rb b/app/models/node.rb index 09f494b7c..755dc82ce 100644 --- a/app/models/node.rb +++ b/app/models/node.rb @@ -16,7 +16,7 @@ class Node < ActiveRecord::Base has_many :ways, :through => :way_nodes has_many :node_tags - + has_many :old_way_nodes has_many :ways_via_history, :class_name=> "Way", :through => :old_way_nodes, :source => :way @@ -57,7 +57,7 @@ class Node < ActiveRecord::Base def self.from_xml_node(pt, create=false) node = Node.new - + raise OSM::APIBadXMLError.new("node", pt, "lat missing") if pt['lat'].nil? raise OSM::APIBadXMLError.new("node", pt, "lon missing") if pt['lon'].nil? node.lat = OSM.parse_float(pt['lat'], OSM::APIBadXMLError, "node", pt, "lat not a number") @@ -74,7 +74,7 @@ class Node < ActiveRecord::Base unless create raise OSM::APIBadXMLError.new("node", pt, "ID is required when updating.") if pt['id'].nil? node.id = pt['id'].to_i - # .to_i will return 0 if there is no number that can be parsed. + # .to_i will return 0 if there is no number that can be parsed. # We want to make sure that there is no id with zero anyway raise OSM::APIBadUserInput.new("ID of node cannot be zero when updating.") if node.id == 0 end @@ -110,7 +110,7 @@ class Node < ActiveRecord::Base raise OSM::APIAlreadyDeletedError.new("node", new_node.id) end - # need to start the transaction here, so that the database can + # need to start the transaction here, so that the database can # provide repeatable reads for the used-by checks. this means it # shouldn't be possible to get race conditions. Node.transaction do @@ -118,17 +118,17 @@ class Node < ActiveRecord::Base check_consistency(self, new_node, user) ways = Way.joins(:way_nodes).where(:visible => true, :current_way_nodes => { :node_id => id }).order(:id) raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by ways #{ways.collect { |w| w.id }.join(",")}.") unless ways.empty? - + rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Node", :member_id => id }).order(:id) raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by relations #{rels.collect { |r| r.id }.join(",")}.") unless rels.empty? self.changeset_id = new_node.changeset_id self.tags = {} self.visible = false - + # update the changeset with the deleted position changeset.update_bbox!(bbox) - + save_with_history! end end @@ -137,27 +137,27 @@ class Node < ActiveRecord::Base Node.transaction do self.lock! check_consistency(self, new_node, user) - + # update changeset first self.changeset_id = new_node.changeset_id self.changeset = new_node.changeset - + # update changeset bbox with *old* position first changeset.update_bbox!(bbox); - + # FIXME logic needs to be double checked - self.latitude = new_node.latitude + self.latitude = new_node.latitude self.longitude = new_node.longitude self.tags = new_node.tags self.visible = true - + # update changeset bbox with *new* position changeset.update_bbox!(bbox); - + save_with_history! end end - + def create_with_history(user) check_create_consistency(self, user) self.version = 0 @@ -200,8 +200,8 @@ class Node < ActiveRecord::Base end def tags=(t) - @tags = t - end + @tags = t + end def add_tag_key_val(k,v) @tags = Hash.new unless @tags @@ -226,7 +226,7 @@ class Node < ActiveRecord::Base def fix_placeholders!(id_map, placeholder_id = nil) # nodes don't refer to anything, so there is nothing to do here end - + private def save_with_history! @@ -242,10 +242,10 @@ class Node < ActiveRecord::Base tags.each do |k,v| tag = NodeTag.new tag.node_id = self.id - tag.k = k - tag.v = v + tag.k = k + tag.v = v tag.save! - end + end # Create an OldNode old_node = OldNode.from_node(self) @@ -259,5 +259,5 @@ class Node < ActiveRecord::Base changeset.save! end end - + end diff --git a/app/models/node_tag.rb b/app/models/node_tag.rb index 6f1bf0388..cb906402c 100644 --- a/app/models/node_tag.rb +++ b/app/models/node_tag.rb @@ -3,7 +3,7 @@ class NodeTag < ActiveRecord::Base self.primary_keys = "node_id", "k" belongs_to :node - + validates_presence_of :node validates_length_of :k, :maximum => 255, :allow_blank => true validates_uniqueness_of :k, :scope => :node_id diff --git a/app/models/oauth_token.rb b/app/models/oauth_token.rb index 0fe0bea30..bd3d57496 100644 --- a/app/models/oauth_token.rb +++ b/app/models/oauth_token.rb @@ -8,25 +8,25 @@ class OauthToken < ActiveRecord::Base validates_presence_of :client_application, :token before_validation :generate_keys, :on => :create - + def invalidated? invalidated_at != nil end - + def invalidate! update_attributes(:invalidated_at => Time.now) end - + def authorized? authorized_at != nil && !invalidated? end - + def to_query "oauth_token=#{token}&oauth_token_secret=#{secret}" end - + protected - + def generate_keys self.token = OAuth::Helper.generate_key(40)[0,40] self.secret = OAuth::Helper.generate_key(40)[0,40] diff --git a/app/models/old_node.rb b/app/models/old_node.rb index 5ea3a778b..b3ed96cd0 100644 --- a/app/models/old_node.rb +++ b/app/models/old_node.rb @@ -38,7 +38,7 @@ class OldNode < ActiveRecord::Base old_node.version = node.version return old_node end - + def to_xml doc = OSM::API.new.get_xml_doc doc.root << to_xml_node() @@ -63,7 +63,7 @@ class OldNode < ActiveRecord::Base def save_with_dependencies! save! - + self.tags.each do |k,v| tag = OldNodeTag.new tag.k = k @@ -79,22 +79,22 @@ class OldNode < ActiveRecord::Base end def tags=(t) - @tags = t + @tags = t end - def tags_as_hash + def tags_as_hash return self.tags - end - - # Pretend we're not in any ways - def ways - return [] - end - - # Pretend we're not in any relations - def containing_relation_members - return [] - end + end + + # Pretend we're not in any ways + def ways + return [] + end + + # Pretend we're not in any relations + def containing_relation_members + return [] + end # check whether this element is the latest version - that is, # has the same version as its "current" counterpart. diff --git a/app/models/old_relation.rb b/app/models/old_relation.rb index 5496f7115..86c4784c4 100644 --- a/app/models/old_relation.rb +++ b/app/models/old_relation.rb @@ -1,7 +1,7 @@ class OldRelation < ActiveRecord::Base include ConsistencyValidations include ObjectMetadata - + self.table_name = "relations" self.primary_keys = "relation_id", "version" @@ -15,7 +15,7 @@ class OldRelation < ActiveRecord::Base has_many :old_members, -> { order(:sequence_id) }, :class_name => 'OldRelationMember', :foreign_key => [:relation_id, :version] has_many :old_tags, :class_name => 'OldRelationTag', :foreign_key => [:relation_id, :version] - + validates_associated :changeset def self.from_relation(relation) @@ -89,7 +89,7 @@ class OldRelation < ActiveRecord::Base member_el['role'] = member.member_role.to_s el << member_el end - + add_tags_to_xml_node(el, self.old_tags) return el diff --git a/app/models/old_relation_tag.rb b/app/models/old_relation_tag.rb index 49324966f..952c51fa5 100644 --- a/app/models/old_relation_tag.rb +++ b/app/models/old_relation_tag.rb @@ -3,7 +3,7 @@ class OldRelationTag < ActiveRecord::Base self.primary_keys = "relation_id", "version", "k" belongs_to :old_relation, :foreign_key => [:relation_id, :version] - + validates_presence_of :old_relation validates_length_of :k, :maximum => 255, :allow_blank => true validates_uniqueness_of :k, :scope => [:relation_id, :version] diff --git a/app/models/old_way.rb b/app/models/old_way.rb index dbdcdd46d..167ed303a 100644 --- a/app/models/old_way.rb +++ b/app/models/old_way.rb @@ -17,7 +17,7 @@ class OldWay < ActiveRecord::Base has_many :old_tags, :class_name => 'OldWayTag', :foreign_key => [:way_id, :version] validates_associated :changeset - + def self.from_way(way) old_way = OldWay.new old_way.visible = way.visible @@ -79,7 +79,7 @@ class OldWay < ActiveRecord::Base node_el['ref'] = nd.node_id.to_s el << node_el end - + add_tags_to_xml_node(el, self.old_tags) return el @@ -87,7 +87,7 @@ class OldWay < ActiveRecord::Base # Read full version of old way # For get_nodes_undelete, uses same nodes, even if they've moved since - # For get_nodes_revert, allocates new ids + # For get_nodes_revert, allocates new ids # Currently returns Potlatch-style array # where [5] indicates whether latest version is usable as is (boolean) # (i.e. is it visible? are we actually reverting to an earlier version?) @@ -98,7 +98,7 @@ class OldWay < ActiveRecord::Base [node.lon, node.lat, n, node.version, node.tags_as_hash, node.visible] end end - + def get_nodes_revert(timestamp) points=[] self.nds.each do |n| diff --git a/app/models/redaction.rb b/app/models/redaction.rb index a9bdf5580..b3c5ec5ba 100644 --- a/app/models/redaction.rb +++ b/app/models/redaction.rb @@ -1,10 +1,10 @@ ## # Redaction represents a record associated with a particular # action on the database to hide revisions from the history -# which are not appropriate to redistribute any more. +# which are not appropriate to redistribute any more. # # The circumstances of the redaction can be recorded in the -# record's title and description fields, which can be +# record's title and description fields, which can be # displayed linked from the redacted records. # class Redaction < ActiveRecord::Base @@ -14,7 +14,7 @@ class Redaction < ActiveRecord::Base has_many :old_ways has_many :old_relations - # this method overrides the AR default to provide the rich + # this method overrides the AR default to provide the rich # text object for the description field. def description RichText.new(read_attribute(:description_format), read_attribute(:description)) diff --git a/app/models/relation.rb b/app/models/relation.rb index 008f365c4..464766802 100644 --- a/app/models/relation.rb +++ b/app/models/relation.rb @@ -1,6 +1,6 @@ class Relation < ActiveRecord::Base require 'xml/libxml' - + include ConsistencyValidations include NotRedactable include ObjectMetadata @@ -18,13 +18,13 @@ class Relation < ActiveRecord::Base has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation validates_presence_of :id, :on => :update - validates_presence_of :timestamp,:version, :changeset_id + validates_presence_of :timestamp,:version, :changeset_id validates_uniqueness_of :id validates_inclusion_of :visible, :in => [ true, false ] validates_numericality_of :id, :on => :update, :integer_only => true validates_numericality_of :changeset_id, :version, :integer_only => true validates_associated :changeset - + scope :visible, -> { where(:visible => true) } scope :invisible, -> { where(:visible => false) } scope :nodes, ->(*ids) { joins(:relation_members).where(:current_relation_members => { :member_type => "Node", :member_id => ids.flatten }) } @@ -54,17 +54,17 @@ class Relation < ActiveRecord::Base relation.version = pt['version'] raise OSM::APIBadXMLError.new("relation", pt, "Changeset id is missing") if pt['changeset'].nil? relation.changeset_id = pt['changeset'] - + unless create raise OSM::APIBadXMLError.new("relation", pt, "ID is required when updating") if pt['id'].nil? relation.id = pt['id'].to_i - # .to_i will return 0 if there is no number that can be parsed. + # .to_i will return 0 if there is no number that can be parsed. # We want to make sure that there is no id with zero anyway raise OSM::APIBadUserInput.new("ID of relation cannot be zero when updating.") if relation.id == 0 end - + # We don't care about the timestamp nor the visibility as these are either - # set explicitly or implicit in the action. The visibility is set to true, + # set explicitly or implicit in the action. The visibility is set to true, # and manually set to false before the actual delete. relation.visible = true @@ -79,13 +79,13 @@ class Relation < ActiveRecord::Base end # need to initialise the relation members array explicitly, as if this - # isn't done for a new relation then @members attribute will be nil, - # and the members will be loaded from the database instead of being + # isn't done for a new relation then @members attribute will be nil, + # and the members will be loaded from the database instead of being # empty, as intended. relation.members = Array.new pt.find('member').each do |member| - #member_type = + #member_type = logger.debug "each member" raise OSM::APIBadXMLError.new("relation", pt, "The #{member['type']} is not allowed only, #{TYPES.inspect} allowed") unless TYPES.include? member['type'] logger.debug "after raise" @@ -128,7 +128,7 @@ class Relation < ActiveRecord::Base if p member_el = XML::Node.new 'member' member_el['type'] = member.member_type.downcase - member_el['ref'] = member.member_id.to_s + member_el['ref'] = member.member_id.to_s member_el['role'] = member.member_role el << member_el end @@ -137,7 +137,7 @@ class Relation < ActiveRecord::Base add_tags_to_xml_node(el, self.relation_tags) return el - end + end # FIXME is this really needed? def members @@ -174,21 +174,21 @@ class Relation < ActiveRecord::Base end ## - # updates the changeset bounding box to contain the bounding box of + # updates the changeset bounding box to contain the bounding box of # the element with given +type+ and +id+. this only works with nodes # and ways at the moment, as they're the only elements to respond to # the :bbox call. def update_changeset_element(type, id) element = Kernel.const_get(type.capitalize).find(id) changeset.update_bbox! element.bbox - end + end def delete_with_history!(new_relation, user) unless self.visible raise OSM::APIAlreadyDeletedError.new("relation", new_relation.id) end - # need to start the transaction here, so that the database can + # need to start the transaction here, so that the database can # provide repeatable reads for the used-by checks. this means it # shouldn't be possible to get race conditions. Relation.transaction do @@ -221,7 +221,7 @@ class Relation < ActiveRecord::Base save_with_history! end end - + def create_with_history(user) check_create_consistency(self, user) unless self.preconditions_ok? @@ -233,9 +233,9 @@ class Relation < ActiveRecord::Base end def preconditions_ok?(good_members = []) - # These are hastables that store an id in the index of all + # These are hastables that store an id in the index of all # the nodes/way/relations that have already been added. - # If the member is valid and visible then we add it to the + # If the member is valid and visible then we add it to the # relevant hash table, with the value true as a cache. # Thus if you have nodes with the ids of 50 and 1 already in the # relation, then the hash table nodes would contain: @@ -273,8 +273,8 @@ class Relation < ActiveRecord::Base ## # if any members are referenced by placeholder IDs (i.e: negative) then - # this calling this method will fix them using the map from placeholders - # to IDs +id_map+. + # this calling this method will fix them using the map from placeholders + # to IDs +id_map+. def fix_placeholders!(id_map, placeholder_id = nil) self.members.map! do |type, id, role| old_id = id.to_i @@ -289,7 +289,7 @@ class Relation < ActiveRecord::Base end private - + def save_with_history! Relation.transaction do # have to be a little bit clever here - to detect if any tags @@ -306,9 +306,9 @@ class Relation < ActiveRecord::Base key = old_tag.k # if we can match the tags we currently have to the list # of old tags, then we never set the tags_changed flag. but - # if any are different then set the flag and do the DB + # if any are different then set the flag and do the DB # update. - if tags.has_key? key + if tags.has_key? key tags_changed |= (old_tag.v != tags[key]) # remove from the map, so that we can expect an empty map @@ -331,7 +331,7 @@ class Relation < ActiveRecord::Base tag.v = v tag.save! end - + # same pattern as before, but this time we're collecting the # changed members in an array, as the bounding box updates for # elements are per-element, not blanked on/off like for tags. @@ -378,7 +378,7 @@ class Relation < ActiveRecord::Base # bounding box. this is similar to how the map call does things and is # reasonable on the assumption that adding or removing members doesn't # materially change the rest of the relation. - any_relations = + any_relations = changed_members.collect { |id,type| type == "relation" }. inject(false) { |b,s| b or s } @@ -387,7 +387,7 @@ class Relation < ActiveRecord::Base # FIXME: check for tag changes along with element deletions and # make sure that the deleted element's bounding box is hit. self.members - else + else changed_members end update_members.each do |type, id, role| diff --git a/app/models/trace.rb b/app/models/trace.rb index bf8d3731b..bf3e4ef93 100644 --- a/app/models/trace.rb +++ b/app/models/trace.rb @@ -63,7 +63,7 @@ class Trace < ActiveRecord::Base f.syswrite(data) f.close end - + def icon_picture= (data) f = File.new(icon_picture_name, "wb") f.syswrite(data) @@ -78,7 +78,7 @@ class Trace < ActiveRecord::Base f.close data end - + def icon_picture f = File.new(icon_picture_name, "rb") logger.info "icon picture file: '#{f.path}'" @@ -86,7 +86,7 @@ class Trace < ActiveRecord::Base f.close data end - + def large_picture_name "#{GPX_IMAGE_DIR}/#{id}.gif" end @@ -192,14 +192,14 @@ class Trace < ActiveRecord::Base def self.from_xml_node(pt, create=false) trace = Trace.new - + raise OSM::APIBadXMLError.new("trace", pt, "visibility missing") if pt['visibility'].nil? trace.visibility = pt['visibility'] unless create raise OSM::APIBadXMLError.new("trace", pt, "ID is required when updating.") if pt['id'].nil? trace.id = pt['id'].to_i - # .to_i will return 0 if there is no number that can be parsed. + # .to_i will return 0 if there is no number that can be parsed. # We want to make sure that there is no id with zero anyway raise OSM::APIBadUserInput.new("ID of trace cannot be zero when updating.") if trace.id == 0 end diff --git a/app/models/user_preference.rb b/app/models/user_preference.rb index b5110bbf5..7faec977e 100644 --- a/app/models/user_preference.rb +++ b/app/models/user_preference.rb @@ -2,7 +2,7 @@ class UserPreference < ActiveRecord::Base self.primary_keys = "user_id", "k" belongs_to :user - + validates_length_of :k, :within => 1..255 validates_length_of :v, :within => 1..255 @@ -11,7 +11,7 @@ class UserPreference < ActiveRecord::Base el1 = XML::Node.new 'preference' el1['k'] = self.k el1['v'] = self.v - + return el1 end diff --git a/app/models/way.rb b/app/models/way.rb index e78d0df0b..c105fa089 100644 --- a/app/models/way.rb +++ b/app/models/way.rb @@ -1,12 +1,12 @@ class Way < ActiveRecord::Base require 'xml/libxml' - + include ConsistencyValidations include NotRedactable include ObjectMetadata self.table_name = "current_ways" - + belongs_to :changeset has_many :old_ways, -> { order(:version) } @@ -56,13 +56,13 @@ class Way < ActiveRecord::Base unless create raise OSM::APIBadXMLError.new("way", pt, "ID is required when updating") if pt['id'].nil? way.id = pt['id'].to_i - # .to_i will return 0 if there is no number that can be parsed. + # .to_i will return 0 if there is no number that can be parsed. # We want to make sure that there is no id with zero anyway raise OSM::APIBadUserInput.new("ID of way cannot be zero when updating.") if way.id == 0 end # We don't care about the timestamp nor the visibility as these are either - # set explicitly or implicit in the action. The visibility is set to true, + # set explicitly or implicit in the action. The visibility is set to true, # and manually set to false before the actual delete. way.visible = true @@ -85,7 +85,7 @@ class Way < ActiveRecord::Base # Find a way given it's ID, and in a single SQL call also grab its nodes # - + # You can't pull in all the tags too unless we put a sequence_id on the way_tags table and have a multipart key def self.find_eager(id) way = Way.find(id, :include => {:way_nodes => :node}) @@ -133,7 +133,7 @@ class Way < ActiveRecord::Base add_tags_to_xml_node(el, self.way_tags) return el - end + end def nds @nds ||= self.way_nodes.collect { |n| n.node_id } @@ -182,7 +182,7 @@ class Way < ActiveRecord::Base unless new_way.preconditions_ok?(self.nds) raise OSM::APIPreconditionFailedError.new("Cannot update way #{self.id}: data is invalid.") end - + self.changeset_id = new_way.changeset_id self.changeset = new_way.changeset self.tags = new_way.tags @@ -228,8 +228,8 @@ class Way < ActiveRecord::Base unless self.visible raise OSM::APIAlreadyDeletedError.new("way", new_way.id) end - - # need to start the transaction here, so that the database can + + # need to start the transaction here, so that the database can # provide repeatable reads for the used-by checks. this means it # shouldn't be possible to get race conditions. Way.transaction do @@ -255,8 +255,8 @@ class Way < ActiveRecord::Base ## # if any referenced nodes are placeholder IDs (i.e: are negative) then - # this calling this method will fix them using the map from placeholders - # to IDs +id_map+. + # this calling this method will fix them using the map from placeholders + # to IDs +id_map+. def fix_placeholders!(id_map, placeholder_id = nil) self.nds.map! do |node_id| if node_id < 0 @@ -270,12 +270,12 @@ class Way < ActiveRecord::Base end private - + def save_with_history! t = Time.now.getutc - # update the bounding box, note that this has to be done both before - # and after the save, so that nodes from both versions are included in the + # update the bounding box, note that this has to be done both before + # and after the save, so that nodes from both versions are included in the # bbox. we use a copy of the changeset so that it isn't reloaded # later in the save. cs = self.changeset @@ -315,7 +315,7 @@ class Way < ActiveRecord::Base # new set of nodes. self.reload - # update and commit the bounding box, now that way nodes + # update and commit the bounding box, now that way nodes # have been updated and we're in a transaction. cs.update_bbox!(bbox) unless nodes.empty? diff --git a/app/models/way_tag.rb b/app/models/way_tag.rb index 98ff62f5f..6204af9a5 100644 --- a/app/models/way_tag.rb +++ b/app/models/way_tag.rb @@ -3,7 +3,7 @@ class WayTag < ActiveRecord::Base self.primary_keys = "way_id", "k" belongs_to :way - + validates_presence_of :way validates_length_of :k, :maximum => 255, :allow_blank => true validates_uniqueness_of :k, :scope => :way_id diff --git a/config/initializers/abstract_adapter.rb b/config/initializers/abstract_adapter.rb index f9b711f6c..7288488a6 100644 --- a/config/initializers/abstract_adapter.rb +++ b/config/initializers/abstract_adapter.rb @@ -4,7 +4,7 @@ if defined?(ActiveRecord::ConnectionAdaptors::AbstractAdapter) class AbstractAdapter protected alias_method :old_log, :log - + def log(sql, name) if block_given? old_log(sql, name) do diff --git a/config/initializers/action_mailer.rb b/config/initializers/action_mailer.rb index 9a8ef011b..6a42c6dfe 100644 --- a/config/initializers/action_mailer.rb +++ b/config/initializers/action_mailer.rb @@ -1,7 +1,7 @@ # Configure ActionMailer SMTP settings ActionMailer::Base.smtp_settings = { :address => 'localhost', - :port => 25, + :port => 25, :domain => 'localhost', :enable_starttls_auto => false } diff --git a/config/initializers/memory_limits.rb b/config/initializers/memory_limits.rb index ce518269f..1b79df7f4 100644 --- a/config/initializers/memory_limits.rb +++ b/config/initializers/memory_limits.rb @@ -11,16 +11,16 @@ if defined?(SOFT_MEMORY_LIMIT) and defined?(PhusionPassenger) def initialize(app) @app = app end - + def call(env) # Process this requst status, headers, body = @app.call(env) - + # Restart if we've hit our memory limit if resident_size > SOFT_MEMORY_LIMIT Process.kill("USR1", Process.pid) end - + # Return the result of this request [status, headers, body] end @@ -31,7 +31,7 @@ if defined?(SOFT_MEMORY_LIMIT) and defined?(PhusionPassenger) fields = File.open("/proc/self/statm") do |file| fields = file.gets.split(" ") end - + # Return resident size in megabytes return fields[1].to_i / 256 end diff --git a/config/initializers/r2.rb b/config/initializers/r2.rb index 70676ca7e..254ce01fc 100644 --- a/config/initializers/r2.rb +++ b/config/initializers/r2.rb @@ -12,7 +12,7 @@ class R2Template < Tilt::Template def prepare @output = R2.r2(data) end - + def evaluate(scope, locals, &block) @output end diff --git a/config/routes.rb b/config/routes.rb index 3d47c6dcf..009930547 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -78,7 +78,7 @@ OpenStreetMap::Application.routes.draw do match 'api/0.6/gpx/:id' => 'trace#api_delete', :via => :delete, :id => /\d+/ match 'api/0.6/gpx/:id/details' => 'trace#api_read', :via => :get, :id => /\d+/ match 'api/0.6/gpx/:id/data' => 'trace#api_data', :via => :get - + # AMF (ActionScript) API match 'api/0.6/amf/read' => 'amf#amf_read', :via => :post match 'api/0.6/amf/write' => 'amf#amf_write', :via => :post diff --git a/db/migrate/001_create_osm_db.rb b/db/migrate/001_create_osm_db.rb index 34b020340..b16e9939f 100644 --- a/db/migrate/001_create_osm_db.rb +++ b/db/migrate/001_create_osm_db.rb @@ -217,6 +217,6 @@ class CreateOsmDb < ActiveRecord::Migration end def self.down - + end end diff --git a/db/migrate/002_cleanup_osm_db.rb b/db/migrate/002_cleanup_osm_db.rb index fb27c91b7..346c7cf4a 100644 --- a/db/migrate/002_cleanup_osm_db.rb +++ b/db/migrate/002_cleanup_osm_db.rb @@ -96,7 +96,7 @@ class CleanupOsmDb < ActiveRecord::Migration add_index "users", ["display_name"], :name => "users_display_name_idx", :unique => true change_column "way_segments", "segment_id", :bigint, :null => false - + change_column "way_tags", "k", :string, :null => false change_column "way_tags", "v", :string, :null => false change_column "way_tags", "version", :bigint, :null => false @@ -120,7 +120,7 @@ class CleanupOsmDb < ActiveRecord::Migration change_column "way_tags", "k", :string, :default => nil change_column "way_segments", "segment_id", :integer - + remove_index "users", :name => "users_display_name_idx" add_index "users", ["display_name"], :name => "users_display_name_idx" remove_index "users", :name => "users_email_idx" @@ -211,7 +211,7 @@ class CleanupOsmDb < ActiveRecord::Migration change_column "current_segments", "user_id", :bigint change_column "current_segments", "node_b", :bigint change_column "current_segments", "node_a", :bigint - + add_index "current_nodes", ["id"], :name => "current_nodes_id_idx" remove_primary_key "current_nodes" change_column "current_nodes", "timestamp", :datetime diff --git a/db/migrate/006_tile_nodes.rb b/db/migrate/006_tile_nodes.rb index 8bfb6bc3f..f8a18671e 100644 --- a/db/migrate/006_tile_nodes.rb +++ b/db/migrate/006_tile_nodes.rb @@ -56,7 +56,7 @@ class TileNodes < ActiveRecord::Migration change_column "current_nodes", "tile", :bigint upgrade_table "current_nodes_v5", "current_nodes", Node - + drop_table "current_nodes_v5" remove_index "nodes", :name=> "nodes_uid_idx" diff --git a/db/migrate/008_remove_segments.rb b/db/migrate/008_remove_segments.rb index 0c68ce050..a72859ae8 100644 --- a/db/migrate/008_remove_segments.rb +++ b/db/migrate/008_remove_segments.rb @@ -9,7 +9,7 @@ class RemoveSegments < ActiveRecord::Migration cmd = "db/migrate/008_remove_segments_helper" src = "#{cmd}.cc" - if not File.exists? cmd or File.mtime(cmd) < File.mtime(src) then + if not File.exists? cmd or File.mtime(cmd) < File.mtime(src) then system 'c++ -O3 -Wall `mysql_config --cflags --libs` ' + "#{src} -o #{cmd}" or fail end diff --git a/db/migrate/020_populate_node_tags_and_remove.rb b/db/migrate/020_populate_node_tags_and_remove.rb index 8fa7b7e5d..b5932bbe8 100644 --- a/db/migrate/020_populate_node_tags_and_remove.rb +++ b/db/migrate/020_populate_node_tags_and_remove.rb @@ -9,7 +9,7 @@ class PopulateNodeTagsAndRemove < ActiveRecord::Migration cmd = "db/migrate/020_populate_node_tags_and_remove_helper" src = "#{cmd}.c" - if not File.exists? cmd or File.mtime(cmd) < File.mtime(src) then + if not File.exists? cmd or File.mtime(cmd) < File.mtime(src) then system 'cc -O3 -Wall `mysql_config --cflags --libs` ' + "#{src} -o #{cmd}" or fail end diff --git a/db/migrate/021_move_to_innodb.rb b/db/migrate/021_move_to_innodb.rb index 030515a98..aeb84028e 100644 --- a/db/migrate/021_move_to_innodb.rb +++ b/db/migrate/021_move_to_innodb.rb @@ -17,8 +17,8 @@ class MoveToInnodb < ActiveRecord::Migration @@ver_tbl.each { |tbl| add_column "current_#{tbl}", "version", :bigint, :null => false - # As the initial version of all nodes, ways and relations is 0, we set the - # current version to something less so that we can update the version in + # As the initial version of all nodes, ways and relations is 0, we set the + # current version to something less so that we can update the version in # batches of 10000 tbl.classify.constantize.update_all("version=-1") while tbl.classify.constantize.count(:conditions => {:version => -1}) > 0 diff --git a/db/migrate/023_add_changesets.rb b/db/migrate/023_add_changesets.rb index 3a6c32e19..aac921ad8 100644 --- a/db/migrate/023_add_changesets.rb +++ b/db/migrate/023_add_changesets.rb @@ -3,7 +3,7 @@ require 'migrate' class AddChangesets < ActiveRecord::Migration @@conv_user_tables = ['current_nodes', 'current_relations', 'current_ways', 'nodes', 'relations', 'ways' ] - + def self.up create_table "changesets", :id => false do |t| t.column "id", :bigserial, :primary_key => true, :null => false @@ -23,13 +23,13 @@ class AddChangesets < ActiveRecord::Migration end add_index "changeset_tags", ["id"], :name => "changeset_tags_id_idx" - + # - # Initially we will have one changeset for every user containing - # all edits up to the API change, + # Initially we will have one changeset for every user containing + # all edits up to the API change, # all the changesets will have the id of the user that made them. # We need to generate a changeset for each user in the database - execute "INSERT INTO changesets (id, user_id, created_at, open)" + + execute "INSERT INTO changesets (id, user_id, created_at, open)" + "SELECT id, id, creation_time, false from users;" @@conv_user_tables.each { |tbl| diff --git a/db/migrate/024_order_relation_members.rb b/db/migrate/024_order_relation_members.rb index 325be5174..4914a8a60 100644 --- a/db/migrate/024_order_relation_members.rb +++ b/db/migrate/024_order_relation_members.rb @@ -7,12 +7,12 @@ class OrderRelationMembers < ActiveRecord::Migration add_column(:relation_members, :sequence_id, :integer, :default => 0, :null => false) - # update the sequence column with default (partial) ordering by + # update the sequence column with default (partial) ordering by # element ID. the sequence ID is a smaller int type, so we can't # just copy the member_id. execute("update relation_members set sequence_id = mod(member_id, 16384)") - # need to update the primary key to include the sequence number, + # need to update the primary key to include the sequence number, # otherwise the primary key will barf when we have repeated members. # mysql barfs on this anyway, so we need a single command. this may # not work in postgres... needs testing. diff --git a/db/migrate/025_add_end_time_to_changesets.rb b/db/migrate/025_add_end_time_to_changesets.rb index 32d27959a..129315a3f 100644 --- a/db/migrate/025_add_end_time_to_changesets.rb +++ b/db/migrate/025_add_end_time_to_changesets.rb @@ -5,21 +5,21 @@ class AddEndTimeToChangesets < ActiveRecord::Migration # swap the boolean closed-or-not for a time when the changeset will # close or has closed. add_column(:changesets, :closed_at, :datetime, :null => false) - + # it appears that execute will only accept string arguments, so # this is an ugly, ugly hack to get some sort of mysql/postgres # independence. now i have to go wash my brain with bleach. execute("update changesets set closed_at=(now()-'1 hour'::interval) where open=(1=0)") execute("update changesets set closed_at=(now()+'1 hour'::interval) where open=(1=1)") - # remove the open column as it is unnecessary now and denormalises + # remove the open column as it is unnecessary now and denormalises # the table. remove_column :changesets, :open # add a column to keep track of the number of changes in a changeset. # could probably work out how many changes there are here, but i'm not # sure its actually important. - add_column(:changesets, :num_changes, :integer, + add_column(:changesets, :num_changes, :integer, :null => false, :default => 0) end diff --git a/db/migrate/040_create_oauth_tables.rb b/db/migrate/040_create_oauth_tables.rb index 95d690512..d1095f834 100644 --- a/db/migrate/040_create_oauth_tables.rb +++ b/db/migrate/040_create_oauth_tables.rb @@ -12,7 +12,7 @@ class CreateOauthTables < ActiveRecord::Migration t.timestamps end add_index :client_applications, :key, :unique => true - + create_table :oauth_tokens do |t| t.integer :user_id t.string :type, :limit => 20 @@ -22,9 +22,9 @@ class CreateOauthTables < ActiveRecord::Migration t.timestamp :authorized_at, :invalidated_at t.timestamps end - + add_index :oauth_tokens, :token, :unique => true - + create_table :oauth_nonces do |t| t.string :nonce t.integer :timestamp @@ -32,7 +32,7 @@ class CreateOauthTables < ActiveRecord::Migration t.timestamps end add_index :oauth_nonces, [:nonce, :timestamp], :unique => true - + end def self.down diff --git a/db/migrate/053_add_map_bug_tables.rb b/db/migrate/053_add_map_bug_tables.rb index 6851a20b4..c5a4a4801 100644 --- a/db/migrate/053_add_map_bug_tables.rb +++ b/db/migrate/053_add_map_bug_tables.rb @@ -5,12 +5,12 @@ class AddMapBugTables < ActiveRecord::Migration create_enumeration :map_bug_status_enum, ["open", "closed", "hidden"] create_table :map_bugs do |t| - t.integer :latitude, :null => false - t.integer :longitude, :null => false + t.integer :latitude, :null => false + t.integer :longitude, :null => false t.column :tile, :bigint, :null => false t.datetime :last_changed, :null => false - t.datetime :date_created, :null => false - t.string :nearby_place + t.datetime :date_created, :null => false + t.string :nearby_place t.string :text t.column :status, :map_bug_status_enum, :null => false end diff --git a/db/migrate/054_refactor_map_bug_tables.rb b/db/migrate/054_refactor_map_bug_tables.rb index d3839aaa8..588f654d0 100644 --- a/db/migrate/054_refactor_map_bug_tables.rb +++ b/db/migrate/054_refactor_map_bug_tables.rb @@ -4,7 +4,7 @@ class RefactorMapBugTables < ActiveRecord::Migration def self.up create_table :map_bug_comment do |t| t.column :bug_id, :bigint, :null => false - t.boolean :visible, :null => false + t.boolean :visible, :null => false t.datetime :date_created, :null => false t.string :commenter_name t.string :commenter_ip @@ -12,7 +12,7 @@ class RefactorMapBugTables < ActiveRecord::Migration t.string :comment end - remove_column :map_bugs, :text + remove_column :map_bugs, :text change_column :map_bug_comment, :id, :bigint diff --git a/db/migrate/056_add_date_closed.rb b/db/migrate/056_add_date_closed.rb index bb4c19c1a..39a63852f 100644 --- a/db/migrate/056_add_date_closed.rb +++ b/db/migrate/056_add_date_closed.rb @@ -6,6 +6,6 @@ class AddDateClosed < ActiveRecord::Migration end def self.down - remove_column :map_bugs, :date_closed + remove_column :map_bugs, :date_closed end end diff --git a/db/migrate/20100516124737_add_open_id.rb b/db/migrate/20100516124737_add_open_id.rb index 2fb9ee5b4..bbe54430d 100644 --- a/db/migrate/20100516124737_add_open_id.rb +++ b/db/migrate/20100516124737_add_open_id.rb @@ -1,6 +1,6 @@ class AddOpenId < ActiveRecord::Migration def self.up - add_column :users, :openid_url, :string + add_column :users, :openid_url, :string add_index :users, [:openid_url], :name => "user_openid_url_idx", :unique => true end diff --git a/db/migrate/20110322001319_add_terms_seen_to_user.rb b/db/migrate/20110322001319_add_terms_seen_to_user.rb index 8178c1592..3cab89652 100644 --- a/db/migrate/20110322001319_add_terms_seen_to_user.rb +++ b/db/migrate/20110322001319_add_terms_seen_to_user.rb @@ -1,7 +1,7 @@ class AddTermsSeenToUser < ActiveRecord::Migration def self.up add_column :users, :terms_seen, :boolean, :null => false, :default => false - + # best guess available is just that everyone who has agreed has # seen the terms, and that noone else has. User.update_all "terms_seen = (terms_agreed is not null)" diff --git a/lib/classic_pagination/pagination.rb b/lib/classic_pagination/pagination.rb index fa1307bee..5db1be02b 100644 --- a/lib/classic_pagination/pagination.rb +++ b/lib/classic_pagination/pagination.rb @@ -13,23 +13,23 @@ module ActionController # # Pagination is included automatically for all controllers. # - # For help rendering pagination links, see + # For help rendering pagination links, see # ActionView::Helpers::PaginationHelper. # # ==== Automatic pagination for every action in a controller # - # class PersonController < ApplicationController + # class PersonController < ApplicationController # model :person # # paginate :people, :order => 'last_name, first_name', # :per_page => 20 - # + # # # ... # end # # Each action in this controller now has access to a @people # instance variable, which is an ordered collection of model objects for the - # current page (at most 20, sorted by last name and first name), and a + # current page (at most 20, sorted by last name and first name), and a # @person_pages Paginator instance. The current page is determined # by the params[:page] variable. # @@ -44,23 +44,23 @@ module ActionController # and @people for a single action, and uses the default of 10 items # per page. # - # ==== Custom/"classic" pagination + # ==== Custom/"classic" pagination # # def list # @person_pages = Paginator.new self, Person.count, 10, params[:page] - # @people = Person.find :all, :order => 'last_name, first_name', + # @people = Person.find :all, :order => 'last_name, first_name', # :limit => @person_pages.items_per_page, # :offset => @person_pages.current.offset # end - # - # Explicitly creates the paginator from the previous example and uses + # + # Explicitly creates the paginator from the previous example and uses # Paginator#to_sql to retrieve @people from the model. # module Pagination unless const_defined?(:OPTIONS) # A hash holding options for controllers using macro-style pagination OPTIONS = Hash.new - + # The default options for pagination DEFAULT_OPTIONS = { :class_name => nil, @@ -80,18 +80,18 @@ module ActionController else DEFAULT_OPTIONS[:group] = nil end - + def self.included(base) #:nodoc: super base.extend(ClassMethods) end - + def self.validate_options!(collection_id, options, in_action) #:nodoc: options.merge!(DEFAULT_OPTIONS) {|key, old, new| old} valid_options = DEFAULT_OPTIONS.keys valid_options << :actions unless in_action - + unknown_option_keys = options.keys - valid_options raise ActionController::ActionControllerError, "Unknown options: #{unknown_option_keys.join(', ')}" unless @@ -110,7 +110,7 @@ module ActionController # :singular_name:: the singular name to use, if it can't be inferred by singularizing the collection name # :class_name:: the class name to use, if it can't be inferred by # camelizing the singular name - # :per_page:: the maximum number of items to include in a + # :per_page:: the maximum number of items to include in a # single page. Defaults to 10 # :conditions:: optional conditions passed to Model.find(:all, *params) and # Model.count @@ -133,13 +133,13 @@ module ActionController paginator_and_collection_for(collection_id, options) end - # These methods become class methods on any controller + # These methods become class methods on any controller module ClassMethods # Creates a +before_filter+ which automatically paginates an Active # Record model for all actions in a controller (or certain actions if # specified with the :actions option). # - # +options+ are the same as PaginationHelper#paginate, with the addition + # +options+ are the same as PaginationHelper#paginate, with the addition # of: # :actions:: an array of actions for which the pagination is # active. Defaults to +nil+ (i.e., every action) @@ -158,17 +158,17 @@ module ActionController next unless options[:actions].include? action_name if options[:actions] - paginator, collection = + paginator, collection = paginator_and_collection_for(collection_id, options) paginator_name = "@#{options[:singular_name]}_pages" self.instance_variable_set(paginator_name, paginator) collection_name = "@#{collection_id.to_s}" - self.instance_variable_set(collection_name, collection) + self.instance_variable_set(collection_name, collection) end end - + # Returns the total number of items in the collection to be paginated for # the +model+ and given +conditions+. Override this method to implement a # custom counter. @@ -185,7 +185,7 @@ module ActionController collection.count end - + # Returns a collection of items for the given +model+ and +options[conditions]+, # ordered by +options[order]+, for the current page in the given +paginator+. # Override this method to implement a custom finder. @@ -199,10 +199,10 @@ module ActionController if options[:select] collection = collection.select(options[:select]) end - + collection.offset(paginator.current.offset).limit(options[:per_page]) end - + protected :create_paginators_and_retrieve_collections, :count_collection_for_pagination, :find_collection_for_pagination @@ -213,10 +213,10 @@ module ActionController count = count_collection_for_pagination(klass, options) paginator = Paginator.new(self, count, options[:per_page], page) collection = find_collection_for_pagination(klass, options, paginator) - - return paginator, collection + + return paginator, collection end - + private :paginator_and_collection_for # A class representing a paginator for an Active Record collection. @@ -236,13 +236,13 @@ module ActionController @item_count = item_count || 0 @items_per_page = items_per_page @pages = {} - + self.current_page = current_page end attr_reader :controller, :item_count, :items_per_page - + # Sets the current page number of this paginator. If +page+ is a Page - # object, its +number+ attribute is used as the value; if the page does + # object, its +number+ attribute is used as the value; if the page does # not belong to this Paginator, an ArgumentError is raised. def current_page=(page) if page.is_a? Page @@ -267,7 +267,7 @@ module ActionController # Returns a new Page representing the last page in this paginator. def last_page - @last_page ||= self[page_count] + @last_page ||= self[page_count] end alias last :last_page @@ -312,12 +312,12 @@ module ActionController attr_reader :paginator, :number alias to_i :number - # Compares two Page objects and returns true when they represent the + # Compares two Page objects and returns true when they represent the # same page (i.e., their paginators are the same and they have the # same page number). def ==(page) return false if page.nil? - @paginator == page.paginator and + @paginator == page.paginator and @number == page.number end @@ -334,12 +334,12 @@ module ActionController def offset @paginator.items_per_page * (@number - 1) end - + # Returns the number of the first item displayed. def first_item offset + 1 end - + # Returns the number of the last item displayed. def last_item [@paginator.items_per_page * @number, @paginator.item_count].min @@ -367,7 +367,7 @@ module ActionController if last? then nil else @paginator[@number + 1] end end - # Returns a new Window object for this page with the specified + # Returns a new Window object for this page with the specified # +padding+. def window(padding=2) Window.new(self, padding) @@ -377,7 +377,7 @@ module ActionController def to_sql [@paginator.items_per_page, offset] end - + def to_param #:nodoc: @number.to_s end diff --git a/lib/classic_pagination/pagination_helper.rb b/lib/classic_pagination/pagination_helper.rb index 069d77566..01260f9e0 100644 --- a/lib/classic_pagination/pagination_helper.rb +++ b/lib/classic_pagination/pagination_helper.rb @@ -27,7 +27,7 @@ module ActionView # (i.e. Older Pages: 1 2 3 4) # :suffix:: suffix for pagination links # (i.e. 1 2 3 4 <- Older Pages) - # :window_size:: the number of pages to show around + # :window_size:: the number of pages to show around # the current page (defaults to 2) # :always_show_anchors:: whether or not the first and last # pages should always be shown @@ -48,18 +48,18 @@ module ActionView # # => 1 2 3 ... 10 # # pagination_links(@person_pages, :always_show_anchors => false) - # # => 1 2 3 + # # => 1 2 3 # # pagination_links(@person_pages, :window_size => 1) # # => 1 2 ... 10 # # pagination_links(@person_pages, :params => { :viewer => "flash" }) - # # => 1 2 3 ... + # # => 1 2 3 ... # # 10 def pagination_links(paginator, options={}, html_options={}) name = options[:name] || DEFAULT_OPTIONS[:name] params = (options[:params] || DEFAULT_OPTIONS[:params]).clone - + prefix = options[:prefix] || '' suffix = options[:suffix] || '' @@ -71,9 +71,9 @@ module ActionView # Iterate through the pages of a given +paginator+, invoking a # block for each page number that needs to be rendered as a link. - # + # # ==== Options - # :window_size:: the number of pages to show around + # :window_size:: the number of pages to show around # the current page (defaults to +2+) # :always_show_anchors:: whether or not the first and last # pages should always be shown @@ -98,9 +98,9 @@ module ActionView current_page = paginator.current_page window_pages = current_page.window(options[:window_size]).pages return if window_pages.length <= 1 unless link_to_current_page - + first, last = paginator.first, paginator.last - + html = '' html << prefix if prefix @@ -110,7 +110,7 @@ module ActionView html << ' ... ' if wp_first.number - first.number > 1 html << ' ' end - + window_pages.each do |page| if current_page == page && !link_to_current_page html << page.number.to_s @@ -119,8 +119,8 @@ module ActionView end html << ' ' end - - if always_show_anchors and not (wp_last = window_pages[-1]).last? + + if always_show_anchors and not (wp_last = window_pages[-1]).last? html << ' ... ' if last.number - wp_last.number > 1 html << yield(last.number) end @@ -129,7 +129,7 @@ module ActionView html end - + end # PaginationHelper end # Helpers end # ActionView diff --git a/lib/consistency_validations.rb b/lib/consistency_validations.rb index d23ef8400..bcb7a26b7 100644 --- a/lib/consistency_validations.rb +++ b/lib/consistency_validations.rb @@ -1,9 +1,9 @@ module ConsistencyValidations # Generic checks that are run for the updates and deletes of - # node, ways and relations. This code is here to avoid duplication, + # node, ways and relations. This code is here to avoid duplication, # and allow the extention of the checks without having to modify the - # code in 6 places for all the updates and deletes. Some of these tests are - # needed for creates, but are currently not run :-( + # code in 6 places for all the updates and deletes. Some of these tests are + # needed for creates, but are currently not run :-( # This will throw an exception if there is an inconsistency def check_consistency(old, new, user) if new.id != old.id or new.id.nil? or old.id.nil? @@ -18,7 +18,7 @@ module ConsistencyValidations raise OSM::APIChangesetAlreadyClosedError.new(new.changeset) end end - + # This is similar to above, just some validations don't apply def check_create_consistency(new, user) if new.changeset.nil? @@ -38,7 +38,7 @@ module ConsistencyValidations # may alter it. if changeset.nil? raise OSM::APIChangesetMissingError.new - elsif user.id != changeset.user_id + elsif user.id != changeset.user_id raise OSM::APIUserChangesetMismatchError.new elsif not changeset.is_open? raise OSM::APIChangesetAlreadyClosedError.new(changeset) diff --git a/lib/daemons/gpx_import.rb b/lib/daemons/gpx_import.rb index 698e858ba..1a87bf6b8 100755 --- a/lib/daemons/gpx_import.rb +++ b/lib/daemons/gpx_import.rb @@ -13,7 +13,7 @@ while(true) do ActiveRecord::Base.logger.info("GPX Import daemon wake @ #{Time.now}.") Trace.find(:all, :conditions => { :inserted => false, :visible => true }, :order => "id").each do |trace| - Signal.trap("TERM") do + Signal.trap("TERM") do terminated = true end @@ -39,7 +39,7 @@ while(true) do end Trace.find(:all, :conditions => { :visible => false }, :order => "id").each do |trace| - Signal.trap("TERM") do + Signal.trap("TERM") do terminated = true end diff --git a/lib/diff_reader.rb b/lib/diff_reader.rb index ca38d3501..40b43c5cd 100644 --- a/lib/diff_reader.rb +++ b/lib/diff_reader.rb @@ -7,9 +7,9 @@ class DiffReader include ConsistencyValidations # maps each element type to the model class which handles it - MODELS = { - "node" => Node, - "way" => Way, + MODELS = { + "node" => Node, + "way" => Way, "relation" => Relation } @@ -40,7 +40,7 @@ class DiffReader end ## - # An element-block mapping for using the LibXML reader interface. + # An element-block mapping for using the LibXML reader interface. # # Since a lot of LibXML reader usage is boilerplate iteration through # elements, it would be better to DRY and do this in a block. This @@ -73,13 +73,13 @@ class DiffReader else read_or_die end - end + end end read_or_die end ## - # An element-block mapping for using the LibXML reader interface. + # An element-block mapping for using the LibXML reader interface. # # Since a lot of LibXML reader usage is boilerplate iteration through # elements, it would be better to DRY and do this in a block. This @@ -89,7 +89,7 @@ class DiffReader model = MODELS[model_name] raise OSM::APIBadUserInput.new("Unexpected element type #{model_name}, " + "expected node, way or relation.") if model.nil? - # new in libxml-ruby >= 2, expand returns an element not associated + # new in libxml-ruby >= 2, expand returns an element not associated # with a document. this means that there's no encoding parameter, # which means basically nothing works. expanded = @reader.expand @@ -112,7 +112,7 @@ class DiffReader # such as save_ and delete_with_history. def check(model, xml, new) raise OSM::APIBadXMLError.new(model, xml) if new.nil? - unless new.changeset_id == @changeset.id + unless new.changeset_id == @changeset.id raise OSM::APIChangesetMismatchError.new(new.changeset_id, @changeset.id) end end @@ -122,7 +122,7 @@ class DiffReader # is *not* transactional, so code which calls it should ensure that the # appropriate transaction block is in place. # - # On a failure to meet preconditions (e.g: optimistic locking fails) + # On a failure to meet preconditions (e.g: optimistic locking fails) # an exception subclassing OSM::APIError will be thrown. def commit @@ -162,7 +162,7 @@ class DiffReader # create element given user new.create_with_history(@changeset.user) - + # save placeholder => allocated ID map ids[model_sym][placeholder_id] = new.id @@ -173,7 +173,7 @@ class DiffReader xml_result["new_version"] = new.version.to_s result.root << xml_result end - + elsif action_name == 'modify' # modify an existing element. again, this code doesn't directly deal # with types, but uses duck typing to handle them transparently. @@ -199,7 +199,7 @@ class DiffReader xml_result = XML::Node.new model.to_s.downcase xml_result["old_id"] = client_id.to_s - xml_result["new_id"] = id.to_s + xml_result["new_id"] = id.to_s # version is updated in "old" through the update, so we must not # return new.version here but old.version! xml_result["new_version"] = old.version.to_s diff --git a/lib/editors.rb b/lib/editors.rb index 101a6f80c..84f2a9468 100644 --- a/lib/editors.rb +++ b/lib/editors.rb @@ -1,4 +1,4 @@ -module Editors +module Editors ALL_EDITORS = [ "potlatch", "potlatch2", "id", "remote" ] RECOMMENDED_EDITORS = [ "id", "potlatch2", "remote" ] end diff --git a/lib/geo_record.rb b/lib/geo_record.rb index fbfb0c2ce..7c65e3af2 100644 --- a/lib/geo_record.rb +++ b/lib/geo_record.rb @@ -1,9 +1,9 @@ module GeoRecord - # This scaling factor is used to convert between the float lat/lon that is + # This scaling factor is used to convert between the float lat/lon that is # returned by the API, and the integer lat/lon equivalent that is stored in # the database. SCALE = 10000000 - + def self.included(base) base.scope :bbox, ->(bbox) { base.where(OSM.sql_for_area(bbox)) } base.before_save :update_tile @@ -40,7 +40,7 @@ module GeoRecord end private - + def lat2y(a) 180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2)) end diff --git a/lib/output_compression/output_compression.rb b/lib/output_compression/output_compression.rb index c7652ae1d..e3db8fb78 100644 --- a/lib/output_compression/output_compression.rb +++ b/lib/output_compression/output_compression.rb @@ -1,66 +1,66 @@ # OutputCompression -# Rails output compression filters -# -# Adds two classmethods to ActionController that can be used as after-filters: -# strip_whitespace and compress_output. -# If you use page-caching, you MUST specify the compress_output filter AFTER -# caches_page, otherwise the compressed data will be cached instead of the HTML -# -# class MyController < ApplicationController -# after_filter :strip_whitespace -# caches_page :index -# after_filter :compress_output -# end +# Rails output compression filters +# +# Adds two classmethods to ActionController that can be used as after-filters: +# strip_whitespace and compress_output. +# If you use page-caching, you MUST specify the compress_output filter AFTER +# caches_page, otherwise the compressed data will be cached instead of the HTML +# +# class MyController < ApplicationController +# after_filter :strip_whitespace +# caches_page :index +# after_filter :compress_output +# end -begin - require 'zlib' - require 'stringio' - GZIP_SUPPORTED = true -rescue - GZIP_SUPPORTED = false -end +begin + require 'zlib' + require 'stringio' + GZIP_SUPPORTED = true +rescue + GZIP_SUPPORTED = false +end -module CompressionSystem - def compress_output +module CompressionSystem + def compress_output return unless accepts_gzip? - output = StringIO.new - def output.close - # Zlib does a close. Bad Zlib... - rewind - end - gz = Zlib::GzipWriter.new(output) - gz.write(response.body) - gz.close - if output.length < response.body.length - @old_response_body = response.body - response.body = output.string - response.headers['Content-encoding'] = @compression_encoding - end - end - - def accepts_gzip? - return false unless GZIP_SUPPORTED - accepts = request.env['HTTP_ACCEPT_ENCODING'] - return false unless accepts && accepts =~ /(x-gzip|gzip)/ - @compression_encoding = $1 - true + output = StringIO.new + def output.close + # Zlib does a close. Bad Zlib... + rewind + end + gz = Zlib::GzipWriter.new(output) + gz.write(response.body) + gz.close + if output.length < response.body.length + @old_response_body = response.body + response.body = output.string + response.headers['Content-encoding'] = @compression_encoding + end + end + + def accepts_gzip? + return false unless GZIP_SUPPORTED + accepts = request.env['HTTP_ACCEPT_ENCODING'] + return false unless accepts && accepts =~ /(x-gzip|gzip)/ + @compression_encoding = $1 + true end - + def strip_whitespace - response.body.gsub!(/()|(.*?<\/script>)|()|()|\s+/m) do |m| - if m =~ /^()(.*?)<\/script>$/m - $1 + $2.strip.gsub(/\s+/, ' ').gsub('',"\n-->") + '' - elsif m =~ /^$/m - '' - elsif m =~ /^<(textarea|pre)/ - m - else ' ' - end + response.body.gsub!(/()|(.*?<\/script>)|()|()|\s+/m) do |m| + if m =~ /^()(.*?)<\/script>$/m + $1 + $2.strip.gsub(/\s+/, ' ').gsub('',"\n-->") + '' + elsif m =~ /^$/m + '' + elsif m =~ /^<(textarea|pre)/ + m + else ' ' + end end - response.body.gsub! /\s+\s+/, '>' - end -end + response.body.gsub! /\s+\s+/, '>' + end +end -class ActionController::Base - include CompressionSystem -end \ No newline at end of file +class ActionController::Base + include CompressionSystem +end diff --git a/lib/potlatch.rb b/lib/potlatch.rb index 359492fa7..bd2c905fe 100644 --- a/lib/potlatch.rb +++ b/lib/potlatch.rb @@ -5,33 +5,33 @@ module Potlatch # The AMF class is a set of helper functions for encoding and decoding AMF. class AMF - + # Return two-byte integer - def self.getint(s) + def self.getint(s) s.getbyte*256+s.getbyte end # Return four-byte long - def self.getlong(s) + def self.getlong(s) ((s.getbyte*256+s.getbyte)*256+s.getbyte)*256+s.getbyte end - # Return string with two-byte length - def self.getstring(s) + # Return string with two-byte length + def self.getstring(s) len=s.getbyte*256+s.getbyte str=s.read(len) str.force_encoding("UTF-8") if str.respond_to?("force_encoding") str end - # Return eight-byte double-precision float - def self.getdouble(s) + # Return eight-byte double-precision float + def self.getdouble(s) a=s.read(8).unpack('G') # G big-endian, E little-endian a[0] end # Return numeric array - def self.getarray(s) + def self.getarray(s) len=getlong(s) arr=[] for i in (0..len-1) @@ -40,8 +40,8 @@ module Potlatch arr end - # Return object/hash - def self.getobject(s) + # Return object/hash + def self.getobject(s) arr={} while (key=getstring(s)) if (key=='') then break end @@ -52,7 +52,7 @@ module Potlatch end # Parse and get value - def self.getvalue(s) + def self.getvalue(s) case s.getbyte when 0; return getdouble(s) # number when 1; return s.getbyte # boolean @@ -68,7 +68,7 @@ module Potlatch end # Envelope data into AMF writeable form - def self.putdata(index,n) + def self.putdata(index,n) d =encodestring(index+"/onResult") d+=encodestring("null") d+=[-1].pack("N") @@ -76,7 +76,7 @@ module Potlatch end # Pack variables as AMF - def self.encodevalue(n) + def self.encodevalue(n) case n.class.to_s when 'Array' a=10.chr+encodelong(n.length) @@ -112,13 +112,13 @@ module Potlatch a.chr+b.chr+n end - # Encode number as eight-byte double precision float - def self.encodedouble(n) + # Encode number as eight-byte double precision float + def self.encodedouble(n) [n].pack('G') end # Encode number as four-byte long - def self.encodelong(n) + def self.encodelong(n) [n].pack('N') end @@ -243,7 +243,7 @@ module Potlatch } end icon_list.reverse! - + # Read auto-complete autotags={}; autotags['point']={}; autotags['way']={}; autotags['POI']={}; File.open("#{Rails.root}/config/potlatch/autocomplete.txt") do |file| @@ -262,4 +262,3 @@ module Potlatch end end - diff --git a/lib/quova.rb b/lib/quova.rb index ed5b9f491..70e5b4601 100644 --- a/lib/quova.rb +++ b/lib/quova.rb @@ -53,7 +53,7 @@ module Quova def status @ipinfo["GetIpInfoResult"]["Response"]["Status"].to_i end - + def country_code @ipinfo["GetIpInfoResult"]["Location"]["Country"]["Name"] end @@ -63,4 +63,3 @@ module Quova end end end - diff --git a/lib/redactable.rb b/lib/redactable.rb index 620b2196e..b7f7046be 100644 --- a/lib/redactable.rb +++ b/lib/redactable.rb @@ -6,7 +6,7 @@ module Redactable # in scope for the module itself. base.scope :unredacted, -> { base.where(:redaction_id => nil) } end - + def redacted? not self.redaction.nil? end diff --git a/lib/rich_text.rb b/lib/rich_text.rb index 533c8fbb4..4cd254720 100644 --- a/lib/rich_text.rb +++ b/lib/rich_text.rb @@ -102,7 +102,7 @@ module RichText else "#{link}" end - end + end end end diff --git a/lib/session_persistence.rb b/lib/session_persistence.rb index 578039f58..2244a3e63 100644 --- a/lib/session_persistence.rb +++ b/lib/session_persistence.rb @@ -37,7 +37,7 @@ module SessionPersistence # session_expires_after 1.hour # session_expires_after 2.weeks def session_expires_after(seconds) - session[session_persistence_key] = seconds + session[session_persistence_key] = seconds end # Expire the session. diff --git a/lib/short_link.rb b/lib/short_link.rb index 045883d57..b09e65f43 100644 --- a/lib/short_link.rb +++ b/lib/short_link.rb @@ -7,12 +7,12 @@ module ShortLink # array of 64 chars to encode 6 bits. this is almost like base64 encoding, but - # the symbolic chars are different, as base64's + and / aren't very + # the symbolic chars are different, as base64's + and / aren't very # URL-friendly. ARRAY = ('A'..'Z').to_a + ('a'..'z').to_a + ('0'..'9').to_a + ['_','~'] ## - # Given a string encoding a location, returns the [lon, lat, z] tuple of that + # Given a string encoding a location, returns the [lon, lat, z] tuple of that # location. def self.decode(str) x = 0 @@ -42,15 +42,15 @@ module ShortLink y <<= (32 - z) # project the parameters back to their coordinate ranges. - [(x * 360.0 / 2**32) - 180.0, - (y * 180.0 / 2**32) - 90.0, + [(x * 360.0 / 2**32) - 180.0, + (y * 180.0 / 2**32) - 90.0, z - 8 - (z_offset % 3)] end ## # given a location and zoom, return a short string representing it. def self.encode(lon, lat, z) - code = interleave_bits(((lon + 180.0) * 2**32 / 360.0).to_i, + code = interleave_bits(((lon + 180.0) * 2**32 / 360.0).to_i, ((lat + 90.0) * 2**32 / 180.0).to_i) str = "" # add eight to the zoom level, which approximates an accuracy of @@ -63,12 +63,12 @@ module ShortLink # partial zoom levels (characters themselves have a granularity # of 3 zoom levels). ((z + 8) % 3).times { str << "-" } - + return str end private - + ## # interleaves the bits of two 32-bit numbers. the result is known # as a Morton code. diff --git a/lib/tasks/add_version_to_nodes.rake b/lib/tasks/add_version_to_nodes.rake index 5301738c0..22762ef2e 100644 --- a/lib/tasks/add_version_to_nodes.rake +++ b/lib/tasks/add_version_to_nodes.rake @@ -6,14 +6,14 @@ namespace 'db' do increment = 1000 offset = 0 id_max = OldNode.find(:first, :order => 'id desc').id - + while offset < (id_max + increment) hash = {} #should be offsetting not selecting OldNode.find(:all, :limit => increment, :offset => offset, :order => 'timestamp').each do |node| if hash[node.id].nil? - hash[node.id] = [] + hash[node.id] = [] end hash[node.id] << node end @@ -31,16 +31,10 @@ namespace 'db' do temp_old_node.tile = node.tile temp_old_node.version = n temp_old_node.save! || raise - n +=1 + n +=1 end end offset += increment end end end - - - - - - diff --git a/lib/tasks/testing.rake b/lib/tasks/testing.rake index 7a915c228..ec0bd9459 100644 --- a/lib/tasks/testing.rake +++ b/lib/tasks/testing.rake @@ -1,5 +1,5 @@ namespace :test do - Rails::TestTask.new(lib: "test:prepare") do |t| + Rails::TestTask.new(lib: "test:prepare") do |t| t.pattern = 'test/lib/**/*_test.rb' end end diff --git a/lib/validators.rb b/lib/validators.rb index 640a49564..94dbdb7f3 100644 --- a/lib/validators.rb +++ b/lib/validators.rb @@ -1,7 +1,7 @@ module ActiveRecord module Validations module ClassMethods - + # error message when invalid UTF-8 is detected @@invalid_utf8_message = " is invalid UTF-8" @@ -13,7 +13,7 @@ module ActiveRecord validates_each(attrs) do |record, attr, value| record.errors.add(attr, @@invalid_utf8_message) unless UTF8.valid? value end - end + end end end diff --git a/script/daemons b/script/daemons index feb98b645..69c7ec948 100755 --- a/script/daemons +++ b/script/daemons @@ -1,2 +1,2 @@ #!/usr/bin/env ruby -Dir[File.dirname(__FILE__) + "/../lib/daemons/*_ctl"].each {|f| `#{f} #{ARGV.first}`} \ No newline at end of file +Dir[File.dirname(__FILE__) + "/../lib/daemons/*_ctl"].each {|f| `#{f} #{ARGV.first}`} diff --git a/script/locale/po2yaml b/script/locale/po2yaml index 3e05363e7..e181bf3d5 100755 --- a/script/locale/po2yaml +++ b/script/locale/po2yaml @@ -30,7 +30,7 @@ def po2hash(f) elsif line[0..7] == 'msgstr "' msgstr = line[8..-2] end - + if !path.empty? and !msgstr.empty? add_translation(trs, path, msgstr) path = [] diff --git a/script/statistics b/script/statistics index ce785bb07..f20e70031 100755 --- a/script/statistics +++ b/script/statistics @@ -57,7 +57,7 @@ begin puts "Nodes#{day_count}#{week_count}#{month_count}" puts "" - + puts "

Top users editing over the past...

" puts "" puts "" diff --git a/test/controllers/amf_controller_test.rb b/test/controllers/amf_controller_test.rb index 073b82235..ef50cfe74 100644 --- a/test/controllers/amf_controller_test.rb +++ b/test/controllers/amf_controller_test.rb @@ -24,7 +24,7 @@ class AmfControllerTest < ActionController::TestCase amf_content "getway", "/1", [id] post :amf_read assert_response :success - amf_parse_response + amf_parse_response way = amf_result("/1") assert_equal 0, way[0] assert_equal "", way[1] @@ -55,7 +55,7 @@ class AmfControllerTest < ActionController::TestCase amf_content "getway", "/1", [id] post :amf_read assert_response :success - amf_parse_response + amf_parse_response way = amf_result("/1") assert_equal 0, way[0] assert_equal "", way[1] @@ -72,7 +72,7 @@ class AmfControllerTest < ActionController::TestCase amf_content "getway", "/1", [id] post :amf_read assert_response :success - amf_parse_response + amf_parse_response way = amf_result("/1") assert_equal 0, way[0] assert_equal "", way[1] @@ -90,7 +90,7 @@ class AmfControllerTest < ActionController::TestCase amf_content "getway", "/1", [id] post :amf_read assert_response :success - amf_parse_response + amf_parse_response way = amf_result("/1") assert_equal 0, way[0] assert_equal "", way[1] @@ -125,7 +125,7 @@ class AmfControllerTest < ActionController::TestCase amf_content "whichways", "/1", [minlon, minlat, maxlon, maxlat] post :amf_read assert_response :success - amf_parse_response + amf_parse_response # check contents of message map = amf_result "/1" @@ -230,7 +230,7 @@ class AmfControllerTest < ActionController::TestCase amf_content "whichways_deleted", "/1", bbox post :amf_read assert_response :success - amf_parse_response + 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" @@ -280,11 +280,11 @@ class AmfControllerTest < ActionController::TestCase # instead of a version number... # try to get version 1 v1 = ways(:way_with_versions_v1) - { latest.id => '', + { latest.id => '', v1.way_id => v1.timestamp.strftime("%d %b %Y, %H:%M:%S") }.each do |id, t| amf_content "getway_old", "/1", [id, t] - post :amf_read + post :amf_read assert_response :success amf_parse_response returned_way = amf_result("/1") @@ -294,7 +294,7 @@ class AmfControllerTest < ActionController::TestCase 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. @@ -323,8 +323,8 @@ class AmfControllerTest < ActionController::TestCase v1 = ways(:way_with_versions_v1) # 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'], + [[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| amf_content "getway_old", "/1", [id, t] @@ -351,7 +351,7 @@ class AmfControllerTest < ActionController::TestCase # ['way',wayid,history] assert_equal 'way', history[0] - assert_equal latest.id, history[1] + 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", @@ -384,14 +384,14 @@ class AmfControllerTest < ActionController::TestCase # ['node',nodeid,history] # note that (as per getway_history) we actually round up # to the next second - assert_equal history[0], 'node', + assert_equal history[0], 'node', 'first element should be "node"' assert_equal history[1], latest.id, 'second element should be the input node ID' - assert_equal history[2].first[0], + assert_equal history[2].first[0], (latest.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], + assert_equal history[2].last[0], (nodes(:node_with_versions_v1).timestamp + 1).strftime("%d %b %Y, %H:%M:%S"), 'last element in third element (array) should be the initial version' end @@ -419,13 +419,13 @@ class AmfControllerTest < ActionController::TestCase assert_response :success amf_parse_response result = amf_result("/1") - + 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 @@ -434,14 +434,14 @@ class AmfControllerTest < ActionController::TestCase assert_response :success amf_parse_response result = amf_result("/2") - + 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 @@ -452,21 +452,21 @@ class AmfControllerTest < ActionController::TestCase lon = rand(100)-50 + rand # normal user has a changeset open changeset = changesets(:public_user_first_change) - + amf_content "putpoi", "/1", ["test@example.com:test", changeset.id, nil, nil, lon, lat, {}, nil] post :amf_write 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] > 0, "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 + + # 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) @@ -482,7 +482,7 @@ class AmfControllerTest < ActionController::TestCase 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 tnd = Node.new @@ -491,7 +491,7 @@ class AmfControllerTest < ActionController::TestCase lon = rand(100)-50 + rand # normal user has a changeset open changeset = changesets(:public_user_first_change) - + amf_content "putpoi", "/2", ["test@example.com:test", changeset.id, nil, nil, lon, lat, { "key" => "value", "ping" => "pong" }, nil] post :amf_write assert_response :success @@ -504,8 +504,8 @@ class AmfControllerTest < ActionController::TestCase assert_equal 0, result[2], "The old id should be 0" assert result[3] > 0, "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 + + # 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) @@ -524,7 +524,7 @@ class AmfControllerTest < ActionController::TestCase 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 @@ -534,24 +534,24 @@ class AmfControllerTest < ActionController::TestCase lon = rand(100)-50 + rand # normal user has a changeset open changeset = changesets(:public_user_first_change) - + mostly_invalid = (0..31).to_a.map {|i| i.chr}.join tags = { "something" => "foo#{mostly_invalid}bar" } - + amf_content "putpoi", "/1", ["test@example.com:test", changeset.id, nil, nil, lon, lat, tags, nil] post :amf_write 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] > 0, "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 + + # 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) @@ -569,10 +569,10 @@ class AmfControllerTest < ActionController::TestCase lon = rand(100)-50 + rand # normal user has a changeset open changeset = changesets(:public_user_first_change) - + invalid = "\xc0\xc0" tags = { "something" => "foo#{invalid}bar" } - + amf_content "putpoi", "/1", ["test@example.com:test", changeset.id, nil, nil, lon, lat, tags, nil] post :amf_write assert_response :success @@ -581,29 +581,29 @@ class AmfControllerTest < ActionController::TestCase 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] + assert_equal "One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1.", result[1] end - + def test_putpoi_delete_valid - + end - + def test_putpoi_delete_already_deleted - + end - + def test_putpoi_delete_not_found - + end - + def test_putpoi_invalid_latlon - + end def test_startchangeset_invalid_xmlchar_comment invalid = "\035\022" comment = "foo#{invalid}bar" - + amf_content "startchangeset", "/1", ["test@example.com:test", Hash.new, nil, comment, 1] post :amf_write assert_response :success @@ -691,7 +691,7 @@ class AmfControllerTest < ActionController::TestCase 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) diff --git a/test/controllers/api_controller_test.rb b/test/controllers/api_controller_test.rb index ba8bdbae6..0ae06be5e 100644 --- a/test/controllers/api_controller_test.rb +++ b/test/controllers/api_controller_test.rb @@ -3,16 +3,16 @@ require 'api_controller' class ApiControllerTest < ActionController::TestCase api_fixtures - + def setup super @badbigbbox = %w{ -0.1,-0.1,1.1,1.1 10,10,11,11 } - @badmalformedbbox = %w{ -0.1 hello + @badmalformedbbox = %w{ -0.1 hello 10N2W10.1N2.1W } @badlatmixedbbox = %w{ 0,0.1,0.1,0 -0.1,80,0.1,70 0.24,54.34,0.25,54.33 } - @badlonmixedbbox = %w{ 80,-0.1,70,0.1 54.34,0.24,54.33,0.25 } + @badlonmixedbbox = %w{ 80,-0.1,70,0.1 54.34,0.24,54.33,0.25 } #@badlatlonoutboundsbbox = %w{ 191,-0.1,193,0.1 -190.1,89.9,-190,90 } - @goodbbox = %w{ -0.1,-0.1,0.1,0.1 51.1,-0.1,51.2,0 + @goodbbox = %w{ -0.1,-0.1,0.1,0.1 51.1,-0.1,51.2,0 -0.1,%20-0.1,%200.1,%200.1 -0.1edcd,-0.1d,0.1,0.1 -0.1E,-0.1E,0.1S,0.1N S0.1,W0.1,N0.1,E0.1} # That last item in the goodbbox really shouldn't be there, as the API should # reall reject it, however this is to test to see if the api changes. @@ -26,7 +26,7 @@ class ApiControllerTest < ActionController::TestCase { :controller => "api", :action => "capabilities" } ) assert_recognizes( - { :controller => "api", :action => "capabilities" }, + { :controller => "api", :action => "capabilities" }, { :path => "/api/0.6/capabilities", :method => :get } ) assert_routing( @@ -75,7 +75,7 @@ class ApiControllerTest < ActionController::TestCase # Should also test for the ways and relation end end - + # This differs from the above test in that we are making the bbox exactly # the same as the node we are looking at def test_map_inclusive @@ -92,7 +92,7 @@ class ApiControllerTest < ActionController::TestCase # Should also test for the ways and relation end end - + def test_tracepoints point = gpx_files(:public_trace_file) minlon = point.longitude-0.001 @@ -108,7 +108,7 @@ class ApiControllerTest < ActionController::TestCase end end end - + def test_tracepoints_trackable point = gpx_files(:trackable_trace_file) minlon = point.longitude-0.002 @@ -130,7 +130,7 @@ class ApiControllerTest < ActionController::TestCase end end end - + def test_tracepoints_identifiable point = gpx_files(:identifiable_trace_file) minlon = point.longitude-0.002 @@ -153,7 +153,7 @@ class ApiControllerTest < ActionController::TestCase end end end - + def test_map_without_bbox ["trackpoints", "map"].each do |tq| get tq @@ -161,7 +161,7 @@ class ApiControllerTest < ActionController::TestCase assert_equal "The parameter bbox is required, and must be of the form min_lon,min_lat,max_lon,max_lat", @response.body, "A bbox param was expected" end end - + def test_traces_page_less_than_0 -10.upto(-1) do |i| get :trackpoints, :page => i, :bbox => "-0.1,-0.1,0.1,0.1" @@ -173,7 +173,7 @@ class ApiControllerTest < ActionController::TestCase assert_response :success, "The page number was #{i} and should have been accepted" end end - + def test_bbox_too_big @badbigbbox.each do |bbox| [ "trackpoints", "map" ].each do |tq| @@ -183,7 +183,7 @@ class ApiControllerTest < ActionController::TestCase end end end - + def test_bbox_malformed @badmalformedbbox.each do |bbox| [ "trackpoints", "map" ].each do |tq| @@ -193,7 +193,7 @@ class ApiControllerTest < ActionController::TestCase end end end - + def test_bbox_lon_mixedup @badlonmixedbbox.each do |bbox| [ "trackpoints", "map" ].each do |tq| @@ -203,7 +203,7 @@ class ApiControllerTest < ActionController::TestCase end end end - + def test_bbox_lat_mixedup @badlatmixedbbox.each do |bbox| ["trackpoints", "map"].each do |tq| @@ -213,7 +213,7 @@ class ApiControllerTest < ActionController::TestCase end end end - + # We can't actually get an out of bounds error, as the bbox is sanitised. #def test_latlon_outofbounds # @badlatlonoutboundsbbox.each do |bbox| @@ -225,8 +225,8 @@ class ApiControllerTest < ActionController::TestCase # end # end #end - - # MySQL and Postgres require that the C based functions are installed for + + # MySQL and Postgres require that the C based functions are installed for # this test to work. More information is available from: # http://wiki.openstreetmap.org/wiki/Rails#Installing_the_quadtile_functions # or by looking at the readme in db/README @@ -235,7 +235,7 @@ class ApiControllerTest < ActionController::TestCase get :changes assert_response :success #print @response.body - # As we have loaded the fixtures, we can assume that there are no + # As we have loaded the fixtures, we can assume that there are no # changes at the time we have frozen at now = Time.now.getutc hourago = now - 1.hour @@ -244,7 +244,7 @@ class ApiControllerTest < ActionController::TestCase end Timecop.return end - + def test_changes_zoom_invalid zoom_to_test = %w{ p -1 0 17 one two } zoom_to_test.each do |zoom| @@ -253,7 +253,7 @@ class ApiControllerTest < ActionController::TestCase assert_equal @response.body, "Requested zoom is invalid, or the supplied start is after the end time, or the start duration is more than 24 hours" end end - + def test_changes_zoom_valid 1.upto(16) do |zoom| get :changes, :zoom => zoom @@ -265,7 +265,7 @@ class ApiControllerTest < ActionController::TestCase end end end - + def test_hours_invalid invalid = %w{ -21 335 -1 0 25 26 100 one two three ping pong : } invalid.each do |hour| @@ -274,14 +274,14 @@ class ApiControllerTest < ActionController::TestCase assert_equal @response.body, "Requested zoom is invalid, or the supplied start is after the end time, or the start duration is more than 24 hours", "Problem with the hour: #{hour}." end end - + def test_hours_valid 1.upto(24) do |hour| get :changes, :hours => hour assert_response :success end end - + def test_capabilities get :capabilities assert_response :success diff --git a/test/controllers/changeset_controller_test.rb b/test/controllers/changeset_controller_test.rb index ff987b6e9..b3d6d7eb2 100644 --- a/test/controllers/changeset_controller_test.rb +++ b/test/controllers/changeset_controller_test.rb @@ -1922,7 +1922,7 @@ EOF assert_no_difference('ChangesetComment.count') do post :comment, { :id => changesets(:normal_user_closed_change).id, :text => '' } end - assert_response :bad_request + assert_response :bad_request end ## @@ -2062,7 +2062,7 @@ EOF post :unhide_comment, { :id => comment.id } assert_response :unauthorized end - + basic_authorization(users(:public_user).email, 'test') # not a moderator diff --git a/test/controllers/diary_entry_controller_test.rb b/test/controllers/diary_entry_controller_test.rb index 32cab96cb..464f5fbfe 100644 --- a/test/controllers/diary_entry_controller_test.rb +++ b/test/controllers/diary_entry_controller_test.rb @@ -89,12 +89,12 @@ class DiaryEntryControllerTest < ActionController::TestCase get :new assert_response :redirect assert_redirected_to :controller => :user, :action => "login", :referer => "/diary/new" - # Now pretend to login by using the session hash, with the + # Now pretend to login by using the session hash, with the # id of the person we want to login as through session(:user)=user.id get(:new, nil, {'user' => users(:normal_user).id}) assert_response :success #print @response.body - + #print @response.to_yaml assert_select "title", :text => /New Diary Entry/, :count => 1 assert_select "div.content-heading", :count => 1 do @@ -112,16 +112,16 @@ class DiaryEntryControllerTest < ActionController::TestCase end end end - + def test_editing_diary_entry entry = diary_entries(:normal_user_entry_1) - # Make sure that you are redirected to the login page when you are + # Make sure that you are redirected to the login page when you are # not logged in, without and with the id of the entry you want to edit get :edit, :display_name => entry.user.display_name, :id => entry.id assert_response :redirect assert_redirected_to :controller => :user, :action => "login", :referer => "/user/#{entry.user.display_name}/diary/#{entry.id}/edit" - + # Verify that you get a not found error, when you pass a bogus id get(:edit, {:display_name => entry.user.display_name, :id => 9999}, {'user' => entry.user.id}) assert_response :not_found @@ -129,7 +129,7 @@ class DiaryEntryControllerTest < ActionController::TestCase assert_select "h2", :text => "No entry with the id: 9999", :count => 1 end - # Now pass the id, and check that you can edit it, when using the same + # Now pass the id, and check that you can edit it, when using the same # user as the person who created the entry get(:edit, {:display_name => entry.user.display_name, :id => entry.id}, {'user' => entry.user.id}) assert_response :success @@ -157,13 +157,13 @@ class DiaryEntryControllerTest < ActionController::TestCase new_latitude = "1.1" new_longitude = "2.2" new_language_code = "en" - post(:edit, {:display_name => entry.user.display_name, :id => entry.id, 'commit' => 'save', + post(:edit, {:display_name => entry.user.display_name, :id => entry.id, 'commit' => 'save', 'diary_entry'=>{'title' => new_title, 'body' => new_body, 'latitude' => new_latitude, 'longitude' => new_longitude, 'language_code' => new_language_code} }, {'user' => entry.user.id}) assert_response :redirect assert_redirected_to :action => :view, :display_name => entry.user.display_name, :id => entry.id - + # Now check that the new data is rendered, when logged in get :view, {:display_name => entry.user.display_name, :id => entry.id}, {'user' => entry.user.id} assert_response :success @@ -203,13 +203,13 @@ class DiaryEntryControllerTest < ActionController::TestCase end end end - + def test_edit_diary_entry_i18n get :edit, {:display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_entry_1).id}, {'user' => users(:normal_user).id} assert_response :success assert_select "span[class=translation_missing]", false, "Missing translation in edit diary entry" end - + def test_create_diary_entry # Make sure that you are redirected to the login page when you # are not logged in @@ -245,7 +245,7 @@ class DiaryEntryControllerTest < ActionController::TestCase new_longitude = "2.2" new_language_code = "en" assert_difference "DiaryEntry.count", 1 do - post(:new, {'commit' => 'save', + post(:new, {'commit' => 'save', 'diary_entry'=>{'title' => new_title, 'body' => new_body, 'latitude' => new_latitude, 'longitude' => new_longitude, 'language_code' => new_language_code} }, {:user => users(:normal_user).id}) @@ -260,14 +260,14 @@ class DiaryEntryControllerTest < ActionController::TestCase assert_equal new_longitude.to_f, entry.longitude assert_equal new_language_code, entry.language_code end - + def test_creating_diary_comment entry = diary_entries(:normal_user_entry_1) # Make sure that you are denied when you are not logged in post :comment, :display_name => entry.user.display_name, :id => entry.id assert_response :forbidden - + # Verify that you get a not found error, when you pass a bogus id post :comment, {:display_name => entry.user.display_name, :id => 9999}, {:user => users(:public_user).id} assert_response :not_found @@ -304,7 +304,7 @@ class DiaryEntryControllerTest < ActionController::TestCase assert_select ".richtext", :text => /New comment/, :count => 1 end end - + # Check that you can get the expected response and template for all available languages # Should test that there are no def test_listing_diary_entries @@ -312,14 +312,14 @@ class DiaryEntryControllerTest < ActionController::TestCase assert_response :success, "Should be able to list the diary entries in locale" assert_template 'list', "Should use the list template in locale" assert_select "span[class=translation_missing]", false, "Missing translation in list of diary entries" - + # Now try to find a specific user's diary entry get :list, {:display_name => users(:normal_user).display_name} assert_response :success, "Should be able to list the diary entries for a user in locale" assert_template 'list', "Should use the list template for a user in locale" assert_no_missing_translations end - + def test_rss get :rss, {:format => :rss} assert_response :success, "Should be able to get a diary RSS" @@ -331,13 +331,13 @@ class DiaryEntryControllerTest < ActionController::TestCase end end end - + def test_rss_language get :rss, {:language => diary_entries(:normal_user_entry_1).language_code, :format => :rss} assert_response :success, "Should be able to get a specific language diary RSS" assert_select "rss>channel>item", :count => 1 #, "Diary entries should be filtered by language" end - + # def test_rss_nonexisting_language # get :rss, {:language => 'xx', :format => :rss} # assert_response :not_found, "Should not be able to get a nonexisting language diary RSS" @@ -354,7 +354,7 @@ class DiaryEntryControllerTest < ActionController::TestCase assert_response :success, "Should be able to get a specific users diary RSS" assert_select "rss>channel>item", :count => 2 #, "Diary entries should be filtered by user" end - + def test_rss_nonexisting_user # Try a user that has never existed get :rss, {:display_name => 'fakeUsername76543', :format => :rss} diff --git a/test/controllers/export_controller_test.rb b/test/controllers/export_controller_test.rb index 8d61b9911..64ba70b19 100644 --- a/test/controllers/export_controller_test.rb +++ b/test/controllers/export_controller_test.rb @@ -22,7 +22,7 @@ class ExportControllerTest < ActionController::TestCase assert_response :redirect assert_redirected_to "http://api.openstreetmap.org/api/#{API_VERSION}/map?bbox=0.0,50.0,1.0,51.0" end - + ### # test the finish action for mapnik images def test_finish_mapnik diff --git a/test/controllers/node_controller_test.rb b/test/controllers/node_controller_test.rb index 9663ed4fb..771842b57 100644 --- a/test/controllers/node_controller_test.rb +++ b/test/controllers/node_controller_test.rb @@ -31,7 +31,7 @@ class NodeControllerTest < ActionController::TestCase def test_create # cannot read password from fixture as it is stored as MD5 digest ## First try with no auth - + # create a node with random lat/lon lat = rand(100)-50 + rand lon = rand(100)-50 + rand @@ -45,11 +45,11 @@ class NodeControllerTest < ActionController::TestCase # 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(users(:normal_user).email, "test") - + # create a node with random lat/lon lat = rand(100)-50 + rand lon = rand(100)-50 + rand @@ -64,10 +64,10 @@ class NodeControllerTest < ActionController::TestCase assert_require_public_data "node create did not return forbidden status" - + ## Now try with the user that has the public data basic_authorization(users(:public_user).email, "test") - + # create a node with random lat/lon lat = rand(100)-50 + rand lon = rand(100)-50 + rand @@ -99,7 +99,7 @@ class NodeControllerTest < ActionController::TestCase changeset = changesets(:public_user_first_change) lat = 3.434 lon = 3.23 - + # test that the upload is rejected when xml is valid, but osm doc isn't content("") put :create @@ -166,10 +166,10 @@ class NodeControllerTest < ActionController::TestCase ## first try to delete node without auth delete :delete, :id => current_nodes(:visible_node).id assert_response :unauthorized - - + + ## now set auth for the non-data public user - basic_authorization(users(:normal_user).email, "test"); + basic_authorization(users(:normal_user).email, "test"); # try to delete with an invalid (closed) changeset content update_changeset(current_nodes(:visible_node).to_xml, @@ -209,10 +209,10 @@ class NodeControllerTest < ActionController::TestCase assert_require_public_data "shouldn't be able to delete a node used in a relation (#{@response.body})" - + ## now set auth for the public data user - basic_authorization(users(:public_user).email, "test"); + basic_authorization(users(:public_user).email, "test"); # try to delete with an invalid (closed) changeset content update_changeset(current_nodes(:visible_node).to_xml, @@ -228,13 +228,13 @@ class NodeControllerTest < ActionController::TestCase # try to delete a node with a different ID content(nodes(:public_visible_node).to_xml) delete :delete, :id => current_nodes(:visible_node).id - assert_response :bad_request, + 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 content("") delete :delete, :id => current_nodes(:visible_node).id - assert_response :bad_request, + assert_response :bad_request, "should not be able to delete a node without a valid XML payload" # valid delete now takes a payload @@ -282,11 +282,11 @@ class NodeControllerTest < ActionController::TestCase content current_nodes(:visible_node).to_xml put :update, :id => current_nodes(:visible_node).id assert_response :unauthorized - - - + + + ## Second test with the private user - + # setup auth basic_authorization(users(:normal_user).email, "test") @@ -317,7 +317,7 @@ class NodeControllerTest < ActionController::TestCase content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'lat', -91.0); put :update, :id => current_nodes(:visible_node).id assert_require_public_data "node at lat=-91 should be forbidden, when data isn't public" - + content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'lon', 181.0); put :update, :id => current_nodes(:visible_node).id assert_require_public_data "node at lon=181 should be forbidden, when data isn't public" @@ -325,20 +325,20 @@ class NodeControllerTest < ActionController::TestCase content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'lon', -181.0); put :update, :id => current_nodes(:visible_node).id assert_require_public_data "node at lon=-181 should be forbidden, when data isn't public" - + ## finally, produce a good request which should work content current_nodes(:visible_node).to_xml put :update, :id => current_nodes(:visible_node).id 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 delete node without auth content current_nodes(:visible_node).to_xml put :update, :id => current_nodes(:visible_node).id assert_response :forbidden - + # setup auth basic_authorization(users(:public_user).email, "test") @@ -369,7 +369,7 @@ class NodeControllerTest < ActionController::TestCase content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'lat', -91.0); put :update, :id => current_nodes(:visible_node).id assert_response :bad_request, "node at lat=-91 should be rejected" - + content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'lon', 181.0); put :update, :id => current_nodes(:visible_node).id assert_response :bad_request, "node at lon=181 should be rejected" @@ -382,34 +382,34 @@ class NodeControllerTest < ActionController::TestCase current_node_version = current_nodes(:visible_node).version # try and submit a version behind - content xml_attr_rewrite(current_nodes(:visible_node).to_xml, + content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'version', current_node_version - 1); put :update, :id => current_nodes(:visible_node).id assert_response :conflict, "should have failed on old version number" - + # try and submit a version ahead - content xml_attr_rewrite(current_nodes(:visible_node).to_xml, + content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'version', current_node_version + 1); put :update, :id => current_nodes(:visible_node).id assert_response :conflict, "should have failed on skipped version number" # try and submit total crap in the version field - content xml_attr_rewrite(current_nodes(:visible_node).to_xml, + content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'version', 'p1r4t3s!'); put :update, :id => current_nodes(:visible_node).id - assert_response :conflict, + assert_response :conflict, "should not be able to put 'p1r4at3s!' in the version field" - + ## try an update with the wrong ID content current_nodes(:public_visible_node).to_xml put :update, :id => current_nodes(:visible_node).id - assert_response :bad_request, + 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. content "" put :update, :id => current_nodes(:visible_node).id - assert_response :bad_request, + 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 @@ -464,7 +464,7 @@ class NodeControllerTest < ActionController::TestCase # try and upload it content node_xml put :update, :id => current_nodes(:public_visible_node).id - assert_response :bad_request, + assert_response :bad_request, "adding duplicate tags to a node should fail with 'bad request'" assert_equal "Element node/#{current_nodes(:public_visible_node).id} has duplicate tags with key #{current_node_tags(:t1).k}", @response.body end @@ -475,20 +475,20 @@ class NodeControllerTest < ActionController::TestCase basic_authorization(users(:normal_user).email, "test") changeset_id = changesets(:normal_user_first_change).id - # try and put something into a string that the API might + # try and put something into a string that the API might # use unquoted and therefore allow code injection... content "" + '' + '' put :create assert_require_public_data "Shouldn't be able to create with non-public user" - - + + ## Then try with the public data user basic_authorization(users(:public_user).email, "test") changeset_id = changesets(:public_user_first_change).id - # try and put something into a string that the API might + # try and put something into a string that the API might # use unquoted and therefore allow code injection... content "" + '' + @@ -500,13 +500,13 @@ class NodeControllerTest < ActionController::TestCase # 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 :read, :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}') diff --git a/test/controllers/notes_controller_test.rb b/test/controllers/notes_controller_test.rb index 430d018e2..fcb1ca9b8 100644 --- a/test/controllers/notes_controller_test.rb +++ b/test/controllers/notes_controller_test.rb @@ -724,7 +724,7 @@ class NotesControllerTest < ActionController::TestCase end get :feed, {:bbox => "1,1,1.2,1.2", :format => "rss"} - assert_response :success + assert_response :success assert_equal "application/rss+xml", @response.content_type assert_select "rss", :count => 1 do assert_select "channel", :count => 1 do @@ -755,6 +755,6 @@ class NotesControllerTest < ActionController::TestCase assert_response :success get :mine, {:display_name => "non-existent"} - assert_response :not_found + assert_response :not_found end end diff --git a/test/controllers/oauth_clients_controller_test.rb b/test/controllers/oauth_clients_controller_test.rb index a1df9f0f2..5b2c5b6e4 100644 --- a/test/controllers/oauth_clients_controller_test.rb +++ b/test/controllers/oauth_clients_controller_test.rb @@ -89,8 +89,8 @@ class OauthClientsControllerTest < ActionController::TestCase } end assert_response :success - assert_template "new" - + assert_template "new" + assert_difference "ClientApplication.count", 1 do post :create, { :display_name => user.display_name, @@ -161,7 +161,7 @@ class OauthClientsControllerTest < ActionController::TestCase assert_template "not_found" put :update, { - :display_name => user.display_name, + :display_name => user.display_name, :id => client.id, :client_application => { :name => "New Name", @@ -174,7 +174,7 @@ class OauthClientsControllerTest < ActionController::TestCase assert_template "edit" put :update, { - :display_name => user.display_name, + :display_name => user.display_name, :id => client.id, :client_application => { :name => "New Name", diff --git a/test/controllers/old_node_controller_test.rb b/test/controllers/old_node_controller_test.rb index f4e88ddd0..74c540cb6 100644 --- a/test/controllers/old_node_controller_test.rb +++ b/test/controllers/old_node_controller_test.rb @@ -27,16 +27,16 @@ class OldNodeControllerTest < ActionController::TestCase ## # test the version call by submitting several revisions of a new node - # to the API and ensuring that later calls to version return the + # 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 + # FIXME Move this test to being an integration test since it spans multiple controllers def test_version ## First try this with a non-public user basic_authorization(users(:normal_user).email, "test") changeset_id = changesets(:normal_user_first_change).id - + # setup a simple XML node xml_doc = current_nodes(:visible_node).to_xml xml_node = xml_doc.find("//osm/node").first @@ -50,7 +50,7 @@ class OldNodeControllerTest < ActionController::TestCase versions[xml_node['version']] = xml_doc.to_s # randomly move the node about - 20.times do + 20.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 @@ -65,7 +65,7 @@ class OldNodeControllerTest < ActionController::TestCase end # add a bunch of random tags - 30.times do + 30.times do xml_tag = XML::Node.new("tag") xml_tag['k'] = random_string xml_tag['v'] = random_string @@ -83,7 +83,7 @@ class OldNodeControllerTest < ActionController::TestCase # probably should check that they didn't get written to the database - + ## Now do it with the public user basic_authorization(users(:public_user).email, "test") changeset_id = changesets(:public_user_first_change).id @@ -101,7 +101,7 @@ class OldNodeControllerTest < ActionController::TestCase versions[xml_node['version']] = xml_doc.to_s # randomly move the node about - 20.times do + 20.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 @@ -116,7 +116,7 @@ class OldNodeControllerTest < ActionController::TestCase end # add a bunch of random tags - 30.times do + 30.times do xml_tag = XML::Node.new("tag") xml_tag['k'] = random_string xml_tag['v'] = random_string @@ -145,21 +145,21 @@ class OldNodeControllerTest < ActionController::TestCase 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(nodes(:visible_node).id, 24354) check_not_found_id_version(24356, nodes(:visible_node).version) end - + def check_not_found_id_version(id, version) get :version, :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. @@ -181,7 +181,7 @@ class OldNodeControllerTest < ActionController::TestCase end ## - # test the redaction of an old version of a node, while being + # 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(users(:public_user).email, "test") @@ -200,10 +200,10 @@ class OldNodeControllerTest < ActionController::TestCase do_redact_node(nodes(:node_with_versions_v4), redactions(:example)) assert_response :bad_request, "shouldn't be OK to redact current version as moderator." - end + end ## - # test that redacted nodes aren't visible, regardless of + # test that redacted nodes aren't visible, regardless of # authorisation except as moderator... def test_version_redacted node = nodes(:redacted_node_redacted_version) @@ -234,7 +234,7 @@ class OldNodeControllerTest < ActionController::TestCase end ## - # test the redaction of an old version of a node, while being + # test the redaction of an old version of a node, while being # authorised as a moderator. def test_redact_node_moderator node = nodes(:node_with_versions_v3) @@ -249,7 +249,7 @@ class OldNodeControllerTest < ActionController::TestCase assert_response :forbidden, "After redaction, node should be gone for moderator, when flag not passed." get :version, :id => node.node_id, :version => node.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, :id => node.node_id assert_response :success, "Redaction shouldn't have stopped history working." @@ -274,7 +274,7 @@ class OldNodeControllerTest < ActionController::TestCase # check can't see the redacted data get :version, :id => node.node_id, :version => node.version assert_response :forbidden, "Redacted node shouldn't be visible via the version API." - + # and when accessed via history get :history, :id => node.node_id assert_response :success, "Redaction shouldn't have stopped history working." @@ -284,7 +284,7 @@ class OldNodeControllerTest < ActionController::TestCase def do_redact_node(node, redaction) get :version, :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, :id => node.node_id, :version => node.version, :redaction => redaction.id end @@ -293,14 +293,14 @@ class OldNodeControllerTest < ActionController::TestCase # get the current version of the node current_node = with_controller(NodeController.new) do get :read, :id => node_id - assert_response :success, "cant get current node #{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, :id => node_id, :version => current_node.version - assert_response :success, "cant get old node #{node_id}, v#{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 diff --git a/test/controllers/old_relation_controller_test.rb b/test/controllers/old_relation_controller_test.rb index ea1550ab4..85f21a5f7 100644 --- a/test/controllers/old_relation_controller_test.rb +++ b/test/controllers/old_relation_controller_test.rb @@ -44,7 +44,7 @@ class OldRelationControllerTest < ActionController::TestCase end ## - # test the redaction of an old version of a relation, while being + # test the redaction of an old version of a relation, while being # authorised as a normal user. def test_redact_relation_normal_user basic_authorization(users(:public_user).email, "test") @@ -63,10 +63,10 @@ class OldRelationControllerTest < ActionController::TestCase do_redact_relation(relations(:relation_with_versions_v4), redactions(:example)) assert_response :bad_request, "shouldn't be OK to redact current version as moderator." - end + end ## - # test that redacted relations aren't visible, regardless of + # test that redacted relations aren't visible, regardless of # authorisation except as moderator... def test_version_redacted relation = relations(:relation_with_redacted_versions_v2) @@ -98,7 +98,7 @@ class OldRelationControllerTest < ActionController::TestCase end ## - # test the redaction of an old version of a relation, while being + # test the redaction of an old version of a relation, while being # authorised as a moderator. def test_redact_relation_moderator relation = relations(:relation_with_versions_v3) @@ -113,7 +113,7 @@ class OldRelationControllerTest < ActionController::TestCase assert_response :forbidden, "After redaction, node should be gone for moderator, when flag not passed." get :version, :id => relation.relation_id, :version => relation.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, :id => relation.relation_id assert_response :success, "Redaction shouldn't have stopped history working." @@ -138,7 +138,7 @@ class OldRelationControllerTest < ActionController::TestCase # check can't see the redacted data get :version, :id => relation.relation_id, :version => relation.version assert_response :forbidden, "Redacted node shouldn't be visible via the version API." - + # and when accessed via history get :history, :id => relation.relation_id assert_response :success, "Redaction shouldn't have stopped history working." @@ -183,7 +183,7 @@ class OldRelationControllerTest < ActionController::TestCase 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 @@ -191,7 +191,7 @@ class OldRelationControllerTest < ActionController::TestCase def do_redact_relation(relation, redaction) get :version, :id => relation.relation_id, :version => relation.version assert_response :success, "should be able to get version #{relation.version} of node #{relation.relation_id}." - + # now redact it post :redact, :id => relation.relation_id, :version => relation.version, :redaction => redaction.id end diff --git a/test/controllers/old_way_controller_test.rb b/test/controllers/old_way_controller_test.rb index 306a48615..1fa0657fa 100644 --- a/test/controllers/old_way_controller_test.rb +++ b/test/controllers/old_way_controller_test.rb @@ -30,19 +30,19 @@ class OldWayControllerTest < ActionController::TestCase get :history, :id => ways(:visible_way).way_id assert_response :success end - + def test_history_invisible # check that an invisible way's history is returned properly get :history, :id => ways(:invisible_way).way_id assert_response :success end - + def test_history_invalid # check chat a non-existent way is not returned get :history, :id => 0 assert_response :not_found end - + ## # check that we can retrieve versions of a way def test_version @@ -52,7 +52,7 @@ class OldWayControllerTest < ActionController::TestCase end ## - # check that returned history is the same as getting all + # check that returned history is the same as getting all # versions of a way from the api. def test_history_equals_versions check_history_equals_versions(current_ways(:visible_way).id) @@ -70,7 +70,7 @@ class OldWayControllerTest < ActionController::TestCase end ## - # test the redaction of an old version of a way, while being + # 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(users(:public_user).email, "test") @@ -89,10 +89,10 @@ class OldWayControllerTest < ActionController::TestCase do_redact_way(ways(:way_with_versions_v4), redactions(:example)) assert_response :bad_request, "shouldn't be OK to redact current version as moderator." - end + end ## - # test that redacted ways aren't visible, regardless of + # test that redacted ways aren't visible, regardless of # authorisation except as moderator... def test_version_redacted way = ways(:way_with_redacted_versions_v2) @@ -124,7 +124,7 @@ class OldWayControllerTest < ActionController::TestCase end ## - # test the redaction of an old version of a way, while being + # test the redaction of an old version of a way, while being # authorised as a moderator. def test_redact_way_moderator way = ways(:way_with_versions_v3) @@ -139,7 +139,7 @@ class OldWayControllerTest < ActionController::TestCase assert_response :forbidden, "After redaction, node should be gone for moderator, when flag not passed." get :version, :id => way.way_id, :version => way.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, :id => way.way_id assert_response :success, "Redaction shouldn't have stopped history working." @@ -164,7 +164,7 @@ class OldWayControllerTest < ActionController::TestCase # check can't see the redacted data get :version, :id => way.way_id, :version => way.version assert_response :forbidden, "Redacted node shouldn't be visible via the version API." - + # and when accessed via history get :history, :id => way.way_id assert_response :success, "Redaction shouldn't have stopped history working." @@ -209,7 +209,7 @@ class OldWayControllerTest < ActionController::TestCase 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 @@ -217,7 +217,7 @@ class OldWayControllerTest < ActionController::TestCase def do_redact_way(way, redaction) get :version, :id => way.way_id, :version => way.version assert_response :success, "should be able to get version #{way.version} of node #{way.way_id}." - + # now redact it post :redact, :id => way.way_id, :version => way.version, :redaction => redaction.id end diff --git a/test/controllers/relation_controller_test.rb b/test/controllers/relation_controller_test.rb index d7a9bf536..10ee25c81 100644 --- a/test/controllers/relation_controller_test.rb +++ b/test/controllers/relation_controller_test.rb @@ -68,7 +68,7 @@ class RelationControllerTest < ActionController::TestCase # 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 - check_relations_for_element(:relations_for_node, "node", + check_relations_for_element(:relations_for_node, "node", current_nodes(:node_used_by_relationship).id, [ :visible_relation, :used_relation ]) end @@ -146,7 +146,7 @@ class RelationControllerTest < ActionController::TestCase def test_create basic_authorization users(:normal_user).email, "test" - + # put the relation in a dummy fixture changset changeset_id = changesets(:normal_user_first_change).id @@ -154,7 +154,7 @@ class RelationControllerTest < ActionController::TestCase content "" put :create # hope for forbidden, due to user - assert_response :forbidden, + assert_response :forbidden, "relation upload should have failed with forbidden" ### @@ -166,11 +166,11 @@ class RelationControllerTest < ActionController::TestCase "" put :create # hope for forbidden due to user - assert_response :forbidden, + 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 + # create an relation with a node as member, this time test that we don't # need a role attribute to be included nid = current_nodes(:used_node_1).id content "" + @@ -178,7 +178,7 @@ class RelationControllerTest < ActionController::TestCase "" put :create # hope for forbidden due to user - assert_response :forbidden, + assert_response :forbidden, "relation upload did not return forbidden status" ### @@ -191,14 +191,14 @@ class RelationControllerTest < ActionController::TestCase "" put :create # hope for forbidden, due to user - assert_response :forbidden, + assert_response :forbidden, "relation upload did not return success status" ## Now try with the public user basic_authorization users(:public_user).email, "test" - + # put the relation in a dummy fixture changset changeset_id = changesets(:public_user_first_change).id @@ -206,23 +206,23 @@ class RelationControllerTest < ActionController::TestCase content "" put :create # hope for success - assert_response :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, + assert_not_nil checkrelation, "uploaded relation not found in data base after upload" # compare values - assert_equal checkrelation.members.length, 0, + assert_equal checkrelation.members.length, 0, "saved relation contains members but should not" - assert_equal checkrelation.tags.length, 1, + 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 users(:public_user).id, checkrelation.changeset.user_id, + assert_equal users(:public_user).id, checkrelation.changeset.user_id, "saved relation does not belong to user that created it" - assert_equal true, checkrelation.visible, + assert_equal true, checkrelation.visible, "saved relation is not visible" # ok the relation is there but can we also retrieve it? get :read, :id => relationid @@ -238,32 +238,32 @@ class RelationControllerTest < ActionController::TestCase "" put :create # hope for success - assert_response :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, + assert_not_nil checkrelation, "uploaded relation not found in data base after upload" # compare values - assert_equal checkrelation.members.length, 1, + assert_equal checkrelation.members.length, 1, "saved relation does not contain exactly one member" - assert_equal checkrelation.tags.length, 1, + 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 users(:public_user).id, checkrelation.changeset.user_id, + assert_equal users(:public_user).id, checkrelation.changeset.user_id, "saved relation does not belong to user that created it" - assert_equal true, checkrelation.visible, + assert_equal true, checkrelation.visible, "saved relation is not visible" # ok the relation is there but can we also retrieve it? - + get :read, :id => relationid assert_response :success - - + + ### - # create an relation with a node as member, this time test that we don't + # create an relation with a node as member, this time test that we don't # need a role attribute to be included nid = current_nodes(:used_node_1).id content "" + @@ -271,26 +271,26 @@ class RelationControllerTest < ActionController::TestCase "" put :create # hope for success - assert_response :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, + assert_not_nil checkrelation, "uploaded relation not found in data base after upload" # compare values - assert_equal checkrelation.members.length, 1, + assert_equal checkrelation.members.length, 1, "saved relation does not contain exactly one member" - assert_equal checkrelation.tags.length, 1, + 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 users(:public_user).id, checkrelation.changeset.user_id, + assert_equal users(:public_user).id, checkrelation.changeset.user_id, "saved relation does not belong to user that created it" - assert_equal true, checkrelation.visible, + assert_equal true, checkrelation.visible, "saved relation is not visible" # ok the relation is there but can we also retrieve it? - + get :read, :id => relationid assert_response :success @@ -304,23 +304,23 @@ class RelationControllerTest < ActionController::TestCase "" put :create # hope for success - assert_response :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, + assert_not_nil checkrelation, "uploaded relation not found in data base after upload" # compare values - assert_equal checkrelation.members.length, 2, + assert_equal checkrelation.members.length, 2, "saved relation does not have exactly two members" - assert_equal checkrelation.tags.length, 1, + 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 users(:public_user).id, checkrelation.changeset.user_id, + assert_equal users(:public_user).id, checkrelation.changeset.user_id, "saved relation does not belong to user that created it" - assert_equal true, checkrelation.visible, + assert_equal true, checkrelation.visible, "saved relation is not visible" # ok the relation is there but can we also retrieve it? get :read, :id => relationid @@ -334,7 +334,7 @@ class RelationControllerTest < ActionController::TestCase ## # test that, when tags are updated on a relation, the correct things - # happen to the correct tables and the API gives sensible results. + # 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 @@ -364,8 +364,8 @@ class RelationControllerTest < ActionController::TestCase ## # 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 + # 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 basic_authorization users(:public_user).email, "test" @@ -407,7 +407,7 @@ class RelationControllerTest < ActionController::TestCase "" put :create # expect failure - assert_response :precondition_failed, + 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 @@ -417,10 +417,10 @@ class RelationControllerTest < ActionController::TestCase # ------------------------------------- def test_create_invalid_xml basic_authorization users(:public_user).email, "test" - + # put the relation in a dummy fixture changeset that works changeset_id = changesets(:public_user_first_change).id - + # create some xml that should return an error content "" + "" + @@ -431,21 +431,21 @@ class RelationControllerTest < ActionController::TestCase 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 ## First try to delete relation without auth delete :delete, :id => current_relations(:visible_relation).id assert_response :unauthorized - - + + ## Then try with the private user, to make sure that you get a forbidden basic_authorization(users(:normal_user).email, "test") - + # this shouldn't work, as we should need the payload... delete :delete, :id => current_relations(:visible_relation).id assert_response :forbidden @@ -481,7 +481,7 @@ class RelationControllerTest < ActionController::TestCase delete :delete, :id => current_relations(:invisible_relation).id assert_response :forbidden - # this works now because the relation which was using this one + # this works now because the relation which was using this one # has been deleted. content(relations(:used_relation).to_xml) delete :delete, :id => current_relations(:used_relation).id @@ -491,10 +491,10 @@ class RelationControllerTest < ActionController::TestCase delete :delete, :id => 0 assert_response :forbidden - + ## now set auth for the public user - basic_authorization(users(:public_user).email, "test"); + basic_authorization(users(:public_user).email, "test"); # this shouldn't work, as we should need the payload... delete :delete, :id => current_relations(:visible_relation).id @@ -520,7 +520,7 @@ class RelationControllerTest < ActionController::TestCase # this won't work because the relation is in a changeset owned by someone else content(relations(:used_relation).to_xml) delete :delete, :id => current_relations(:used_relation).id - assert_response :conflict, + 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 @@ -528,11 +528,11 @@ class RelationControllerTest < ActionController::TestCase delete :delete, :id => current_relations(:used_relation).id assert_not_equal relations(:public_used_relation).id, current_relations(:used_relation).id 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 content(relations(:public_used_relation).to_xml) delete :delete, :id => current_relations(:public_used_relation).id - assert_response :precondition_failed, + assert_response :precondition_failed, "shouldn't be able to delete a relation used in a relation (#{@response.body})" assert_equal "Precondition failed: The relation 5 is used in relation 6.", @response.body @@ -550,17 +550,17 @@ class RelationControllerTest < ActionController::TestCase content(relations(:invisible_relation).to_xml) delete :delete, :id => current_relations(:invisible_relation).id assert_response :gone - + # Public visible relation needs to be deleted content(relations(:public_visible_relation).to_xml) delete :delete, :id => current_relations(:public_visible_relation).id assert_response :success - # this works now because the relation which was using this one + # this works now because the relation which was using this one # has been deleted. content(relations(:public_used_relation).to_xml) delete :delete, :id => current_relations(:public_used_relation).id - assert_response :success, + 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 @@ -582,10 +582,10 @@ class RelationControllerTest < ActionController::TestCase 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 content relation_xml put :update, :id => current_relations(:visible_relation).id @@ -613,25 +613,25 @@ class RelationControllerTest < ActionController::TestCase 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 content relation_xml put :update, :id => current_relations(:visible_relation).id assert_response :success, "can't update relation for add #{element.class}/bbox test: #{@response.body}" - # get it back and check the ordering + # get it back and check the ordering get :read, :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 + # remove a member from a relation and check the bounding box is # only that element. def test_remove_member_bounding_box check_changeset_modify(BoundingBox.new(5,5,5,5)) do |changeset_id| @@ -640,22 +640,22 @@ class RelationControllerTest < ActionController::TestCase relation_xml. find("//osm/relation/member[@type='node'][@ref='5']"). first.remove! - + # update changeset ID to point to new changeset update_changeset(relation_xml, changeset_id) - + # upload the change content relation_xml put :update, :id => current_relations(:visible_relation).id assert_response :success, "can't update relation for remove node/bbox test" end end - + ## # check that relations are ordered def test_relation_member_ordering basic_authorization(users(:public_user).email, "test") - + doc_str = < @@ -707,7 +707,7 @@ OSM end end - ## + ## # check that relations can contain duplicate members def test_relation_member_duplicates doc_str = < OSM doc = XML::Parser.string(doc_str).parse - basic_authorization(users(:public_user).email, "test"); + basic_authorization(users(:public_user).email, "test"); content doc put :create @@ -780,28 +780,28 @@ OSM ## # remove all the members from a relation. the result is pretty useless, but # still technically valid. - def test_remove_all_members + def test_remove_all_members check_changeset_modify(BoundingBox.new(3,3,5,5)) do |changeset_id| relation_xml = current_relations(:visible_relation).to_xml relation_xml. find("//osm/relation/member"). each {|m| m.remove!} - + # update changeset ID to point to new changeset update_changeset(relation_xml, changeset_id) - + # upload the change content relation_xml put :update, :id => current_relations(:visible_relation).id assert_response :success, "can't update relation for remove all members test" checkrelation = Relation.find(current_relations(:visible_relation).id) - assert_not_nil(checkrelation, + 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 # ============================================================ @@ -830,7 +830,7 @@ OSM # 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(users(:normal_user).email, "test"); + basic_authorization(users(:normal_user).email, "test"); # create a new changeset for this operation, so we are assured # that the bounding box will be newly-generated. @@ -840,10 +840,10 @@ OSM 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(users(:public_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(ChangesetController.new) do @@ -886,8 +886,8 @@ OSM end ## - # updates the relation (XML) +rel+ and - # yields the new version of that relation into the block. + # 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 @@ -908,7 +908,7 @@ OSM ## # updates the relation (XML) +rel+ via the diff-upload API and - # yields the new version of that relation into the block. + # 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 @@ -927,29 +927,29 @@ OSM post :upload, :id => cs_id assert_response :success, "can't upload diff relation: #{@response.body}" version = xml_parse(@response.body).find("//diffResult/relation").first["new_version"].to_i - end - + end + # now get the new version get :read, :id => rel_id assert_response :success new_rel = xml_parse(@response.body) - + yield new_rel - + return version end ## # returns a k->v hash of tags from an xml doc - def get_tags_as_hash(a) + def get_tags_as_hash(a) a.find("//osm/relation/tag").sort_by { |v| v['k'] }.inject({}) do |h,v| h[v['k']] = v['v'] h end end - + ## - # assert that all tags on relation documents +a+ and +b+ + # 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 @@ -958,7 +958,7 @@ OSM 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], + assert_equal v, b_tags[k], "Tags which were not altered should be the same. " + "#{a_tags.inspect} != #{b_tags.inspect}" end diff --git a/test/controllers/trace_controller_test.rb b/test/controllers/trace_controller_test.rb index 68cacdce3..408ae0cd1 100644 --- a/test/controllers/trace_controller_test.rb +++ b/test/controllers/trace_controller_test.rb @@ -493,7 +493,7 @@ class TraceControllerTest < ActionController::TestCase basic_authorization(users(:normal_user).display_name, "test") content gpx_files(:anon_trace_file).to_xml put :api_update, :id => gpx_files(:public_trace_file).id - assert_response :bad_request, + 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 diff --git a/test/controllers/user_controller_test.rb b/test/controllers/user_controller_test.rb index 75d057b9f..93b7f76d6 100644 --- a/test/controllers/user_controller_test.rb +++ b/test/controllers/user_controller_test.rb @@ -2,7 +2,7 @@ require 'test_helper' class UserControllerTest < ActionController::TestCase fixtures :users - + ## # test all routes which lead to this controller def test_routes @@ -269,7 +269,7 @@ class UserControllerTest < ActionController::TestCase assert_template 'new' assert_select "form > fieldset > div.form-row > input.field_with_errors#user_email" end - + def test_user_create_submit_duplicate_name user = new_user user.display_name = users(:public_user).display_name @@ -284,7 +284,7 @@ class UserControllerTest < ActionController::TestCase assert_template 'new' assert_select "form > fieldset > div.form-row > input.field_with_errors#user_display_name" end - + def test_user_create_submit_duplicate_name_uppercase user = new_user user.display_name = users(:public_user).display_name.upcase @@ -556,14 +556,14 @@ class UserControllerTest < ActionController::TestCase assert_equal user.new_email, email.to.first ActionMailer::Base.deliveries.clear end - + # Check that the user account page will display and contains some relevant # information for the user def test_user_view_account # Test a non-existent user get :view, {:display_name => "unknown"} assert_response :not_found - + # Test a normal user get :view, {:display_name => "test"} assert_response :success @@ -577,7 +577,7 @@ class UserControllerTest < ActionController::TestCase assert_select "a[href='/user/test/blocks_by']", 0 assert_select "a[href='/blocks/new/test']", 0 end - + # Test a user who has been blocked get :view, {:display_name => "blocked"} assert_response :success @@ -591,7 +591,7 @@ class UserControllerTest < ActionController::TestCase assert_select "a[href='/user/blocked/blocks_by']", 0 assert_select "a[href='/blocks/new/blocked']", 0 end - + # Test a moderator who has applied blocks get :view, {:display_name => "moderator"} assert_response :success @@ -691,7 +691,7 @@ class UserControllerTest < ActionController::TestCase # 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(users(:normal_user).email, "test") get :api_details diff --git a/test/controllers/user_preference_controller_test.rb b/test/controllers/user_preference_controller_test.rb index 4966ae748..46c631f92 100644 --- a/test/controllers/user_preference_controller_test.rb +++ b/test/controllers/user_preference_controller_test.rb @@ -45,7 +45,7 @@ class UserPreferenceControllerTest < ActionController::TestCase assert_select "preference", :count => 0 end end - + # authenticate as a user with preferences basic_authorization("test@openstreetmap.org", "test") diff --git a/test/controllers/way_controller_test.rb b/test/controllers/way_controller_test.rb index ca87e6543..58984923c 100644 --- a/test/controllers/way_controller_test.rb +++ b/test/controllers/way_controller_test.rb @@ -65,11 +65,11 @@ class WayControllerTest < ActionController::TestCase # 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 + + # 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 @@ -118,14 +118,14 @@ class WayControllerTest < ActionController::TestCase # use the first user's open changeset changeset_id = changesets(:normal_user_first_change).id - + # create a way with pre-existing nodes content "" + - "" + + "" + "" put :create # hope for success - assert_response :forbidden, + assert_response :forbidden, "way upload did not return success status" # read id of created way and search for it wayid = @response.body @@ -137,32 +137,32 @@ class WayControllerTest < ActionController::TestCase # use the first user's open changeset changeset_id = changesets(:public_user_first_change).id - + # create a way with pre-existing nodes content "" + - "" + + "" + "" put :create # hope for success - assert_response :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, + assert_not_nil checkway, "uploaded way not found in data base after upload" # compare values - assert_equal checkway.nds.length, 2, + assert_equal checkway.nds.length, 2, "saved way does not contain exactly one node" - assert_equal checkway.nds[0], nid1, + assert_equal checkway.nds[0], nid1, "saved way does not contain the right node on pos 0" - assert_equal checkway.nds[1], nid2, + assert_equal checkway.nds[1], nid2, "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 users(:public_user).id, checkway.changeset.user_id, + assert_equal users(:public_user).id, checkway.changeset.user_id, "saved way does not belong to user that created it" - assert_equal true, checkway.visible, + assert_equal true, checkway.visible, "saved way is not visible" end @@ -180,11 +180,11 @@ class WayControllerTest < ActionController::TestCase nid1 = current_nodes(:used_node_1).id # create a way with non-existing node - content "" + + content "" + "" put :create # expect failure - assert_response :forbidden, + assert_response :forbidden, "way upload with invalid node using a private user did not return 'forbidden'" # create a way with no nodes @@ -192,7 +192,7 @@ class WayControllerTest < ActionController::TestCase "" put :create # expect failure - assert_response :forbidden, + assert_response :forbidden, "way upload with no node using a private userdid not return 'forbidden'" # create a way inside a closed changeset @@ -200,10 +200,10 @@ class WayControllerTest < ActionController::TestCase "" put :create # expect failure - assert_response :forbidden, - "way upload to closed changeset with a private user did not return 'forbidden'" + assert_response :forbidden, + "way upload to closed changeset with a private user did not return 'forbidden'" + - ## Now test with a public user basic_authorization users(:public_user).email, "test" @@ -213,11 +213,11 @@ class WayControllerTest < ActionController::TestCase nid1 = current_nodes(:used_node_1).id # create a way with non-existing node - content "" + + content "" + "" put :create # expect failure - assert_response :precondition_failed, + 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 @@ -226,7 +226,7 @@ class WayControllerTest < ActionController::TestCase "" put :create # expect failure - assert_response :precondition_failed, + 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 @@ -235,8 +235,8 @@ class WayControllerTest < ActionController::TestCase "" put :create # expect failure - assert_response :conflict, - "way upload to closed changeset did not return 'conflict'" + assert_response :conflict, + "way upload to closed changeset did not return 'conflict'" # create a way with a tag which is too long content "" + @@ -245,31 +245,31 @@ class WayControllerTest < ActionController::TestCase "" put :create # expect failure - assert_response :bad_request, + assert_response :bad_request, "way upload to with too long tag did not return 'bad_request'" end # ------------------------------------- # Test deleting ways. # ------------------------------------- - + def test_delete # first try to delete way without auth delete :delete, :id => current_ways(:visible_way).id assert_response :unauthorized # now set auth using the private user - basic_authorization(users(:normal_user).email, "test"); + basic_authorization(users(:normal_user).email, "test"); # this shouldn't work as with the 0.6 api we need pay load to delete delete :delete, :id => current_ways(:visible_way).id assert_response :forbidden - + # Now try without having a changeset content "" delete :delete, :id => current_ways(:visible_way).id assert_response :forbidden - + # try to delete with an invalid (closed) changeset content update_changeset(current_ways(:visible_way).to_xml, changesets(:normal_user_closed_change).id) @@ -300,27 +300,27 @@ class WayControllerTest < ActionController::TestCase # this shouldn't work as the way is used in a relation content current_ways(:used_way).to_xml delete :delete, :id => current_ways(:used_way).id - assert_response :forbidden, + 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, :id => 0 assert_response :forbidden - + ### Now check with a public user # now set auth - basic_authorization(users(:public_user).email, "test"); + basic_authorization(users(:public_user).email, "test"); # this shouldn't work as with the 0.6 api we need pay load to delete delete :delete, :id => current_ways(:visible_way).id assert_response :bad_request - + # Now try without having a changeset content "" delete :delete, :id => current_ways(:visible_way).id assert_response :bad_request - + # try to delete with an invalid (closed) changeset content update_changeset(current_ways(:visible_way).to_xml, changesets(:public_user_closed_change).id) @@ -351,7 +351,7 @@ class WayControllerTest < ActionController::TestCase # this shouldn't work as the way is used in a relation content current_ways(:used_way).to_xml delete :delete, :id => current_ways(:used_way).id - assert_response :precondition_failed, + assert_response :precondition_failed, "shouldn't be able to delete a way used in a relation (#{@response.body})" assert_equal "Precondition failed: Way 3 is still used by relations 1.", @response.body @@ -383,7 +383,7 @@ class WayControllerTest < ActionController::TestCase # try and upload it content way_xml put :update, :id => current_ways(:visible_way).id - assert_response :forbidden, + assert_response :forbidden, "adding a duplicate tag to a way for a non-public should fail with 'forbidden'" ## Now try with the public user @@ -402,7 +402,7 @@ class WayControllerTest < ActionController::TestCase # try and upload it content way_xml put :update, :id => current_ways(:visible_way).id - assert_response :bad_request, + assert_response :bad_request, "adding a duplicate tag to a way should fail with 'bad request'" assert_equal "Element way/#{current_ways(:visible_way).id} has duplicate tags with key #{current_way_tags(:t1).k}", @response.body end @@ -428,9 +428,9 @@ class WayControllerTest < ActionController::TestCase # try and upload it content way_xml put :update, :id => current_ways(:visible_way).id - assert_response :forbidden, + 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(users(:public_user).email, "test") @@ -449,10 +449,10 @@ class WayControllerTest < ActionController::TestCase # try and upload it content way_xml put :update, :id => current_ways(:visible_way).id - assert_response :bad_request, + assert_response :bad_request, "adding new duplicate tags to a way should fail with 'bad request'" assert_equal "Element way/#{current_ways(:visible_way).id} has duplicate tags with key i_am_a_duplicate", @response.body - + end ## @@ -473,9 +473,9 @@ class WayControllerTest < ActionController::TestCase # try and upload it content way_str put :create - assert_response :forbidden, + 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(users(:public_user).email, "test") @@ -489,7 +489,7 @@ class WayControllerTest < ActionController::TestCase # try and upload it content way_str put :create - assert_response :bad_request, + 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 @@ -498,7 +498,7 @@ class WayControllerTest < ActionController::TestCase # 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 - # in current fixtures ways 1 and 3 all use node 3. ways 2 and 4 + # in current fixtures ways 1 and 3 all use node 3. ways 2 and 4 # *used* to use it but doesn't. get :ways_for_node, :id => current_nodes(:used_node_1).id assert_response :success @@ -512,7 +512,7 @@ class WayControllerTest < ActionController::TestCase 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 #{current_nodes(:used_node_1).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 diff --git a/test/helpers/application_helper_test.rb b/test/helpers/application_helper_test.rb index 5604b09bf..3a1264628 100644 --- a/test/helpers/application_helper_test.rb +++ b/test/helpers/application_helper_test.rb @@ -20,7 +20,7 @@ class ApplicationHelperTest < ActionView::TestCase assert_dom_equal "Test #{link} is made into a link", html html = linkify(text.html_safe) - assert_equal true, html.html_safe? + assert_equal true, html.html_safe? assert_dom_equal "Test #{link} is made into a link", html end @@ -32,7 +32,7 @@ class ApplicationHelperTest < ActionView::TestCase assert_dom_equal text, html html = linkify(text.html_safe) - assert_equal true, html.html_safe? + assert_equal true, html.html_safe? assert_dom_equal text, html end end diff --git a/test/integration/oauth_test.rb b/test/integration/oauth_test.rb index dd03fde46..da8738b42 100644 --- a/test/integration/oauth_test.rb +++ b/test/integration/oauth_test.rb @@ -8,7 +8,7 @@ class OAuthTest < ActionDispatch::IntegrationTest def test_oauth10_web_app client = client_applications(:oauth_web_app) - post_via_redirect "/login", + post_via_redirect "/login", :username => client.user.email, :password => "test" assert_response :success @@ -21,8 +21,8 @@ class OAuthTest < ActionDispatch::IntegrationTest assert_nil token.invalidated_at assert_allowed token, client.permissions - post "/oauth/authorize", - :oauth_token => token.token, + post "/oauth/authorize", + :oauth_token => token.token, :allow_read_prefs => true, :allow_write_prefs => true assert_response :redirect assert_redirected_to "http://some.web.app.org/callback?oauth_token=#{token.token}" @@ -65,9 +65,9 @@ class OAuthTest < ActionDispatch::IntegrationTest assert_nil token.invalidated_at assert_allowed token, client.permissions - post "/oauth/authorize", - :oauth_token => token.token, - :oauth_callback => "http://another.web.app.org/callback", + post "/oauth/authorize", + :oauth_token => token.token, + :oauth_callback => "http://another.web.app.org/callback", :allow_write_api => true, :allow_read_gpx => true assert_response :redirect assert_redirected_to "http://another.web.app.org/callback?oauth_token=#{token.token}" @@ -105,7 +105,7 @@ class OAuthTest < ActionDispatch::IntegrationTest def test_oauth10_desktop_app client = client_applications(:oauth_desktop_app) - post_via_redirect "/login", + post_via_redirect "/login", :username => client.user.email, :password => "test" assert_response :success @@ -118,8 +118,8 @@ class OAuthTest < ActionDispatch::IntegrationTest assert_nil token.invalidated_at assert_allowed token, client.permissions - post "/oauth/authorize", - :oauth_token => token.token, + post "/oauth/authorize", + :oauth_token => token.token, :allow_read_prefs => true, :allow_write_prefs => true assert_response :success assert_template "authorize_success" @@ -266,7 +266,7 @@ class OAuthTest < ActionDispatch::IntegrationTest def test_oauth10a_desktop_app client = client_applications(:oauth_desktop_app) - post_via_redirect "/login", + post_via_redirect "/login", :username => client.user.email, :password => "test" assert_response :success @@ -280,8 +280,8 @@ class OAuthTest < ActionDispatch::IntegrationTest assert_nil token.invalidated_at assert_allowed token, client.permissions - post "/oauth/authorize", - :oauth_token => token.token, + post "/oauth/authorize", + :oauth_token => token.token, :allow_read_prefs => true, :allow_write_prefs => true assert_response :success assert_template "authorize_success" diff --git a/test/integration/user_changeset_comments_test.rb b/test/integration/user_changeset_comments_test.rb index c984149db..629929a1c 100644 --- a/test/integration/user_changeset_comments_test.rb +++ b/test/integration/user_changeset_comments_test.rb @@ -7,7 +7,7 @@ class UserChangesetCommentsTest < ActionDispatch::IntegrationTest def test_log_in_message get "/changeset/#{changesets(:normal_user_closed_change).id}" assert_response :success - + assert_select "div#content" do assert_select "div#sidebar" do assert_select "div#sidebar_content" do @@ -30,7 +30,7 @@ class UserChangesetCommentsTest < ActionDispatch::IntegrationTest assert_response :redirect get "/changeset/#{changesets(:normal_user_closed_change).id}" - + assert_response :success assert_template 'browse/changeset' diff --git a/test/integration/user_diaries_test.rb b/test/integration/user_diaries_test.rb index 58e70bfd2..c724e6a00 100644 --- a/test/integration/user_diaries_test.rb +++ b/test/integration/user_diaries_test.rb @@ -3,7 +3,7 @@ require 'test_helper' class UserDiariesTest < ActionDispatch::IntegrationTest fixtures :users, :diary_entries - # Test the creation of a diary entry, making sure that you are redirected to + # Test the creation of a diary entry, making sure that you are redirected to # login page when not logged in def test_showing_create_diary_entry get_via_redirect '/diary/new' @@ -25,13 +25,13 @@ class UserDiariesTest < ActionDispatch::IntegrationTest # http://markmail.org/message/wnslvi5xv5moqg7g @html_document = nil follow_redirect! - + assert_response :success assert_template 'diary_entry/edit' #print @response.body #print @html_document.to_yaml - # We will make sure that the form exists here, full + # We will make sure that the form exists here, full # assert testing of the full form should be done in the # functional tests rather than this integration test # There are some things that are specific to the integratio diff --git a/test/integration/user_terms_seen_test.rb b/test/integration/user_terms_seen_test.rb index 1bed53bce..554649396 100644 --- a/test/integration/user_terms_seen_test.rb +++ b/test/integration/user_terms_seen_test.rb @@ -38,7 +38,7 @@ class UserTermsSeenTest < ActionDispatch::IntegrationTest post "/user/save", {'decline' => 'decline', 'referer' => '/'} assert_redirected_to "/" follow_redirect! - + # should be carried through to a normal login with a message assert_response :success assert !flash[:notice].nil? diff --git a/test/lib/short_link_test.rb b/test/lib/short_link_test.rb index 7aa21f363..401d133c3 100644 --- a/test/lib/short_link_test.rb +++ b/test/lib/short_link_test.rb @@ -6,7 +6,7 @@ class ShortLinkTest < ActiveSupport::TestCase # the acceptable quantisation range. def test_encode_decode cases = Array.new - 1000.times do + 1000.times do cases << [ 180.0 * rand - 90.0, 360.0 * rand - 180.0, (18 * rand).to_i ] end @@ -14,9 +14,9 @@ class ShortLinkTest < ActiveSupport::TestCase lon2, lat2, zoom2 = ShortLink.decode(ShortLink.encode(lon, lat, zoom)) # zooms should be identical assert_equal zoom, zoom2, "Decoding a encoded short link gives different zoom for (#{lat}, #{lon}, #{zoom})." - # but the location has a quantisation error introduced at roughly - # one pixel (i.e: zoom + 8). the sqrt(5) is because each position - # has an extra bit of accuracy in the lat coordinate, due to the + # but the location has a quantisation error introduced at roughly + # one pixel (i.e: zoom + 8). the sqrt(5) is because each position + # has an extra bit of accuracy in the lat coordinate, due to the # smaller range. distance = Math.sqrt((lat - lat2) ** 2 + (lon - lon2) ** 2) max_distance = 360.0 / (1 << (zoom + 8)) * 0.5 * Math.sqrt(5) @@ -25,16 +25,16 @@ class ShortLinkTest < ActiveSupport::TestCase end ## - # test that links are backwards-compatible, so any old links with + # test that links are backwards-compatible, so any old links with # the deprecated @ characters in them still work properly. def test_deprecated_at_sign cases = [["~v2juONc--", "@v2juONc--"], - ["as3I3GpG~-", "as3I3GpG@-"], - ["D~hV--", "D@hV--"], + ["as3I3GpG~-", "as3I3GpG@-"], + ["D~hV--", "D@hV--"], ["CO0O~m8--", "CO0O@m8--"]] cases.each do |new_code, old_code| - assert_equal ShortLink.decode(old_code), ShortLink.decode(new_code), + assert_equal ShortLink.decode(old_code), ShortLink.decode(new_code), "old (#{old_code}) and new (#{new_code}) should decode to the same location." end end diff --git a/test/models/changeset_comment_test.rb b/test/models/changeset_comment_test.rb index c13fde8e2..ed4f0e032 100644 --- a/test/models/changeset_comment_test.rb +++ b/test/models/changeset_comment_test.rb @@ -10,7 +10,7 @@ class ChangesetCommentTest < ActiveSupport::TestCase # validations def test_does_not_accept_invalid_author comment = changeset_comments(:normal_comment_1) - + comment.author = nil assert !comment.valid? diff --git a/test/models/changeset_tag_test.rb b/test/models/changeset_tag_test.rb index 1564361c4..296183a45 100644 --- a/test/models/changeset_tag_test.rb +++ b/test/models/changeset_tag_test.rb @@ -6,7 +6,7 @@ class ChangesetTagTest < ActiveSupport::TestCase def test_changeset_tag_count assert_equal 2, ChangesetTag.count end - + def test_length_key_valid key = "k" (0..255).each do |i| @@ -17,7 +17,7 @@ class ChangesetTagTest < ActiveSupport::TestCase assert tag.valid? end end - + def test_length_value_valid val = "v" (0..255).each do |i| @@ -28,7 +28,7 @@ class ChangesetTagTest < ActiveSupport::TestCase assert tag.valid? end end - + def test_length_key_invalid ["k"*256].each do |k| tag = ChangesetTag.new @@ -39,7 +39,7 @@ class ChangesetTagTest < ActiveSupport::TestCase assert tag.errors[:k].any? end end - + def test_length_value_invalid ["v"*256].each do |v| tag = ChangesetTag.new @@ -50,13 +50,13 @@ class ChangesetTagTest < ActiveSupport::TestCase assert tag.errors[:v].any? end end - + def test_empty_tag_invalid tag = ChangesetTag.new assert !tag.valid?, "Empty tag should be invalid" assert tag.errors[:changeset].any? end - + def test_uniqueness tag = ChangesetTag.new tag.changeset_id = changeset_tags(:changeset_1_tag_1).changeset_id diff --git a/test/models/diary_comment_test.rb b/test/models/diary_comment_test.rb index e96c12230..bf778c27a 100644 --- a/test/models/diary_comment_test.rb +++ b/test/models/diary_comment_test.rb @@ -3,7 +3,7 @@ require 'test_helper' class DiaryCommentTest < ActiveSupport::TestCase api_fixtures fixtures :diary_comments - + def test_diary_comment_count assert_equal 4, DiaryComment.count end diff --git a/test/models/diary_entry_test.rb b/test/models/diary_entry_test.rb index e8667bc74..12fd69512 100644 --- a/test/models/diary_entry_test.rb +++ b/test/models/diary_entry_test.rb @@ -3,11 +3,11 @@ require 'test_helper' class DiaryEntryTest < ActiveSupport::TestCase api_fixtures fixtures :diary_entries, :diary_comments, :languages - + def test_diary_entry_count assert_equal 5, DiaryEntry.count end - + def test_diary_entry_validations diary_entry_valid({}) diary_entry_valid({:title => ''}, false) @@ -30,12 +30,12 @@ class DiaryEntryTest < ActiveSupport::TestCase DiaryEntry.visible.find(diary_entries(:deleted_entry).id) end end - + def test_diary_entry_comments assert_equal 0, diary_entries(:normal_user_entry_1).comments.count assert_equal 4, diary_entries(:normal_user_geo_entry).comments.count end - + def test_diary_entry_visible_comments assert_equal 0, diary_entries(:normal_user_entry_1).visible_comments.count assert_equal 1, diary_entries(:normal_user_geo_entry).visible_comments.count @@ -47,5 +47,5 @@ private entry = DiaryEntry.new(diary_entries(:normal_user_entry_1).attributes) entry.assign_attributes(attrs) assert_equal result, entry.valid?, "Expected #{attrs.inspect} to be #{result}" - end + end end diff --git a/test/models/friend_test.rb b/test/models/friend_test.rb index c9f671e7e..9b0d34d41 100644 --- a/test/models/friend_test.rb +++ b/test/models/friend_test.rb @@ -7,5 +7,5 @@ class FriendTest < ActiveSupport::TestCase def test_friend_count assert_equal 1, Friend.count end - + end diff --git a/test/models/message_test.rb b/test/models/message_test.rb index 079e10c42..622942737 100644 --- a/test/models/message_test.rb +++ b/test/models/message_test.rb @@ -21,14 +21,14 @@ class MessageTest < ActiveSupport::TestCase assert message.errors[:sent_on].any? assert !message.message_read end - + def test_validating_msgs message = messages(:unread_message) assert message.valid? massage = messages(:read_message) assert message.valid? end - + def test_invalid_send_recipient message = messages(:unread_message) message.sender = nil @@ -69,9 +69,9 @@ class MessageTest < ActiveSupport::TestCase msg = make_message(char, 1) # if the save throws, thats fine and the test should pass, as we're # only testing invalid sequences anyway. - msg.save! + msg.save! - # get the saved message back and check that it is identical - i.e: + # get the saved message back and check that it is identical - i.e: # its OK to accept invalid UTF-8 as long as we return it unmodified. db_msg = msg.class.find(msg.id) assert_equal char, db_msg.title, "Database silently truncated message title" @@ -83,7 +83,7 @@ class MessageTest < ActiveSupport::TestCase # because we only test invalid sequences it is OK to barf on them end end - end + end def test_from_mail_plain mail = Mail.new do diff --git a/test/models/node_tag_test.rb b/test/models/node_tag_test.rb index aa50b2f39..87f657ddc 100644 --- a/test/models/node_tag_test.rb +++ b/test/models/node_tag_test.rb @@ -2,7 +2,7 @@ require 'test_helper' class NodeTagTest < ActiveSupport::TestCase api_fixtures - + def test_tag_count assert_equal 12, NodeTag.count node_tag_count(:visible_node, 1) @@ -11,12 +11,12 @@ class NodeTagTest < ActiveSupport::TestCase node_tag_count(:used_node_2, 1) node_tag_count(:node_with_versions, 2) end - + def node_tag_count (node, count) nod = current_nodes(node) assert_equal count, nod.node_tags.count end - + def test_length_key_valid key = "k" (0..255).each do |i| @@ -27,7 +27,7 @@ class NodeTagTest < ActiveSupport::TestCase assert tag.valid? end end - + def test_length_value_valid val = "v" (0..255).each do |i| @@ -38,7 +38,7 @@ class NodeTagTest < ActiveSupport::TestCase assert tag.valid? end end - + def test_length_key_invalid ["k"*256].each do |i| tag = NodeTag.new @@ -49,7 +49,7 @@ class NodeTagTest < ActiveSupport::TestCase assert tag.errors[:k].any? end end - + def test_length_value_invalid ["k"*256].each do |i| tag = NodeTag.new @@ -60,13 +60,13 @@ class NodeTagTest < ActiveSupport::TestCase assert tag.errors[:v].any? end end - + def test_empty_node_tag_invalid tag = NodeTag.new assert !tag.valid?, "Empty tag should be invalid" assert tag.errors[:node].any? end - + def test_uniqueness tag = NodeTag.new tag.node_id = current_node_tags(:t1).node_id diff --git a/test/models/node_test.rb b/test/models/node_test.rb index 612bff703..9a38dd947 100644 --- a/test/models/node_test.rb +++ b/test/models/node_test.rb @@ -2,7 +2,7 @@ require 'test_helper' class NodeTest < ActiveSupport::TestCase api_fixtures - + def test_node_count assert_equal 18, Node.count end @@ -10,41 +10,41 @@ class NodeTest < ActiveSupport::TestCase def test_node_too_far_north invalid_node_test(:node_too_far_north) end - + def test_node_north_limit valid_node_test(:node_north_limit) end - + def test_node_too_far_south invalid_node_test(:node_too_far_south) end - + def test_node_south_limit valid_node_test(:node_south_limit) end - + def test_node_too_far_west invalid_node_test(:node_too_far_west) end - + def test_node_west_limit valid_node_test(:node_west_limit) end - + def test_node_too_far_east invalid_node_test(:node_too_far_east) end - + def test_node_east_limit valid_node_test(:node_east_limit) end - + def test_totally_wrong invalid_node_test(:node_totally_wrong) end - + # This helper method will check to make sure that a node is within the world, and - # has the the same lat, lon and timestamp than what was put into the db by + # has the the same lat, lon and timestamp than what was put into the db by # the fixture def valid_node_test(nod) node = current_nodes(nod) @@ -58,8 +58,8 @@ class NodeTest < ActiveSupport::TestCase #assert_equal node.tile, QuadTile.tile_for_point(node.lat, node.lon) assert node.valid? end - - # This helper method will check to make sure that a node is outwith the world, + + # This helper method will check to make sure that a node is outwith the world, # and has the same lat, lon and timesamp than what was put into the db by the # fixture def invalid_node_test(nod) @@ -74,14 +74,14 @@ class NodeTest < ActiveSupport::TestCase #assert_equal node.tile, QuadTile.tile_for_point(node.lat, node.lon) assert_equal false, dbnode.valid? end - + # Check that you can create a node and store it def test_create node_template = Node.new( :latitude => 12.3456, :longitude => 65.4321, :changeset_id => changesets(:normal_user_first_change).id, - :visible => 1, + :visible => 1, :version => 1 ) assert node_template.create_with_history(users(:normal_user)) @@ -163,7 +163,7 @@ class NodeTest < ActiveSupport::TestCase assert_equal false, old_node.visible #assert_equal node_template.tags, old_node.tags end - + def test_from_xml_no_id lat = 56.7 lon = -2.3 @@ -180,7 +180,7 @@ class NodeTest < ActiveSupport::TestCase } assert_match /ID is required when updating./, message.message end - + def test_from_xml_no_lat nolat = "" message_create = assert_raise(OSM::APIBadXMLError) { @@ -192,7 +192,7 @@ class NodeTest < ActiveSupport::TestCase } assert_match /lat missing/, message_update.message end - + def test_from_xml_no_lon nolon = "" message_create = assert_raise(OSM::APIBadXMLError) { @@ -216,7 +216,7 @@ class NodeTest < ActiveSupport::TestCase } assert_match /Changeset id is missing/, message_update.message end - + def test_from_xml_no_version no_version = "" assert_nothing_raised(OSM::APIBadXMLError) { @@ -227,19 +227,19 @@ class NodeTest < ActiveSupport::TestCase } assert_match /Version is required when updating/, message_update.message end - + def test_from_xml_double_lat nocs = "" message_create = assert_raise(OSM::APIBadXMLError) { Node.from_xml(nocs, true) - } + } assert_match /Fatal error: Attribute lat redefined at/, message_create.message message_update = assert_raise(OSM::APIBadXMLError) { Node.from_xml(nocs, false) } assert_match /Fatal error: Attribute lat redefined at/, message_update.message end - + def test_from_xml_id_zero id_list = ["", "0", "00", "0.0", "a"] id_list.each do |id| @@ -253,7 +253,7 @@ class NodeTest < ActiveSupport::TestCase assert_match /ID of node cannot be zero when updating/, message_update.message end end - + def test_from_xml_no_text no_text = "" message_create = assert_raise(OSM::APIBadXMLError) { @@ -265,7 +265,7 @@ class NodeTest < ActiveSupport::TestCase } assert_match /Must specify a string with one or more characters/, message_update.message end - + def test_from_xml_no_node no_node = "" message_create = assert_raise(OSM::APIBadXMLError) { @@ -277,7 +277,7 @@ class NodeTest < ActiveSupport::TestCase } assert_match /XML doesn't contain an osm\/node element/, message_update.message end - + def test_from_xml_no_k_v nokv = "" message_create = assert_raise(OSM::APIBadXMLError) { @@ -289,7 +289,7 @@ class NodeTest < ActiveSupport::TestCase } assert_match /tag is missing key/, message_update.message end - + def test_from_xml_no_v no_v = "" message_create = assert_raise(OSM::APIBadXMLError) { @@ -301,7 +301,7 @@ class NodeTest < ActiveSupport::TestCase } assert_match /tag is missing value/, message_update.message end - + def test_from_xml_duplicate_k dupk = "" message_create = assert_raise(OSM::APIDuplicateTagsError) { @@ -318,7 +318,7 @@ class NodeTest < ActiveSupport::TestCase node = current_nodes(:node_with_versions) tags = Node.find(node.id).node_tags.order(:k) assert_equal 2, tags.count - assert_equal "testing", tags[0].k + assert_equal "testing", tags[0].k assert_equal "added in node version 3", tags[0].v assert_equal "testing two", tags[1].k assert_equal "modified in node version 4", tags[1].v diff --git a/test/models/oauth_nonce_test.rb b/test/models/oauth_nonce_test.rb index ffbad0af6..04b8dad23 100644 --- a/test/models/oauth_nonce_test.rb +++ b/test/models/oauth_nonce_test.rb @@ -9,7 +9,7 @@ class OauthNonceTest < ActiveSupport::TestCase def test_nonce_uniqueness string = "0123456789ABCDEF" timestamp = Time.now - + nonce1 = OauthNonce.remember(string, timestamp) assert_not_equal false, nonce1, "First nonce should be unique. Check your test database is empty." diff --git a/test/models/old_node_tag_test.rb b/test/models/old_node_tag_test.rb index 249b810a9..f3923d743 100644 --- a/test/models/old_node_tag_test.rb +++ b/test/models/old_node_tag_test.rb @@ -6,7 +6,7 @@ class OldNodeTagTest < ActiveSupport::TestCase def test_old_node_tag_count assert_equal 19, OldNodeTag.count, "Unexpected number of fixtures loaded." end - + def test_length_key_valid key = "k" (0..255).each do |i| @@ -18,7 +18,7 @@ class OldNodeTagTest < ActiveSupport::TestCase assert tag.valid? end end - + def test_length_value_valid val = "v" (0..255).each do |i| @@ -30,7 +30,7 @@ class OldNodeTagTest < ActiveSupport::TestCase assert tag.valid? end end - + def test_length_key_invalid ["k"*256].each do |i| tag = OldNodeTag.new @@ -42,7 +42,7 @@ class OldNodeTagTest < ActiveSupport::TestCase assert tag.errors[:k].any? end end - + def test_length_value_invalid ["k"*256].each do |i| tag = OldNodeTag.new @@ -54,13 +54,13 @@ class OldNodeTagTest < ActiveSupport::TestCase assert tag.errors[:v].any? end end - + def test_empty_tag_invalid tag = OldNodeTag.new assert !tag.valid?, "Empty tag should be invalid" assert tag.errors[:old_node].any? end - + def test_uniqueness tag = OldNodeTag.new tag.node_id = node_tags(:t1).node_id diff --git a/test/models/old_node_test.rb b/test/models/old_node_test.rb index cdc31f4f1..9adac9f81 100644 --- a/test/models/old_node_test.rb +++ b/test/models/old_node_test.rb @@ -2,7 +2,7 @@ require 'test_helper' class OldNodeTest < ActiveSupport::TestCase api_fixtures - + def test_node_count assert_equal 23, OldNode.count end @@ -10,41 +10,41 @@ class OldNodeTest < ActiveSupport::TestCase def test_node_too_far_north invalid_node_test(:node_too_far_north) end - + def test_node_north_limit valid_node_test(:node_north_limit) end - + def test_node_too_far_south invalid_node_test(:node_too_far_south) end - + def test_node_south_limit valid_node_test(:node_south_limit) end - + def test_node_too_far_west invalid_node_test(:node_too_far_west) end - + def test_node_west_limit valid_node_test(:node_west_limit) end - + def test_node_too_far_east invalid_node_test(:node_too_far_east) end - + def test_node_east_limit valid_node_test(:node_east_limit) end - + def test_totally_wrong invalid_node_test(:node_totally_wrong) end - + # This helper method will check to make sure that a node is within the world, and - # has the the same lat, lon and timestamp than what was put into the db by + # has the the same lat, lon and timestamp than what was put into the db by # the fixture def valid_node_test(nod) node = nodes(nod) @@ -58,8 +58,8 @@ class OldNodeTest < ActiveSupport::TestCase #assert_equal node.tile, QuadTile.tile_for_point(nodes(nod).lat, nodes(nod).lon) assert node.valid? end - - # This helpermethod will check to make sure that a node is outwith the world, + + # This helpermethod will check to make sure that a node is outwith the world, # and has the same lat, lon and timesamp than what was put into the db by the # fixture def invalid_node_test(nod) @@ -87,7 +87,7 @@ class OldNodeTest < ActiveSupport::TestCase node = nodes(:node_with_versions_v3) tags = OldNode.find(node.id).old_tags.order(:k) assert_equal 3, tags.count - assert_equal "testing", tags[0].k + assert_equal "testing", tags[0].k assert_equal "added in node version 3", tags[0].v assert_equal "testing three", tags[1].k assert_equal "added in node version 3", tags[1].v @@ -97,7 +97,7 @@ class OldNodeTest < ActiveSupport::TestCase node = nodes(:node_with_versions_v4) tags = OldNode.find(node.id).old_tags.order(:k) assert_equal 2, tags.count - assert_equal "testing", tags[0].k + assert_equal "testing", tags[0].k assert_equal "added in node version 3", tags[0].v assert_equal "testing two", tags[1].k assert_equal "modified in node version 4", tags[1].v diff --git a/test/models/old_relation_tag_test.rb b/test/models/old_relation_tag_test.rb index ec4987ee0..21a6a1d66 100644 --- a/test/models/old_relation_tag_test.rb +++ b/test/models/old_relation_tag_test.rb @@ -2,11 +2,11 @@ require 'test_helper' class OldRelationTagTest < ActiveSupport::TestCase api_fixtures - + def test_tag_count assert_equal 12, OldRelationTag.count end - + def test_length_key_valid key = "k" (0..255).each do |i| @@ -18,7 +18,7 @@ class OldRelationTagTest < ActiveSupport::TestCase assert tag.valid? end end - + def test_length_value_valid val = "v" (0..255).each do |i| @@ -30,7 +30,7 @@ class OldRelationTagTest < ActiveSupport::TestCase assert tag.valid? end end - + def test_length_key_invalid ["k"*256].each do |i| tag = OldRelationTag.new @@ -42,7 +42,7 @@ class OldRelationTagTest < ActiveSupport::TestCase assert tag.errors[:k].any? end end - + def test_length_value_invalid ["k"*256].each do |i| tag = OldRelationTag.new @@ -54,13 +54,13 @@ class OldRelationTagTest < ActiveSupport::TestCase assert tag.errors[:v].any? end end - + def test_empty_tag_invalid tag = OldRelationTag.new assert !tag.valid?, "Empty tag should be invalid" assert tag.errors[:old_relation].any? end - + def test_uniqueness tag = OldRelationTag.new tag.relation_id = relation_tags(:t1).relation_id diff --git a/test/models/old_relation_test.rb b/test/models/old_relation_test.rb index 14fe8a72c..66b93c9bb 100644 --- a/test/models/old_relation_test.rb +++ b/test/models/old_relation_test.rb @@ -19,7 +19,7 @@ class OldRelationTest < ActiveSupport::TestCase relation = relations(:relation_with_versions_v3) tags = OldRelation.find(relation.id).old_tags.order(:k) assert_equal 3, tags.count - assert_equal "testing", tags[0].k + assert_equal "testing", tags[0].k assert_equal "added in relation version 3", tags[0].v assert_equal "testing three", tags[1].k assert_equal "added in relation version 3", tags[1].v @@ -29,7 +29,7 @@ class OldRelationTest < ActiveSupport::TestCase relation = relations(:relation_with_versions_v4) tags = OldRelation.find(relation.id).old_tags.order(:k) assert_equal 2, tags.count - assert_equal "testing", tags[0].k + assert_equal "testing", tags[0].k assert_equal "added in relation version 3", tags[0].v assert_equal "testing two", tags[1].k assert_equal "modified in relation version 4", tags[1].v diff --git a/test/models/old_way_tag_test.rb b/test/models/old_way_tag_test.rb index 07bdfbca8..1194641da 100644 --- a/test/models/old_way_tag_test.rb +++ b/test/models/old_way_tag_test.rb @@ -2,11 +2,11 @@ require 'test_helper' class OldWayTagTest < ActiveSupport::TestCase api_fixtures - + def test_tag_count assert_equal 12, OldWayTag.count end - + def test_length_key_valid key = "k" (0..255).each do |i| @@ -18,7 +18,7 @@ class OldWayTagTest < ActiveSupport::TestCase assert tag.valid? end end - + def test_length_value_valid val = "v" (0..255).each do |i| @@ -30,7 +30,7 @@ class OldWayTagTest < ActiveSupport::TestCase assert tag.valid? end end - + def test_length_key_invalid ["k"*256].each do |i| tag = OldWayTag.new @@ -42,7 +42,7 @@ class OldWayTagTest < ActiveSupport::TestCase assert tag.errors[:k].any? end end - + def test_length_value_invalid ["k"*256].each do |i| tag = OldWayTag.new @@ -54,13 +54,13 @@ class OldWayTagTest < ActiveSupport::TestCase assert tag.errors[:v].any? end end - + def test_empty_tag_invalid tag = OldWayTag.new assert !tag.valid?, "Empty tag should be invalid" assert tag.errors[:old_way].any? end - + def test_uniqueness tag = OldWayTag.new tag.way_id = way_tags(:t1).way_id diff --git a/test/models/old_way_test.rb b/test/models/old_way_test.rb index c002ebe39..d9b2a186a 100644 --- a/test/models/old_way_test.rb +++ b/test/models/old_way_test.rb @@ -49,7 +49,7 @@ class OldWayTest < ActiveSupport::TestCase way = ways(:way_with_versions_v3) tags = OldWay.find(way.id).old_tags.order(:k) assert_equal 3, tags.count - assert_equal "testing", tags[0].k + assert_equal "testing", tags[0].k assert_equal "added in way version 3", tags[0].v assert_equal "testing three", tags[1].k assert_equal "added in way version 3", tags[1].v @@ -59,7 +59,7 @@ class OldWayTest < ActiveSupport::TestCase way = ways(:way_with_versions_v4) tags = OldWay.find(way.id).old_tags.order(:k) assert_equal 2, tags.count - assert_equal "testing", tags[0].k + assert_equal "testing", tags[0].k assert_equal "added in way version 3", tags[0].v assert_equal "testing two", tags[1].k assert_equal "modified in way version 4", tags[1].v diff --git a/test/models/relation_member_test.rb b/test/models/relation_member_test.rb index 82eaa7e58..8ce0fc81f 100644 --- a/test/models/relation_member_test.rb +++ b/test/models/relation_member_test.rb @@ -2,7 +2,7 @@ require 'test_helper' class RelationMemberTest < ActiveSupport::TestCase api_fixtures - + def test_relation_member_count assert_equal 9, RelationMember.count end diff --git a/test/models/relation_tag_test.rb b/test/models/relation_tag_test.rb index 0b5bedb05..ea095574c 100644 --- a/test/models/relation_tag_test.rb +++ b/test/models/relation_tag_test.rb @@ -2,11 +2,11 @@ require 'test_helper' class RelationTagTest < ActiveSupport::TestCase api_fixtures - + def test_relation_tag_count assert_equal 9, RelationTag.count end - + def test_length_key_valid key = "k" (0..255).each do |i| @@ -17,7 +17,7 @@ class RelationTagTest < ActiveSupport::TestCase assert tag.valid? end end - + def test_length_value_valid val = "v" (0..255).each do |i| @@ -28,7 +28,7 @@ class RelationTagTest < ActiveSupport::TestCase assert tag.valid? end end - + def test_length_key_invalid ["k"*256].each do |i| tag = RelationTag.new @@ -39,7 +39,7 @@ class RelationTagTest < ActiveSupport::TestCase assert tag.errors[:k].any? end end - + def test_length_value_invalid ["v"*256].each do |i| tag = RelationTag.new @@ -50,13 +50,13 @@ class RelationTagTest < ActiveSupport::TestCase assert tag.errors[:v].any? end end - + def test_empty_tag_invalid tag = RelationTag.new assert !tag.valid?, "Empty relation tag should be invalid" assert tag.errors[:relation].any? end - + def test_uniquness tag = RelationTag.new tag.relation_id = current_relation_tags(:t1).relation_id @@ -70,12 +70,12 @@ class RelationTagTest < ActiveSupport::TestCase ## # test that tags can be updated and saved uniquely, i.e: tag.save! - # only affects the single tag that the activerecord object + # only affects the single tag that the activerecord object # represents. this amounts to testing that the primary key is # unique. # # Commenting this out - I attempted to fix it, but composite primary keys - # wasn't playing nice with the column already called :id. Seemed to be + # wasn't playing nice with the column already called :id. Seemed to be # impossible to have validations on the :id column. If someone knows better # please fix, otherwise this test is shelved. # diff --git a/test/models/relation_test.rb b/test/models/relation_test.rb index 5d60ebb52..33e2fa0b0 100644 --- a/test/models/relation_test.rb +++ b/test/models/relation_test.rb @@ -2,11 +2,11 @@ require 'test_helper' class RelationTest < ActiveSupport::TestCase api_fixtures - + def test_relation_count assert_equal 8, Relation.count end - + def test_from_xml_no_id noid = "" assert_nothing_raised(OSM::APIBadXMLError) { @@ -17,7 +17,7 @@ class RelationTest < ActiveSupport::TestCase } assert_match /ID is required when updating/, message.message end - + def test_from_xml_no_changeset_id nocs = "" message_create = assert_raise(OSM::APIBadXMLError) { @@ -29,7 +29,7 @@ class RelationTest < ActiveSupport::TestCase } assert_match /Changeset id is missing/, message_update.message end - + def test_from_xml_no_version no_version = "" assert_nothing_raised(OSM::APIBadXMLError) { @@ -40,7 +40,7 @@ class RelationTest < ActiveSupport::TestCase } assert_match /Version is required when updating/, message_update.message end - + def test_from_xml_id_zero id_list = ["", "0", "00", "0.0", "a"] id_list.each do |id| @@ -54,7 +54,7 @@ class RelationTest < ActiveSupport::TestCase assert_match /ID of relation cannot be zero when updating/, message_update.message end end - + def test_from_xml_no_text no_text = "" message_create = assert_raise(OSM::APIBadXMLError) { @@ -66,7 +66,7 @@ class RelationTest < ActiveSupport::TestCase } assert_match /Must specify a string with one or more characters/, message_update.message end - + def test_from_xml_no_k_v nokv = "" message_create = assert_raise(OSM::APIBadXMLError) { @@ -78,7 +78,7 @@ class RelationTest < ActiveSupport::TestCase } assert_match /tag is missing key/, message_update.message end - + def test_from_xml_no_v no_v = "" message_create = assert_raise(OSM::APIBadXMLError) { @@ -90,7 +90,7 @@ class RelationTest < ActiveSupport::TestCase } assert_match /tag is missing value/, message_update.message end - + def test_from_xml_duplicate_k dupk = "" message_create = assert_raise(OSM::APIDuplicateTagsError) { @@ -131,7 +131,7 @@ class RelationTest < ActiveSupport::TestCase relation = current_relations(:relation_with_versions) tags = Relation.find(relation.id).relation_tags.order(:k) assert_equal 2, tags.count - assert_equal "testing", tags[0].k + assert_equal "testing", tags[0].k assert_equal "added in relation version 3", tags[0].v assert_equal "testing two", tags[1].k assert_equal "modified in relation version 4", tags[1].v diff --git a/test/models/trace_test.rb b/test/models/trace_test.rb index 9f713924d..4b3c5b07d 100644 --- a/test/models/trace_test.rb +++ b/test/models/trace_test.rb @@ -2,7 +2,7 @@ require 'test_helper' class TraceTest < ActiveSupport::TestCase api_fixtures - + def setup @gpx_trace_dir = Object.send("remove_const", "GPX_TRACE_DIR") Object.const_set("GPX_TRACE_DIR", File.dirname(__FILE__) + "/../traces") diff --git a/test/models/tracepoint_test.rb b/test/models/tracepoint_test.rb index 74a0d22f9..7e2d449d0 100644 --- a/test/models/tracepoint_test.rb +++ b/test/models/tracepoint_test.rb @@ -2,9 +2,9 @@ require 'test_helper' class TracepointTest < ActiveSupport::TestCase api_fixtures - + def test_tracepoint_count assert_equal 4, Tracepoint.count end - + end diff --git a/test/models/tracetag_test.rb b/test/models/tracetag_test.rb index 74a1d49aa..d5849e37f 100644 --- a/test/models/tracetag_test.rb +++ b/test/models/tracetag_test.rb @@ -2,7 +2,7 @@ require 'test_helper' class TracetagTest < ActiveSupport::TestCase api_fixtures - + def test_tracetag_count assert_equal 4, Tracetag.count end diff --git a/test/models/user_preference_test.rb b/test/models/user_preference_test.rb index 4d485b276..2cadac3e8 100644 --- a/test/models/user_preference_test.rb +++ b/test/models/user_preference_test.rb @@ -22,7 +22,7 @@ class UserPreferenceTest < ActiveSupport::TestCase assert_not_equal newUP.v, up.v assert_raise (ActiveRecord::RecordNotUnique) {newUP.save} end - + def test_check_valid_length key = "k" val = "v" @@ -38,7 +38,7 @@ class UserPreferenceTest < ActiveSupport::TestCase assert_equal val*i, resp.v, "User preference with #{i} #{val} chars (i.e. #{val.length*i} bytes) fails" end end - + def test_check_invalid_length key = "k" val = "v" diff --git a/test/models/user_test.rb b/test/models/user_test.rb index f10e8c023..0f74f8f3e 100644 --- a/test/models/user_test.rb +++ b/test/models/user_test.rb @@ -16,11 +16,11 @@ class UserTest < ActiveSupport::TestCase assert !user.errors[:home_lon].any? assert !user.errors[:home_zoom].any? end - + def test_unique_email new_user = User.new( :email => users(:normal_user).email, - :status => "active", + :status => "active", :pass_crypt => Digest::MD5.hexdigest('test'), :display_name => "new user", :data_public => 1, @@ -29,39 +29,39 @@ class UserTest < ActiveSupport::TestCase assert !new_user.save assert new_user.errors[:email].include?("has already been taken") end - + def test_unique_display_name new_user = User.new( :email => "tester@openstreetmap.org", :status => "pending", :pass_crypt => Digest::MD5.hexdigest('test'), - :display_name => users(:normal_user).display_name, + :display_name => users(:normal_user).display_name, :data_public => 1, :description => "desc" ) assert !new_user.save assert new_user.errors[:display_name].include?("has already been taken") end - + def test_email_valid - ok = %w{ a@s.com test@shaunmcdonald.me.uk hello_local@ping-d.ng + ok = %w{ a@s.com test@shaunmcdonald.me.uk hello_local@ping-d.ng test_local@openstreetmap.org test-local@example.com } bad = %w{ hi ht@ n@ @.com help@.me.uk help"hi.me.uk も対@応します 輕觸搖晃的遊戲@ah.com も対応します@s.name } - + ok.each do |name| user = users(:normal_user) user.email = name assert user.valid?(:save), user.errors.full_messages.join(",") end - + bad.each do |name| user = users(:normal_user) user.email = name - assert user.invalid?(:save), "#{name} is valid when it shouldn't be" + assert user.invalid?(:save), "#{name} is valid when it shouldn't be" end end - + def test_display_name_length user = users(:normal_user) user.display_name = "123" @@ -71,17 +71,17 @@ class UserTest < ActiveSupport::TestCase user.display_name = "" assert !user.valid? user.display_name = nil - # Don't understand why it isn't allowing a nil value, + # Don't understand why it isn't allowing a nil value, # when the validates statements specifically allow it # It appears the database does not allow null values assert !user.valid? end - + def test_display_name_valid - # Due to sanitisation in the view some of these that you might not + # Due to sanitisation in the view some of these that you might not # expact are allowed # However, would they affect the xml planet dumps? - ok = [ "Name", "'me", "he\"", "
", "*ho", "\"help\"@", + ok = [ "Name", "'me", "he\"", "
", "*ho", "\"help\"@", "vergrößern", "ルシステムにも対応します", "輕觸搖晃的遊戲" ] # These need to be 3 chars in length, otherwise the length test above # should be used. @@ -95,14 +95,14 @@ class UserTest < ActiveSupport::TestCase user.display_name = display_name assert user.valid?, "#{display_name} is invalid, when it should be" end - + bad.each do |display_name| user = users(:normal_user) user.display_name = display_name assert !user.valid?, "#{display_name} is valid when it shouldn't be" end end - + def test_friend_with assert users(:normal_user).is_friends_with?(users(:public_user)) assert !users(:normal_user).is_friends_with?(users(:inactive_user)) diff --git a/test/models/user_token_test.rb b/test/models/user_token_test.rb index 7be5a2cf7..c6d9a9554 100644 --- a/test/models/user_token_test.rb +++ b/test/models/user_token_test.rb @@ -7,5 +7,5 @@ class UserTokenTest < ActiveSupport::TestCase def test_user_token_count assert_equal 0, UserToken.count end - + end diff --git a/test/models/way_tag_test.rb b/test/models/way_tag_test.rb index 4d6116159..498c1ff10 100644 --- a/test/models/way_tag_test.rb +++ b/test/models/way_tag_test.rb @@ -2,11 +2,11 @@ require 'test_helper' class WayTagTest < ActiveSupport::TestCase api_fixtures - + def test_way_tag_count assert_equal 5, WayTag.count end - + def test_length_key_valid key = "k" (0..255).each do |i| @@ -17,7 +17,7 @@ class WayTagTest < ActiveSupport::TestCase assert tag.valid? end end - + def test_length_value_valid val = "v" (0..255).each do |i| @@ -28,7 +28,7 @@ class WayTagTest < ActiveSupport::TestCase assert tag.valid? end end - + def test_length_key_invalid ["k"*256].each do |i| tag = WayTag.new @@ -39,7 +39,7 @@ class WayTagTest < ActiveSupport::TestCase assert tag.errors[:k].any? end end - + def test_length_value_invalid ["v"*256].each do |i| tag = WayTag.new @@ -50,13 +50,13 @@ class WayTagTest < ActiveSupport::TestCase assert tag.errors[:v].any? end end - + def test_empty_tag_invalid tag = WayTag.new assert !tag.valid?, "Empty way tag should be invalid" assert tag.errors[:way].any? end - + def test_uniqueness tag = WayTag.new tag.way_id = current_way_tags(:t1).way_id diff --git a/test/models/way_test.rb b/test/models/way_test.rb index de0eb6146..69529e654 100644 --- a/test/models/way_test.rb +++ b/test/models/way_test.rb @@ -8,7 +8,7 @@ class WayTest < ActiveSupport::TestCase def test_db_count assert_equal 7, Way.count end - + def test_bbox node = current_nodes(:used_node_1) [ :visible_way, @@ -21,8 +21,8 @@ class WayTest < ActiveSupport::TestCase assert_equal node.bbox.max_lat, way.bbox.max_lat, 'max_lat' end end - - # Check that the preconditions fail when you are over the defined limit of + + # Check that the preconditions fail when you are over the defined limit of # the maximum number of nodes in each way. def test_max_nodes_per_way_limit # Take one of the current ways and add nodes to it until we are near the limit @@ -39,7 +39,7 @@ class WayTest < ActiveSupport::TestCase way.add_nd_num(current_nodes(:visible_node).id) assert way.valid? end - + def test_from_xml_no_id noid = "" assert_nothing_raised(OSM::APIBadXMLError) { @@ -50,7 +50,7 @@ class WayTest < ActiveSupport::TestCase } assert_match /ID is required when updating/, message.message end - + def test_from_xml_no_changeset_id nocs = "" message_create = assert_raise(OSM::APIBadXMLError) { @@ -62,7 +62,7 @@ class WayTest < ActiveSupport::TestCase } assert_match /Changeset id is missing/, message_update.message end - + def test_from_xml_no_version no_version = "" assert_nothing_raised(OSM::APIBadXMLError) { @@ -87,7 +87,7 @@ class WayTest < ActiveSupport::TestCase assert_match /ID of way cannot be zero when updating/, message_update.message end end - + def test_from_xml_no_text no_text = "" message_create = assert_raise(OSM::APIBadXMLError) { @@ -99,7 +99,7 @@ class WayTest < ActiveSupport::TestCase } assert_match /Must specify a string with one or more characters/, message_update.message end - + def test_from_xml_no_k_v nokv = "" message_create = assert_raise(OSM::APIBadXMLError) { @@ -111,7 +111,7 @@ class WayTest < ActiveSupport::TestCase } assert_match /tag is missing key/, message_update.message end - + def test_from_xml_no_v no_v = "" message_create = assert_raise(OSM::APIBadXMLError) { @@ -123,7 +123,7 @@ class WayTest < ActiveSupport::TestCase } assert_match /tag is missing value/, message_update.message end - + def test_from_xml_duplicate_k dupk = "" message_create = assert_raise(OSM::APIDuplicateTagsError) { @@ -167,7 +167,7 @@ class WayTest < ActiveSupport::TestCase way = current_ways(:way_with_versions) tags = Way.find(way.id).way_tags.order(:k) assert_equal 2, tags.count - assert_equal "testing", tags[0].k + assert_equal "testing", tags[0].k assert_equal "added in way version 3", tags[0].v assert_equal "testing two", tags[1].k assert_equal "modified in way version 4", tags[1].v diff --git a/test/test_helper.rb b/test/test_helper.rb index 9464d6623..2787ed83f 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -44,21 +44,21 @@ class ActiveSupport::TestCase fixtures :relation_members, :relation_tags set_fixture_class :relation_members => OldRelationMember set_fixture_class :relation_tags => OldRelationTag - + fixtures :gpx_files, :gps_points, :gpx_file_tags set_fixture_class :gpx_files => Trace set_fixture_class :gps_points => Tracepoint set_fixture_class :gpx_file_tags => Tracetag fixtures :client_applications - + fixtures :redactions fixtures :notes, :note_comments end ## - # takes a block which is executed in the context of a different + # takes a block which is executed in the context of a different # ActionController instance. this is used so that code can call methods # on the node controller whilst testing the old_node controller. def with_controller(new_controller) @@ -86,8 +86,8 @@ class ActiveSupport::TestCase end ## - # for some reason a==b is false, but there doesn't seem to be any - # difference between the nodes, so i'm checking all the attributes + # for some reason a==b is false, but there doesn't seem to be any + # difference between the nodes, so i'm checking all the attributes # manually and blaming it on ActiveRecord def assert_nodes_are_equal(a, b) assert_equal a.id, b.id, "node IDs" @@ -110,20 +110,20 @@ class ActiveSupport::TestCase def content(c) @request.env["RAW_POST_DATA"] = c.to_s end - + # Used to check that the error header and the forbidden responses are given # when the owner of the changset has their data not marked as public def assert_require_public_data(msg = "Shouldn't be able to use API when the user's data is not public") assert_response :forbidden, msg assert_equal @response.headers['Error'], "You must make your edits public to upload new data", "Wrong error message" end - + # Not sure this is the best response we could give def assert_inactive_user(msg = "an inactive user shouldn't be able to access the API") assert_response :unauthorized, msg #assert_equal @response.headers['Error'], "" end - + def assert_no_missing_translations(msg="") assert_select "span[class=translation_missing]", false, "Missing translation #{msg}" end @@ -165,6 +165,6 @@ class ActiveSupport::TestCase return openid_response_qs end - + # Add more helper methods to be used by all tests here... end -- 2.39.5
DayWeekMonth